Вы находитесь на странице: 1из 590

( , )

Dino Esposito

Programming Microsoft
ASP.NET 2.0 Applications:
Advanced Topics

Microsoft

ASP.NET 2.0

* - * *
* -- * *
* *
2008

004.738.5
32.973.202
85
.
85 Microsoft ASP.NET 2.0. . / . . .:
; . : , 2008. 592 .: .

ISBN 978-5-7502-0286-7 ( )
ISBN 978-5-91180-196-0 ()
-
ASP.NET.
ASP.NET 2.0 ,
, ,
. , ,
ASP.NET 2.0 .
15 . ,
, ,
ASP.NET 2.0.

004.738.5
32.973.202

Microsoft Corporation, , , .
Active Directory, ActiveSync, Hotmail, Links, Microsoft, Microsoft Press, MSN, Natural, NetMeeting, Outlook,
Powerpoint, Win32 Windows Microsoft
Corporation. .
, , , , , , ,
.

ISBN 0-7356-2177-2 (.)


ISBN 978-5-7502-0286-7 ( )
ISBN 978-5-91180-196-0 ()

,
Dino Esposito, 2006
, Microsoft Corporation,
2006
,
, 2007

........................................................................................................................................................ XI
..................................................................................................................................................... XV
.........................................................................................................................................XVI
I
ASP.NET...............................................................................................1
1 ASP.NET ..........................................................................................2
ASP.NET ....................................................................................................................3
.......................................................................................................................................3
ASP.NET ...............................................................................................................10
.........................................................................................................................13
..................................................................................................................21
...................................................................................................................21
..............................................................................................23
ASP.NET ........................................................................................26
.......................................................................................................................26
ASP.NET ................................................................................................29
.....................................................................................................................34
........................................................37
........................................................................................................46
......................................................................................................................................................49
2 HTTP ..........................................................................................50
API IIS ........................................................................................................51
ISAPI ...........................................................................................................................................51
IIS 7.0 ........................................................................................................54
HTTP...............................................................................................................55
IHttpHandler .....................................................................................................................55
HTTP ...................................................................57
..............................................................................64
HTTP ....................................................68
HTTP .........................................................................................................................72
IHttpModule ......................................................................................................................72
HTTP ......................................................................................................73
...........................................................................................................................77
......................................................................................................................................................82

VI

3 ASP.NET .....................................................................................................84
ASP.NET.................................................................................................84
.................................................................................................................85
<system.web> .............................................................................................................................92
.................................................................................................... 120
..................................................................................... 122
API .................................................................................... 122
................................................................................................... 129
................................................................................................................................................... 134
4 ASP.NET ..................................... 136
..................................................................................................................... 137
...................................................................................................................... 137
.............................................................................................................................. 139
ASP.NET ....................................................................................................... 141
.................................................................................................................................... 142
.............................................................................................................. 146
............................................................................................. 149
................................................................................................................... 150
...................................................................................................................... 152
Web ..................................................................................................... 154
Web Parts ................................................................................................ 158
........................................................................................................ 159
................................................................................................................... 164
................................................................................................................... 164
, cookie .................................................. 166
...................................................................................................................... 172
................................................................................................................................................... 174
5 ......................................................................................... 175
......................................................................................................... 175
ASP.NET ......................................... 176
ASP.NET 2.0 ........................................................................................................................ 178
................................................................................................. 183
............................................................................ 188
.................................................................................................... 203
ASP- ....................................................................................................................... 203
............................................................................................... 206
ASP.NET 2.0 ................................................................................... 208
....................................................... 210
ASP.NET ........................................................... 215
PageParserFilter ........................................................................................................................ 215
............................................................................................................................... 217
................................................................................................................................................... 221

VII

II
ASP.NET ..................................................................... 223
6 ............................................................................................ 224
................................................................................ 224
........................................................................................... 225
....................................................................................................... 228
.......................................................................................................... 236
Script Callbacks .................................................................................................................... 239
API ASP.NET ....................................................................................................................... 240
.............................................................................................. 243
Ajax.NET ................................................................................................................................ 252
.............................................................................................................. 253
Ajax.NET ASP.NET Script Callbacks............................................. 257
................................................................................................................................................... 259
7 Web Parts .......................................................................... 261
Web Parts........................................................................................................................................... 261
Web Parts ............................................................................................................................. 261
Web Parts Framework ................................................................................................... 263
Web Parts ................................................................................. 266
Web Parts ............................................................................................................... 269
Web Part StockViewer ......................................................................................................................... 274
Web Parts ........................................................................ 281
Web- ...................................................................................................................................... 284
Web Parts .................................................................................. 290
................................................................................................... 290
.............................................................................................................. 292
Editor Zone .......................................................................................................................... 294
Catalog Zone ....................................................................................................................... 296
Web Parts ............................................................................................................................... 300
Web Parts......................................................................................................... 300
................................................................................ 302
................................................................................................................................ 304
................................................................................................................................................... 305
8 ................................................ 307
.......................................................................................... 307
...................................................................... 307
ASP.NET...................................................................................................... 310
........................................................................................... 316
.................................................................................................. 316
.................................................................................................... 320
............................................................................................. 323

VIII

.................................................................................................... 325
................................................................................................. 326
............................................................................................. 328
...................................................................................................................... 332
................................................................................................................................................... 335
9 ............................................................................................... 336
Web- ........................................................................................... 336
, .................................................. 338
............................................................................................... 339
, .................................................................... 342
............................................................................................................ 342
........................................................................................................................ 347
..................................................................................... 350
GDI+ .......................................................................................................... 350
............................................................................................................................ 353
, ................................................................ 358
................................................................................................................................................... 364
10 ......................................................................................................... 366
......................................................................................................................... 366
......................................................................................................................... 366
..................................................................................................... 369
................................................................................................... 372
SiteMap........................................................................................................................................ 372
SiteMapPath ................................................................................................. 375
SiteMapDataSource.................................................................................... 377
........................................................................................................... 380
TreeView ........................................................................................................ 380
Menu ............................................................................................................... 384
................................................................................................................................................... 390
III
ASP.NET ............................................................................................. 391
11 ASP.NET................................................. 392
................................................................................... 392
....................................... 392
-....... 393
Repeater ................................................................................................................ 394
Repeater .......................................... 394
Repeater.................................................................................... 397
Repeater ................................................................................... 401
DataList ................................................................................................................ 405
DataList .......................................... 405
....................................................................................................... 408

IX

DataList .................................................................................... 412


DataList.................................................................................... 413
................................................................................................................................................... 416
12 ASP.NET..................................... 418
.......................................................................... 418
UserControl ................................................................................................................................ 419
.................................... 421
................................................................... 424
TabStrip ..................................................................................... 424
........................... 428
........................................... 433
............................ 436
..................................... 436
........................................................................ 443
................................................................................................................................................... 444
13 ASP.NET...... 446
............................................................... 447
....................................................................................................................... 447
HyperLink.......................................................... 449
............................................................................................. 451
........................................................................................................... 451
............................................................................................................... 453
SimpleGaugeBar .......................................................................................... 455
.................................................................................................... 459
......... 468
................................................................................................................... 469
......................................................................................................................... 473
.................................................................................... 479
................................................................................................................ 482
................................................................................................................................................... 485
14 ,
......................................................................................... 487
, ......................................... 487
, ............................................................... 488
.................................................................................................. 489
, ............................................. 493
........................................................................... 494
GaugeBar ....................................................................................................... 496
............................................................................. 499
.......................................................... 503
.................................................. 503
HyperLinkList .............................................................................................. 506

, .............................. 513
, ...... 513
BarChart ........................................................................................................ 516
.................................................................................................. 524
................................................................................................................................................... 530
15


..................................................................................................... 533
.NET .............................................................................................. 533
, .............................................................................. 534
.............................................................................................. 535
-............................................................................................................................... 536
, .......................................................................... 536
, ........................................................................ 542
....................................................................................................... 543
......................................................................................................... 543
................................................................................................................ 552
................................................................................ 554
................................................................................................................. 556
...................................................................................................................... 556
.................................................................................. 558
................................................................................................................................................... 565
....................................................................................................................... 567

ASP.NET 2.0 2004 .


1600 , , , , .
, .
: , , , ,
, . , ,
, , , .
, :
Programming Microsoft ASP.NET 2.0: Core Reference*, Programming Microsoft
ASP.NET 2.0 Applications: Advanced Topics ( ).
ASP.NET.
, ,
, ASP.NET 2.0, , ,
, . Programming Microsoft
ASP.NET 2.0: Core Reference, ,
. ,
, ,
ASP.NET.
, Programming Microsoft ASP.NET 2.0: Core Reference,
; ,
( , , ), ,
( , Web Part, ,
, ).
ASP.NET 2.0.


.
, Programming Microsoft ASP.NET 2.0: Core
Reference, , . , ,
Microsoft Visual Studio 2005 ,
,
IDE. , , Visual Studio 2005
ASP.NET. Visual
*

. : Microsoft ASP.NET 2.0: . . .

XII

Studio 2005 , ASP.NET


. ASP.NET,
.
, , Programming Microsoft ASP.NET 2.0: Core Reference . ,
. ,
Web Part, ,
, ASP.NET.
III .


: ASP.NET, ASP.NET, ASP.NET.
I , , . 5
,
, .
II ASP.NET. , Web Part,
,
, API,
.
III .
Repeater DataList, GridView, DetailsView FormView
, . , -
, , ,
,
.


, , :


Microsoft Windows XP Service Pack 2, Microsoft Windows Server 2003 Service


Pack 1 Microsoft Windows 2000 Service Pack 4;

Microsoft Visual Studio 2005 Standard Edition Microsoft Visual Studio 2005
Professional Edition;

Internet Information Services (IIS);


ASP.NET Visual Studio, , ;

Microsoft SQL Server 2005 Express ( Visual Studio 2005) Microsoft SQL Server 2005;

Northwind Traders Microsoft SQL Server 2000,


;
SQL Server 2005, Northwind Microsoft http://www.microsoft.com/

XIII

downloads/details.aspx?FamilyId=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en;


Pentium 766 ( Pentium


1,5 );

RAM 256 ( 512 );

800600 , 256
( : 1024768, 16 );

CD-ROM DVD-ROM;

Microsoft Mouse .

SQL Server 2005 Express Edition



SQL Server 2005 Express Edition ( SQL Server 2005),
Northwind Traders.
SQL Server 2005 Express Edition,
, , .
1. Windows \ \ \ ,
.
2. , _
:
sqlcmd S _\SQLExpress E
, hostname ( sqlcmd).
3. 1> ,
:
sp_grantlogin [_\_]
_ , _ Windows, SQL
Server.
4. 2> :
go
, ,
sp_grantlogin.
5. 1>, ,
:
sp_addsrvrolemember [_\_], dbcreator
6. 2> :
go
, ,
sp_addsrvrolemember.
7. , 1> :
exit
8. .

XIV


Microsoft
Press Technology Updates . , Visual Studio 2005
. :
http://www.microsoft.com/mspress/updates/


:
http://www.microsoft.com/mspress/companion/0-7356-2177-2/

,
. , Microsoft Knowledge Base.
Microsoft Press
:
http://www.microsoft.com/learning/support/books/


, , , ,
Microsoft Press :
mspinput@microsoft.com
:
Microsoft Press
Attn: Programming Microsoft ASP.NET: Advanced Topics Editor
One Microsoft Way
Redmond, WA 98052-6399

ASP.NET ADO.NET
Solid Quality Learning,
.
Cutting Edge MSDN Magazine
.NET Framework Microsoft ASP.NET Developer Center Microsoft
Visual Studio Developer Center, ,
asp.netPRO Magazine, CoDe Magazine
ASP.NET-2-The-Max. Microsoft Press
Programming Microsoft ASP.NET (2003), Building Web Solutions with ASP
.NET and ADO.NET (2002), Applied XML Programming for Microsoft .NET (2002)
Programming Microsoft ASP.NET 2.0 Core Reference (2006).
http://weblogs.asp.net/despos.
.NET Association (INETA),
, ,
.
, ,
.
DNA 1994
Web- .
, DevConnections, DevWeek,
WinDev Microsoft TechEd. , .

,
: (Ben Ryan), (Lynn Finnel),
(Kenn Scribner), (Roger LeBlanc) (Robert Lyon).
,
. , ,
.
, , , .
, ,
, ,
. , ,
. (
.)
, .
, , ,
, .
,
. (Fernando Guerrero),
Solid Quality Learning, (Marius Constantinescu), (Marco Bellinaso), (Steve Toub), (Jay Greenfield),
(Andrea Saltarello) (Raffaele Rialdi).
(Matthew Gibbs),
(Nikhil Kothari), (David Ebbo), (Simon Calvert),
(Dmitri Robsman) (Jonathan Hawkins)
ASP.NET,
. (Scott Guthrie) ,
.
(Lutz Roeder)
.NET Reflector,
ASP.NET.
, , ,
. 800
. , , . .
,
. -
. , ,
, .
.

ASP.NET

1. ASP.NET ................................................................................. 2
2. HTTP ................................................................................ 50
3. ASP.NET ......................................................................................... 84
4. ASP.NET ......................................... 136
5. ................................................................................. 175

ASP.NET

, ASP.NET,
, ,
. ASP.NET
. ASP.NET 1.x
, ASP.NET (*.aspx), Web-
ASP.NET (*.asmx), HTTP (*.ashx), global.asax .
, ASP.NET ,
global.asax ,
, .
ASP.NET .
, ASP, , . ASP.NET , .
: C#
Microsoft Visual Basic .NET, ASP.NET,
.
(AppDomain), .
, , ,
. ,
. (, .aspx)
, .
, , -,
.
. -, : Save, . -, ,
. , ,
, , .
ASP.NET 2.0 ,
XSD, WSDL, , . , ASP.NET 2.0
,
. ASP.NET 1.x
ASP.NET 2.0 ,
Microsoft Visual Studio .NET. Web-.
ASP.NET, , ASP.NET , ,
.

ASP.NET

ASP.NET
, Web- Internet Information Server (IIS),
.
. IIS , HTML-,
, . ,
,
, ,
. 14
Programming Microsoft ASP.NET 2.0: Core Reference (Microsoft Press, 2005).
IIS, ASP.NET,
(DLL) aspnet_isapi.
DLL, ISAPI (Internet Server Application Programming Interface -). ISAPI-
( ISAPI-) DLL, ,
IIS .
ISAPI DLL Microsoft Win32,
GetExtensionVersion HttpExtensionProc, . IIS HttpExtensionProc
.

aspnet_isapi
IIS, Properties Web- IIS, . 1-1.

. 1-1. , ASP.NET

, aspnet_isapi, , ,
. ASP.NET
, .
ASP.NET .


ASP.NET , IIS,
. ASP.NET

ASP.NET

IIS 5.x, IIS 5. IIS 6.0 . , IIS


.
IIS 5.0

aspnet_isapi
, . URL
, ASP.NET
aspnet_wp.exe. ISAPI .
ASPNET.
ASP.NET.
,
- Web-, . ,
Web- (Web-garden),
, .
Web-,
, ASP.NET AppDomain,
. , AppDomain, ;
,
, .
. IIS 5.0
. 1-2.

. 1-2. IIS 5.0

IIS 6.0

IIS 6.0 ,
. IIS 5.0 . IIS 6.0, ,

ASP.NET

. Web-,
.
Web-
.
,
.
, IIS 6.0 , , ASP.NET, w3wp.exe.
, ASP.NET
, Web-.
, Web- ,
w3wp.exe.
IIS 6.0
http.sys. HTTP
. , http.sys
, , . .
IIS 5.0 http.sys ,
.
IIS 6.0
Internet Information Services (IIS) 6.0 Resource Kit (Microsoft
Press, 2004).

( w3wp.exe) aspnet_isapi.dll; ISAPI- (CLR)


. IIS 6.0
ASP.NET . . 1-3 , IIS 6.0.

. 1-3. IIS 6.0

ASP.NET

http.sys. NETWORK
SERVICE, ,
.
3 Programming Microsoft
ASP.NET 2.0: Core Reference (Microsoft Press, 2005).
.

ASP.NET

ASP.NET IIS
CLR . CLR
, , , ,
Web-. ,
ASP.NET, , cookie
. , .
, .
ASP.NET 2.0 , ,
.
.aspx ,
. 1-2 1-3. , .
, ,
AppDomain, ASP.NET. HTTP
,
. . 1-1.
. 1-1. HTTP

HttpApplicationFactory
HttpApplication, .
HttpApplicationFactory HttpApplication ,
, ,
, , AppDomain. ,
, HttpApplicationFactory

HttpApplication .
HttpApplication (,
),
HttpApplication

ASP.NET , HttpApplication.
global.asax.
HttpApplication ,
(
ASP.NET, Web- , , ),
HTTP ,

ASP.NET

. 1-1. ()

HTTP modules

HttpApplication
HTTP,
.
, .
HTTP Forms,
,

PageHandlerFactory ( )
, .
-
, Web- HTTP
-, ,
System.Web.UI.Page ( ),
IHttpHandler. ,
ASP.NET, -
ProcessRequest IHttpHandler.

PageHandlerFactory

IHttpHandler

HTTP . 1-4.

. 1-4. HTTP

ASP.NET

Web-
HttpRuntime. HTTP, ,
. (aspnet_wp.exe
aspnet_isapi w3wp.exe) HTTP,
HttpRuntime ProcessRequest.
, HTTP- , ASP.NET.
Page, . , , xxx.aspx,
ASP.xxx_aspx. @Page ClassName, ASP._,
_ ClassName.
,
IHttpHandler. . , ASP.NET ,
(
).

. ,
, , ,
.
( ,
, , ).
, .
, .
.

HttpApplication machine.config -,
.
, PageHandlerFactory .aspx. .asmx (Web-)
.ashx ( HTTP).
<httpHandlers>
<add path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory"
validate="True" />
<add path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory"
validate="True" />
<add path="*.asmx" verb="*"
type="System.Web.Services.Protocols.WebServiceHandlerFactory,
System.Web.Services, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
validate="False" />
</httpHandlers>

PageHandlerFactory IHttpHandlerFactory,
. 1-2.

ASP.NET

. 1-2. IHttpHandlerFactory

GetHandler

IHttpHandler ,
. , Page.
HTTP, URL

ReleaseHandler , . ,
HTTP- ,
void

,
, .
.aspx
ASP.NET:
%SystemRoot%\Microsoft.NET\Framework\[]\Temporary ASP.NET Files

ASP.NET 1.x ,
Visual Studio, ASP.NET 2.0
, Visual Studio .NET.
ASP.NET
.
! ASP.NET 1.x - ASP.NET. , Visual
Studio 2005.

. 1-5 , ,
.

. 1-5. ASP.NET ,

10

ASP.NET

.
,
, . ( , .aspx-.)

.NET Framework 2.0. , .


,
.
,
, , - . ,

, ,
,
.
-
. Visual Studio .NET 2003,
, , , .
,
, Web-. Web- , .aspx- HTML-!
. ,
, . ,

, .

ASP.NET
.aspx ,
. , .aspx-.
, Temporary ASP.NET Files. ASP.NET.

Temporary ASP.NET Files


- . . , Web-, Root.
,
.
(
, ):
\Framework
\[version]

ASP.NET

11

\Temporary ASP.NET Files


\MyWebApp
\3678b103
\e60405c7

, ,
ASP.NET
:
string tempAspNetDir = HttpRuntime.CodegenDir;

. ASP.NET .aspx?

:
[].aspx.XXXXX.compiled

.aspx-, XXXXX -,
, . ,
,
, .
( ,
), -.
ASP.NET -,
- .
.compiled.
<preserve virtualPath="/Compilation/Test.aspx"
hash="7421446ce"
filehash="4d443b62d9942247"
flags="10000"
assembly="App_Web_g5u1sfqg"
type="ASP.Test_aspx">
<filedeps>
<filedep name="/Compilation/Test.aspx" />
<filedep name="/Compilation/Test.aspx.cs" />
</filedeps>
</preserve>
.compiled
. , ASP.NET. , , ,
.

<preserve> (test.aspx),
(ASP.Test_aspx) , , , (App_Web_g5u1sfqg). <filedeps>
,
.
HTTP ,
, .compiled
. .compiled
, ,
.aspx, C# Visual Basic .NET.
, .

12

ASP.NET

ASP.NET 2.0 ,
, App_Web_.
, , , global.asax,
.


. .aspx ,
. .aspx-
.compiled. ,
<filedeps>, .
ASP.NET
, Win32.
. ASP.NET , , . , , ,
. (
)
.
ASP.NET

, ASP.NET ,
. , . ,
( ), .
.delete. (Microsoft Windows
, , ,
.)
,
.
.delete
(sweep mode).
,
(global.asax web.config).
ASP.NET ( 15), . ,
. :
AppDomain, .
, CLR , . , , AppDomain.
! , ,
, , AppDomain.
,
.
ASP.NET
,
.

ASP.NET

13

, . 1-6 ( showruntimeinfo.aspx
), . HttpRuntime,
,
, , ,
ASP.NET (CodegenDir),
Bin (BinDirectory).

. 1-6.

, AppDomain. 17 , global.asax .
, .aspx,
,
, . .aspx ( Ctrl+S), ,
15 , ( 17).
, .


,
test.aspx Compilation.
:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test"
Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/
xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">

14

ASP.NET

<title>Sample page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Enter some text and click.</h1>
<h2><asp:Label ID="Today" runat="server" Text='<%# DateTime.Now %>' /></h2>
<asp:TextBox ID="TextBox1" runat="server" Text="Type here" />
<asp:Button ID="Button1" runat="server" Text="Reverse" OnClick="ReverseText" />
<hr />
<asp:Label ID="Label1" runat="server" Text="[No info]" />
</div>
</form>
</body>
</html>

:
using
using
using
using

System;
System.Web.UI;
System.Web.UI.WebControls;
System.Text;

public partial class Test : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
protected void ReverseText(object sender, EventArgs e)
{
string reverseText = Reverse(TextBox1.Text);
Label1.Text = reverseText;
}
private string Reverse(string text)
{
if (text.Length == 1)
return text;
else
{
StringBuilder sb = new StringBuilder();
sb.Append(Reverse(text.Substring(1)));
sb.Append(text.Substring(0, 1));
return sb.ToString();
}
}
}

, , , ,
. Label, . (
Programming Microsoft ASP.NET 2.0: Core Reference.)
,
-, .

ASP.NET

15

, test.aspx,
. ( )
, @Page debug=true.
, , compilation,
ASP.NET (
. 1-7), .

. 1-7. ,
compilation

. 1-8 , test.aspx. ,
( , , )
.

. 1-8. , test.aspx

. 1-3 . ,
xgpc4gcp . .
. 1-3. test.aspx

hash.web

-,
-

, test.aspx.
xxx -,
,

App_Web_test.aspx.xxx.dll

(. . .)

16

ASP.NET

. 1-3. ()

Test.aspx.xxx.compiled

XML-, test.aspx
. , .compiled
test.aspx ,
C#,
test.aspx, . ,
Visual Basic .NET, Visual Basic .NET.
x 0- , .
debug,

, ,
.
debug,

, ,
error.
debug,
, ,

xgpc4cgb.x.cs

xgpc4cgb.cmdline

xgpc4cgp.err

xgpc4cgb.out

ASP.NET,
xgpc4cgb.x.cs x 0 2. . 1-4.
test.aspx.
. 1-4. test.aspx

xgpc4cgb.0.cs () Test, ASP.test_aspx : Test,


, test.aspx
, ,

test.aspx
xgpc4cgb.1.cs () Test
test.aspx.cs,

xgpc4cgb.2.cs ASP.FastObjectFactory
- ,

(.NET reflection)

xxx.1.cs , ASP.NET. , Test,


Inherits @Page, ,
. :
public partial class Test : IRequiresSessionState
{
protected Label Today;
protected TextBox TextBox1;
protected Button Button1;

ASP.NET

17

protected Label Label1;


protected HtmlForm form1;
protected DefaultProfile Profile {
get {return (DefaultProfile) Context.Profile;}
}
protected HttpApplication ApplicationInstance {
get {return (HttpApplication) Context.ApplicationInstance;}
}
}

,
. , ASP.NET 1.x
Visual Studio .NET 2003 .
FastObjectFactory. :
namespace ASP {
internal class FastObjectFactory
{
private FastObjectFactory() {}
static object Create_ASP_Test_aspx()
{
return new ASP.Test_aspx();
}
}
}

, .
,
.
.
! FastObjectFactory, ,
,
, ,
. , ASP.NET, .

,
test.aspx, , Inherits .
Test. , ,
test.aspx.cs , , Page.
Test ASP.NET ,
.
test.aspx, Test,
ASP.Test_aspx. :
namespace ASP {
public class Test_aspx : Test {
private static bool __initialized;
private static object __fileDependencies;

18

ASP.NET

public Test_aspx() {
string[] dependencies;
AppRelativeVirtualPath = "~/Test.aspx";
if (__initialized == false) {
dependencies = new string[2];
dependencies[0] = "~/Test.aspx";
dependencies[1] = "~/Test.aspx.cs";
__fileDependencies = GetWrappedFileDependencies(dependencies);
__initialized = true;
}
Server.ScriptTimeout = 30000000;
}
protected override void FrameworkInitialize() {
base.FrameworkInitialize();
__BuildControlTree(this);
AddWrappedFileDependencies(__fileDependencies);
Request.ValidateInput();
}
public override int GetTypeHashCode() {
//
//
return 850224717;
}
}

.
, .
. , ASP.Test_aspx
Page, . 1-5.
. 1-5. ASP.Test_aspx

FrameworkInitialize
GetTypeHashCode - ,
. GetHashCode,
.NET Framework System.Object.
, ,
GetHashCode ,
.
,

FrameworkInitialize .
-, __BuildControlTree, Controls
, . __BuildControlTree, ,
ASP.NET. -, ValidateInput Request, ,
, . , ValidateInput,
ValidateRequest @Page,
.
, , .

ASP.NET

19

__BuildControlTree
, ASPX-. IParserAccessor ,
Controls .
private void __BuildControlTree(Test_aspx __ctrl)
{
//
IParserAccessor __parser = (IParserAccessor) __ctrl);
// <head>
HtmlHead __ctrl1 = __BuildControl__control2();
__parser.AddParsedSubObject(__ctrl1);
//
__parser.AddParsedSubObject(new LiteralControl("<body>"));
// <form>
HtmlForm __ctrl2 = __BuildControlform1();
__parser.AddParsedSubObject(__ctrl2);
//
__parser.AddParsedSubObject(new LiteralControl("</body></html>"));
}

<head> , <form>
. (, <body>)
. , , .
,
. /r/n . HTML,
,
.

,
, TextBox1:
private TextBox __BuildControlTextBox1()
{
TextBox __ctrl = new TextBox();
this.TextBox1 = __ctrl;
__ctrl.ApplyStyleSheetSkin(this);
__ctrl.ID = "TextBox1";
__ctrl.Text = "Type here";
return __ctrl;
}

:
<asp:TextBox ID="TextBox1" runat="server" Text="Type here" />

20

ASP.NET

Build- <form> build- . : __BuildControl,


. controlN.

?
Click. , ,
TextBox Button,
:
__ctrl.Click += new EventHandler(this.ReverseText);

, <%# %>,
, DataBinding:
__ctrl.DataBinding += new EventHandler(__DataBindingToday);


. :
public void __DataBindingToday(object sender, EventArgs e)
{
Label target = (Label) sender;
target.Text = Convert.ToString(DateTime.Now, CultureInfo.CurrentCulture);
}

ASP.NET 2.0 $- ,
.
5.

, ,
.aspx-, .
,
,
Windows Forms? , .
, ,
Bin ,
, .
, , , ,
ASP.NET <head>
<form>. , . ,
, , . , ASP.NET 2.0
, , . (
6
Programming Microsoft ASP.NET 2.0: Core Reference).
-
Web-, -

ASP.NET

21

, .
, (, .ascx,
12), . , ,
, . Visual
Studio 2005 Web-, global.asax
, web.config.
, . ,
Build\Publish. ,
,
. Visual Studio, MSBuild.
Fixed Names,
.
, , , ,
, - .


ASP.NET
, , ,
. ASP.NET 1.0 . : -,
, , -,
Web- .
: (in-place) (deploy
precompilation). ,
, .
,
( ). , ,
, Windows:
. ,

,
, .


. FTP,
xcopy . ,
.
,

. ,
.

22

ASP.NET

, IIS , , .NET.
, .
.
,
, ,
, . , .
, , .
aspnet_compiler

,
, .
aspnet_compiler.exe,
.
%WINDOWS%\Microsoft.NET\Framework\[]

, , /proaspnet20
:
aspnet_compiler v /proaspnet20

. 1-6 aspnet_compiler,
.
. 1-6. aspnet_compiler

-m

IIS- .
-v -p
-v
.
-p, .
, ,
, , W3SVC/1/Root
-p
.
, IIS.
-p -v
-d
,

-c
,

-keyfile
key-
-keycontainer key-
-aptca
,
(partially trusted)
-delaysign
,

ASP.NET

23

. 1-6. ()

-fixednames

aspnet_compiler ( ),
, . . . 1-9
.

. 1-9. aspnet_compiler

,
,
, .
, aspnet_compiler localhost , .


,
. ASP.NET
, ,
( , ).
, , , .
CAB, ZIP MSI,
. , ,
.
, ,
.

24

ASP.NET

aspnet_compiler. , ,
. 1-7.
. 1-7. aspnet_compiler

-u

-f

, , ,

targetDir

,
. ,

, ,
,
. :
aspnet_compiler -v /ProAspNet20 c:\Deliverable

. 1-10.

. 1-10.

, precompiledapp.config :
<precompiledApp version="2" updatable="false"/>

, ASP.NET
, . ,
web.config web.sitemap . , , , web.config web.sitemap,
.
, .
, . -, .aspx .

ASP.NET

25

, ,
, .
ASP.NET -, . ,
.
, .
,
.
Bin ,
. , ,
App_Web_xxx .
, ,
,
. , ,
. ;
web.config web.sitemap
.

-u,
, .
.aspx : CodeFile
Inherits. .

ASP.NET . ,
, . .
, , ,
.
,
.

.
ASP.NET 2.0
ASP.NET 1.1,
.aspx , (
) .

. ClientBuildManager API ASP.NET.


aspnet_compiler
. ,
, PrecompileApplication.

. ,
, .
ClientBuildManagerParameter params = new ClientBuildManagerParameter();
params.PrecompilationFlags = PrecompilationFlags.Updatable |

26

ASP.NET

PrecompilationFlags.OverwriteTarget;
ClientBuildManager cbm;
cbm = new ClientBuildManager(vdir, sourceDir, targetDir, params);
cbm.PrecompileApplication();

PrecompilationFlags :
public enum PrecompilationFlags {
AllowPartiallyTrustedCallers = 0x20,
Clean = 8,
CodeAnalysis = 0x10,
Default = 0,
DelaySign = 0x40,
FixedNames = 0x80,
ForceDebug = 4,
OverwriteTarget = 2,
Updatable = 1
}

System.Web.Compilation.

ASP.NET
ASP.NET -
, (build providers).
ClientBuildManager BuildManager.
ClientBuildManager ,
Visual Studio, ASP.NET,
. BuildManager ASP.NET.
, . , ,
.
C# Visual Basic.NET ,
, .
, ASP.NET,
.
, ,
ASP.NET. , ,
.
ASP.NET
.


ASP.NET , web.config. <compilation>,
, . 1-8.
,
<compilation>. Debug ,
retail debug.
false. DefaultLanguage ,
. Visual Basic .NET. Strict Explicit
Visual Basic. ,

ASP.NET

27

TempDirectory , .
. 1-8. <compilation>

<assemblies>

,
ASP.NET

<codeSubDirectories> , , . App_Code
<buildProviders>


( )

<expressionBuilders>


( 5)

<assemblies> , .
:
<assemblies>
<add assembly="mscorlib" />
<add assembly="System, ..." />
<add assembly="System.Configuration, ..." />
<add assembly="System.Web, ..." />
<add assembly="System.Data, ..." />
<add assembly="System.Web.Services, ..." />
<add assembly="System.Xml, ..." />
<add assembly="System.Drawing, ..." />
<add assembly="System.EnterpriseServices, ..." />
<add assembly="System.Web.Mobile, ..." />
<add assembly="*" />
</assemblies>

<add> ,
, /Bin. web.config, , , <clear>,
<remove> <add>,
, .

ASP.NET
; ,
. ,
, .
, .
Web-, ,
.aspx .ascx. , App_Code,
. , , .

28

ASP.NET

,
.
, <compilation>
(. 1-9).
. 1-9.

batch

.
true
batchTimeout
.
,

. ASP.NET 2.0
, batchTimeout
maxBatchSize

maxBatchGeneratedFileSize
( )

, <compilation> , ( ), ,
. , ,

, ,
.

ASP.NET 2.0 (no-compile) , . CompilationMode @Page Never.


HTML-?
, . Web-,
. ,
ASP.NET, .
.
<script> .
, ,
$-. 5, $-,
, .
. , Microsoft SharePoint Services,
,
- .
,
. , Windows DLL,
.
. ,

ASP.NET

29

, . , ,
AppDomain, ,
.
, , .
, .
, ASP.NET HTML- ,
.
ASP.NET? ,
. ,

. , ,
, .

ASP.NET
ASP.NET ,
. 1-10.
. 1-10. ASP.NET

Bin

.dll

App_Browsers

.browser


, ASP.NET

App_Code

.cs, .vb, .xsd,

,
. ASP.NET


.

App_Data

.mdb, .mdf, .xml

Microsoft Office Access SQL Express,


XML-

App_GlobalResources .resx

App_LocalResources

.resx

App_Themes

.skin, .css, .xsl,

,
ASP.NET

App_WebReferences

.wsdl

WSDL-,
-, ,
Web-

Bin

Bin , , , .
, .dll, ,
. ,

30

ASP.NET

ambiguous reference. ,
(
), ASP.NET ,
, . ,
- ,
. , , Bin ,
<assemblies> :
<add assembly="*" />

, . 1-10, Bin
ASP.NET 1.x. .
App_Browsers

.browser.
, . ASP.NET
.browser Config\Browsers . .
App_Browsers, ,
. .browser , ASP.NET
.
,
.browser. , ,
.
.browser,
, ASP.NET, ,
. .browser
, , ( , browserID
, ASP.NET):
<browsers>
<browser id="browserID">
<controlAdapters>
<adapter controlType="Samples.CustomControl"
adapterType="Samples.Adapters.CustomControlAdapter" />
</controlAdapters>
</browser>
</browsers>

ASP.NET, CustomControl CustomControlAdapter.


App_Code

App_Code, Web-, ,
. ,

. , App_Code, ASP.NET (custom)
, , , , , HTTP . .

ASP.NET

31

, App_Code
, .
,
. ,
, , App_Code.

, App_Code,
. ,
,
web.config :
<compilation>
<codeSubDirectories>
<add directoryName="VBFolder" />
</codeSubDirectories>
</compilation>

web.config,
App_Code
. ,
, , , C#, App_Code,
Visual Basic.NET VBFolder.
, <codeSubDirectories>, ,
.
App_Code App_Code_xxx.dll,
xxx . , ,
App_SubCode_xxx_yyy.dll, xxx , yyy . <codeSubDirectories>
web.config, .
assemblyinfo.cs
( assemblyinfo.vb, , ) App_Code .
.snk, ,
.
, . Strong Name (sn.exe), SDK
, .NET Framework. .snk.
assemblyinfo.cs, :

[assembly: AssemblyKeyFileAttribute(@"__.snk")]
, Visual Basic.NET ,
Visual Studio, C# ,
. , , .

,
AppDomain , .
App_Code . ,
XSD,

32

ASP.NET

. App_Code,
DataSet, . ASP.NET 1.x Visual Studio .NET, ,
, xsd.exe.
web.config (, HTTP),
, .
, App_Code?
.
, ASP.NET
, , App_Code.

App_Data

App_Data .
Microsoft Access Microsoft SQL Server Express
XML, , .
ASP.NET. App_Data , ASP.NET .
ASP.NET
App_Data. ASP.NET,

.

App_GlobalResources

ASP.NET, ,
,
. , .
, , , , .
,
, .
ASP.NET , ,
,
.
ASP.NET 1.x .
XML- ( .resx) .resources.
.NET,
(satellite assemblies). XML-
.resources Resource File Generator (resgen.exe).
: _..resources.
. ,
ProAspNet20:
resgen.exe ProAspNet20.resx ProAspNet20.it.resources

.resources , .

ASP.NET

33

Assembly Linker (al.exe).


( ) :
al /out:ProAspNet20.resources.dll /c:it /embed:ProAspNet20.it.resources

.
, .
, ASP.NET 2.0 .
, ,
App_GlobalResources.
.resx . .resx , ASP.NET . ,
: resources.resx, resources.it.resx resources.fr.resx , , . ,
, .
, App_GlobalResources, , .
ASP. NET 2.0 , ASP.NET 1.x:
<asp:Label Runat="server" Text="<%$ Resources:_resx, _ %>" />

, $- Resources. ( $- 5.)
: .resx
. :
HttpContext.GetGlobalResourceObject(_resx, _)

, , $-. ,
$- Resources GetGlobalResourceObject.
App_LocalResources

App_LocalResources ,
ASP.NET. .resx,
, . , , test.aspx, App_LocalResources , ,
: test.aspx.resx, test.aspx.it.resx, test.aspx.fr.resx. ,
, , test.aspx.
?
:
HttpContext.GetLocalResourceObject("/ProAspNet20/ResPage.aspx", "PageResource1.Title")

, .
meta:ResourceKey. :
<asp:Button Runat="server" meta:resourcekey="ButtonResource1" />


. .resx .,
, .
( Text),
ButtonResource1.Text.

34

ASP.NET

, , . , ,
, .resx,
. ASP.NET.
App_Themes

App_Themes ASP.NET .
. , , , .
App_Themes , . ,
, :
%WINDOWS%\Microsoft.NET\Framework\[]\ASP.NETClientFiles\Themes

. ,
, .
App_WebReferences

Visual Studio .NET 2003 ASP.NET, Web, .wsdl, Add Web


Reference. WSDL- (Web Service Description Language
Web-) ,
. , ASP.NET
, ,
. Web- -.
Visual Studio
wsdl.exe. - , Web- Web-, .
, Web-.
,
Visual Studio, -.
.wsdl-
ASP.NET ? App_WebReferences!
ASP.NET .wsdl, Web-, -,
Web- . App_WebReferences
.
-, .wsdl . ,
samples.wsdl, ProAspNet20, - ProAspNet20.Samples.
, App_WebReferences.xxx.dll, xxx .


ASP.NET 1.x :
ASP.NET, , Web- ASP.NET,
HTTP. ASP.NET 2.0
, .

ASP.NET

35


,
ASP.NET .
. ,
, .aspx,
aspx- ,
ASP.NET.
.
ASP.NET . , ASP.NET 2.0
, (.cs, .vb), (.resx), Web- (.wsdl), (.xsd), . .
,
.
,
, , ASP.NET.

,
ASP.NET .
-,
.
;
,
, .
,

.
.
<compilation>
<buildProviders>
<add extension=".aspx"
type="System.Web.Compilation.PageBuildProvider" />
<add extension=".ascx"
type="System.Web.Compilation.UserControlBuildProvider" />
<add extension=".master"
type="System.Web.Compilation.MasterPageBuildProvider" />
<add extension=".asmx"
type="System.Web.Compilation.WebServiceBuildProvider" />
<add extension=".ashx"
type="System.Web.Compilation.WebHandlerBuildProvider" />
<add extension=".resx"
type="System.Web.Compilation.ResXBuildProvider" />
<add extension=".resources"
type="System.Web.Compilation.ResourcesBuildProvider" />
<add extension=".wsdl"
type="System.Web.Compilation.WsdlBuildProvider" />
<add extension=".xsd"
type="System.Web.Compilation.XsdBuildProvider" />
<add extension=".js"
type="System.Web.Compilation.ForceCopyBuildProvider" />
</buildProviders>
</compilation>

36

ASP.NET

,
System.Web.Compilation system.web. BuildProvider.
( .) . 1-11
ASP.NET.

. 1-11. ASP.NET

- ,
(, Visual Studio 2005 ), API ClientBuildManager, ASP.NET,
(build manager). , ,
(build provider), . - , (assembly builder), .
ASP.NET, , .
, , ,
,
ASP.NET. ;
.


,
, .
.
, ,
:
( ). , .
. ,
.NET (, .cs .vb), , . ,
, .
.
: .js ,
.
.

ASP.NET

37

ForceCopyBuildProvider

.js, . .js
.NET JScript.
JavaScript .
.js , ,
. , .js ForceCopyBuildProvider, .js
Web- Copy Web Site Visual Studio 2005.
IgnoreFileBuildProvider

ForceCopyBuildProvider , IgnoreFileBuildProvider,
, .
,
,
Microsoft Office Word, Microsoft Office Visio . .
, web.config,
.doc.
<compilation>
<buildProviders>
<add extension=".doc"
type="System.Web.Compilation.IgnoreFileBuildProvider" />
</buildProviders>
</compilation>

IgnoreFileBuildProvider Web .


, , Visual Studio 2005 ASP.NET.
, ASP.NET .
,
. , .
,
.
.
,
IntelliSense Visual Studio 2005.
, Visual Studio 2005
.aspx, IntelliSense? ASP.NET 1.x Visual Studio .NET 2003
, ,
, . ASP.NET 2.0 , ,
. IntelliSense
, ? : Visual Studio 2005
, . Visual
Studio 2005,
IntelliSense.

38

ASP.NET

OrmBuildProvider
, Web- . : DataSet ADO.NET
-? DataSet
: , , ... , -,
, .
, .
.NET Framework , - ,
. .NET Framework 2.0 (generic),
.
:
public class CustomerCollection : Collection<Customer> {
}

, , Customer,
. ,
Web-
, ASP.NET ! ,
.xsd .resx. XML-,
, ASP.NET
.
( , )
, .
, . ,
API CodeDOM ( ).
BuildProvider , .
OrmBuildProvider, ,
.map, XML- , ,
, -.
.map
,
,
. , , , DataSet , .
,
.
, .map
OrmBuildProvide.
DataSet,
, . DataSet ,
:
. , DataSet .
: http://msdn.microsoft.
com/msdnmag/issues/05/08/CuttingEdge.

ASP.NET

39

, .map , ,
XML. XML-:
<mappings namespace="ProAspNet20.Components">
<mapping connectionString="SERVER=.;DATABASE=northwind;UID=...;"
tableName="Customers"
className="Customer"
selectCommand="SELECT companyname AS CompanyName,
contactname AS Contact,
country As Country FROM customers"
allowPartialClass="true"
allowCollectionClass="true"
collectionClassName="CustomerCollection">
</mapping>
</mappings>

<mappings> ,
<mapping>,
.
, <mappings>.
. 1-11.
. 1-11. <mappings>

allowCollectionClass , -
allowPartialClass

, , ,

className

collectionClassName ,
connectionString

selectCommand

, ; ,

tableName

, ,

,
SELECT.
.NET, , . . , , ,
. - - .
.


Employee ,
, SELECT.
, AS.

EmployeeCollection Employee.

.map App_Code,
, . , .

40

ASP.NET

, .map. ,
Data Mapper
(DM),
. DM ,
. ,
.
.

, BuildProvider.
GenerateCode. :
public class OrmBuildProvider : BuildProvider
{
public OrmBuildProvider() {
}
public override void GenerateCode(AssemblyBuilder ab)
{
//
string fileName = base.VirtualPath;
// ,
CodeCompileUnit code = BuildCodeTree(fileName);
// ,
ab.AddCodeCompileUnit(this, code);
}
}

GenerateCode
.map .

CodeDOM. . , GenerateCode :
BuildCodeTree,
. :
private CodeCompileUnit BuildCodeTree(string fileName)
{
OrmDescriptor desc = ExtractInfo(fileName);
return GenerateCodeDomTree(desc);
}

: .map . , ,
OrmDescriptor, :
class OrmDescriptor
{
public string Namespace;
public OrmTableDescriptor[] Descriptors;
}
class OrmTableDescriptor
{
public string ConnectionString;

ASP.NET

public
public
public
public
public
public

41

string TableName;
string ClassName;
string SelectCommand;
bool IsPartial;
bool AllowCollectionClass;
string CollectionClassName;

ExtractInfo API XMLDOM (XML Document


Object Model XML-) .map OrmDescriptor.
OrmDescriptor ExtractInfo(string fileName)
{
//
XmlDocument doc = new XmlDocument();
using (Stream file = VirtualPathProvider.OpenFile(fileName))
{
// ,
//
//
doc.Load(file);
}
// namespace
XmlNode root = doc.DocumentElement;
string ns = root.Attributes["namespace"].Value;
// <mapping>
XmlNodeList mappings = doc.SelectNodes("mappings/mapping");
OrmTableDescriptor[] descriptors;
descriptors = new OrmTableDescriptor[mappings.Count];
for(int i=0; i<descriptors.Length; i++)
{
XmlNode mapping = mappings[i];
OrmTableDescriptor t = new OrmTableDescriptor();
descriptors[i] = t;
t.ConnectionString = mapping.Attributes["connectionString"].Value;
t.ClassName = mapping.Attributes["className"].Value;
t.TableName = mapping.Attributes["tableName"].Value;
t.SelectCommand = mapping.Attributes["selectCommand"].Value;
bool isPartial = false;
Boolean.TryParse(
mapping.Attributes["allowPartialClass"].Value,out isPartial);
t.IsPartial = isPartial;
bool allowCollection = false;
Boolean.TryParse(
mapping.Attributes["allowCollectionClass"].Value,
out allowCollection))
t.AllowCollectionClass = allowCollection;
if (allowCollection)
{
string coll = mapping.Attributes["collectionClassName"].Value;
t.CollectionClassName = coll;
}
}

42

ASP.NET

//
OrmDescriptor desc = new OrmDescriptor();
desc.Namespace = ns;
desc.Descriptors = descriptors;
return desc;
}

.
,
. . CodeDOM. ,
API.
.
CodeDOM

CodeDOM Code Document Object Model , . API .NET


Framework, . API CodeDOM,
ASP.NET, System.CodeDom. ,
Visual Basic.NET C#.
API CodeDOM ,
, CodeDOM
. System.CodeDom
.
, . .NET Framework 2.0 API CodeDOM
,
.
GenerateCodeDomTree CodeDOM
.
( ), -. , -.
, :
CodeCompileUnit GenerateCodeDomTree(OrmDescriptor desc)
{
CodeCompileUnit code = new CodeCompileUnit();
//
CodeNamespaceImport import;
import = new CodeNamespaceImport("System.Collections.Generic");
//
CodeNamespace ns = new CodeNamespace(desc.Namespace);
ns.Imports.Add(import);
code.Namespaces.Add(ns);
//
for (int i = 0; i < desc.Descriptors.Length; i++)
{
//
OrmTableDescriptor t = desc.Descriptors[i];

ASP.NET

// ,
CodeTypeDeclaration cls = new CodeTypeDeclaration(t.ClassName);
cls.IsPartial = t.IsPartial;
ns.Types.Add(cls);
//
SqlDataAdapter adapter = new SqlDataAdapter(
t.SelectCommand, t.ConnectionString);
DataTable dt = new DataTable();
adapter.FillSchema(dt, SchemaType.Mapped);
for(int j=0; j<dt.Columns.Count; j++)
{
DataColumn column = dt.Columns[j];
string colName = column.ColumnName;
Type colType = column.DataType;
string fieldName = "_" + colName.ToLower();
//
//
//
// private-
CodeMemberField fld = new CodeMemberField(colType, fieldName);
cls.Members.Add(fld);
// get/set
CodeMemberProperty prop = new CodeMemberProperty();
prop.Name = column.ColumnName;
prop.Type = new CodeTypeReference(column.DataType);
prop.Attributes = MemberAttributes.Public;
// codeDOM- private-
CodeFieldReferenceExpression fldRef;
fldRef = new CodeFieldReferenceExpression();
fldRef.TargetObject = new CodeThisReferenceExpression();
fldRef.FieldName = fieldName;
// Get
CodeMethodReturnStatement ret;
ret = new CodeMethodReturnStatement(fldRef);
prop.GetStatements.Add(ret);
// Set
CodeAssignStatement assign = new CodeAssignStatement();
assign.Left = fldRef;
assign.Right = new CodePropertySetValueReferenceExpression();
prop.SetStatements.Add(assign);
cls.Members.Add(prop);
}
// , -
if (t.AllowCollectionClass)
{
string collName = t.CollectionClassName;
CodeTypeDeclaration coll = new CodeTypeDeclaration(collName);
CodeTypeReference type = new CodeTypeReference("List",
CodeTypeReferenceOptions.GenericTypeParameter);

43

44

ASP.NET

type.TypeArguments.Add(t.ClassName);
coll.BaseTypes.Add(type);
ns.Types.Add(coll);
}
}
}

-
. - Customer,
:
public class CustomerCollection : List<Customer> {}

CodeTypeDeclaration -.
CodeDOM- CodeTypeReference.
List<T>. , , , T , Customer. TypeArguments.
, List<Customer>
.
.map App_Code , .
-:
List<T> Collection<T>?
IList ICollection. : List<T>
, Collection<T> .

.map , web.config, <buildProviders> :


<buildProviders>
<add extension=".map"
type="Samples.OrmBuildProvider,OrmBuildProvider" />
</buildProviders>

extension , type
. , , .map, App_Code.
, .
, AppDomain.
Sources_App_Code ,
.
. 1-12 C#,
- .

, <mappings>. . ,

.
public CustomerCollection GetCustomers()
{
SqlDataAdapter adapter = new SqlDataAdapter(

ASP.NET

45

"SELECT companyname, contactname, country FROM customers",


"SERVER=...;DATABASE=...;UID=...");
DataTable dt = new DataTable();
adapter.Fill(dt);
CustomerCollection coll = new CustomerCollection();
foreach (DataRow row in dt.Rows) {
Customer c = new Customer();
c.CompanyName = (string) row[0];
c.Contact = (string) row[1];
c.Country = (string) row[2];
coll.Add(c);
}
return coll;
}

-,
.
Customer ToString:
public partial class Customer
{
public override string ToString()
{
return String.Format("{0} ({1})", this.CompanyName, this.Country);
}
}

,
Customer, , App_Code
.map.
TextWriter

CodeDOM,
. . GenerateCode
:
public override void GenerateCode(AssemblyBuilder ab)
{
TextWriter tw = ab.CreateCodeFile(this);
if (tw == null)
return;
try {
//
string code = ParseFileAndCreateCode(base.VirtualPath);
tw.Write(code);
}
catch {
throw new ApplicationException("Can't build class");
}
finally {
tw.Close();
}
}
string ParseFileAndCreateCode(string fileName) {

46

ASP.NET

StringBuilder sb = new StringBuilder();


sb.Append("public class Customer {");
return sb.ToString();
}

, , . API CodeDOM
, , API, ; ,
.
: CodeDOM
, -
, (
). , ,
.
,
ASP.NET 2.0. Windows Forms . MSBuild ,
, , .
MSBuild :
http://msdn.microsoft.com/msdnmag/issues/06/02/CuttingEdge.


ASP.NET 2.0 ASP.NET
.aspx, . .aspx --.
ASP.NET 2.0 , .
Web- .
SharePoint
ASP.NET. , , , ASP.NET
. ( , - ?
SharePoint , ASP.NET 2.0.)

(virtual path provider, VPP) , VirtualPathProvider Web.


,
. ,
, ASP.NET. ASP.NET, , , , ,
, Web-,
HTML- .
VPP ,
global.asax web.config, Bin, App_Code, App_Data, App_GlobalResources, App_LocalResources. . 1-12
VirtualPathProvider, VPP.

ASP.NET

47

. 1-12. VirtualPathProvider

CombineVirtualPaths

DirectoryExists

FileExists

GetCacheDependency

GetCacheKey

GetDirectory

VirtualDirectory ,

GetFile

VirtualFile ,

GetFileHash

Previous

;
VPP
VPP:

VPP GetFile
GetDirectory, Previous. :
public override VirtualFile GetFile(string virtualPath)
{
if (IsPathVirtual(virtualPath))
return new YourVirtualFile(virtualPath, this);
else
return Previous.GetFile(virtualPath);
}

IsPathVirtual , , VPP
. ,
VPP ASP.NET. Previous
.
private bool IsPathVirtual(string virtualPath)
{
// ,
//
}

MSDN.
VirtualFile

.
, ASP.NET , VPP ,
URL. , VPP
ASP.NET . VPP
, VirtualFile. . 1-13
VirtualFile, .

48

ASP.NET

. 1-13. VirtualFile

IsDirectory

, ,

Name

VirtualPath

Open

, , Open,
, .
Open .
MSDN.

web.config.
Application_Start,
AppInitialize - , App_Code.
, App_Code, VPP:
public static class AppStart
{
public static void AppInitialize()
{
// VPP
MyPathProvider vpp = new MyPathProvider();
HostingEnvironment.RegisterVirtualPathProvider(vpp);
}
}

, , ,
AppInitialize . , App_Code, ,
.
! , ,
.
(, web.config)
.
, VPP, ,
Page_Load. VPP , ,
. VPP
. VPP , , , -, VPP, -,
, VPP. , .

ASP.NET

49

ASP.NET ,
.aspx, . ,
. , ,
, .
,
, .
ASP.NET 2.0 , , . ,
, .
, .
, ASP.NET, ,
, XSD.
,
. IntelliSense Visual Studio 2005.
,
IDE Visual Studio.

.aspx, ASP.NET, ,
IHttpHandler. ,
.

: .aspx, ,
. , ASP.NET 1.x ,
.

,
, . , ,
API CodeDOM. ,
.

ASP.NET 2.0 ,
, , WSDL-.

ASP.NET 2.0 :
. ,
, ,
, .aspx,
.

HTTP

, ASP.NET, HTTP Microsoft ASP.NET.


HTTP Web-
Microsoft .NET. ASP.NET HTTP HTTP,
HTML- .
HTTP ,
. , IHttpHandler. ProcessRequest
, . , Page ,
ASP.NET ,
IHttpHandler, ProcessRequest
, , Init,
Load, PreRender .
ASP.NET HTTP-
HTTP. , HTTP (HTTP
handler factory),
, . , PageHandlerFactory
.aspx , . HTTP
URL. ,

, , .
machine.config web.config, ,
.
HTTP , IHttpModule . ,
. , HttpApplication (
), , HTTP. ,
SessionStateModule ASP.NET,
, . SessionStateModule
End Start,
Session_End Session_Start.
HTTP , ISAPI , . ASP.NET .
Web-, -

HTTP

51

Internet Information Server (IIS), ,


HTTP.
, IIS , ISAPI (Internet Server Application Programming Interface
). ISAPI (DLL) Microsoft Win32, . IIS 7.0
ASP.NET,
HTTP. .

API IIS
Web- , , HTTP, FTP, NNTP SMTP.
IIS Web-,
Windows.
Web- API . CGI (Common
Gateway Interface ). CGI
, Web- .
CGI Web- ,
HTTP- , CGI-. ,
Web- . IIS CGI, ,
. Web-
. IIS
ISAPI.

ISAPI
ISAPI Web-
. IIS ISAPI, DLL Win32,
DLL. ISAPI
IIS , , . ,
, Web-,

. , IIS 4.0,
. IIS 6.0 ,
: , .
, ( )
Web- (inetinfo.exe). ,
(dllhost.exe). , , , (dllhost.exe).
IIS 6.0 Web- ,
,
.

52

ASP.NET

, w3wp.exe.
. 2-1 IIS 6.0 Microsoft Windows Server 2003,
Web-.

. 2-1. Web- IIS 6.0


Microsoft Windows Server 2003

ASP.NET ISAPI

ISAPI , . , ISAPI DLL Win32. ,


HTML-,
. C C++; , ,
.
Microsoft ISAPI MFC (Microsoft Foundation
Classes), , .
MFC ,
Web-, , , DLL
( ).
Active Server Pages (ASP), ASP.NET, ISAPI. DLL ISAPI
( asp.dll), HTTP .asp. DLL ,
.
IIS 6.0 ,
IIS, ,
ISAPI. ASP ASP.NET. ASP.NET IIS, .
IIS ASP.NET ISAPI- aspnet_isapi.dll.
.aspx IIS
aspnet_isapi.dll, , ,
ASP.NET CLR.

HTTP

53

, ,
DLL Win32 . IIS 7.0 .
ISAPI

ISAPI URL, DLL,


, :
http://www.contoso.com/apps/hello.dll

DLL : GetExtensionVersion HttpExtensionProc. GetExtensionVersion


ISAPI. , ,
.
, true.
, false, Web- DLL
.
ISAPI HttpExtensionProc.
HTTP-, (,
),
.
ISAPI , , ,
ASP ASP.NET, ,
.

ISAPI
ISAPI ISAPI.
ISAPI

ISAPI CGI, , IIS. ,


ISAPI DLL, , IIS
-. DLL,
, .
ISAPI ,
. ISAPI
ASP ASP.NET: HTTP-
.
ISAPI ,
. DLL
Web-, .
DLL , . , , ,
Web-, IIS.
ISAPI

ISAPI ,
, .
, . ,
.
ISAPI , ,
HTTP, . IIS

54

ASP.NET

, . , , . .
IIS 5.0 Web-,
Web-.
ISAPI ,
, , . , ,
ISAPI .
:
, .

IIS 7.0
ASP.NET 1.0 , , IIS. ASP.NET 1.1 IIS 6.0
Web- ,
. ASP.NET 2.0 ,
IIS 7.0 .

IIS 7.0 ASP.NET


IIS. HTTP, ,
.
IIS , .
web.config ,
IIS.
, , ASP.NET
Web-. , , ASP.NET IIS 7.0
Web-. , , Forms
, ASP.NET.
ISAPI

,
IIS, , DLL C C++, MFC ,
, ActiveX Template Library (ATL). HTTP ASP.NET,
, , IIS
ASP.NET.
IIS 7.0 HTTP
, .NET,
Web-. , HTTP
, ASP.NET, , . , ,
ISAPI - ,
.

HTTP

55

HTTP
ASP.NET HTTP.
ASP.NET, Web- .NET .NET Remoting , IIS
-. Web- (trace.axd)
, .config .asax. ASP.NET 2.0
(webresource.axd),
. Web-
9.
, ASP.NET
,
HTTP. , , .
, .
, ,
, , .
HTTP , .
,
.
.
, 5. ,
.

ISAPI IIS.
HTTP web.config,
, Web-
HTTP. , ISAPI,
URL. , IIS 7.0
web.config, -
URL. , ,
.

IHttpHandler
HTTP? .
IHttpHandler.
HTTP , . ,
IHttpHandler, IHttpAsyncHandler. .
IHttpHandler , HTTP-.
IHttpHandler

IHttpHandler : ProcessRequest IsReusab le


(. 2-1). ProcessRequest , IsReusable Boolean.

56

ASP.NET

. 2-1. IHttpHandler

IsReusable

Boolean, ,

HTTP

ProcessRequest

HTTP-

IsReusable Page false, ,



HTTP. false ,
.
, ,
, IsReusable true,
. ,
.
ProcessRequest :
void ProcessRequest(HttpContext context);

.
.
HTTP

, HTTP , IHttpHandler.
ProcessRequest, :
using System.Web;
namespace ProAspNet20.Advanced.CS.Components
{
public class SimpleHandler : IHttpHandler
{
// ProcessRequest
public void ProcessRequest(HttpContext context)
{
context.Response.Write("<H1>Hello, I'm an HTTP handler</H1>");
}
// IsReusable
public bool IsReusable
{
get { return true; }
}
}
}

.
, HTTP,
URL. URL , IIS
ASP.NET .
HTTP Web- web.config:
<configuration>
<system.web>

HTTP

57

<httpHandlers>
<add verb="*" path="myHandler.aspx"
type="ProAspNet20.Advanced.CS.Components.SimpleHandler" />
</httpHandlers>
</system.web>
</configuration>

<httpHandlers> , . , SimpleHandler
myHandler.aspx.
, URL myHandler.aspx
, , . type , .
[,]. ,
App_Code .
machine.config, SimpleHandler Web-,
.

URL myHandler.aspx, ,
. 2-2.

. 2-2. HTTP,
myHandler.aspx


HTTP , - ; ,
. HTTP.

HTTP
HTTP IIS.

.
,
.
HTTP .sqlx.
SQLX XML-, SQL-.
,
, . . 2-3 .

58

ASP.NET

. 2-3. HTTP

IHttpHandler.
!
XML- ,
hello world. Microsoft SQL Server Web.

SQL-

HTTP ,
.sqlx. , , , SQL-
.
SQL-. .sqlx .
<queries>
<query connString="DATABASE=northwind;SERVER=localhost;UID=...;">
SELECT firstname, lastname, country FROM employees
</query>
<query connString="DATABASE=northwind;SERVER=localhost;UID=...;">
SELECT companyname FROM customers WHERE country='Italy'
</query>
</queries>

XML- <query>. ,
, .
ProcessRequest ,
HTML-.
class SqlxData
{
public string ConnectionString;
public string QueryText;
}
public class QueryHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)

HTTP

59

{
// SQLX
SqlxData[] data = ParseFile(context);
// HTML-
StringCollection htmlColl = CreateOutput(data);
//
context.Response.Write("<html><head><title>");
context.Response.Write("QueryHandler Output");
context.Response.Write("</title></head><body>");
foreach (string html in htmlColl)
{
context.Response.Write(html);
context.Response.Write("<hr />");
}
context.Response.Write("</body></html>");
}
// IsReusable
public bool IsReusable
{
get { return false; }
}
}

ParseFile .sqlx
SqlxData.
private SqlxData[] ParseFile(HttpContext context)
{
XmlDocument doc = new XmlDocument();
string file = context.Request.Path;
using (Stream file = VirtualPathProvider.OpenFile(file)) {
doc.Load(file);
}
// <mapping>
XmlNodeList mappings = doc.SelectNodes("queries/query");
SqlxData[] descriptors = new SqlxData[mappings.Count];
for (int i=0; i < descriptors.Length; i++)
{
XmlNode mapping = mappings[i];
SqlxData query = new SqlxData();
descriptors[i] = query;
try {
query.ConnectionString =
mapping.Attributes["connString"].Value;
query.QueryText = mapping.InnerText;
}
catch {
context.Response.Write("Error parsing the input file.");
}
}
return descriptors;
}

60

ASP.NET

SqlxData
SQL-. CreateOutput, SQL- .
private StringCollection CreateOutput(SqlxData[] descriptors)
{
StringCollection coll = new StringCollection();
foreach (SqlxData data in descriptors)
{
//
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(data.QueryText,
data.ConnectionString);
adapter.Fill(dt);
//
DataGrid grid = new DataGrid();
grid.DataSource = dt;
grid.DataBind();
// HTML
string html = Utils.RenderControlAsString(grid);
coll.Add(html);
}
return coll;
}

DataGrid. ASP.NET , , HTML.


HTTP-, .aspx.
, .sqlx, . , HTML- Web-
RenderControl HtmlTextWriter.
RenderControlAsString:
static class Utils
{
public static string RenderControlAsString(Control ctl)
{
StringWriter sw = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
ctl.RenderControl(writer);
return sw.ToString();
}
}
HTTP, ,
IRequiresSessionState. INamingContainer,
-, . , IRequiresSessionState , HTTP
.
, IReadOnlySessionState.

HTTP , , Bin .

HTTP

61

,
(GAC).
,
Web-. .
<system.web>
<httpHandlers>
<add verb="*"
path="*.sqlx"
type= "ProAspNet20.CS.Components.QueryHandler,ProAspCompLib" />
</httpHandlers>
</system.web>

<httpHandlers>
web.config. : <add>, <remove> <clear>. <add>
HTTP ,
.config. <remove> ,
<clear>
. :
verb, path type; . 2-2.
. 2-2. , HTTP

verb

HTTP, : GET, PUT, POST.


*,

path

URL, ,
, : *.aspx

type

, . ASP.NET DLL
Bin ,

. validate. false, ASP.NET


. ,
, , .
ASP.NET , ,
. ,
.
, HTTP,
, , .
, .sqlx
ASP.NET, IIS !
.sqlx IIS. ISAPI, , IIS
, .
, .sqlx IIS, . 2-4.
IIS Manager
Web Site.
.sqlx
ISAPI aspnet_isapi.dll. .sqlx

62

ASP.NET

ASP.NET . ,
aspnet_isapi.dll ASP.NET, .

. 2-4. .sqlx IIS


! Microsoft Visual Studio 2005
.sqlx Web- .sqlx IIS. IIS! ,
Web- IIS:
, .

Web- - ,
Web, IIS
. aspnet_isapi
HttpForbiddenHandler:
<add verb="*" path="*.xyz" type="System.Web.HttpForbiddenHandler" />

.xyz
.
ASHX

HTTP .ashx.
.ashx. .ashx
@WebHandler.
.ashx:
<%@ WebHandler Language="C#" Class="Namespace.MyHandler" %>

HTTP- URL, .ashx,


MyHandler. .ashx. , ,
@WebHandler:
<%@ WebHandler Language="C#" Class="MyHandler" %>
using System.Web;
public class MyHandler : IHttpHandler {

HTTP

63

public void ProcessRequest (HttpContext context) {


context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}

HTTP .ashx,
. ,
web.config, <httpHandlers>,
.
, . Web-,
. .ashx ASP.NET IIS ,
Web-.
.ashx SimpleHandleFactory.
- HTTP, .
HTTP .
SimpleHandleFactory @WebHandler, HTTP, ,
.
! HTTP ,
, .ashx.
; ,
.ashx, ASP.NET, ,
.

HTTP ASP.NET

HTTP , ,
Web-. HTTP-,
, .
.ashx , HTTP,
, .aspx.
,
( Init Load), ,
, . , HTTP
.aspx, .
, HTTP
,
.
, ASP.NET HTTP. ,
, . HTTP, , , ,
, ,
. , ,

64

ASP.NET

( 9).
Image URL, MIME-. URL ?
, HTTP, .
ASP.NET , HTTP Page. , , , . ,
, ,
,
.
: .ashx ? , .
.ashx , ( ),
. , ,
, .


, HTTP.
.ashx
, IIS.
IIS ,
Web-, ISAPI.
, HTML. , GIF JPG ? IIS
,
.
. .
, ?
IIS
, . 2-5.

. 2-5. IIS-

HTTP

65


.
HTTP

, ,
.
IIS, ISAPI
IIS 7.0. ,
HTTP ASP.NET IIS ASP.NET,
.
, , view.axd. ,
HTTP , .
URL , , :
http://www.contoso.com/images/misc/view.axd

URL,
, view.axd .
ASP.NET .axd ,
. Trace.axd,
, WebResource.axd, . , Trace.axd ,
. URL,
.

HTTP

, .
:
class PictureViewerInfo
{
public PictureViewerInfo() {
DisplayWidth = 200;
ColumnCount = 3;
}
public int DisplayWidth;
public int ColumnCount;
public string FolderName;
}
public class PictureViewerHandler : IHttpHandler
{
// ProcessRequest
public void ProcessRequest(HttpContext context)
{
PictureViewerInfo info = GetFolderInfo(context);
string html = CreateOutput(info);
//
context.Response.Write("<html><head><title>");
context.Response.Write("Picture Web Viewer");

66

ASP.NET

context.Response.Write("</title></head><body>");
context.Response.Write(html);
context.Response.Write("</body></html>");
}
// IsReusable
public bool IsReusable
{
get { return false; }
}
}

: URL view.axd, ( ).
,
URL, , API .NET Framework,
.
private ArrayList GetAllImages(string path)
{
string[] fileTypes = { "*.bmp", "*.gif", "*.jpg", "*.png" };
ArrayList images = new ArrayList();
DirectoryInfo di = new DirectoryInfo(path);
foreach (string ext in fileTypes)
{
FileInfo[] files = di.GetFiles(ext);
if (files.Length > 0)
images.AddRange(files);
}
return images;
}

DirectoryInfo . , GetFiles ,
. FileInfo.
GetFiles ;
,
ArrayList .
,
. ,
.
Image <img>. width
(, 200 ),
. , URL .
, , ,
.
string CreateOutputForFolder(PictureViewerInfo info)
{
ArrayList images = GetAllImages(info.FolderName);
Table t = new Table();

HTTP

67

int index = 0;
bool moreImages = true;
while (moreImages)
{
TableRow row = new TableRow();
t.Rows.Add(row);
for (int i = 0; i < info.ColumnCount; i++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
//
Image img = new Image();
FileInfo fi = (FileInfo)images[index];
img.ImageUrl = fi.Name;
img.Width = Unit.Pixel(info.DisplayWidth);
// ,
//
HtmlAnchor a = new HtmlAnchor();
a.HRef = fi.Name;
a.Controls.Add(img);
cell.Controls.Add(a);
// ,
index++;
moreImages = (index < images.Count);
if (!moreImages)
break;
}
}
}

, , , .
PictureViewerInfo . , HTTP-
, :
PictureViewerInfo info = new PictureViewerInfo();
object p1 = context.Request.Params["Width"];
object p2 = context.Request.Params["Cols"];
if (p1 != null)
Int32.TryParse((string)p1, out info.DisplayWidth);
if (p2 != null)
Int32.TryParse((string)p2, out info.ColumnCount);

. 2-6 .

web.config :
<add verb="*" path="view.axd"
type="ProAspNet20.CS.Components.PictureViewerHandler,ProAspCompLib" />

68

ASP.NET

GAC, machine.config,
.

. 2-6.
( )

HTTP
HTTP ProcessRequest. IHttpHandler IsReusable
.
HTTP ,
.
, IsReusable, -. HttpApplication (
IHttpHandler), ,
true, , Web Forms, ,
false. IsReusable , true,
.

. HTTP ,
HTTP.
HTTP

HTTP- HTTP,
. HTTP , IHttpHandlerFactory
.
SimpleHandlerFactory. , .ashx. ,
, @WebHandler,
.
.NET Framework HTTP
, . - PageHandlerFac-

HTTP

69

tory, .aspx.
, ,
.
- HTTP
. 2-3 IHttpHandlerFactory: GetHandler ReleaseHandler.
. 2-3. IHttpHandlerFactory

GetHandler

HTTP

ReleaseHandler

GetHandler :
public virtual IHttpHandler GetHandler(HttpContext context,
string requestType, string url, string pathTranslated);

requestType , GET POST


HTTP-. URL
. ReleaseHandler
, IHttpHandlerFactory; .
HTTP,
, (GET POST)
:
class MyHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context,
string requestType, String url, String pathTranslated)
{
if(context.Request.RequestType.ToLower() == "get")
return (IHttpHandler) new MyGetHandler();
else if(context.Request.RequestType.ToLower() == "post")
return (IHttpHandler) new MyPostHandler();
return null;
}
public void ReleaseHandler(IHttpHandler handler)
{
//
}
}

, , ,
ASP.NET. , .
, ,
, .

HTTP , IHttpAsyncHandler. BeginProcessRequest. ,

70

ASP.NET

, EndProcessRequest. .NET Framework


HttpApplication.
IHttpAsyncHandler . 2-4.
. 2-4. IHttpAsyncHandler

BeginProcessRequest

HTTP

EndProcessRequest

BeginProcessRequest :
IAsyncResult BeginProcessRequest(
HttpContext context,
AsyncCallback cb, object extraData);

context , . AsyncCallback, , .
, .
AsyncCallback , ,
. ,
. - ,
, . . , AsyncCallback
, , .

AsyncCallback :
public delegate void AsyncCallback(IAsyncResult ar);

IAsyncResult
.
, ,
ASP.NET, .
BeginProcessRequest:
// HttpContext
//
context.AsyncAppHandler = asyncHandler;
// BeginProcessRequest
//
asyncHandler.BeginProcessRequest(context,
OnCompletionCallback, context);

context HttpContext, . HTTP , ,


. extraData BeginProcessRequest
. BeginProcessRequest HttpAsyncResult,
IAsyncResult. AsyncState, extraData HTTP.

HTTP

71

OnCompletionCallback .
. ,
HttpRuntime:
// AsyncCallback
private void OnHandlerCompletion(IAsyncResult ar)
{
// ar HttpAsyncResult
HttpContext context = (HttpContext) ar.AsyncState;
// HTTP
//
IHttpAsyncHandler asyncHandler = context.AsyncAppHandler;
asyncHandler.EndProcessRequest(ar);
//
}

HTTP-
AsyncState IAsyncResult, . ,
HttpAsyncResult
BeginProcessRequest.

EndProcessRequest.
void EndProcessRequest(IAsyncResult result);

EndProcessRequest IAsyncResult,
BeginProcessRequest. HttpApplication EndProcessRequest
,
.

, , ,
Web-.
ASP.NET .
ASP.NET,
.
.
, ,
. BeginProcessRequest .
, ,
.
, . , . . , ,
. ,
IAsyncResult, BeginProcessRequest.

72

ASP.NET

ManualResetEvent, ,
, .
, ,
. ,
, .aspx.
ProcessRequest Page. (,
,
-,
.)
ASP.NET 2.0
, . API 5.

HTTP
, , ASP.NET IIS ISAPI.
ASP.NET . IIS 5.0 6.0
IIS,
ASP.NET . ( IIS 6.0 Web-
.)
ASP.NET HttpApplication, ,
. 1, ,
global.asax, HttpApplication, global.asax . HttpApplication
HTTP.
HttpApplication HTTP
HTTP. HTTP .NET Framework,
IHttpModule. , HTTP,
,
web.config. ASP.NET
HTTP, machine.config.
HTTP - ,
, , . ,
ASP.NET,
.

IHttpModule
IHttpModule : Init Dispose. .
. Dispose
(, !). , Dispose,
.
IHttpModule :
void Init(HttpApplication app);
void Dispose();

HTTP

73

Init HttpApplication, .
. HttpApplication Context,
ASP.NET, Response, Request, Session . .
, HTTP,
. 2-5.
. 2-5. HttpApplication

AcquireRequestState,

, ,
. PostAcquireRequestState
ASP.NET 1.x

PostAcquireRequestState
AuthenticateRequest,
PostAuthenticateRequest
AuthorizeRequest,

.
PostAuthenticateRequest ASP.NET 1.x

PostAuthorizeRequest

.
PostAuthorizeRequest ASP.NET 1.x

BeginRequest

HTTP

Disposed

HttpApplication
Dispose

EndRequest

HTTP

Error

PostMapRequestHandler

HTTP, .
ASP.NET 1.x

PostRequestHandlerExecute HTTP .

PreRequestHandlerExecute

HTTP

PreSendRequestContent

,
ASP.NET

PreSendRequestHeaders

,
ASP.NET HTTP

ReleaseRequestState,

,
. PostReleaseRequestState
ASP.NET 1.x

PostReleaseRequestState
ResolveRequestCache,
PostResolveRequestCache
UpdateRequestCache,
PostUpdateRequestCache

ASP.NET . PostResolveRequestCache
ASP.NET 1.x
ASP.NET

. PostUpdateRequestCache
ASP.NET 1.x

HttpApplication, HTTP
Init.

HTTP
Marker,

74

ASP.NET

. , .
using System;
using System.Web;
namespace ProAspNet20.CS.Components
{
public class MarkerModule : IHttpModule
{
public void Init(HttpApplication app)
{
//
}
public void Dispose()
{
//
}
}
}

Init HttpApplication .
.
Dispose, , , . HTTP
.

Marker
: BeginRequest EndRequest. ,
HttpApplication BeginRequest. EndRequest, , . ,
,
HTTP , Page.
Init Dispose
.
public void Init(HttpApplication app)
{
//
app.BeginRequest += new EventHandler(OnBeginRequest);
app.EndRequest += new EventHandler(OnEndRequest);
}
public void Dispose()
{
}

BeginRequest EndRequest . HttpApplication HTTP. Response,


.
public void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
HttpContext ctx = app.Context;
//

HTTP

75

// HTTP
// PageHeaderText ,
//
ctx.Response.AppendHeader("Author", "DinoE");
ctx.Response.Write(PageHeaderText);
}
public void OnEndRequest(object sender, EventArgs e)
{
// HTTP
HttpApplication app = (HttpApplication) sender;
HttpContext ctx = app.Context;
//
//
// PageFooterText ,
//
ctx.Response.Write(PageFooterText);
}

OnBeginRequest , HTTP. OnEndRequest .


HTTP . 2-7.

. 2-7. HTTP- Marker



IEWatch 2.0, ,
Microsoft Internet Explorer, HTTP/HTTPS
HTML. http://www.iewatch.com.

IEWatch 2.0, , HTTP, .


.

76

ASP.NET

HTTP <httpModules> .
, HTTP.
<add>, name type.
,
Modules HttpApplication. ,
global.asax.
<system.web>
<httpModules>
<add name="Marker"
type=
"ProAspNet20.CS.Components.MarkerModule,ProAspCompLib" />
</httpModules>
</system.web>

type -,
.
. , ,
.
.
, .
web.config <remove>
, , <add> .
HTTP,
<clear>, .
HTTP

, HTTP, , HttpApplication.
, ? HttpApplication
Modules, .
Modules HttpModuleCollection. - NameObjectCollectionBase
. , . , ,
:
SessionStateModule sess = app.Modules["Session"];
sess.Start += new EventHandler(OnSessionStart);

, , HTTP, global.asax, , _. ,
HTTP.

HTTP

77


, ,
HTTP, ,
. : ,
, .

, ,
. Web , ASP.NET.

.
, , .
SQL-:
DELETE FROM employees WHERE employeeid=9

1000 , , ,
WHERE. :
INSERT INTO employees VALUES (...)


,
, . ,
, SQL.
, Web-.
: ,
, F5
?

,
, , .
, , .
.
,
, ,
.
, (ASP.NET, ASP DLL ISAPI)

. ASP.NET ,
, .

HTTP-. , , ASP.NET
.

78

ASP.NET

.
.

: , HTTP .
, ,
: , , . HTTP,
, , . ,
-, HTTP, -,
.
HTTP HTTP .
( ), . HTTP
Items HttpContext.
, ,
.
.
, . . . 2-6
.
. 2-6.

0.
,
,
Items

,
. ,

, Items

, ,
, , . HTTP
, , ,
. IsRefreshed, ,
.
! Items HttpContext HTTP
, HTTP,
. HTTP, ,
Items . ,
; .
, ,
, HTTP.

HTTP

79

. -,
, ? -,
HTTP
, ?
? ?
, ,
. ,
, .
.

. , , ,
HTTP. , ,
HTTP:
public class RefreshModule : IHttpModule
{
public void Init(HttpApplication app) {
app.BeginRequest += new EventHandler(OnAcquireRequestState);
}
public void Dispose() {
}
void OnAcquireRequestState(object sender, EventArgs e) {
HttpApplication app = (HttpApplication) sender;
HttpContext ctx = app.Context;
RefreshAction.Check(ctx);
return;
}
}

BeginRequest Check
RefreshAction.
public class RefreshAction
{
static Hashtable requestHistory = null;
//
public static void Check(HttpContext ctx) {
//
EnsureRefreshTicket(ctx);
// Session ,
//
int lastTicket = GetLastRefreshTicket(ctx);
//
int thisTicket = GetCurrentRefreshTicket(ctx, lastTicket);
//
if (thisTicket > lastTicket ||

80

ASP.NET

(thisTicket==lastTicket && thisTicket==0)) {


UpdateLastRefreshTicket(ctx, thisTicket);
ctx.Items[PageRefreshEntry] = false;
}
else
ctx.Items[PageRefreshEntry] = true;
}
//
static void EnsureRefreshTicket(HttpContext ctx)
{
if (requestHistory == null)
requestHistory = new Hashtable();
}
// URL
static int GetLastRefreshTicket(HttpContext ctx)
{
//
if (!requestHistory.ContainsKey(ctx.Request.Path))
return 0;
else
return (int) requestHistory[ctx.Request.Path];
}
// ,
static int GetCurrentRefreshTicket(HttpContext ctx, int lastTicket)
{
int ticket;
object o = ctx.Request[CurrentRefreshTicketEntry];
if (o == null)
ticket = lastTicket;
else
ticket = Convert.ToInt32(o);
ctx.Items[RefreshAction.NextPageTicketEntry] = ticket + 1;
return ticket;
}
// URL
static void UpdateLastRefreshTicket(HttpContext ctx, int ticket)
{
requestHistory[ctx.Request.Path] = ticket;
}
}

Item, Add, Item .
, Add .

HTTP ,
, . :
//
public class Page : System.Web.UI.Page

HTTP

81

{
public bool IsRefreshed {
get {
HttpContext ctx = HttpContext.Current;
object o = ctx.Items[RefreshAction.PageRefreshEntry];
if (o == null)
return false;
return (bool) o;
}
}
// PreRenderComplete
protected override void OnPreRenderComplete(EventArgs e) {
base.OnPreRenderComplete(e);
SaveRefreshState();
}
//
private void SaveRefreshState() {
HttpContext ctx = HttpContext.Current;
int ticket = (int) ctx.Items[RefreshAction.NextPageTicketEntry];
ClientScript.RegisterHiddenField(
RefreshAction.CurrentRefreshTicketEntry,
ticket.ToString());
}
}


IsRefreshed, IsPostBack
IsCallback. , OnPreRenderComplete .
, HTTP,
(
) Items.
. 2-8 . , .
public partial class TestRefresh : ProAspNet20.CS.Components.Page
{
protected void AddContactButton_Click(object sender, EventArgs e)
{
Msg.InnerText = "Added";
if (!this.IsRefreshed)
AddRecord(FName.Text, LName.Text);
else
Msg.InnerText = "Page refreshed";
BindData();
}
}

IsRefreshed, ,
, .
AddRecord ,
. , IsRefreshed ,

82

ASP.NET

. , ,
, .

. 2-8. ,

HTTP ASP.NET.
HTTP,
. ,
. ,
HTTP
.
, ASP.NET,
HTTP. Web- Web-, , .
HTTP ISAPI. :
HTTP .NET, ,
. CLR, ,
. ISAPI, , Win32,
IIS. ASP.NET
aspnet_isapi ISAPI, ISAPI-, HTTP ISAPI
IIS. IIS 7.0,
HTTP IIS.
HTTP ISAPI , HTTP
ISAPI-,
, .
,
HTTP Web- ASP.NET .
, HTTP , , .

HTTP

83

.
, web.config
. .

HTTP
ISAPI,
.

HTTP ASP.NET, . ASP.NET , , ,


HTTP.

HTTP , IHttpHandler .

HTTP , IHttpModule .

HTTP web.config,
.

ASP.NET

Microsoft .NET Framework XML,


.
. API
, , , , , .
ASP.NET
:
, .
, ,
, . .
ASP.NET,
, . ASP.NET
System.Configuration , ASP.NET 2.0
.
ASP.NET.
ASP.NET
, .

ASP.NET
XML-, . C ,
, .
<configuration>.
.
ASP.NET, , . machine.config,
,
, web.config, ;

ASP.NET,
, .
, machine.config web.config, . web.config.

ASP.NET

85

, ,
, :
<configuration>
<system.web>
<authorization>
<allow users="YourDomain\Administrator" />
<deny users="*" />
</authorization>
</system.web>
</configuration>

,
web.config , .
! ASP.NET
Web, IIS . ,
.config ( URL),
HTTP access 403 Forbidden. ,
, .


web.config machine.config XML . ASP.NET , , , machine.config.
, web.config,
.
machine.config ASP.NET;
: %Windows%\Microsoft.NET\Framework\[]\CONFIG. , : machine.config, machine.config.default
machine.config.comments.

. machine.config
: ,
.

ASP.NET , , machine.config.
web.config,
.
web.config , .
web.config
.
ASP.NET
.
web.config .
, . . 3-1 , ASP.NET
.

86

ASP.NET

. 3-1. ASP.NET

machine.config ,
.
web.config . ,
, URL ,
,
, .
! ASP.NET 2.0 , . 3-1,
web.config . ,
machine.config. . , machine.config
. web.config
.

machine.config web.config . ,

ASP.NET

87

, API .
, , , ,
.
API,
5 Programming Microsoft
ASP.NET 2.0: Core Reference (Microsoft Press, 2005).
.

ASP.NET 2.0 API - . ,



.
, web.config, , .
. ,
web.config, ,
.
, , . ,
, ,
.

,
<configuration>. . 3-1
. , , , . , <system.web>
<authorization>, , ASP.NET.
. 3-1. <configuration>

<appSettings>

<configSections>

, . ,
<configuration>

<connectionStrings>

,
. ASP.NET 1.x

<configProtectedData>

.
ASP.NET 1.x

<runtime>

;

,

(. . .)

88

ASP.NET

. 3-1. ()

<startup>

; , CLR

<system.diagnostics>

, -, ,

<system.net>

; , .NET Framework
, -,
,

<system.runtime.remoting> .NET remoting;


, .NET remoting
<system.web>

ASP.NET ,
ASP.NET

ASP.NET, <system.web>, <connectionStrings> <configProtectedData>.


ASP.NET, .
, <configSections> , .
, <appSettings>,
<configSections>. <system.diagnostics>
(trace listener),
, . <runtime> , .
ASP.NET ,
<system.runtime.remoting>.

<configSections>.
, <system.web>
machine.config:
<configSections>
<sectionGroup name="system.web"
type="System.Web.Configuration.SystemWebSectionGroup, ...">
<section name="authentication"
type="System.Web.Configuration.AuthenticationSection, ..."
allowDefinition="MachineToApplication" />
</sectionGroup>
</configSections>

<sectionGroup>
, : , . <section> : name type.
, ,

ASP.NET

89

.
type
.
, <section> : allowDefinition allowLocation. allowDefinition ,
.
. 3-2.
. 3-2. allowDefinition

Everywhere


( )
machine.config
machine.config
web.config, , web.config,

MachineOnly
MachineToApplication

allowLocation ,
<location>. <location> machine.config
, .
( <location> .)

<add>, <remove> <clear>. :
, ,
, . <remove> <clear>
. , <remove> web.config , .
<remove> <clear> , .
, ASP.NET
.
. web.config
. ASP.NET
, machine.config.
machine.config, .NET Framework, .
, , <configSections>
, .

<location>.
<location>

<location> ,
. . , , ,
.
, <location> web.config, , .

90

ASP.NET

web.config,

.
machine.config web.config, , .
! web.config
. ASP.NET ,
machine.config
,
. <location>, ,
, ; path
.

<location> : path allowOverride. path


, . , . web.config.
:
.
<configuration>
<system.web>
<!-- , . -->
</system.web>
<location path="Reserved">
<system.web>
<!-- , /Reserved. -->
</system.web>
</location>
</configuration>

, ,
web.config, ,
.
web.config ,
, . ,
;
web.config , ,
.
<location> path,
, : web.config
web.config machine.config
.


, <location>
machine.config machine.config, .

ASP.NET

91

, path, ( IIS), ,
IIS Manager. , ProAspNet20,
Web- (. 3-2).
<location path="Default Web Site/ProAspNet20">
<system.web>
<!-- Web- -->
</system.web>
</location>

. 3-2. Web- ,
IIS

ASP.NET ,
, machine.config
web.config . , , ,
, . , -,
, , ,
, , .
.
, ,
web.config, .
, , ,
<location> machine.config web.config. ( ,
, .)
web.
config , .
(, HTTP) <location>
machine.config, ,
GAC. ( 1.) . ,
machine.config HTTP view.axd
ProAspNet20.
<location path="Default Web site/proaspnet20">
<system.web>
<httpHandlers>
<add verb="*" path="view.axd"

92

ASP.NET

type="ProAspNet20.CS.Components.PictureViewerHandler,
ProAspCompLib, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=54943ebb40058fcb" />
</httpHandlers>
</system.web>
</location>

, .
view.axd 2.

allowOverride <location> .
<location>, allowOverride false,
ASP.NET
.
<location path="Default Web Site/ProAspNet20" allowOverride="false">
<system.web>
<!-- These settings cannot be overridden -->
</system.web>
</location>

,
ASP.NET. ,
. machine.config ,
.
,
,
, -
.
<location> , <runtime>, <mscorlib>, <system.runtime.remoting> <startup>.
<location>
allowLocation. <section>, . false,
<location>.

<system.web>
<system.web> ,
ASP.NET. . 3-3
,
.
. 3-3. , <system.web>


<anonymousIdentification> ,

. ASP.NET 1.x

<authentication>
,

ASP.NET

93

. 3-3. ()

<authorization>

<browserCaps>

<clientTarget>

<compilation>


(. 1)

<customErrors>

<deployment>

.
ASP.NET 1.x

<deviceFilters>

(. 9). ASP.NET 1.0


<globalization>

<healthMonitoring>


. ASP.NET 1.x

<hostingEnvironment>

- .
ASP.NET 1.x

<httpCookies>

cookie,
ASP.NET. ASP.NET 1.x

<httpHandlers>


HTTP (. 2)

<httpModules>

HTTP
(. 2)

<httpRuntime>

HTTP

<identity>

<machineKey>

<membership>


ASP.NET. ASP.NET 1.x

<mobileControls>



(. 8). ASP.NET 1.0

<pages>


ASP.NET

<processModel>

<profile>


. ASP.NET 1.x

<protocols>

,
Web- ASP.NET. ASP.NET 1.x

(. . .)

94

ASP.NET

. 3-3. ()

<roleManager>

<securityPolicy>
<sessionState>
<siteMap>

<trace>
<trust>


,
. ASP.NET 1.x

<webControls>
<webParts>

<webServices>
<xhtmlConformance>


Session

(. 10). ASP.NET 1.x




Web- (. 7).
ASP.NET 1.x

Web-
XHTML.
ASP.NET 1.x

, . 3-3,
, , .
, . 3-3, <system.web> <Caching>. . 3-4
.
. 3-4. , <Caching>

<cache>

<outputCache>

<outputCacheSettings>

<sqlCacheDependency>


ASP.NET. ASP.NET 1.x


ASP.NET. ASP.NET 1.x

. ASP.NET 1.x

SQL ASP.NET. ASP.NET 1.x

.
<system.web> MSDN.
. 3-3 3-4 , . ,
, <sessionState>, <authentication> <membership>,
Programming Microsoft ASP.NET 2.0: Core Reference
(Microsoft Press, 2005).

ASP.NET

95

<anonymousIdentification>

ASP.NET, ,
.
, IIS, ASP.NET. , API , ,
,
.
<anonymousIdentification> . :
<anonymousIdentification
enabled="[true | false]"
cookieless="[UseUri | UseCookies | AutoDetect | UseDeviceProfile]"
cookieName=""
cookiePath=""
cookieProtection="[None | Validation | Encryption | All]"
cookieRequireSSL="[true | false]"
cookieSlidingExpiration="[true | false]"
cookieTimeout="[DD.HH:MM:SS]"
domain="cookie domain"
/>

cookie, .
enabled. cookieless ASP.NET cookie;
. 3-5.
. 3-5. cookieless

AutoDetect

cookie, .
,

cookie,
cookie, ,
, .
, ,
cookie .

cookie,

UseCookie
UseDeviceProfile

UseUri

, cookie . cookie ( .ASPXANONYMOUS),


, , , , , cookie Secure Sockets Layer (SSL).
<authentication>

<authentication> Web- Forms, Microsoft Passport ,

96

ASP.NET

IIS.
<forms> <passport>, mode,
, . mode
. 3-6.
. 3-6.

Forms
Passport
None

Windows

, ,

Microsoft Passport
ASP.NET ,
: ,

IIS: basic, digest,
NTLM\Kerberos certificates.

Forms , name, loginURL, protection cookieless. . 3-7


<forms>.
. 3-7. <forms>

cookieless

, cookie,
. , . 3-5.
ASP.NET 1.x
defaultUrl
URL,
. default.aspx. ASP.NET 1.x

domain
cookie. ASP.NET 1.x

enableCrossApp- , Redirects
, cookie.
cookie , ;
,
(cross-application authentication)
loginUrl
URL, ,
cookie
name
cookie, .
.ASPXAUTH
path
cookie, .
(/). ,
cookie,

protection
, cookie.
: All, Encryption, Validation None.
All
requireSSL
, cookie SSL. false.
true, ASP.NET Secure cookie , cookie
SSL-. ASP.NET 1.0

ASP.NET

97

. 3-7. ()

slidingExpiration , cookie .
false, cookie
. timeout.
ASP.NET 1.0
timeout
, ,
cookie . 30

, , cookie, . 3-7, <anonymousIdentification>.


15 Programming
Microsoft ASP.NET 2.0: Core Reference (Microsoft Press, 2005).

<authorization>

<authorization> , . <authorization>
<allow> <deny>,
. users, roles verbs,
, :
<authorization>
<allow users=" "
roles=" "
verbs=" " />
<deny users=" "
roles=" "
verbs=" " />
</authorization>
<allow> ,
users, , , roles.

HTTP (, POST GET), verbs.
<deny>, , , .
.
: (*), , (?), .
15 Programming
Microsoft ASP.NET 2.0: Core Reference (Microsoft Press, 2005).

<browserCaps>

<browserCaps> , 1.1 .NET Framework


. <browserCaps> HttpBrowserCapabilities,
1.1 MobileCapabilities,
ASP.NET , . ASP.NET Browser

98

ASP.NET

Request.
(user-agent), HTTP-,
<browserCaps>.
, HttpBrowserCapabilities .
Browser.
<browserCaps>
, cookie, ,
XML DOM, .
,
. ,
, .
! <browserCaps>
ASP.NET 2.0 , .
.browser,
systemroot\Microsoft.NET\Framework\[]\CONFIG\Browsers,
.browser, App_Browsers .
ASP.NET .browser.

<caching>

<caching> ASP.NET . : cache, outputCache, outputCacheSettings


sqlCacheDependency.
, <cache>, .
percentagePhysicalMemoryUsedLimit privateBytesLimit ( ), ,
. .
<cache disableMemoryCollection = "false"
disableExpiration = "false"
privateBytesLimit = "0"
percentagePhysicalMemoryUsedLimit = "89"
privateBytesPollTime = "00:02:00" />

2 . , ,
disableExpiration,
ASP.NET, .
<outputCache> ,
(output caching).
:
<outputCache enableOutputCache = "true"
enableFragmentCache = "true"
sendCacheControlHeader = "true"
omitVaryStar = "false">
</outputCache>

(fragment caching) , , -

ASP.NET

99

, . sendCacheControlHeader
,
cache-control:private; omitVaryStar
Vary: * .
<outputCacheSettings> ,
@OutputCache.
<outputCacheProfiles>, (output cache profile),
. :
<outputCacheSettings>
<outputCacheProfiles>
<add name="ServerOnly"
duration="60"
varyByCustom="browser" />
</outputCacheProfiles>
</outputCacheSettings>

ServerOnly , 60
. <outputCacheProfiles>:
<outputCacheProfiles>
<add name = ""
enabled = "true"
duration = "-1"
location = ""
sqlDependency = ""
varyByCustom = ""
varyByControl = ""
varyByHeader = ""
varyByParam = ""
noStore = "false"/>
</outputCacheProfiles>

, <sqlCacheDependency> ,
SqlCacheDependency SQL Server 7.0 SQL Server 2000. ASP.NET 2.0 , ,
. , ,
.
<sqlCacheDependency enabled="true" pollTime="1000">
<databases>
<add name="Northwind" connectionStringName="LocalNWind" />
</databases>
</sqlCacheDependency>

pollTime ( ).
, , .
, , <databases>.
name , . ,
, connectionStringName,
<connectionStrings> web.config.

100

ASP.NET

, aspnet_regsql.exe, .
, <sqlCacheDependency>,
, SqlCacheDependency
(query notifications) SQL
Server 2005.
<clientTarget>

<clientTarget> , ClientTarget ASP.NET.


, <clientTarget>
ClientTarget Page. : ie5,
ie4, uplevel downlevel. Internet Explorer 5.5 Internet
Explorer 4.0. , ASP.NET (uplevel) Internet Explorer 4.0 ,
HTML, (downlevel) .
<clientTarget>
<add alias="ie5" userAgent="Mozilla/4.0 (compatible; MSIE 5.5; ...)"/>
<add alias="ie4" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; ...)"/>
<add alias="uplevel" userAgent="Mozilla/4.0 (compatible; MSIE 4.0; ...)/>
<add alias="downlevel" userAgent="Unknown"/>
</clientTarget>

, ClientTarget , <clientTarget>, HttpBrowserCapabilities


, , .
<customErrors>

<customErrors> ASP.NET . ,
ASP.NET , ,
ASP.NET, .
ASP.NET Mode.
On, Off RemoteOnly ( ).
Mode On,
, ; Off,

ASP.NET
.
:
.
defaultRedirect <customErrors>. ,
Mode Off.
<customErrors defaultRedirect="Errors/appGenericErr.aspx" mode="On">
<error statusCode="404" redirect="Errors/notfound.aspx" />
<error statusCode="500" redirect="Errors/internal.aspx" />
</customErrors>

ASP.NET

101

<customErrors>
<error>,
. , 403, IIS ASP.NET. <error> : redirect statusCode. redirect URL ,
statusCode HTTP, .
,
,
. ,
ASP.NET .
<deployment>

<deployment> .
, retail, , ,
( true)
(false). retail true, ASP.NET
, ,
. retail
false, .
ASP.NET 1.x ,
. ASP.NET 2.0
web.config.
<deployment retail="true" />
<globalization>

<globalization> ASP.NET,
. <globalization>
. 3-8.
. 3-8. <globalization>

requestEncoding

, ,
, . UTF-8

responseEncoding

. UTF-8

fileEncoding

ASP.NET (.aspx, .asmx .asax).


Unicode UTF-8 ,
,

culture

uiCulture

, Accept-Charset,
requestEncoding.
, ,
ASP.NET .

102

ASP.NET

requestEncoding responseEncoding
.
culture uiCulture , , en-US, en-AU it-IT.
,
.
<healthMonitoring>

ASP.NET 2.0
(health monitoring), , , .
, .
<healthMonitoring>, :
<healthMonitoring
enabled="true|false"
heartbeatInterval="HH:MM:SS">
<bufferModes>...</bufferModes>
<providers>...</providers>
<eventMappings>...</eventMappings>
<profiles>...</profiles>
<rules>...</rules>
</healthMonitoring>

enabled , .
true. heartbeatInterval
heartbeat,
. , .
,
, , . , . 3-9,
.
. 3-9.

bufferModes

Microsoft SQL Server


Web ( )
,
,

eventMappings

profiles

providers

,
. SQL Server ,
.

rules

ASP.NET

103

heartbeat 0,
.
<hostingEnvironment>

<hostingEnvironment> ,
- . ,
: idleTimeout, shadowCopyBinAssemblies shutdownTimeout.
<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
shutdownTimeout="number"/>
idleTimeout , , . Infinite,
. ,
, , , . shadowCopyBinAssemblies ,
Bin ASP.NET,
. shadowCopyBinAssemblies=true. shutdownTimeout,
( shutdownTimeout=30).
ASP.NET .NET Framework. , - ASP.NET
. , , . , ASP.NET 1.x. ASP.NET 2.0
shadowCopyBinAssemblies.

<httpCookies>

<httpCookies> cookie-, ASP.NET. :


<httpCookies domain="string"
httpOnlyCookies="true|false"
requireSSL="true|false" />

domain cookie ; .
requireSSL false. true, cookie
SSL. httpOnlyCookies ASP.NET cookie HttpOnly, cookie
. , (,
Internet Explorer 6.0 SP1), cookie HttpOnly true,
cookie .
: ;HttpOnly cookie, . ASP.NET 1.x .
! , HttpOnly
, ,
. ,
. ,
(, Fiddler, http://www.fiddlertool.com) .

104

ASP.NET

, <httpCookies>,
, cookie ASP.NET.
<httpRuntime>

<httpRuntime>
ASP.NET. , ,
.
. <httpRuntime> . 3-10.
. 3-10. ASP.NET

apartmentThreading


ASP.NET. false.
ASP.NET 1.x

appRequestQueueLimit

,
, 503 Server Too
Busy. 100 ASP.NET 1.x 5000
ASP.NET 2.0

delayNotificationTimeout

. 5 .
ASP.NET 1.x

enable

, AppDomain .
true

enableHeaderChecking

, ASP.NET ,
, injection
( ).
, ASP.NET .
true. ASP.NET 1.x

enableKernelOutputCache

http.sys IIS 6.0 .


true. ASP.NET 1.0

enableVersionHeader

,
ASP.NET. true.
Microsoft Visual Studio 2005. . ASP.NET 1.0

executionTimeout


ASP.NET.
90 ASP.NET 1.x 110 ASP.NET 2.0

maxRequestLength

Web- .
4

minLocalRequestFreeThreads ,
,
. 4
minFreeThreads

,
,
Web-. 8

requestLengthDiskThreshold

.
maxRequestLength.
256 . ASP.NET 1.x

ASP.NET

105

. 3-10. ()

requireRootedSaveAsPath

, , , SaveAs Request .
ASP.NET 1.x

sendCacheControlHeader

, ,
. ASP.NET 1.x

shutDownTimeout

, .
ASP.NET
. ASP.NET 1.x

useFullyQualifiedRedirectUrl ,
URL (true) ,
(false).
false
waitChangeNotification,
maxWaitChangeNotification


( 0) AppDomain
. ASP.NET 1.x

, ASP.NET ,
.
, , , appRequestQueueLimit. ASP.NET
?
(,
, ) ,
.
( )
, . IP- 127.0.0.1
, , .
, , , ASP.NET Web-,
. ,
. ,

.
<identity>

<identity> ASP.NET. : impersonate, userName password.


impersonate. false, , ,
.
<identity impersonate="true" />

impersonate true, ASP.NET Windows, ,


userName password.

106

ASP.NET

!
. IIS , web.config .
<identity>. ASP.NET 1.x
:

userName="registry:HKLM\Software\AspNetProcess,Name"
password="registry:HKLM\Software\AspNetProcess,Pswd"
Name Pswd ,
. REG_BINARY DPAPI (Data Protection API ).
aspnet_setreg.exe .
ASP.NET 2.0, XML Encryption,
<identity>. .

<machineKey>

<machineKey>, ,
,
. :
<machineKey
validationKey="AutoGenerate|value[,IsolateApps]"
decryptionKey="AutoGenerate|value[,IsolateApps]"
validation="[SHA1|MD5|3DES|AES]"
decryption="[Auto|AES|3DES]" />

validationKey decryptionKey . 40
128 . validation ,
. : SHA1 ( ), MD5, AES 3DES.
, decryption (AES 3DES),
.
Auto, ASP.NET , .
validationKey decryptionKey AutoGenerate,IsolateApps. ,
Local Security Authority (LSA)
Windows NT- ,
. IsolateApps
ASP.NET .
<machineKey> ,
, Web- . <machineKey>. , validationKey
decryptionKey , .
<membership>

<membership> , , API ASP.NET. :


<membership
defaultProvider="provider name"

ASP.NET

107

userIsOnlineTimeWindow="number of minutes"
hashAlgorithmType="SHA1">
<providers>
</providers>
</membership>

defaultProvider AspNetSqlMembershipProvider. userIsOnlineTimeWindow , . 15 .


hashAlgorithmType , .
<membership>
<providers>
<add name="MyProvider"
type="Samples.MyMembershipProvider"
connectionStringName="MyConnString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed" />
</providers>
</membership>

<providers> . .
.
<pages>

<pages>
@Page Web- . . 3-11 .
. 3-11. , ASP.NET

asyncTimeout

( )
. 45 .
ASP.NET 1.x
,

(, Page_Load). true
, .
true
, ASP.NET
. :
Never, Auto Always ( ). Auto , ASP.NET
, .
ASP.NET 1.x
, .
true; false ReadOnly.
,
false, , ReadOnly

autoEventWireup

Buffer
compilationMode

enableSessionState

(. . .)

108

ASP.NET

. 3-11. ()

enableViewState

, .
true
enableViewStateMac
,

. true
maintainScrollPosition true,
. ASP.NET 1.x
OnPostBack

masterPageFile
,
.
ASP.NET 1.x
maxPageStateFieldLength . , .

, . ASP.NET 1.x

pageBaseType
, .aspx
, ,
.
System.Web.UI.Page.

pageParserFilterType
,
ASP.NET
. ASP.NET 1.x
smartNavigation
, . false. maintainScrollPositionOnPostBack
styleSheetTheme
, ,

. ASP.NET 1.x
theme
, ,
. ASP.NET 1.x

userControlBaseType
.ascx,
. System.Web.UI.UserControl.

validateRequest
, ASP.NET ,
,
. true.
ASP.NET 1.0
viewStateEncryptionMode . Always, Never Auto. Auto ,
, ,
. ASP.NET 1.x

pageBaseType , ,
.
, web.config (, ,
).

ASP.NET

109

maxPageStateFieldLength. ,
,
. ,
. Web-, Microsoft WebTV
(). ASP.NET 1.x ,
:

, . ASP.NET 2.0
maxPageStateFieldLength.
, ,
ASP.NET ,
. , maxPageStateFieldLength 5, HTML-:
<input
<input
<input
<input

type="hidden"
type="hidden"
type="hidden"
type="hidden"

id="__VIEWSTATEFIELDCOUNT" value="..." />


id="__VIEWSTATE" value="/wEPD" />
id="__VIEWSTATE1" value="wUKLT" />
id="__VIEWSTATE2" value="I2MjI" />

( ) ,
- ,
.
<processModel>

<processModel> ASP.NET, , HTTP.


<processModel> ISAPI-
aspnet_isapi.dll. , IIS.
<processModel> web.config.
machine.config, ASP.NET,
. <processModel>.
<processModel
enable="true|false"
timeout="hrs:mins:secs|Infinite"
idleTimeout="hrs:mins:secs|Infinite"
shutdownTimeout="hrs:mins:secs|Infinite"
requestLimit="num|Infinite"
requestQueueLimit="num|Infinite"
restartQueueLimit="num|Infinite"
memoryLimit="percent"
webGarden="true|false"
cpuMask="num"
userName="username"
password="password"
logLevel="All|None|Errors"
clientConnectedCheck="hrs:mins:secs|Infinite"
comAuthenticationLevel="Default|None|Connect|Call|
Pkt|PktIntegrity|PktPrivacy"
comImpersonationLevel="Default|Anonymous|Identify|
Impersonate|Delegate"

110

ASP.NET

responseDeadlockInterval="hrs:mins:secs|Infinite"
responseRestartDeadlockInterval="hrs:mins:secs|Infinite"
autoConfig="true|false"
maxWorkerThreads="num"
maxIoThreads="num"
minWorkerThreads="num"
minIoThreads="num"
serverErrorMessageFile=""
pingFrequency="Infinite"
pingTimeout="Infinite"
maxAppDomains="2000" />

ASP.NET IIS 6.0 , IIS 6.0, <processModel>


. ,
IIS 6.0 IIS Manager. ,
. 3-3, ,
.

. 3-3.
IIS 6.0

. 3-12 <processModel>,
IIS 6.0.
. 3-12. ASP.NET

autoConfig

,
ASP.NET
. true.

821268 Microsoft Knowledge Base

maxIoThreads

- .
20 ( 20 N
)

ASP.NET

111

. 3-12. ()

maxWorkerThreads

.
20 ( 20 N
)

minIoThreads

- .
1

minWorkerThreads

.
1

requestQueueLimit

, ASP.NET , 503 Server


Too Busy. 5000

responseDeadlockInterval ,
, ,
.
3

, ::. ,
00:00:05 5 . Infinite ,
, .
! IIS 5.0 ,
Windows 2000 Server, MSDN ,
. 3-12. , , ASP.NET IIS 6.0
. ASP.NET, 6
Improving .NET Application Performance and Scalability, Microsoft
Patterns & Practices http://msdn.microsoft.com/library/enus/dnpag/html/
scalenetchapt06.asp.

<profile>

<profile> , ASP.NET 2.0.


,
. -
,
. ,
AspNetDb.mdf SQL Server 2005 Express. <profile>
:
<profile
enabled="true|false"
inherits="fully qualified type reference"
automaticSaveEnabled="true|false"
defaultProvider="provider name">
<properties>...</properties>
<providers>...</providers>
</profile>

enabled , .
true, .

112

ASP.NET

, , <properties>:
<profile>
<properties>
<add name="BackColor" type="string" />
<add name="ForeColor" type="string" />
</properties>
</profile>

. 3-13 ,
<profile>.
. 3-13.

allowAnonymous

.
false

customProviderData

defaultValue

name

provider

readOnly

, .
false

serializeAs

.
: Xml, Binary, String ProviderSpecific

type

.NET Framework- . string

,
Profile HttpContext.
Inherits ,
. automaticSaveEnabled ,
ASP.NET.
( true.) , ,
HTTP , .
<providers> . . defaultProvider , .
<roleManager>

<roleManager>
ASP.NET 2.0. : HTTP,
, , .
, . <providers>.
, .
defaultProvider.
:
<roleManager
cacheRolesInCookie="true|false"
cookieName="name"

ASP.NET

113

cookiePath="/"
cookieProtection="All|Encryption|Validation|None"
cookieRequireSSL="true|false "
cookieSlidingExpiration="true|false "
cookieTimeout="number of minutes"
createPersistentCookie="true|false"
defaultProvider="provider name"
domain="cookie domain">
enabled="true|false"
maxCachedResults="maximum number of role names cached"
<providers>...</providers>
</roleManager>

, , HTTP
cookie, .
,
cookie. cookie .ASPXROLES.
<securityPolicy>

<securityPolicy> ( ) .
<trustLevel> name policyFile.
, .
,
.
web.config,
ASP.NET 2.0.
<securityPolicy>
<trustLevel name="Full" policyFile="internal" />
<trustLevel name="High" policyFile="web_hightrust.config" />
<trustLevel name="Medium" policyFile="web_mediumtrust.config" />
<trustLevel name="Low" policyFile="web_lowtrust.config" />
<trustLevel name="Minimal" policyFile="web_minimaltrust.config" />
</securityPolicy>

.NET Framework name


Full, High Low. 1.1 Minimal
Medium. ,
. XML-, , machine.config.
Full,
. ASP.NET ,
policyFile .
<sessionPageState>

<sessionPageState> ,
, . ,
ASP.NET .
?
, . ,

114

ASP.NET


. ? <sessionPageState>
:
<sessionPageState historySize="9" />

historySize, 9.
ASP.NET, .
<sessionState>

<sessionState> , .
ASP.NET Session. , ,
. . 3-14
<sessionState>. mode.
.
. 3-14. ,

allowCustomSqlDatabase

true, SQL Server ,


ASPState.
ASP.NET 1.x

cookieless

,
. . 3-5

cookieName

cookie, cookie. ASP.NET 1.x

customProvider

, .
ASP.NET 1.x

mode

.
Off, InProc, Custom, StateServer SQLServer.
Off,
Session .
InProc ,
Web-.
( StateServer)
SQL Server (SQLServer). ASP.NET 2.0 Custom
,

partitionResolverType

partition resolver, ,
SQLServer StateServer.
partition resolver , sqlConnectionString
stateConnectionString . ASP.NET 1.x

regenerateExpiredSessionId true,
; false,
. ASP.NET 1.x

ASP.NET

115

. 3-14. ()

sessionIDManagerType

Null.
, ,
. ASP.NET 1.x

sqlCommandTimeout

( ) SQL-
, .
30

sqlConnectionString

SQL Server,
. ,
mode SQLServer

stateConnectionString

.
, mode SQLServer

stateNetworkTimeout

( )
TCP/IP Web-
, .
10

timeout

( )
, .
20

useHostingIdentity

, ASP.NET

SQLServer, .
true. ASP.NET 1.x

<providers>
. ASP.NET , Web-, SQL Server .
,
(,
Oracle) .
SQLServer :
data source=127.0.0.1;Integrated Security=SSPI

, ,
AspState. ,
T-SQL, aspnet_regsql.
StateServer :
tcpip=127.0.0.1:42424

IP- . , ,

Port :
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters

116

ASP.NET

<siteMap>

<siteMap> .
:
<siteMap
enabled="true|false"
defaultProvider="provider name">
<providers>...</providers>
</siteMap>


, . ASP.NET
AspNetXmlSiteMapProvider. defaultProvider.
, , <providers>.
<trace>


. ,
.
<trace> .
. 3-15.
. 3-15. ,

enabled

, .
false. Trace Viewer (trace.axd) ,

localOnly

true, Trace Viewer


;
. true. ,
trace.axd
HTTP,

pageOutput

,
. false,
Trace Viewer.
false.
, Trace
@Page

requestLimit

,

trace.axd. 10.
10 000

traceMode


. : SortByTime ( ) SortByCategory. ,
, .
,
,

writeToDiagnosticsTrace , , ,
. false.
ASP.NET 1.x

ASP.NET

117

.NET Framework
API, , .
. ,
, .
<system.diagnostics>. writeToDiagnosticsTrace
true, ASP.NET .
<trust>

<trust> , , , . Web- ASP.NET


, , .
.
, (,
) ,
, ,
ASP.NET.
<trust> ,
. <trust> machine.config.
<trust level="Full" originUrl="" />

level <trustLevel>,
<securityPolicy>.
originUrl . ,
, URL, HTTP
Socket WebRequest. ,
Web ,
, <trust>. Medium
.
ASP.NET 2.0 <trust> processRequestInApplicationTrust , true. , ,
, .
false, ,
, .
<trust> , .
ASP.NET , , .
, AppDomain ,
. ,
ASP.NET.

,
Medium . web.config, . allowOverride

118

ASP.NET

false,
, web.config,
.
<location allowOverride="false">
<system.web>
<trust level="Medium" originUrl="" />
</system.web>
</location>

, , :
<location allowOverride="true" path="Default Web Site/ProAspNet20">
<system.web>
<trust level="Medium" originUrl="" />
</system.web>
</location>
<urlMappings>

<urlMappings> URL
. , :
<urlMappings enabled="true">
<add url="~/main.aspx" mappedUrl="~/default.aspx?tab=main" />
</urlMappings>

url URL, ,
mappedUrl URL, .
URL . <add>
<urlMappings> <remove> <clear>.
ASP.NET 2.0 <urlMappings>
RewritePath RewritePath.

<webControls>

<webControls> clientScriptsLocation, .
HTML, .aspx, , ,
.
<webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />

<webControls>.
clientScriptsLocation, ,
URL, .
ASP.NET Web-
aspnet_client. , ASP.NET .
system_web, , .NET Framework.
ASP.NET 2.0, ,
. system.web
HTTP webresource.axd.
, ASP.NET.

ASP.NET

119

<webServices>

<webServices> Web- ASP.NET.


,
SOAP, Web- .
. . 3-16.
. 3-16. Web-

conformanceWarnings

WS-I,
Web-.
ASP.NET 1.x

Protocols

ASP.NET ,
Web-

serviceDescriptionFormatExtensionTypes -,

Web-
soapExtensionImporterTypes

SOAP-,
Web-
-

soapExtensionReflectorTypes

SOAP-,
Web-

soapExtensionTypes

SOAP-,
Web-

soapServerProtocolFactoryType

, ,
Web-.
ASP.NET 1.x

wsdlHelpGenerator

.aspx,
Web-, , Web- .asmx

Web- ASP.NET .
<protocols>
<add name="HttpSoap12" />
<add name="HttpSoap" />
<add name="HttpPostLocalhost" />
<add name="Documentation" />
</protocols>

1.1 ASP.NET HTTP-POST HTTP-GET.


,
:
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>

Documentation ,
ASP.NET ,
.asmx. ,

120

ASP.NET

Web- ,
ASP.NET Requested Format Is Unrecognized.
, ,
href <wsdlHelpGenerator>:
<webServices>
<wsdlHelpGenerator href="YourNewGeneratorPage.aspx" />
</webServices>


Web-, Web-.
<xhtmlConformance>

ASP.NET 2.0 <xhtmlConformance> XHTML.


XHTML 1.0 Transitional.
, Visual Studio 2005.
<xhtmlConformance>, : XHTML 1.0 Transitional,
XHTML1.0 Strict (legacy):
<xhtmlConformance mode="Transitional|Legacy|Strict"/>

Legacy, , ASP.NET 1.x.


<system.web> , ASP.NET.
.
<appSettings>

<appSettings> , , , URL,
, .
<configuration>
<appSettings>
<add key="StockPickerWebServiceUrl" value="..." />
</appSettings>
</configuration>

<appSettings> :
<appSettings>
<add key="..." value="..." />
<remove key="..." />
<clear />
</appSettings>

<add> ,
. <remove>
, <clear>,
, <appSettings>.
ASP.NET 1.x . ASP.NET 2.0 .

ASP.NET

121

<appSettings> ,
. ASP.NET 1.x , ASP.NET 2.0 API .
, ,
<appSettings>, , file.
<appSettings file="myfile.config" />

, file,
, <appSettings> web.config.
, <appSettings>.
,
, <appSettings>
web.config .

<connectionStrings>

.NET Framework 2.0 , . <connectionStrings>,


:
<connectionStrings>
<add name="NWind"
connectionString="SERVER=...;DATABASE=...;UID=...;PWD=...;"
providerName="System.Data.SqlClient" />
</connectionStrings>

<add>,
<remove> <clear>. , name. connectionString. providerName, , ADO.NET
.
ASP.NET 2.0 ,
<providers> <membership> <profile>.
<configProtectedData>

ASP.NET 2.0 , .
, XML encryption.
( http://www.w3.org/TR/xmlenc-core) XML-.
ASP.NET 2.0 - .
,
, , .
.NET Framework 2.0 ,
, ,
.
, . .NET Framework 2.0

122

ASP.NET

: DPAPIProtectedConfigurationProvider RSAProtectedConfigurationProvider. Windows DPAPI (Data


Protection API API ), , , RSA. ,
. <configProtectedData>
,
. , Win32
XML, , . : <processModel>, <runtime>,
<mscorlib>, <startup> <system.runtime.remoting>.



API,
, XML , ,
MMC- ASP.NET. .

API
ASP.NET 2.0 API , ,
, .
,
.
System.Configuration.
, API .
, . API.
Web-

ASP.NET WebConfigurationManager. , Web-. , HTTP,


.
void Button1_Click(object sender, EventArgs e)
{
string name = @"system.web/httpHandlers";
Configuration cfg =
WebConfigurationManager.OpenWebConfiguration("/");
HttpHandlersSection hdlrs =
(HttpHandlersSection)cfg.GetSection(name);
EnumerateHandlers(hdlrs, ListBox1);
}
void EnumerateHandlers(HttpHandlersSection section, ListBox ctl)
{
foreach (HttpHandlerAction h in section.Handlers)
ctl.Items.Add(h.Path);
}

ASP.NET

123

OpenWebConfiguration,
, .
null /,
. ,
OpenMachineConfiguration.
OpenWebConfiguration Configuration.
GetSection, . , HTTP :
HttpHandlersSection section;
section = (HttpHandlersSection) cfg.GetSection(@"system.web/httpHandlers");

, . . 3-4
.

. 3-4. HTTP,

. ,
, , .
, ,
web.config,
:
<httpHandlers>
<add verb="*" path="myHandler.aspx" type="..." />
<add verb="*" path="*.sqlx" type="..." />
<add verb="*" path="view.axd" type="..." />
</httpHandlers>


URL OpenWebConfiguration:
string path = Request.CurrentExecutionFilePath;
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(path);

, .

WebConfigurationManager , ASP.NET. , ,
ASP.NET ,

124

ASP.NET

<system.web>. <appSettings>
<connectionString>.
ConfigurationManager. WebConfigurationManager
, AppSettings ConnectionStrings. :
public static NameValueCollection AppSettings {
get {return ConfigurationManager.AppSettings;}
}
public static NameValueCollection ConnectionStrings {
get {return ConfigurationManager.ConnectionStrings;}
}

, AppSettings ConnectionStrings
WebConfigurationManager ConfigurationManager. , , Northwind:
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString

, <appSettings>, :
WebConfigurationManager.AppSettings["StockPickerWebServiceUrl"]

, , <system.web>, ConfigurationManager OpenMachineConfiguration, .


, , , Web (https, http, ftp . .):
string name = @"system.net/webRequestModules";
Configuration cfg = ConfigurationManager.OpenMachineConfiguration();
WebRequestModulesSection section;
section = (WebRequestModulesSection) cfg.GetSection(name);
foreach (WebRequestModuleElement m in section.WebRequestModules)
ListBox3.Items.Add(m.Prefix);

DOM (Document Object Model


). , Save Configuration.
,
HTTP:
string name = @"system.web/httpHandlers";
string path = "/proaspnetadv";
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(path);
HttpHandlersSection section;
section = (HttpHandlersSection)appConfig.GetSection(name);
HttpHandlerAction newHandler = new HttpHandlerAction("*.xyz",
"System.Web.HttpForbiddenHandler", "*");
section.Handlers.Add(newHandler);
cfg.Save();

ASP.NET

125

, .xyz. web.config
:
<httpHandlers>
<add path="*.xyz"
verb="*"
type="System.Web.HttpForbiddenHandler" />
</httpHandlers>

. 3-5 , .xyz,
.

. 3-5. .xyz

.xyz, .
:
string name = @"system.web/httpHandlers";
string path = "/proaspnetadv";
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(path);
HttpHandlersSection section;
section = (HttpHandlersSection)cfg.GetSection(name);
section.Handlers.Remove("*", "*.xyz");
appConfig.Save();

.xyz ,
, Resource
Not Found.

( <protectedData>)
,
API,
. .
aspnet_regiis.exe.

126

ASP.NET

/ProAspNetAdv. ,
.
aspnet_regiis.exe pe connectionStrings app /ProAspNetAdv

web.config .
<connectionStrings> <EncryptedData>, .
, :
<configuration>
<connectionStrings
configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData ...>
<CipherData>
<CipherValue>cQyofWFQ... =</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
</configuration>

web.config
, , pe pd.
,
, .

ProtectSection UnprotectSection SectionInformation. :
string name = "connectionStrings";
string path = "/proaspnetadv";
string provider = "RsaProtectedConfigurationProvider";
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(path);
ConnectionStringsSection section;
section = (ConnectionStringsSection) cfg.GetSection(name);
section.SectionInformation.ProtectSection(provider);
cfg.Save();

UnprotectSection :
section.SectionInformation.UnprotectSection();

, , ,
Save Configuration.

,
Web, Visual Studio 2005.
, IIS, RSA. ?
, RSA-, , .
ASP.NET NetFrameWork-

ASP.NET

127

ConfigurationKey. aspnet_regiis.exe
, .
, , , RSA. ,
,
. ( Web-) , ASP.NET
Web- . ,
ASP.NET NETWORK SERVICE (
Windows Server 2003),
:
aspnet_regiis.exe pa "NetFrameworkConfigurationKey"
"NT AUTHORITY\NETWORK SERVICE"

, . ,
RSA-.
RSA DPAPI ,
. DPAPI
, .
DPAPI Web-,
web.config .
,
.
, XML,
, web.config. (
):
aspnet_regiis.exe pc YourContainerName exp

XML-:
aspnet_regiis.exe px YourContainerName YourXmlFile.xml

XML-
:
aspnet_regiis.exe pi YourContainerName YourXmlFile.xml

ASP.NET
.

XML-
, . :
, XML- ;
,
.
(, , ) web.config () .

128

ASP.NET

, ,
, .
, ,
.
ASP.NET 1.x
, IConfigurationSectionHandler.
Create, XML ,
. ASP.NET 2.0
, ConfigurationSection. , XML-.
ConfigurationProperty.
, <MyPages>
pageBackColor.
public class MyPagesSection : ConfigurationSection
{
private static readonly ConfigurationProperty propPageBackColor = null;
static MyPagesSection()
{
MyPagesSection.propPageBackColor = new ConfigurationProperty(
"PageBackColor", typeof(string), "yellow",
ConfigurationPropertyOptions.IsRequired);
}
[ConfigurationProperty("pageBackColor")]
public string PageBackColor
{
get
{
return (string) base[MyPagesSection.propPageBackColor];
}
set
{
base[MyPagesSection.propPageBackColor] = value;
}
}
}


ConfigurationProperty.
, .
.
:
<configuration>
<configSections>
<section name="myPages"
type="ProAspNet20.Components.MyPagesSection, ProAspCompLib" />

ASP.NET

129

</configSections>
<configuration>

type <section> ,
.
<myPages> MyPagesSection,
.
, .


ASP.NET 2.0 ,
. Web Site Administration Tool, Visual Studio 2005,
MMC .
.
MMC- ASP.NET

ASP.NET Microsoft Management Console , IIS Manager ASP.NET Properties. . 3-6.

. 3-6. MMC- ASP.NET

ASP.NET
IIS, .
, , .
1. Administrative Tools/Internet Information Services MMC IIS, IIS Manager.
2. , , Action Properties.
3. ASP.NET.
Edit Configuration (. 3-7), ( ,
, . .).
.

130

ASP.NET

. 3-7. ASP.NET,
, MMC

Apply,
web.config.
Web Site Administration Tool

. 3-8 Web Site Administration Tool (WSAT).


( Home),
: , , .

. 3-8. Web Site Administration Tool Visual Studio 2005

ASP.NET

131

WSAT , Visual Studio 2005


ASP.NET 2.0.
IIS.
Visual Studio 2005.
ASP.NET, Website ASP.NET Configuration.
Security WSAT
. , ,
, ,
.
.
Application <appSettings>
web.config. ,
, .
ASP.NET, Provider. .
WSAT

WSAT , .
%WINDOWS%\Microsoft.NET\Framework\[version]\ASP.NETWebAdminFiles

WSAT . ,
,
HTTP (. 3-9).

. 3-9. WSAT

132

ASP.NET

. Handlers.
ASP.NET manageHandlers.aspx :
<%@ Page masterPageFile="~/WebAdmin.master"
inherits="System.Web.Administration.HandlersPage" %>
<%@ MasterType virtualPath="~/WebAdmin.master" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server" language="CS">
public void Page_Load()
{
}
</script>
<asp:content runat="server" contentplaceholderid="titleBar">
<asp:literal runat="server" text="<%$ Resources:ConfigureHandlers %>"/>
</asp:content>
<asp:content runat="server" contentplaceholderid="content">
</asp:content>

manageHandlers.aspx ,
WSAT.
(manageHandlers.aspx.resx),
App_LocalResources ( ASP.NET 1).
,
, . 3-9. :
public class HandlersPage : WebAdminPage
{
protected override void OnInit(EventArgs e)
{
NavigationBar.SetSelectedIndex(4);
base.OnInit(e);
}
}

4 WSAT. , . ,
WebAdminPage. ApplicationPath,
.
.

WSAT, default.aspx navigationBar.ascx, . Default.aspx WSAT;
, . 3-10, .
HTML. :
<tr class="gridRowStyle8">
<td>
<a id="ProviderLink" href="handlers/chooseHandlers.aspx">

ASP.NET

133

<asp:literal runat="server"
text="<%$ Resources: HandlersConfig %>"/></a>
</td>
<td>
<asp:literal runat="server"
text="<%$ Resources: EnablesHandlers %>"/>
</td>
</tr>

.
default.aspx.resx, App_LocalResources
WSAT.
navigationBar ,
.
, .
WSAT,
.

. 3-10. WSAT

ASP.NET 2.0 aspnet_regsql aspnet_regiis.



%WINDOWS%\Microsoft.NET\Framework\[]

aspnet_regsql.exe ,
, , SQL , SQL Server. ,
: ,
. aspnet_regsql.exe
, .

134

ASP.NET

, .
:
aspnet_regsql -?

aspnet_regiis.exe ASP.NET. , ASP.NET 2.0. , ASP.NET


aspnet_regiis.
.
aspnet_regiis -s W3SVC/1/ROOT/_

IIS ASP.NET, aspnet_regiis. , IIS.


aspnet_regiis -lv

ASP.NET,
.
aspnet_regiis -i

ASP.NET, .

ASP.NET .
, ,
. ASP.NET
(, Web-,
) .
ASP.NET ,
, .
, Visual Studio .NET ( ),
- . ASP.NET , ,
Web- -,
machine.config web.config. ASP.NET , .

ASP.NET
.


.NET Framework.
.
, XML- , .

machine. config , ,
.

ASP.NET

135

<system.web> ,
ASP.NET, , , , HTTP . .

XML encryption.
.

,
Web-.

ASP.NET
, API, ASP.
NET, , WSAT,
MMC .


ASP.NET

ASP.NET 2.0.
- , , ASP.NET,
.
, , , ,
, ,
, API,
. ,
.
API ,
.
ASP.NET, ,
,
.
ASP.NET , , .
, ASP.NET .
, ,
. , , , ,
, , Oracle DB2, ,

.

ASP.NET. ,
, .

, .
ASP.NET, ,
.
ASP.NET
.
ASP.NET 2.0 Providers, http://msdn.microsoft.com/asp.net/
downloads/providers/.

ASP.NET

137


ASP.NET ,
, ,
. . . 4-1.

. 4-1. ASP.NET

ASP.NET , ,
, , , . ,
. ,
, . , , , ,
, ASP.NET,
.
? - , ?
, -.
, (, )
ASP.NET.
ASP.NET, Microsoft Windows Forms ,
, , , . ASP.NET
, , . Windows Forms,
, ,
.


ASP.NET, API,
, .

138

ASP.NET

ASP.NET ,
.
, ,
, .NET ASP.NET,
. , ,
,
. , http://www.
dofactory.com.


.
API, , ,
. ,
.
ASP.NET, ,
,
,
, API.
,

, . ASP.NET
, , , , . , ASP.NET
.

, ASP.NET ,
.
. ,
, -, .
?
,
, , . , ,
XML-
. , .
ASP.NET 2.0? ,
, . ( ),
, ASP.NET 2.0 .
, .

ASP.NET

139

,
.
, ASP.NET 2.0.
, , API ASP.NET, , , .

3,

ASP.NET , .
ASP.NET
. ASP.NET ,
. .


ASP.NET 2.0 ,
, .
,
, .
ProviderBase
(. 4-2).

. 4-2. ASP.NET

ASP.NET , . ,
, .
, ASP.NET . ,
,
. ,
XML- .

140

ASP.NET

,
. ,
: GetPropertyValues SetPropertyValues (. . 4-2).
, ,
. ASP.NET
.
,
ProviderBase. Initialize, ,
. ,
, , ,
ProviderBase. , ,
. 4-2, . ProfileProvider ProviderBase. SettingsProvider, , ,
ProviderBase. .


, ,
, . (
3.) ,
.

Initialize ProviderBase , .
.


. ,
. <providers>. , SqlProfileProvider,
. 4-2, , Microsoft SQL Server 2005 Express aspnetdb.mdf.
,
.
, ASP.NET 1.x, ASP.NET 2.0.
: , , , .
.
ASP.NET 2.0. ,
, .
, ASP.NET 1.x.
ASP.NET 1.x , ,
, ASP.NET 1.x, , .
http://msdn.microsoft.com/asp.net/beta2/providers.

ASP.NET

141

ASP.NET
ASP.NET ,
:


- ;

, , , , ;

,
ASP.NET 2.0, . 4-1.
. 4-1. ASP.NET



MembershipProvider

Web Parts

PersonalizationProvider

,
Web Parts

ProfileProvider

- ProtectedConfigurationProvider
,

RoleProvider

SessionStateStoreProviderBase

SiteMapProvider

Web


WebEventProvider

, . 4-1, ,
. , , . ProfileProvider
GetPropertyValues SetPropertyValues. ProfileProvider
.
, ProfileProvider,
SqlProfileProvider. .

142

ASP.NET


ASP.NET 2.0, ,
. .


, ASP.NET
. , , ,
.
, .
, ,
- . ,
,
. ,
:
.
! , ,
. , ;
not supported.
.

MembershipProvider. ASP.NET : SqlMembershipProvider ActiveDirectoryMembershipProvider.


System.Web.Security.
SqlMembershipProvider

SqlMembershipProvider
aspnetdb.mdf SQL Server 2005 Express
. ,
aspnet_regsql.exe (. 3).
Web Site Administration Tool (WSAT),
Microsoft Visual Studio 2005 Website.
aspnetdb : aspnet_Applications, aspnet_Membership, aspnet_SchemaVersions
aspnet_Users. , ASP.NET (
NT AUTHORITY/NETWORK SERVICE)
aspnetdb.
web.config ,
, SqlMembershipProvider SQL Server 2000 SQL Server 2005 , . SQL Server 2005 Express
,
, , .
, aspnetdb.mdf.

ASP.NET

143

aspnetdb

aspnetdb.mdf ASP.NET 2.0,


SQL Server.
,
. ,
. . 4-3
aspnetdb.mdf Server Explorer. ,
, Solution Explorer.

. 4-3. aspnetdb

aspnetdb . 4-2. .
. 4-2. aspnetdb

aspnet_Applications

aspnet_Membership

;
aspnet_Users,
aspnet_Applications

aspnet_Paths

, Web Parts

aspnet_PersonalizationAllUsers

,
Web Parts, .
aspnet_Paths

aspnet_PersonalizationPerUser


, Web Parts.
aspnet_Paths,
aspnet_Users

aspnet_Profile

.
aspnet_Users , aspnet_Applications

aspnet_Roles

aspnet_SchemaVersions

(. . .)

144

ASP.NET

. 4-2. ()

aspnet_Users

aspnet_UsersInRoles
aspnet_WebEvent_Events

.
,

Web

,
. , , aspnet_Users, , , , , Web Parts. , . aspnet_Users
( GUID ),
aspnet_Membership, (
, ).
, SQL Server, . aspnet_SchemaVersions
, (,
. .), ,
(1.0, 1.1, 2.0 . .), , , , , .
,
.
SQL-, ,
.

ASP.NET, aspnetdb.mdf.
, , ,
. , -
, aspnetdb.mdf.
, ,
SQL Server. , , .

ActiveDirectoryMembershipProvider

ActiveDirectoryMembershipProvider
Active Directory Active Directory Application Mode (ADAM).
web.config
, Active Directory.
web.config, Active Directory
ASP.NET. ,
Active Directory .
, , Active
Directory, Active Directory. , Active Directory ,
.
Active Directory , , , . , ,

ASP.NET

145

, Active Directory.
Active Directory,
. ,
.
, Active Directory, ,
.
, , ,
.
, Active
Directory .
Active Directory, - Windows.
Active Directory

ActiveDirectoryMembershipProvider ,
, , , . , <membership>
web.config ,
. , ,
<connectionStrings> ,
.
<connectionStrings>
<add name="TestDomain1ConnString"
connectionString="LDAP://TestDomain1.com/CN=Users,DC=..." />
<add name="TestDomain2ConnString"
connectionString="LDAP://TestDomain2.com/CN=Users,DC=..." />
</connectionStrings>

, ,
Active Directory.
, , , . ,
<providers>, .
<providers>
<add name="TestDomain1"
type="System.Web.Security.ActiveDirectoryMembershipProvider, ..."
connectionStringName="TestDomain1ConnString"
connectionUsername="TestDomain1\Admin"
connectionPassword="..." />
<add name="TestDomain2"
type="System.Web.Security.ActiveDirectoryMembershipProvider, ..."
connectionStringName="TestDomain2ConnString"
connectionUsername="TestDomain2\Admin"
connectionPassword="..." />
</providers>

, ,
, Active Directory? .
, ,
/_,

146

ASP.NET

. ,
, , :
//
//
string userName = "...";
string pswd = "...";
string domainName = "...";
MembershipProvider domainProvider;
if (domainName == "TestDomain1")
domainProvider = Membership.Providers["TestDomain1"];
else if (domainName == "TestDomain2.test.com")
domainProvider = Membership.Providers["TestDomain2"];
//
//
if (domainProvider.ValidateUser(userName, pswd) {
}

,
SQL Server ,
, Oracle DB2. , ASP.NET 1.x
ASP.NET 2.0.

, ,
LDAP (Lightweight Directory Access Protocol
), Web- .


ASP.NET ,
.
, . ,
. ASP.NET
.
- .
,
, , ,
.
RoleProvider. ASP.NET 2.0
: SqlRoleProvider, WindowsTokenRoleProvider AuthorizationStoreRoleProvider. System.Web.Security.
SqlRoleProvider -

ASP.NET

147

aspnetdb.mdf SQL
Server 2005 Express.
aspnetdb.mdf, WSAT Server Explorer Visual Studio 2005.

WindowsTokenRoleProvider
WindowsTokenRoleProvider ,
Windows.
- ASP.NET,
Windows .
Windows. .
,
Windows. WindowsTokenRoleProvider
IsUserInRole GetUsersInRole,
RoleProvider. .
AuthorizationStoreRoleProvider

AuthorizationStoreRoleProvider ,
AzMan. Microsoft
Windows Server 2003, Windows XP Professional Windows 2000 Server
AzMan Windows, () . AzMan MMC,
, , .
,
XML-, Active Directory ADAM. AzMan
. 4-4.

. 4-4. AzMan

148

ASP.NET

AzMan . , API ,
,
. ASP.NET, AuthorizationStoreRoleProvider,
AzMan API .
, , AuthorizationStoreRoleProvider
API. , ,
, , . ,
.
API AzMan, ASP.NET, COM Interop.
AzMan , http://msdn.microsoft.com/library/enus/dnpag2/html/paght000019.asp. AzMan http://windowsupdate.microsoft.com,
.

AuthorizationStoreRoleProvider ASP.NET
, . :
<connectionString>
<add name="LocalPolicyStore"
connectionString="msxml://c:/mystore.xml" />
</connectionString>
<system.web>
<roleManager>
<providers>
<add name="RoleManagerAzManProvider"
type="System.Web.Security.AuthorizationStoreRoleProvider, ... "
connectionStringName="LocalPolicyStore"
applicationName="AzManDemo" />
</providers>
</roleManager>
</system.web>

XML- msxml.
Active Directory ADAM, .
API ASP.NET AzMan

API AzMan - API


ASP.NET? , API AzMan .
AzMan .NET ASP.NET. COM-, Windows.
, AzMan
ASP.NET.
. ,
,
API AzMan,
, AuthorizationStoreRoleProvider.

ASP.NET

149

, SQL Server .
, ASP.NET 2.0.
, ,
Web-
. ,
API AzMan API.
AzMan ASP.NET, , , . AuthorizationStoreRoleProvider, API.



.
. -,
, , .
-, ,
, . , ,
. , , ,
.
web.config,
, . ,
, .
HTTP , . .
,
.
SqlProfileProvider
ProfileProvider. ASP.NET
SqlProfileProvider, System.Web.Profile.
aspnetdb.mdf SQL Server 2005 Express. .
. , (. 4-5).

,
SQL Server
, Oracle DB2.

ASP.NET 2.0. , ,

150

ASP.NET

(XML , , Access)
,
.
, SQL Server.

. 4-5. aspnet_Profile aspnetdb


ASP.NET. ,
, API ,
Session. ASP.NET 2.0 ,
HTTP, .
HTTP ASP.NET
, .
, HTTP ASP.NET
,
, . ,
, . ,
.
SessionStateStoreProviderBase, System.Web.SessionState. ASP.NET

ASP.NET

151

, ,
SQL Server.
ASP.NET 1.x , , .
IStateClientManager. 2.0
.

InProcSessionStateStore

InProcSessionStateStore
ASP.NET. ,
InProcSessionStateStore .
, , .
aspnet_wp.exe,
IIS 5.0, w3wp.exe IIS 6.0.
, HTTP Session_End, ,
.
OutOfProcSessionStateStore

OutOfProcSessionStateStore ASP.NET. ,
Microsoft Windows NT, aspnet_state.exe.
, . ASP.NET:
%WINDOWS%\Microsoft.NET\Framework\[]

ASP.NET
, . HTTP TCP/IP, web.config (. 3).
ASP.NET , .
, ,
Web- Web-. ,
- ASP.NET.
, AppDomain, .

(-),
, .
SqlSessionStateStore

, ,
ASP.NET . , , . ,
.

152

ASP.NET

. ,
, SqlSessionStateStore.
SQL Server.
SQL Server,
, , , .
, Web-
SQL Server 7.0 .
, OutOfProcSessionStateStore,
, . ,
,
- .
SqlSessionStateStore ASPState,
. .
, SQL Server,
.
( ASPState), .
, , ,
. SqlSessionStateStore
web.config.



, SQL Server.
, , , , , , ,
.
. , Oracle. ,
, . (SQL Server) ,
?
, SqlSessionStateStore,
SQL Server Oracle.

SessionStateUtility. -
, .
,
HTTP Session.


,
Web-. . ,
. , ASP.NET 2.0
, TreeView Menu, . ,
10. ?

ASP.NET

153

ASP.NET XML-,
web.sitemap, .
.
. ,
.
, ASP.NET.
SiteMapProvider. , ,
,
. , URL,
, .
. ,
,
.
SiteMapProvider .

,
. ,
, RESX-,
,
ASP.NET . , ,
, .

. , SiteMapResolve
, , .

XmlSiteMapProvider

XmlSiteMapProvider StaticSiteMapProvider, , , SiteMapProvider.


, XML-,
siteMapFile .
web.config:
<siteMap>
<providers>
<add name="AspNetXmlSiteMapProvider"
siteMapFile="web.sitemap"
type="System.Web.XmlSiteMapProvider, System.Web, ... " />
</providers>
</siteMap>

web.sitemap, XmlSiteMapProvider ,
, . , , XmlSiteMapProvider .sitemap.
XML-,
. <siteMap>, <siteMapNode>.
siteMapNode.

154

ASP.NET

siteMapNode, .
:
<siteMap>
<siteMapNode title="Intro" url="intro.aspx" >
<siteMapNode title="Acknowledgements" url="ack.aspx" />
<siteMapNode title="References" url="ref.aspx" />
</siteMapNode>
<siteMapNode title="Samples" url="samples.aspx">
</siteMapNode>
</siteMap>

siteMapNode ,
Url, XmlSiteMapProvider XML- .sitemap URL
.
siteMapNode Key. , Key,
.
XmlSiteMapProvider XML- ,
.

,
XML- .sitemap
.
, . -, ,
ASP.NET 2.0.
,
SiteMapProvider StaticSiteMapProvider. ,
,
. .

Web
ASP.NET , , , . :
.
Web. Web , , ,
. ,
. .

web.config (. 3).
Web- WebEventProvider.
BufferedWebEventProvider.
System.Web.Management.

ASP.NET

155

EventLogWebEventProvider

EventLogWebEventProvider
Windows. ,
.
<rules>
<add name="All Errors Default" eventName="All Errors"
provider="EventLogProvider" ... />
<add name="Failure Audits Default" eventName="Failure Audits"
provider="EventLogProvider" ... />
</rules>

web.config , EventLogWebEventProvider Windows.


MailWebEventProvider

MailWebEventProvider , ,
BufferedWebEventProvider. , BufferedWebEventProvider, ,
. MailWebEventProvider , . :
SimpleMailWebEventProvider TemplatedMailWebEventProvider.
Web, SimpleMailWebEventProvider
. ,
:
<providers>
<add name="CriticalMailEventProvider"
type="System.Web.Management.SimpleMailWebEventProvider, ..."
from="admin@contoso.com"
to="someone@contoso.com"
bodyHeader="Warning!"
bodyFooter="Please investigate ASAP."
subjectPrefix="Action required." />
</providers>


Web
.
, :
<rules>
<add name="All Errors by Email"
eventName="All Errors"
provider="CriticalMailEventProvider" />
</rules>

name ,
. Event Log All Errors.
, , -,
, , .

156

ASP.NET

web.config , . 3, <healthMonitoring>
<rules> <providers>.
, ,
, , <add> Web SMTP.
<mailSettings> . :
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network host="mail.contoso.com" />
</smtp>
</mailSettings>
</system.net>
. 4-6.

. 4-6. Web

, SimpleMailWebEventProvider, . ,
TemplatedMailWebEventProvider. , template, ASP.NET. :
<%@ Page Language="C#" AutoEventWireup="true" Inherits="MyEmailTemplate"
CodeFile="MyEmailTemplate.aspx.cs" %>
<html>
<body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="TheMailBody" />
</form>

ASP.NET

157

</body>
</html>

:
using System.Web.Management;
public partial class MyEmailTemplate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// StringBuilder
StringBuilder pageBody = new StringBuilder();
// ,
//
WebBaseEventCollection events;
events = TemplatedMailWebEventProvider.CurrentNotification.Events;
foreach (WebBaseEvent e in events)
{
// , WebBaseEvent
}
//
TheMailBody.Text = pageBody.ToString();
}
}

CurrentNotification TemplateMailWebEventProvider .
MailEventNotificationInfo, Events
WebBaseEvent.
TraceWebEventProvider

TraceWebEventProvider
ASP.NET,
trace.axd.
<providers> <rules> :
<trace enabled="true" />

ASP.NET .
WmiWebEventProvider

WmiWebEventProvider
Windows Management Instrumentation (WMI). , Windows,
. , WMI ,
,
.
893664 Knowledge Base
WMI, WMI System.Management. . 4-7 :

158

ASP.NET

ASP.NET,
:
<rules>
<add name="All Errors to WMI" eventName="All Errors"
provider="WmiWebEventProvider" />
</rules>

. 4-7. WMI-, ASP.NET

ASP.NET Web. ,

SQL Server, , Oracle, -
, , Microsoft Message Queue (MSMQ).
,
XML- , . , ,
Windows ,
SQL Server WMI . , ,
.

Web Parts
Web Parts ASP.NET
Web- . , ,
, .
Web Parts ,
. , . ,
. Web Part
HTML , , ,
. Web Parts , ,
.
Web Parts 7.

ASP.NET

159

Web Parts
. . Web
Parts .
SqlPersonalizationProvider

Web Parts PersonalizationProvider


, System.Web.UI.WebControls.
WebParts. ASP.NET ,
SqlPersonalizationProvider.
SqlPersonalizationProvider aspnetdb.mdf. , ,
aspnet_Paths. ,
. aspnet_PersonalizationPerUser,
aspnet_PersonalizationAllUsers.

, Web Parts,
, .
SQL Server SQL Server 2005 Express,
web.config, SQL
Server .
, .
aspnet_regsql , .
MSDN.


3, ASP.NET 2.0
web.config . .
<providers> <protectedData>.
: , ,
XML-.
ProtectedConfigurationProvider,
ProviderBase. ASP.NET RSA, Windows Data Protection
API (DPAPI).

,
:
public abstract class ProtectedConfigurationProvider : ProviderBase
{
public abstract XmlNode Decrypt(XmlNode encryptedNode);
public abstract XmlNode Encrypt(XmlNode node);
}

160

ASP.NET

Encrypt XmlNode,
, ,
XmlNode, .
:
public override XmlNode Encrypt(XmlNode node)
{
//
string clearText = node.OuterXml;
string encText = EncryptText(clearText);
// XML-
StringBuilder finalText = new StringBuilder();
finalText.Append("EncryptedData><CipherData><CipherValue>");
finalText.Append(encText);
finalText.Append("</CipherValue></CipherData></EncryptedData>");
// XML web.config
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(finalText.ToString());
return doc.DocumentElement;
}

Decrypt :
public override XmlNode Decrypt(XmlNode encryptedNode)
{
//
string cipherValue = TraverseToNodeValue(encryptedNode);
string clearText = this.DecryptText(cipherValue);
// XML web.config
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(clearText);
return doc.DocumentElement;
}

, ,
. -,
,
, .
RsaProtectedConfigurationProvider

RSA
,
, . ,
, , .
. ,
, ,
. ,
. ,
, .

ASP.NET

161

, RSA
-.
.NET Framework - RSACryptoServiceProvider
, .
, . .
RSACryptoServiceProvider . machine.config,
:
<protectedData defaultProvider="RsaProtectedConfigurationProvider">
<providers>
<add keyContainerName="NetFrameworkConfigurationKey"
useMachineContainer="true"
name="RsaProtectedConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider,
System.Configuration, ..." />
</providers>
</protectedData>

, RsaProtectedConfigurationProvider . NetFrameworkConfigurationKey.
ASP.NET ,
. ,
RsaProtectedConfigurationProvider.
.
, ,
.
, ASP.NET Web-
. ?
Web-, Visual Studio 2005,
. IIS
IIS, .
, ASP.NET,
.
ASP.NET NETWORK SERVICE (
, Windows Server 2003),
Windows :
aspnet_regiis.exe pa "NetFrameworkConfigurationKey"
"NT AUTHORITY\NETWORK SERVICE"


. , , "NT
AUTHORITY\NETWORK SERVICE", . ,

, RSA.
aspnet_regiis ,
. , , (
web.config ), RsaProtectedConfigurationProvider.

162

ASP.NET

Web-

, RSA Web-. Web-


,
web.config . ( ) :
, . ASP.NET
,
x-copy.
, ,
, , , web.config. :
 web.config , web.config ,
;
 x-copy
web.config, .
, web.config. , web.config.
:
aspnet_regiis.exe px "NetFrameworkConfigurationKey" _.xml


_.xml.
XML- Web, . .
aspnet_regiis.exe pi "NetFrameworkConfigurationKey" _.xml

ASP.NET :
aspnet_regiis.exe pa "NetFrameworkConfigurationKey"
"NT AUTHORITY\NETWORK SERVICE"
DpapiProtectedConfigurationProvider

web.config, Windows Data


Protection API (DPAPI). Windows 2000
: CryptProtectData CryptUnprotectData.
.NET Framework 2.0 DPAPI ProtectedData.
API P/Invoke. .NET Framework 1.x
P/Invoke
, . :
http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT07.asp.

RSA DPAPI . -, DPAPI ,

ASP.NET

163

. -, DPAPI .
, DPAPI , , .
,
, .
.
DPAPI , ,
. ,
, , , , ,
, . DpapiProtectedConfigurationProvider .
machine.config:
<providers>
<add useMachineProtection="true"
name="DataProtectionConfigurationProvider"
keyEntropy=""
type="System.Configuration.DpapiProtectedConfigurationProvider,
System.Configuration, ..." />
</providers>

DPAPI, IIS Web- Visual Studio 2005. Web-



.
,
. ,
Web- RSA.
DPAPI . ? DPAPI
.
, .

, ,
.
: , .
, , , .
,
RSA DPAPI. .
, ,
. , , . ,
, ,
.

164

ASP.NET


, ,
. , . , ASP.NET 2.0
, .
ASP.NET, , , , .
ASP.NET 2.0 , .
?
ASP.NET 2.0? , , , , , ASP.NET 2.0
, . , ,
.
, ASP.NET 1.x,
cookie.
cookie , . cookie
, . ( , ,
.) ,
.
, ,
, ,
ASP.NET 2.0.
(,
. .) .
, ,
.
,
cookie: API, , .
,
. ,
,
.


ProviderBase , ,
Initialize, : Name Description. , . .

Initialize :
public virtual void Initialize(string name, NameValueCollection config)

, name, , . -

ASP.NET

165

. config null
, .
if (config == null)
throw new ArgumentNullException("Null configuration parameters");

Initialize , , name
null :
if (String.IsNullOrEmpty(name))
name = "CookieProfileProvider";

. name web.config,
. Initialize .
. ,
, cookie,
cookie-.
_cookieName = config["cookieName"];
if (String.IsNullOrEmpty(_cookieName))
_cookieName = ".PROF";
config.Remove("cookieName");

config.
,
. , -, .
,
, .
! ,
API, , Initialize . ,
. ,
, Initialize.
, Providers,
, Membership, ProfileManager
Roles. Initialize ,
Initialize, .

, . ,
, - ,
.
,
.
, , ,
. ,
(thread-safe).
Initialize ProviderBase
, . lock.

166

ASP.NET

API . .
.NET Framework , , , . , , ArgumentException,
NotImplementedException NullReferenceException.
.NET Framework ProviderException, . , .
, .

, cookie
( CookieProfileProvider) cookie. cookie- ,
,
. , ,
web.config, -,
Base64. ,
. ,
.

CookieProfileProvider ProfileProvider, ,
, SettingsProvider. , ,
. 4-3.
. 4-3.

DeleteInactiveProfiles

SettingsProvider

DeleteProfiles

SettingsProvider

FindInactiveProfilesByUserName

SettingsProvider

FindProfilesByUserName

SettingsProvider

GetAllInactiveProfiles

SettingsProvider

GetAllProfiles

SettingsProvider

GetNumberOfInactiveProfiles

SettingsProvider

GetPropertyValues

ProfileProvider

Initialize

ProviderBase

SetPropertyValues

ProfileProvider

ASP.NET

167

,
SettingsProvider. not supported:
public override int DeleteProfiles(string[] usernames)
{
throw new NotSupportedException();
}

: ApplicationName (),
CookieName CookieExpires.
public class CookieProfileProvider : ProfileProvider
{
private string _cookieName;
private int _cookieExpires;
private string _appName;
public CookieProfileProvider()
{}
public override string ApplicationName
{
get { return _appName; }
set { _appName = value; }
}
public virtual string CookieName
{
get { return _cookieName; }
set { _cookieName = value; }
}
public virtual int CookieExpires
{
get { return _cookieExpires; }
set { _cookieExpires = value; }
}
}
Initialize

cookieName
cookieExpires .
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("Null configuration parameters");
// ,
if (String.IsNullOrEmpty(name))
name = "CookieProfileProvider";
//
base.Initialize(name, config);
//
_appName = config["applicationName"];

168

ASP.NET

if (String.IsNullOrEmpty(_appName))
_appName = HostingEnvironment.ApplicationVirtualPath;
config.Remove("applicationName");
// cookie
_cookieName = config["cookieName"];
if (String.IsNullOrEmpty(_cookieName))
_cookieName = ".PROF";
config.Remove("cookieName");
// cookie
bool success = Int32.TryParse(config["cookieExpires"],
out _cookieExpires);
if (!success)
_cookieExpires = 10;
config.Remove("cookieExpires");
// ,
if (config.Count > 0)
{
string attrib = config.GetKey(0);
if (!String.IsNullOrEmpty(attrib))
throw new ProviderException("Unrecognized attribute: " + attrib);
}
}
GetPropertyValues

GetPropertyValues .
.
ASP.NET
, . , GetPropertyValues, ,
.
, <profile>
web.config,
. . :
public override SettingsPropertyValueCollection GetPropertyValues(
SettingsContext context,
SettingsPropertyCollection properties)
{
SettingsPropertyValueCollection settings;
settings = new SettingsPropertyValueCollection();
// ,
if (properties.Count == 0)
return settings;
// ,
//
// Profile , null
foreach (SettingsProperty property in properties) {
SettingsPropertyValue pv = new SettingsPropertyValue(property);
settings.Add(pv);
}

ASP.NET

169

// cookie ( )
string username = (string)context["UserName"];
string cookie = CookieName + "_" + username;
HttpCookie cookieProfile = HttpContext.Current.Request.Cookies[cookie];
if (cookieProfile == null)
return settings;
// Base64
string data = cookieProfile["SerializedData"];
byte[] bits = Convert.FromBase64String(data);
Hashtable table = null;
using(MemoryStream mem = new MemoryStream(bits)
{
BinaryFormatter bin = new BinaryFormatter();
table = (Hashtable) bin.Deserialize(mem);
mem.Close();
}
//
foreach (SettingsPropertyValue spv in settings) {
//
spv.Deserialized = true;
spv.PropertyValue = table[spv.Name];
}
return settings;
}

for ... each ,


. ,
: false
, 0 . . , settings, Profile (
null).
cookie -, , .
cookie .
SetPropertyValues
SetPropertyValues
. ,
, .
SettingsContext -. ASP.NET, , ProfileBase, .
SetPropertyValues : UserName IsAuthenticated; , , ,
.
-. ,
. -
Base64. cookie- SerializedData.
public override void SetPropertyValues(SettingsContext context,
SettingsPropertyValueCollection properties)

170

ASP.NET

{
//
string username = (string)context["UserName"];
bool authenticated = (bool)context["IsAuthenticated"];
// ,
if (String.IsNullOrEmpty(username) || properties.Count == 0)
return;
// cookie
string cookie = CookieName + "_" + username;
HttpCookie cookieProfile = HttpContext.Current.Request.Cookies[cookie];
if (cookieProfile == null)
cookieProfile = new HttpCookie(cookie);
cookieProfile.Expires = DateTime.Now.AddMinutes(CookieExpires);
//
Hashtable table = new Hashtable();
foreach (SettingsPropertyValue pp in properties)
{
if (!authenticated &&
!(bool)pp.Property.Attributes["AllowAnonymous"])
continue;
table.Add(pp.Name, pp.PropertyValue);
}
// - cookie
BinaryFormatter bin = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
bin.Serialize(mem, table);
string data = Convert.ToBase64String(mem.GetBuffer(), 0,
(int) mem.Length);
cookieProfile["SerializedData"] = data;
// cookie
HttpContext.Current.Response.AppendCookie(cookieProfile);
}


HttpContext.Profile. ProfileCommon. .NET Framework,
<properties> <profile> web.config. ProfileCommon ,
<properties>. ,
ProfileCommon. . 4-4 , , <add>. (
3.)
. 4-4. , <add>

allowAnonymous

.
false

defaultValue

customProviderData

ASP.NET

171

. 4-4. ()

name
provider
readOnly



, .
false
. : Xml,
Binary, String ProviderSpecific
.NET Framework,

serializeAs
type

, ProfileCommon, readOnly type. . ProfileCommon .NET


Framework ProfileBase. ,
. SettingsBase.
GetPropertyValues SetPropertyValues.
web.config. SettingsProperty,
, . 4-4. GetPropertyValues SetPropertyValues
SettingsProperty
. . 4-8
.

. 4-8.

ProfileBase , Create Save,


, . Create GetPropertyValues. Save
SetPropertyValues.
SetPropertyValues, ,
. SettingsPropertyValue.
. 4-5.
. 4-5. SettingsPropertyValue

Deserialized

, . ,
false, ASP.NET , , SerializeAs
SettingsProperty. ,
true.

(. . .)

172

ASP.NET

. 4-5. ()

IsDirty
Name
Property
PropertyValue
SerializedValue

,

SettingsProperty
, ,
.
SerializeAs SettingsProperty
UseDefaultValue ,

, . , ,
IsDirty.
, web.config
. , , UseDefaultValue.
, .
, ; ,
. , , .
.
Deserialized, ,
: true, PropertyValue, false, SerializedValue.
Deserialized true, PropertyValue
null, , null.
,
, .
, ?
. ,
Profile
. ,
.

ApplicationName, .
. ,
, SQL Server, .
, . , MDF,
Web-.
, cookie, .


,
, .

ASP.NET

173

, , . .
<anonymousIdentification enabled="true" />
<profile enabled="true" defaultProvider="CookieProfileProvider">
<properties>
<add name="BackColor" allowAnonymous="true"
type="string" />
<add name="ForeColor"
type="string" allowAnonymous="true"/>
<add name="Links" allowAnonymous="true"
type="System.Collections.Specialized.StringCollection"
serializeAs="Xml" />
</properties>
<providers>
<clear />
<add name="CookieProfileProvider"
type="ProAspNet20.CS.Components.CookieProfileProvider,
ProAspCompLib" />
</providers>
</profile>

, ,
. ,
. ,
. ,
Forms . ASP.NET . , ,
5 Programming Microsoft ASP.NET 2.0:
Core Reference (Microsoft Press, 2005).
,
. Profile
.

, . ,
, . ,
, <appSettings> web.config.
,
.
AppSettingsManager.
AppSettings, .
,
AppSettingsManager.AppSettings.
get AppSettings
, (, GetValues)
.
,
, .

174

ASP.NET

GetValues.
, .
, web.config.
,
.
,
.


; ,
.
, ,
.
ASP.NET ,
, , .

, ASP.NET . , ,
. ,
, .

, .

(, , )
, .


ASP.NET ,
, .

ASP.NET 2.0 , .

,
, .
ProviderBase.

- .

, , Web-, cookie . .

ASP.NET aspnetdb.mdf SQL Server 2005 Express.

. ,
.

ASP.NET , ,
- .
, , Web-.

ASP.NET . HTTP
ASP.NET 1.0, ASP.NET 2.0 . , ,
.
,
ASP.NET 2.0, . , ? ASP.NET 1.x ASP- . , , ASP.NET 2.0,
, .
ASP.NET
, .
, .

, ,
ASP.NET.


2 , ASP.NET.
.
ASP.NET , ASP.NET. HTTP,
, web.config. HTTP
, IHttpHandler,
ProcessRequest, , , .
ProcessRequest .
?
,
.
, ,
.
,
.

176

ASP.NET

. ASP.NET 1.x
.NET Framework
HTTP, , .
ASP.NET 2.0 ,
.

ASP.NET
,
ASP.NET .
, , , .
. appRequestQueueLimit <httpRuntime>.
,
, 503 Server too busy. ASP.NET 1.x 100, ASP.NET 2.0
5000.
, ,
HTTP,
. , , , ,
.
Server too busy.
, , , , ,
. .
, Web-, ,
.
, ,
, .
, .

IHttpAsyncHandler

ASP.NET HTTP . .
,
. ProcessRequest , IHttpAsyncHandler;
. 5-1
. 5-1. IHttpAsyncHandler

BeginProcessRequest .

EndProcessRequest

, HTTP IHttpHandler IHttpAsyncHandler. , ASP.NET

177

, IHttpAsyncHandler, IHttpHandler.
HttpRuntime, ASP.NET, , (. 1).
BeginProcessRequest

BeginProcessRequest :
IAsyncResult BeginProcessRequest(
HttpContext context,
AsyncCallback cb,
object extraData);

context HTTP. ,
, Request Response.
AsyncCallback, ,
. , extraData, , ,
.
BeginProcessRequest
, , Web-,
.
, .
, BeginProcessRequest, ,
IAsyncResult, , ,
.
IAsyncResult?
IAsyncResult

, IAsyncResult . , . .
BeginRead FileStream. ,
IAsyncResult, , , , EndRead FileStream.
, IAsyncResult,
, .
EndProcessRequest

EndProcessRequest ,
, . :
void EndProcessRequest(IAsyncResult result);

IAsyncResult ,
BeginProcessRequest.
! BeginProcessRequest ,
HTTP.
HttpContext.Current null.

. ,

178

ASP.NET

. ASP.NET 1.x , ASP.NET 2.0 ,


. .aspx.
HTTP,
, ASP.NET 1.x. ASP.NET 2.0 2.

ASP.NET 1.x MSDN Magazine 2003
: http://msdn.microsoft.com/msdnmag/issues/03/06/Threading.

ASP.NET 2.0
@Page
, . : Begin End PreRenderComplete PageAsyncTask,
.
PreRenderComplete PreRender.
Page_Load AddOnPreRenderCompleteAsync Page.
, RegisterAsyncTask
PageAsyncTask, ,
.

, . .
ASP.NET - ,
Page. ,
.

Async

Asynk @Page .
false.
<%@ Page Async="true" ... %>

Async .
, .aspx, IHttpAsyncHandler. Async
PreRenderComplete.
.
TestAsync.aspx, Async.
ASP.TestAsync_aspx
:
public class TestAsync_aspx : TestAsync, IHttpAsyncHandler
{
}

179

TestAsync . Page , Page. IHttpAsyncHandler, ,


ASP.
NET 1.0. .
AddOnPreRenderCompleteAsync

AddOnPreRenderCompleteAsync
PreRenderComplete , , Begin End:
AddOnPreRenderCompleteAsync (
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask)
);

BeginEventHandler EndEventHandler ,
:
IAsyncResult BeginEventHandler(
object sender,
EventArgs e,
AsyncCallback cb,
object state)
void EndEventHandler(
IAsyncResult ar)

AddOnPreRenderCompleteAsync,
, , PreRender.
Page_Load.
.
AddOnPreRenderCompleteAsync
Page_Load, . ,
, . ,
.
,
.
, , Page_Load
AddOnPreRenderCompleteAsync ,
.

Begin ,
. IAsyncResult,
. End
. , ,
IAsyncResult.
, IAsyncResult.
! Begin End
, . . ASP.NET Begin End
,
: Begin End. Begin ,
ASP.NET, End ,
.

180

ASP.NET

PreRenderComplete.
. ASP.NET
Begin, ,
.
,
, PreRenderComplete.
End, ,
.
PreRenderComplete

, ,
PreRenderComplete, , PreRenderComplete.
: ,
PreRenderComplete?
ASP.NET 2.0 , (async point).
PreRender PreRenderComplete.
PreRender, .
PreRenderComplete . ,
. PreRenderComplete.
, .
RegisterAsyncTask

AddOnPreRenderCompleteAsync .
RegisterAsyncTask. void PageAsyncTask.
PageAsyncTask , . ( RegisterAsyncTask .)

. ,
, RSS- .
:
<%@ Page Async="true" Language="C#" AutoEventWireup="true"
CodeFile="TestAsync.aspx.cs" Inherits="TestAsync" %>
<html>
<body>
<form id="form1" runat="server">
<% = rssData %>
</form>
</body>
</html>

:
public partial class TestAsync : System.Web.UI.Page
{

const string RSSFEED = "http://weblogs.asp.net/despos/rss.aspx";


private WebRequest req;
public string rssData;
void Page_Load (object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync (
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask));
}
IAsyncResult BeginTask(object sender,
EventArgs e, AsyncCallback cb, object state)
{
//
Trace.Warn("Begin async: Thread=" +
Thread.CurrentThread.ManagedThreadId.ToString());
// Web- RSS-
req = WebRequest.Create(RSSFEED);
// IAsyncResult
return req.BeginGetResponse(cb, state);
}
void EndTask(IAsyncResult ar)
{
//
string text;
using (WebResponse response = req.EndGetResponse(ar))
{
StreamReader reader;
using (reader = new StreamReader(response.GetResponseStream()))
{
text = reader.ReadToEnd();
}
// RSS
rssData = ProcessFeed(text);
}
//
Trace.Warn("End async: Thread=" +
Thread.CurrentThread.ManagedThreadId.ToString());
// ASP-
// ASPX, rssData
}
string ProcessFeed(string feed)
{
// XML-
}
}

181

182

ASP.NET

, , , RSS (Really Simple Syndication


) . RSS XML, XML
W3C. RSS
http://blogs.law.harvard.edu/tech/rss.

, Async Page . . 5-1 .

. 5-1.

,
(. 5-2). Begin End .

. 5-2.

183

, , Exit BeginTask Enter EndTask,


. ,
RSS. , , .
,

? .
: -. ,
, ,
.
,
,
. .
ASP.NET,
, ,
. ,
- .
, -,
.
Web-
.
,
(, , ,
),
, .
, , , -,
- , .


,
ASP.NET 2.0, .
, .
, Async
. , ASP.NET
IHttpAsyncHandler,
ASP.NET . HTTP , HTTP
, :
// ProcessRequest HttpRuntime (. 1)
if (requestHandler is IHttpAsyncHandler)
{
// completionCallback ,
// (PreRenderComplete)

184

ASP.NET

ctx.AsyncAppHandler = requestHandler;
requestHandler.BeginProcessRequest(ctx, completionCallback, ctx);
}
else
{
requestHandler.ProcessRequest(context1);
FinishRequest(ctx.WorkerRequest, ctx, null);
}

Async true,
, . PreRenderComplete ,
BeginProcessRequest , . .


Async ; ,
.

Async=true , .

, ,
.
, .
.

IHttpAsyncHandler,
ASP.NET.
IHttpAsyncHandler

1 , . , ,
TestAsync.aspx:
public virtual IAsyncResult BeginProcessRequest(
HttpContext context, AsyncCallback cb, object data)
{
return base.AsyncPageBeginProcessRequest(context, cb, data);
}
public virtual void EndProcessRequest(IAsyncResult ar)
{
base.AsyncPageEndProcessRequest(ar);
}

AsyncPageBeginProcessRequest ASP.NET 2.0.


.
,
, PreRenderComplete. , AsyncPageBeginProcessRequest
.
(async point) (unwind point)
, . , ,
: .

185

AsyncPageBeginProcessRequest
WaitCallback :
private void AsyncPageProcessRequestBeforeAsyncPoint(object state)
{
this.ProcessRequest(true, false);
}

ProcessRequest
Page, . , ? ,
, PreRender.
ProcessRequest:
void ProcessRequest(
bool includeStagesBeforeAsyncPoint,
bool includeStagesAfterAsyncPoint)

?
. ProcessRequest ,
.
AsyncPageBeginProcessRequest .
,
. , Begin. , RegisterAsyncTask,
ExecuteRegisteredAsyncTasks Page,
.
AsyncPageEndProcessRequest ,
, , . . 5-3
.

. 5-3.

186

ASP.NET

, .

IHttpAsyncHandler ASP.NET , .
.
 HttpRuntime BeginProcessRequest .
ASP.NET. .
 .
, , PreRender .

-. Begin , IAsyncResult. ,
, .
 , , ,
. .
 , ,
End,
. ,
.
 .
,
. ,
HttpRuntime.
 HttpRuntime EndProcessRequest
. , .
 , HTTP ,
EndRequest.
. 5-4
.
, , , . ,
.
HttpRuntime, Begin End .

.
. ,
,
.
private void OnHandlerCompletion(IAsyncResult ar)
{
// HttpRuntime
// .
// ,

//
HttpContext ctx = (HttpContext) ar.AsyncState;
try {
ctx.AsyncAppHandler.EndProcessRequest(ar);
}
catch (Exception ex) {
//
}
finally {
//
ctx.AsyncAppHandler = null;
}
//
FinishRequest(ctx.WorkerRequest, ctx, ctx.Error);
}

. 5-4.

187

188

ASP.NET

EndProcessRequest AsyncPageEndProcessRequest . FinishRequest


HttpRuntime. , .
.
.

.
. , .


, .
Web-

Web- ASP.NET, Web- WSDL


(Web Service Description Language Web-).
WSDL- -,
Web-. - Web-
Web- Begin-End,
.
, Web-:
private MyWeatherService weather;
private int temperature;
IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)
{
weather = new MyWeatherService();
return weather.BeginGetTemperature(cb, state);
}
void EndTask(IAsyncResult ar)
{
temperature = weather.EndGetTemperature(ar);
}

BeginTask EndTask PreRenderComplete.



PreRenderComplete, . PreRenderComplete
End-.

- Web-, ASP.NET 2.0,


Web-. Web- ASP.NET 2.0.
- xxxAsync
xxxCompleted. :
private MyWeatherService weather;
private int temperature;

189

//
protected void OnQueryWeather(object sender, EventArgs e)
{
// - Web-
weather = new MyWeatherService();
// xxxCompleted
GetTempCompletedEventHandler hdlr;
hdlr = new GetTemperatureCompletedEventHandler(GetTemperatureCompleted);
weather.GetTemperatureCompleted += hdlr;
// Web-
weather.GetTemperatureAsync(...);
}
void GetTemperatureCompleted(object s, GetTemperatureCompletedEventArgs e)
{
// , e.Result
}

? , - .
, xxxAsync . - , .
Begin-End
PreRenderComplete . ,
IAsyncResult
( AsyncWaitHandle ) WaitHandle.WaitAll.
,
xxxAsync ASP.NET .
xxxAsync ,
, MethodCompleted,
, , End
PreRenderComplete. , , HTTP ASP.NET, Server Response.

, .
Web- , . 3, ASP.NET
, , Web. minLocalRequestFreeThreads <httpRuntime>.
Web-, ,
. ,
Web-.
.

Web-,

Web- ,
Web- , . End .

190

ASP.NET

, ASP.NET 2.0. End (null),


. , ,
End Web- OneWay=true,
, -.
, ,
. Web- OneWay,
HTTP 202, .
Web-, OneWay, void
. ,
ASP.NET IIS .

.NET Framework 2.0 Microsoft SQL Server .NET


. SqlCommand
, ,
XML .
, ,
, , , . ADO.NET ,
. ,
ADO.NET TCP overlapped-
-.

ASP.NET, ,
. ASP.NET 1.x , ASP.NET 2.0 , . ,
,
, , .
Microsoft Windows,
ASP.NET. , ASP.NET 1.x
.
ASP.NET 2.0 , .
, .

PreRenderComplete:
void Page_Load (object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask));
}

, ,
BeginTask:
SqlConnection conn;
IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)

191

{
// (Utils.TraceThread ,
// )
Utils.TraceThread("Enter BeginTask");
//
conn = new SqlConnection(GetConnectionString("LocalNWind"));
// :
cmd = new SqlCommand("SalesByCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@CategoryName",
SqlDbType.NVarChar, 15).Value = "Seafood";
cmd.Parameters.Add("@OrdYear",
SqlDbType.Int).Value = 1997;
//
conn.Open();
IAsyncResult ar = cmd.BeginExecuteReader(cb, state);
Utils.TraceThread("Command started");
//
Utils.TraceThread("Exit BeginTask");
return ar;
}
string GetConnectionString(string cnEntry)
{
string cs;
cs = ConfigurationManager.ConnectionStrings[cnEntry].ConnectionString;
return cs + ";Asynchronous Processing=true;";
}

, BeginExecuteReader
, ASP.NET. IAsyncResult, ADO.NET
.
, :
void EndTask(IAsyncResult ar)
{
using(SqlDataReader reader = cmd.EndExecuteReader(ar))
{
if (!reader.Read())
return;
// GridView1
GridView1.DataSource = reader;
GridView1.DataBind();

192

ASP.NET

//
reader.Close();
conn.Close();
}
}
! BeginExecuteReader . , , Begin .
BeginExecuteReader ,
.

EndTask .
. 5-5.

. 5-5.

. , .
, Asynchronous Processing. -,
, .
-, BeginTask ,
:
public static void TraceThread(string msg)
{
string displayThread = "Thread=" +
Thread.CurrentThread.ManagedThreadId.ToString();

193

HttpContext.Current.Trace.Warn(displayThread, msg);
}

, , Trace
HttpContext.Current. ,

PreRenderComplete, , End, HttpContext.Current, , Begin.
Microsoft Visual Studio 2005,

. , ,
When Hit.
,
, , , .
.
, , Output Visual
Studio 2005.

AddOnPreRenderCompleteAsync,
Begin End.
. ,
AddOnPreRenderCompleteAsync . :
void Page_Load (object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginTask1),
new EndEventHandler(EndTask1));
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginTask2),
new EndEventHandler(EndTask2));
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginTask3),
new EndEventHandler(EndTask3));
}


. - ? , .
Page_Load
Begin-End, , Output Visual Studio 2005
( ,
):
Page_Load(object, EventArgs), Thread: 0x230
BeginTask1(object, EventArgs, AsyncCallback, object), Thread: 0x230
EndTask1(IAsyncResult), Thread: 0x1228
BeginTask2(object, EventArgs, AsyncCallback, object), Thread: 0x1228
EndTask2(IAsyncResult), Thread: 0x230

194

ASP.NET

BeginTask3object, EventArgs, AsyncCallback, object), Thread: 0x230


EndTask3(IAsyncResult), Thread: 0xD78

? , . , ,
.
- , , . ,
?
, , . :
void Page_Load (object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask));
}
IAsyncResult BeginTask(object sender, EventArgs e,
AsyncCallback cb, object state)
{
//
//
}
void EndTask(IAsyncResult ar)
{
//
//
}

. IAsyncResult, .
, Begin; .
IAsyncResult ASP.NET,
.
, IAsyncResult

,
IAsyncResult, ,
. ,
. :
public class CompositeAsyncResult : IAsyncResult
{
AsyncCallback _cb;
object _state;
AsyncCallback _completionCallBack;
int _pendingOperations;

// volatile ,
//
// ,
volatile bool _allCompletedSynchronously;
// Ctor
public CompositeAsyncResult(AsyncCallback cb, object state, int count)
{
_cb = cb;
_state = state;
_pendingOperations = count;
_allCompletedSynchronously = true;
_completionCallBack = new AsyncCallback(this.CompletionCallback);
}
//
public AsyncCallback Callback
{
get { return _completionCallBack; }
}
//
public void CompletionCallback(IAsyncResult ar)
{
// ,
//
if (!ar.CompletedSynchronously)
_allCompletedSynchronously = false;
// ,
if (Interlocked.Decrement(ref _pendingOperations) == 0)
{
// ; ASP.NET
_cb(this);
}
}
// , ctor
object IAsyncResult.AsyncState
{
get { return _state; }
}
// wait-handle,
WaitHandle IAsyncResult.AsyncWaitHandle
{
get { return null; }
}
// ,
bool IAsyncResult.CompletedSynchronously
{
get { return (_pendingOperations == 0) &&
_allCompletedSynchronously; }
}

195

196

ASP.NET

// ,
bool IAsyncResult.IsCompleted
{
get { return (_pendingOperations == 0); }
}
}

ASP.NET, , .
,
. ,
. ,
ASP.NET. ,
, .
Begin
RSS-.
void Page_Load (object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync (
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask));
}
IAsyncResult BeginTask(object sender, EventArgs e,
AsyncCallback cb, object state)
{
// AsyncResult
CompositeAsyncResult ar = new CompositeAsyncResult(cb, state, 2);
//
req1 = WebRequest.Create(RSSFEED1);
ar1 = req1.BeginGetResponse(ar.Callback, state);
//
req2 = WebRequest.Create(RSSFEED2);
ar2 = req2.BeginGetResponse(ar.Callback, state);
return ar;
}
void EndTask(IAsyncResult ar)
{
string text;
WebResponse response;
StreamReader reader;
using (response = req1.EndGetResponse(ar1))
{
using (reader = new StreamReader(response.GetResponseStream())) {
text = reader.ReadToEnd();
}
rssData += ProcessFeed(text);
}
using (response = req2.EndGetResponse(ar2))
{
using (reader = new StreamReader(response.GetResponseStream())) {

197

text = reader.ReadToEnd();
}
rssData += ProcessFeed(text);
}
}

, , ,
RegisterAsyncTask. .
Begin

,
-, .NET Framework,
BeginGetResponse WebRequest.
, ?
BeginInvoke EndInvoke:
public partial class MultiTaskAsync : System.Web.UI.Page
{
protected delegate void AsyncTaskDelegate();
private AsyncTaskDelegate _func;
void Page_Load(object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync( new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask));
}
IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)
{
_func = new AsyncTaskDelegate(DoTheAsyncTask);
IAsyncResult result = _func.BeginInvoke(cb, state);
return result;
}
public void DoTheAsyncTask()
{
// , ,
// : Thread.Sleep(10000);
}
void EndTask(IAsyncResult ar)
{
_func.EndInvoke(ar);
}
}
! Page,
AsyncMode .
, .
Async @Page.
, . IsAsync.
, IHttpAsyncHandler;
, HTTP .
, .

198

ASP.NET

AsyncMode ,
IsAsync, ,
Async @Page.
RegisterAsyncTask

RegisterAsyncTask
, ASP.NET. ,
API, . , Async @Page false.
RegisterAsyncTask , .

. ,
, PreRender.

, ,
RSS, RegisterAsyncTask.
void Page_Load (object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask),
null,
null);
RegisterAsyncTask(task);
}

RegisterAsyncTask PageAsyncTask.
:
public PageAsyncTask(
BeginEventHandler beginHandler,
EndEventHandler endHandler,
EndEventHandler timeoutHandler,
object state,
bool executeInParallel)

beginHandler endHandler ,
, AddOnPreRenderCompleteAsync.
RegisterAsyncTask - ,
.
timeoutHandler , , , 45 .
- , @Page.
:
<system.web>
<pages asyncTimeout="30" />
</system.web>

@Page, AsyncTimeout,
.

199

, AddOnPreRenderCompleteAsync,
, . state .

:
void Page_Load (object sender, EventArgs e)
{
PageAsyncTask task1 = new PageAsyncTask(
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask),
null,
RSSFEED1,
true);
PageAsyncTask task2 = new PageAsyncTask(
new BeginEventHandler(BeginTask),
new EndEventHandler(EndTask),
null,
RSSFEED2,
true);
RegisterAsyncTask(task1);
RegisterAsyncTask(task2);
}
public IAsyncResult BeginTask(object sender, EventArgs e,
AsyncCallback cb, object state)
{
// Web-
string blog = (string) state;
req = WebRequest.Create(blog);
//
IAsyncResult obj = req.BeginGetResponse(cb, state);
return obj;
}


-.
RssFeedAsyncReader, RSS:
public class RssFeedAsyncReader
{
private WebRequest _req;
private string _rssData;
private string _blogUrl;
public RssFeedAsyncReader(string blog)
{
_blogUrl = blog;
}
public IAsyncResult BeginRead(object sender, EventArgs e,
AsyncCallback cb, object state)
{
// Web-
_req = WebRequest.Create(_blogUrl);

200

ASP.NET

//
IAsyncResult obj = _req.BeginGetResponse(cb, state);
return obj;
}
public void EndRead(IAsyncResult ar)
{
string text;
using (WebResponse response = _req.EndGetResponse(ar))
{
StreamReader reader;
using (reader = new StreamReader(response.GetResponseStream()))
{
text = reader.ReadToEnd();
}
// RSS
_rssData = ProcessFeed(text);
}
}
private string ProcessFeed(string feed)
{
}
public string GetRssData()
{
return _rssData;
}
}

, . -. ,
, . (RssAsync.aspx)
, :
public partial class RssAsync : System.Web.UI.Page
{
const string RSSFEED1 = "http://weblogs.asp.net/despos/rss.aspx";
const string RSSFEED2 = "http://blogs.ugidotnet.org/dinoes/rss.aspx";
RssFeedAsyncReader rss1, rss2;
public string rssData;
void Page_Load (object sender, EventArgs e)
{
// PreRenderComplete
PreRenderComplete += new EventHandler(RssAsync_PreRenderComplete);
//
rss1 = new RssFeedAsyncReader(RSSFEED1);
rss2 = new RssFeedAsyncReader(RSSFEED2);

201

//
PageAsyncTask task1 = new PageAsyncTask(
new BeginEventHandler(rss1.BeginRead),
new EndEventHandler(rss1.EndRead),
null,
null,
true);
PageAsyncTask task2 = new PageAsyncTask(
new BeginEventHandler(rss2.BeginRead),
new EndEventHandler(rss2.EndRead),
null,
null,
true);
//
RegisterAsyncTask(task1);
RegisterAsyncTask(task2);
}
void RssAsync_PreRenderComplete(object sender, EventArgs e)
{
// ,
//
rssData = rss1.GetRssData() + rss2.GetRssData();
}
}

, , , ,
. , .
. 5-6 .

. 5-6. RSS

202

ASP.NET

, RegisterAsyncTask,
ExecuteRegisteredAsyncTasks Page. Page ,
:
//
// ProcessRequest Page
// PreRender
//
this.PreRenderRecursiveInternal();
//
if (this._asyncInfo == null)
this.ExecuteRegisteredAsyncTasks();
// : ,
//
if (!includeStagesAfterAsyncPoint)
return;
//
// . PreRenderComplete
//
this.PerformPreRenderComplete();

ExecuteRegisteredAsyncTasks ,
,
.
RegisterAsyncTask

AddOnPreRenderCompleteAsync , Async, .
RegisterAsyncTask, , .
RssAsync.aspx Async @Page false.
:
Page_Load(object, EventArgs), Thread: 0x230
BeginRead(object, EventArgs, AsyncCallback, object), Thread: 0x230
BeginRead(object, EventArgs, AsyncCallback, object), Thread: 0x230
EndRead(IAsyncResult), Thread: 0x1718
EndRead(IAsyncResult), Thread: 0x1228
RssAsync_PreRenderComplete(object, EventArgs), Thread: 0x230

, 0x230 , ,
.
BeginRead,
.

203

AddOnPreRenderCompleteAsync,
RegisterAsyncTask?
.
. ?
. RegisterAsyncTask API,
. AddOnPreRenderCompleteAsync API, .
. , RegisterAsyncTask End
, AddOnPreRenderCompleteAsync.
HTTP.
, RegisterAsyncTask ,
.
, RegisterAsyncTask
.
,
IAsyncResult.
: ,
,
RegisterAsyncTask.


ASP.NET , .
? ASP.NET
, ASP.NET,
<% ... %>.
ASP.NET 1.x ,
ASP, , . ASP.NET 2.0
,
.

ASP-
ASP , <% ... %>. ,
ASP, , ,
, , .
ASP , , ( ).
ASP

ASP.NET , .
, .
<% ... %> .

204

ASP.NET

ASP
, , ,
. ,
.
ASP.NET , ASP.NET
.

ASP (inline)
.
Response.Write :
<% x = 1 %>
<% = x %>

; , x.
ASP.NET

ASP.NET ASP, , , .
, ASP.NET 2.0
.
ASP.NET ,
.
, . :
<form id="Form1" runat="server">
<% for (int i=0; i<8; i++) %>
<% { %>
<font size="<%=i %>">
I <b style="font-family:Webdings;color:Red">Y</b>
this book!
</font><br>
<% } %>
</form>

. 5-7.

. 5-7. ASP.NET,
ASP-

205


, Form1.
form <head>,
runat=server. , ,
. , Control. ( Control
Page.) Control? ,
, SetRenderMethodDelegate.
, , , SetRenderMethodDelegate.
, . (
, 1.)
HtmlForm BuildControlForm1()
{
HtmlForm ctrl = new HtmlForm();
form1 = ctrl;
ctrl.ID = "Form1";
//
//
//
ctrl.SetRenderMethodDelegate(new RenderMethod(RenderForm1));
return ctrl;
}
void RenderForm1(HtmlTextWriter w, Control parameterContainer)
{
for (int i=1; i<8; i++)
{
w.Write("<font size=\"");
w.Write(i);
w.Write("\">" + I
"<b style=\"font-family:Webdings;color:Red\">Y</b> " +
"this book! </font><br>");
}
}

, RenderControl
.
, .
ASP.NET

ASP.NET
. , :
<asp:Button runat=server id="Button1" Text=<% =GetText() %> />

, .
, , <% ... %>. ,

206

ASP.NET

SetRenderMethodDelegate,
,
.
ASP ,
.
ASP.NET .
:
?
.


, ASP.NET 1.x , (data-binding
expressions). :
<form id="form1" runat="server">
<h2>Today is
<asp:Label ID="Today" runat="server" Text="<%# DateTime.Now %>" />
</h2>
</form>

Text Label
, .

#.
#-.

# . ASP.NET
DataBinding. (
), ASP.NET:
Label BuildControlToday()
{
Label ctrl = new Label();
this.Today = ctrl;
ctrl.ApplyStyleSheetSkin(this);
ctrl.ID = "Today";
ctrl.DataBinding += new EventHandler(DataBindingToday);
return ctrl;
}
void DataBindingToday(object sender, EventArgs e)
{
Label target = (Label) sender;
Control container = (Control) target.BindingContainer;
target.Text = Convert.ToString(DateTime.Now,
CultureInfo.CurrentCulture);
}

DataBindingToday DataBinding Text.

207

, ,
. ,
. , , ,
( ).
Page
.
!
DataBind. . , .

ASP.NET 2.0 , . .
, , , , ,
, . , , , ,
, . .
,
, Programming Microsoft ASP.NET 2.0:
Core Reference (Microsoft Press, 2005).

,
DataBind. , ,

GridView DetailsView. ,
, ,
, ,
DataBind?
, , . DataBind ,
, , . ,
, ,
. #-
.
#- , , DataBind. ,
, . .
#- ,


DataBinding,
. , ?

208

ASP.NET

:
<asp:SqlDataSource id="MySource" runat="server"
ConnectionString=<% #ConfigurationManager.ConnectionStrings[...] %>
/>
<asp:GridView id="grid" runat="server" datasourceid="MySource" />

DataBind Page_Load,
. DataBind, ConnectionString SqlDataSource. GridView ,
, , .
,
GridView SqlDataSource. DataBind ,
. GridView,
,
SqlDataSource. , SqlDataSource ,
. .
, , . ASP.NET 2.0
. $-.
, . , , Page_Load.
,
, ASP.NET.

ASP.NET 2.0

, . , , ,
#-.
DataBinding. $-
, .
ExpressionBuilder. CodeDOM. ; . 5-2.
. 5-2.

AppSettings:[]


<appSettings>

ConnectionStrings:[].[]


<appSettings>

Resources:[_],[_]

209

:
<%$ : %>
, . (:) .
$ConnectionStrings

.
$- ConnectionStrings; , :
<connectionStrings> . :
<%$ ConnectionStrings:LocalNWind.ConnectionString %>

LocanNWind <connectionStrings>
connectionString.
:
<%$ ConnectionStrings:LocalNWind %>

ConnectionString ProviderName. , , .
<asp:SqlDataSource runat="server" id="MySource"
ConnectionString="<%$ ConnectionStrings:LocalNWind %>"
ProviderName="<%$ ConnectionStrings:LocalNWind.ProviderName %>"
/>
$AppSettings

$AppSettings
<appSettings> . appSettings,
. , . , web.config
:
<appSettings>
<add key="AppVersionNumber" value="8.2.2001" />
</appSettings>
<% $AppSettings:AppVersionNumber %> value. :
<asp:Label runat="server" id="Label1"
Text="<%$ AppSettings:AppVersionNumber %>"
/>
$Resources

$Resources , .resx. Resources;


, ( ) .resx,
. .
<asp:Label runat="server" id="Label1"
Text="<%$ Resources:MyResources, AppTitle %>"
/>

210

ASP.NET

,
. ( ,
, .)
AppTitle MyResources.resx. , $Resources
; .resx,
App_GlobalResources.
,
, , . , ,
, .

Visual Studio 2005.


Expressions,
, ,
(. 5-8).
, .

. 5-8. Visual Studio 2005 Expression Designer

.aspx- ASP.NET 2.0 @Page


CompilationMode=Never. ASP.NET,
( 1).

, ,
. $-
.


: , ExpressionBuilder,
<compilation> .
, Profile.

211

HTTP, Profile . ProfileBase


, <profile> .
Profile . 4 , . API
5 Programming Microsoft ASP.NET 2.0: Core
Reference (Microsoft Press, 2005).
ProfileExpressionBuilder

, ExpressionBuilder,
(. 5-3).
. 5-3. ExpressionBuilder

EvaluateExpression , .
,
SupportsEvaluate true.
EvaluateExpression ,
null
GetCodeExpression CodeDOM,
,
.
ParseExpression

,
.
, .
,
null

SupportsEvaluate

, , . false

GetCodeExpression. , ParseExpression, , ,
. GetCodeExpression CodeDOM,
, .
Profile :
<%$ Profile:_ %>

Profile, _ , . .
[ExpressionPrefix("Profile")]
public class ProfileExpressionBuilder : ExpressionBuilder
{
//
public override object ParseExpression(string expression,
Type propertyType, ExpressionBuilderContext context)
{
return expression;
}
}

212

ASP.NET

[ExpressionPrefix] .
web.config ,
. ParseExpression expression. ,
.
,
. , ,
, ,
(, )
. , ParseExpression,
GetCodeExpression.
public override CodeExpression GetCodeExpression(
BoundPropertyEntry entry,
object parsedData,
ExpressionBuilderContext context)
{
//
// (, parsedData , )
string property = (string) parsedData;
// .
// .
// CodeDOM,
CodePrimitiveExpression prim = new CodePrimitiveExpression(property);
CodeExpression[] args = new CodeExpression[1] { prim };
// CodeDOM,
CodeTypeReferenceExpression refType;
refType = new CodeTypeReferenceExpression(base.GetType());
return new CodeMethodInvokeExpression(refType, "GetProperty", args);
}

GetCodeExpression parsedData,
, ParseExpression. GetCodeExpression CodeDOM,
. :
_._ = __;

CodeDOM-
. CodeDOM
, . CodeDOM, GetProperty. , . GetProperty
ProfileExpressionBuilder. Profile.
public static object GetProperty(string propertyName)
{
return HttpContext.Current.Profile.GetPropertyValue(propertyName);
}

CodeMethodInvokeExpression .
, .
, .

213

. , , - . EvaluateExpression.
. :
,
. CodeDOM- ,
C# Visual Basic .NET.
public override object EvaluateExpression(object target,
BoundPropertyEntry entry,
object parsedData,
ExpressionBuilderContext context)
{
// parsedData , ParseExpression
string propName = (string) parsedData;
return GetProperty(propName);
}
public override bool SupportsEvaluate
{
get { return true; }
}

, SupportsEvaluate,
true, .
$Profile


<expressionBuilders> <compilation> .
<compilation>
<expressionBuilders>
<add expressionPrefix="Profile"
type="ProAspNet20.CS.Components.ProfileExpressionBuilder" />
</expressionBuilders>
</compilation>

web.config, .
web.config .
$Profile

$Profile ASP.NET
. , ,
( 4):
<profile enabled="true">
<properties>
<add name="BackColor" type="string" allowAnonymous="true"/>
<add name="ForeColor" type="string" allowAnonymous="true"/>
<add name="Links"
type="System.Collections.Specialized.StringCollection"
allowAnonymous="true" serializeAs="Xml" />
</properties>
</profile>

214

ASP.NET

<body> :
<body runat="server" bgcolor="<%$ Profile:BackColor %>">
<form id="form1" runat="server">
<asp:DropDownList id="List1" runat="server"
DataSource="<%$ Profile:Links %>" />
</form>
</body>

Links , ,
.
DataBind. (

, .)
.
, , .
<body>
<%$ Profile:CopyrightText %>
</body>

,
. Literal
ASP.NET
. :
<asp:Literal runat="server" Text="<%$ Profile:CopyrightText %>" />

,
.


, ASP.NET ,
. , , .
ASP.NET .
, DataSource :
DropDownList BuildControlList1()
{
DropDownList ctl = new DropDownList();
List1 = ctl;
ctl.ApplyStyleSheetSkin(this);
ctl.ID = "List1";
ctl.DataSource = (object) ProfileExpressionBuilder.GetProperty("Links");
return ctl;
}

GetProperty ProfileExpressionBuilder . CodeDOM,


GetCodeExpression, .

215

ASP.NET
ASP.NET : , . ASP.NET 1.x , PageParser ,
,
. ,
, . :
public static IHttpHandler GetCompiledPageInstance(
string virtualPath,
string inputFile,
HttpContext context)

,
HTTP , Page,
.aspx. PageParser ,
.
ASP.NET 2.0 PageParser ,
ASP.NET 1.x,
. , ,
. ,
,
Microsoft SharePoint, , , ,
.
! , .
, ,
, .
,
, .aspx.

PageParserFilter
ASP.NET 2.0 .
.
PageParserFilter, System.Web.UI.
PageParserFilter , , . , ,
. , ,
,
.

. 5-4 5-5 PageParserFilter.


.
, ,
.

216

ASP.NET

. 5-4. PageParserFilter

AllowBaseType

AllowControl

,
.
,
SharePoint

AllowServerSideInclude

AllowVirtualReference

,
( ,
)

GetCompilationMode

ParseComplete

PreprocessDirective

. ,

. ,
, , ASP.NET ,
.
. 5-5. PageParserFilter

AllowCode

NumberOfControlsAllowed

,
. false, ,
<script> ,

, .
0

NumberOfDirectDependenciesAllowed , .
0
TotalNumberOfDependenciesAllowed

,
. 0

:
public class CustomPageFilter : PageParserFilter
{
public override bool AllowCode {
get { return true; }
}

217

public override int NumberOfControlsAllowed {


get { return 20; }
}
public override int NumberOfDirectDependenciesAllowed {
get { return 10; }
}
public override int TotalNumberOfDependenciesAllowed {
get { return 100; }
}
}

, , ,
.

ASP.NET PageParserFilter
,
. , ,
, web.config:
<pages pageParserFilterType="ProAspNet20.CS.Components._" />

<pages> <system.web>. ,
, , ,
Visual Studio 2005.


,
. , Windows SharePoint
Services .
Web-
. ASP.NET , .
,
,
.

SharePoint
, .
ASP.NET , . , , ASP.NET ,
.
AllowControl, , ,
, . AllowControl :
,
ControlBuilder,

218

ASP.NET

. , .
public class SafeListPageFilter : PageParserFilter
{
private List<Type> _safeControlList;
protected virtual List<Type> SafeControlList
{
get {
if (_safeControlList == null) {
_safeControlList = new List<Type>();
LoadSafeControlList();
}
return _safeControlList;
}
}
public override bool AllowControl(
Type controlType, ControlBuilder builder)
{
return SafeControlList.Contains(controlType);
}
private void LoadSafeControlList()
{
// :
// , XML-, , ,
//
SafeControlList.Add(typeof(System.Web.UI.WebControls.TextBox));
SafeControlList.Add(typeof(System.Web.UI.WebControls.Button));
}
}

Type,
, .
, ,
XML-. , 4,
.
TextBox
Button. ,
(. 5-9).
, , SharePoint ASP.NET. ASP.NET,
.
, . AllowControl true, ,
;
.

219

. 5-9. ,

, ASP.NET,
, . AllowBaseType,
, , .
public virtual bool AllowBaseType(Type baseType)
{
return IsSafeClass(baseType);
}
private bool IsSafeClass(Type classType)
{
//
}

,
.
pageBaseType <pages>
.
AllowBaseType?
,
pageBaseType ,
: .

AllowVirtualReference , . ,
:
public virtual bool AllowVirtualReference(
string virtualPath,
VirtualReferenceType referenceType
)

,
, ASP.NET ,
. VirtualReferenceType
; . 5-6.

220

ASP.NET

. 5-6. VirtualReferenceType

Master

Page

ASP.NET

SourceFile

UserControl

Other


. :
public override bool AllowVirtualReference(string virtualPath,
VirtualReferenceType refType)
{
// ,
return (refType != VirtualReferenceType.UserControl)
}

, , PageParser,
ASP.NET.
, ,
, .
:
. ,
, . ,

. :
public override void ParseComplete(ControlBuilder rootBuilder)
{
// , , -
if (rootBuilder is FileLevelPageControlBuilder)
rootBuilder.AppendLiteralString("<b>written by Dino Esposito</b>");
}

ParseComplete
-. ,
, , , skin- . ,
.
ParseComplete , .
,
BuildControlTree ( . 1).
BuildControlTree . ,
. ,

221

( ,
):
private void BuildControlTree(YourPage_aspx ctrl)
{
IParserAccessor parser = (IParserAccessor) ctrl;
//
parser.AddParsedSubObject(new LiteralControl("<html>"));
// <head>,
HtmlHead ctrl1 = BuildControl__control1();
parser.AddParsedSubObject(ctrl1);
//
parser.AddParsedSubObject(new LiteralControl("<body>"));
//
HtmlForm ctrl2 = BuildControl__form1();
parser.AddParsedSubObject(ctrl1);
parser.AddParsedSubObject(new LiteralControl("</body></html>"));
// ,
parser.AddParsedSubObject(new LiteralControl(__));
}

.
, HTML-, ,
. ,
</html>, .

, , ASP.NET 2.0
, . , ,
. , ,
. ASP.NET 2.0 ,
, ,
. , .
,
,
.

.

, , , . ,
,
, .

222

ASP.NET

I , ASP.NET.
ASP.NET, .
.

,
Web-,
.

ASP.NET 2.0 API,


. ASP.NET 1.x ,
, .

ASP.NET 2.0 Async . ,


. ,
. ,
.
, .

ASP.NET 2.0 : ,
.
.


, , ExpressionBuilder.

,
. ,
.
, .

,
ASP.NET.

II


ASP.NET

6. ................................................................................ 224
7. Web Parts ................................................................... 261
8. ................................................ 307
9. ................................................................................... 336
10. ............................................................................................ 366

Web ,
.
, . ,
.
, .
,
,
- . , !
, ( ,
). :
JavaScript
.


Web-,
. ,
, ,
.
Web- , . ,
, : ,
, , , , .
.
? ,

.
,
. , ,
, .
.

225


HttpCapabilitiesBase,
Request.Browser. .NET Framework , HttpCapabilitiesBase: BrowserCapabilities MobileCapabilities.
, .
, . ,
(, Internet Explorer
Firefox), . ,
,
, , cookie, .

User-Agent
.
Request.UserAgent. Internet Explorer (IE) 6.0
:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322;
.NET CLR 2.0.50727; InfoPath.1)

Mozilla Firefox 1.0 :


Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0

,
, , . , ,
Internet Explorer Firefox? Browser Type:
<h2>This browser is <% =Request.Browser.Browser %></h2>
<h2>This browser is <% =Request.Browser.Type %></h2>
<h2>This browser is <% =Request.UserAgent %></h2>

Browser , Type
. . 6-1 , .
. 6-1.

Internet Explorer 6.0


Internet Explorer 5.5
Mozilla Firefox 1.0
Netscape 7.2
Netscape Communicator 4.6

Browser
IE
IE
Mozilla
Netscape
Netscape

Type
IE6
IE55
Mozilla1.7.5
Netscape72
Netscape4

HttpCapabilitiesBase IsBrowser,
.
true, , false . ,
Browser. Internet Explorer IsBrowser("IE6") IsBrowser("Internet Explorer") false,
"IE":
<h2>This browser is IE: <% =Request.Browser.IsBrowser("IE") %></h2>

226

II

ASP.NET

, , , Internet Explorer 5.5 Internet


Explorer 4.0? , ,
Internet Explorer 4.0 :
HttpBrowserCapabilities caps = Request.Browser;
if (caps.IsBrowser("IE") && caps.MajorVersion >3)
{
}
, ASP.NET?
, IE, Internet Explorer, Mozilla, Firefox?
,
, ASP.NET.
( )
ASP.NET, .

, , . , :
%WINDOWS%\Microsoft.NET\Framework\[]\Config\Browsers

.browser,
. .browser XML;

. : , ;
. ,
ASP.NET,
Browsers.

HttpCapabilitiesBase. ,
.
. 6-2. .
. 6-2. HttpCapabilitiesBase

ActiveXControls

, ActiveX

BackgroundSounds ,
Beta

, -

Browser

ClrVersion

Version,
.NET,

Cookies

, cookie

Crawler

EcmaScriptVersion

ECMAScript,

Frames

, HTML-

Item

227

. 6-2. ()

JavaApplets
JavaScript
MajorVersion
MinorVersion

, Java-
, JavaScript
,
,

Microsoft HTML (MSHTML)


,
, CSS
, XML HTTP
XmlHttpRequest
, HTML
,
(, "Internet Explorer 6" "Netscape 7")
, VBScript
,
( , )
W3C DOM

MSDomVersion
SupportsCallback
SupportsCss
SupportsXmlHttp
Tables
Type
VBScript
Version
W3CdomVersion

,
, Request.Browser, MobileCapabilities . .NET Framework 1.0 MobileCapabilities ,
,
.

Request.Browser HttpCapabilitiesBase, , . , ASP.NET


. ASP.NET
, . ,
, .
: ,
ClientTarget Page, , @Page. ClientTarget ,
, . 3, <clientTarget>
.
, .
,


. , ,
ASP.NET 2.0,
, .
<asp:Button ID="Button1" runat="server" Text="I'm a Button"
ie:Text="IE Button"
mozilla:Text="Firefox Button" />

228

II

ASP.NET

Text "IE button", Internet Explorer, "Firefox button", Firefox.


,
Text, .
, . Browser HttpCapabilitiesBase.

, . ,
, , , ,
.
,
. 13.


, , , , . , TextBox. ,
, . ? ,
<script> ,
,
. .

HTML- <script>, language. , HTML- ,


, . ASP.NET
, <script>,
runat=server. ,
:
<script language="javascript" type="text/javascript">
function SetAsHomePage(obj) {
obj.style.behavior="url(#default#homepage)";
obj.setHomePage("http://www.contoso.com");
}
</script>


:
<input type="button" value="Set home page" onclick="SetAsHomePage(this)" />

button , .
, .
? , ,
Dynamic HTML, , Internet
Explorer 5.5 . ,
,
,

229

, .
document.write,
.
,
. , , HTML-, , ,
.
. ,
, .
.
ClientScriptManager

Page . ,
, , . ,
JavaScript,
. . , , .
Page ,
,
. ASP.NET 2.0 ClientScript
Page ClientScriptManager,
. ASP.NET 1.x Page. ClientScriptManager,
, . 6-3.
. 6-3. ClientScriptManager,

GetCallbackEventReference

GetPostBackClientHyperlink

javascript: ,
GetPostBackEventReference, :
javascript:__doPostBack('CtlID','')

GetPostBackEventReference

,
;
Control , :
__doPostBack('CtlID','')

GetWebResourceUrl

URL ,

IsClientScriptBlockRegistered

IsClientScriptIncludeRegistered

IsOnSubmitStatementRegistered

,
submit-

(. . .)

230

II

ASP.NET

. 6-3. ()

IsStartupScriptRegistered

,
startup-
ECMAScript.
, ,
, . , "theArray" "'a', 'b'", JavaScript:

RegisterArrayDeclaration

RegisterClientScriptBlock

RegisterClientScriptInclude
RegisterClientScriptResource

RegisterExpandoAttribute
RegisterHiddenField
RegisterOnSubmitStatement
RegisterStartupScript

var theArray = new Array('a', 'b');


, HTML-
<form>

src <script>
RegisterClientScriptInclude
,
,

, OnSubmit
<form>,
,

, ClientScriptManager : GetXXX,
IsXXX RegisterXXX. GetXXX JavaScript
.
, (script callback),
. RegisterXXX
, . IsXXX, ,
,
.
,


, ,
JavaScript, .
RegisterClient
ScriptBlock. ,
<script>, ,
, .
, RegisterClientScriptBlock, <form>
, . ,

231

,
Internet Explorer 5.5:
<body>
<form id="form1" runat="server">
<div>
<input runat="server" type="button" ID="HomePageButton"
value="Set home page" />
</div>
</form>
</body>

submit-
. , , .
:
protected void Page_Load(object sender, EventArgs e)
{
string HOMEPAGE = "http://weblogs.asp.net/despos";
// IE55
HttpBrowserCapabilities caps = Request.Browser;
if (caps.IsBrowser("IE") && (caps.MajorVersion > 5 ||
(caps.MajorVersion == 5 && caps.MinorVersion >= 5)))
{
// onclick
HomePageButton.Disabled = false;
HomePageButton.Attributes["onclick"] = "SetHomePage(this)";
//
Type t = this.GetType();
if (!ClientScript.IsClientScriptBlockRegistered(t, "SetHomePage"))
{
//
string js = BuildScriptCode(HOMEPAGE);
ClientScript.RegisterClientScriptBlock(t, "SetHomePage", js);
}
}
else
HomePageButton.Disabled = true;
}
private string BuildScriptCode(string url)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("function SetHomePage(obj) {");
sb.AppendLine(" obj.style.behavior=\"url(#default#homepage)\";");
sb.AppendFormat(" obj.setHomePage(\"{0}\");\r\n", url);
sb.AppendLine("}");
return sb.ToString();
}

Page_Load ,
,
. , ,
.

232

II

ASP.NET

Page - ,
. - . IsClientScriptBlockRegistered
, .
, .
.
, ,
.
. 6-1 , Mozilla
Firefox Internet Explorer 6.0. , Internet Explorer .

. 6-1. Internet Explorer 5.5

ASP.NET 2.0 RegisterXXX , , false.


true, <script>.
false, <script>
.
! ASP.NET ( <asp:Button>)
<input type=submit>. , , onclick, . ASP.NET 2.0 Button
UseSubmitBehavior, true.
false, <input> Button, onclick
. , ,
, onclick
. submit DOM, OnSubmit
.
RegisterOnSubmitStatement.

233

(startup) , , , .
,
. ,
, .
,
RegisterStartupScript. <script>
</form>. ,
, .
( ), . HTML- ,

HTML-.
! DOM, HTML 4.0. , ,
, DOM,
, ( Internet
Explorer). HTML-, , document.getElementById ,
. :

function ShowValue()
{
var obj = document.getElementById("TextBox1");
alert(obj.value);
}
Visual Studio 2005 IntelliSense- document.

submit-

, . , .
submit (
<input> submit, reset image),
onclick. onclick
.
, ,
( false):
function ConfirmDeletion(msg) {
return confirm(msg);
}

, submit- OnSubmit . W3C DOM


OnSubmit. submit-,
OnSubmit .
, DOM submit.
ASP.NET ,
, Button, LinkButton Button,

234

II

ASP.NET

, .
submit
OnSubmit , , . ,
, GetPostBackEventReference, . 6-3.
RegisterOnSubmitStatement:
ClientScript.RegisterOnSubmitStatement(this.GetType(), "MySubmit", js);

OnSubmit, , WebForm_OnSubmit. <script> . ,


RegisterOnSubmitStatement.
- .
submit-:
<script type="text/javascript">
function WebForm_OnSubmit()
{
// , RegisterOnSubmitStatement
// True , False
return true;
}
</script>

, , onsubmit:
<form id="form1" method="post" action="HomePage.aspx"
onsubmit="javascript:return WebForm_OnSubmit();">

OnSubmit ,
. ,
submit-, , ,
onclick, OnSubmit. ,
. ,
,
. OnSubmit .
, ,
,
<input> submit, reset image.

,
, . JavaScript RegisterClientScriptInclude:
ClientScript.RegisterClientScriptInclude("MyScript",
"http://www.foo.com/script.js");

. ,
:
<script src="http://www.foo.com/script.js"
type="text/javascript"></script>

235

,
,
RegisterClientScriptResource:
ClientScript.RegisterClientScriptResource(this.GetType(), "MyScript.js");

<script>:
<script src="/ProAspNetAdv/WebResource.axd?d=...&t=..."
type="text/javascript"></script>

HTTP WebResource.axd. RegisterClientScriptResource RegisterClientScriptInclude, URL,


WebResource.axd.
RegisterClientScriptResource:
public void RegisterClientScriptResource(Type type, string resourceName)
{
RegisterClientScriptInclude(type, resourceName,
GetWebResourceUrl(type, resourceName));
}

GetWebResourceUrl ClientScriptManager; URL . URL WebResource.axd


. GetWebResourceUrl
Type, , .
AppDomain . GetWebResourceUrl
.

?
,
.
, ,
, , .
, , , ,
GetWebResourceUrl URL, .
, , (, )
.
Assembly current = Assembly.GetExecutingAssembly();
Stream stm = current.GetManifestResourceStream("MyScript.js");
StreamReader reader = new StreamReader(stm);
string contents = reader.ReadToEnd();
reader.Close();
stm.Close();
//

236

II

ASP.NET

,

.
, ASP.NET 1.x ClientScript
, , Page. ASP.NET 2.0
ClientScript. ,
. ClientScript
, Page.


, . , , , ,
, .
, ,
. , , - - ,
, , .
,
,
, , .
:
, , ,
.
ASP.NET 2.0 Web- Register- .
, , , -,
, -,
. ,
API, , Register-, .
Web ,
. , ,
, : http://www.accessify.com/tutorials/the-perfect-pop-up.asp.

API

DOM window,

open. , :
window.open(url, title, [, style]);

url URL , title


, style . Internet Explorer Mozilla.
4.0, Internet Explorer ,
showModalDialog showModalessDialog:
window.showModalDialog(url [, params] [, style]);
window.showModalessDialog(url [, params] [, style]);

237

URL . URL , , params


JavaScript, ,
, style ,
, , . .
ASP.NET , .
:
<script language="javascript">
function ShowPopup(url)
{
window.showModalDialog(url, "", "");
}
</script>


, , ,
. , .
Internet Explorer
Mozilla . , http://msdn.microsoft.com/library/default.asp?url=/
workshop/author/dom/domoverview.asp http://www.mozilla.org/docs/dom.

,
Web-:
RegisterXXX, , .
13, .
public void RegisterPopupWindow(Type t, string functionName,
string targetUrl, bool modal, string style, bool addScriptTag)
{
// JavaScript
string js = BuildScriptCode(targetUrl, functionName, modal, style);
//
if (!ClientScript.IsClientScriptBlockRegistered(functionName))
ClientScript.RegisterClientScriptBlock(t, functionName, js,
addScriptTag);
}

RegisterPopupWindow
RegisterXXX. ,
, , <script>.
, ,
, URL ,
.

238

II

ASP.NET

, RegisterPopupWindow
JavaScript, ,
RegisterClientScriptBlock ClientScript .
,
:
public void RegisterPopupWindow(Type t, string functionName, string targetUrl)
{
RegisterPopupWindow(t, functionName, targetUrl, true, "", true);
}
public void RegisterPopupWindow(Type t, string functionName,
string targetUrl, bool modal)
{
RegisterPopupWindow(t, functionName, targetUrl, modal, "", true);
}

RegisterPopupWindow
, , .
.
.
Mozilla Modal=yes .
, dependent=true.
dependent .


, . functionName -
, . ,
, :
protected void Page_Load(object sender, EventArgs e)
{
string URL = "http://weblogs.asp.net/despos";
//
Type t = this.GetType();
if (!Page.ClientScript.IsClientScriptBlockRegistered(t, "ShowPopup"))
{
//
PopupButton.Attributes["onclick"] = "ShowPopup()";
PopupButton.Disabled = false;
//
RegisterPopupWindow(t, "ShowPopup", URL, true);
}
else
PopupButton.Disabled = true;
}

239

, Page_Load ShowPopup,
JavaScript. RegisterPopupWindow. ,
, Web-, URL,
(. 6-2).

. 6-2.
Internet Explorer

Script Callbacks
Web-
, . ,
, . ASP.NET . ,
, , , , ,
, .
,
. , 50

( ,
)?
HTTP Web-
, , .

240

II

ASP.NET

, Web ,
, .
, , . , URL ,
,
Dynamic HTML.
, ,
. , ,
, . ,
,
,
. , ,
.
JavaScript, ,
.
, ASP.NET.

API ASP.NET
, , , , (
) .
- ActiveX, Java- ,
.
,
ASP.NET.
.
Dynamic HTML. - ,
ASP.NET 1.x ASP.
ASP.NET 2.0 , , .
, (script callback) .

, .
XmlHttpRequest

1999 Internet Explorer 5.0, , , XML HTTP


XmlHttpRequest. , , HTTP. XML : XML HTTP, ,
HTTP-.

241

Internet Explorer XmlHttpRequest COM-


(progID) Microsoft.XmlHttp.
.
JavaScript, URL :
function DoPost(url)
{
var http = new ActiveXObject("Microsoft.XmlHttp");
http.open("POST", url, false);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(null);
return http.responseText;
}

open : HTTP (, GET POST),


URL , ,
( false ). ,
send. .
send .
. Web- .
XmlHttpRequest,
, XML
DOM. responseText , responseXml
, , XML DOM.
COM- MSXML. .NET
XmlHttpRequest .
ASP.NET 2.0
XmlHttpRequest, .
XmlHttpRequest ,
XML COM, .NET Framework.
XML, . , COM
, XmlHttpRequest
COM ,
. .

,
JavaScript.
system.web; URL WebResource.axd
, ,
Internet Explorer.
WebForm_DoCallback, . ,
JavaScript, ,
. URL ,
.
ASP.NET, URL
.

242

II

ASP.NET

WebForm_DoCallback
XmlHttpRequest, , JavaScript , .
,
. , , ProcessRequest
Page , . ,
: CALLBACKPARAM CALLBACKID.
,
, ( ),
. ,
IsCallback Page true.
(
)
. POST
, . ,
.
. ,
, .

Internet Explorer XmlHttpRequest Mozilla


, DOM .
, WebForm_DoCallback,
, ,
. :
__nonMSDOMBrowser = (window.navigator.appName.indexOf('explorer') == -1);
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback,
context, errorCallback)
{
if (__nonMSDOMBrowser) {
var xmlRequest = new XMLHttpRequest();
}
else
{
var xmlRequest = new ActiveXObject("Microsoft.XmlHttp");
}
}

, ASP.NET
Internet Explorer, Mozilla, Firefox, Netscape 6.x
Safari 1.2, Opera. 95 % .
?
! , Internet Explorer XmlHttpRequest
COM-.
, , ActiveX. .

243



, JavaScript. URL,
. ASP.NET
,
, , .
,
, .
, , ,
HTML.
, .
Microsoft
Remote Scripting, 90- .
Java-, ASP.
. . . Remote Scripting

Netscape 4.x Internet Explorer 4, ,
Windows.
http://msdn.microsoft.com/library/en-us/rmscpt/Html/rmscpt.asp.

ASP.NET
JavaScript. ,
.
More Info,
.
submit, , ,
, .
:
<asp:dropdownlist id="cboEmployees" runat="server"
DataTextField="lastname" DataValueField="employeeid" />
<input type="button" runat="server" id="buttonTrigger"
value="More Info">

. ,
.
onclick.
Page_Load:
private IEnumerable GetListOfNames()
{
//
}
protected void Page_Load(object sender, EventArgs e)

244

II

ASP.NET

{
if (!IsPostBack)
{
//
cboEmployees.DataSource = GetListOfNames();
cboEmployees.DataBind();
// JavaScript
string rpc = ClientScript.GetCallbackEventReference(
this,
"document.forms[0].elements['cboEmployees'].value",
"UpdateEmployeeViewHandler",
"null",
"null",
false);
//
string js = String.Format("javascript:{0}", rpc);
buttonTrigger.Attributes["onclick"] = js;
}
}

GetCallbackEventReference JavaScript,
onclick . ,
:
<input name="buttonTrigger" type="button" id="buttonTrigger"
value="More Info"
onclick="javascript:WebForm_DoCallback('__Page',
document.forms[0].elements['cboEmployees'].value,
UpdateEmployeeViewHandler,
null, null, false)" />

WebForm_DoCallback?
system.web , ,
:
<script src="/ProAspNetAdv/WebResource.axd?d=...&t=..."
type="text/javascript"></script>

, , <form>. ,
. </form>:
<script type="text/javascript">
var pageUrl = '/ProAspNetAdv/Samples/Ch06/Callback/ShowInfo.aspx';
WebForm_InitCallback();
</script>

pageUrl URL . , WebForm_InitCallback


( ),
,
.

245

, ASP.NET, ,
JavaScript ,
. GetCallbackEventReference ClientScript. ,
, ,
.
public string GetCallbackEventReference(
Control target,
string argument,
string clientCallback,
string context,
string clientErrorCallback,
bool useAsync)

. 6-4.
,
. target
.
, __Page.
. 6-4. GetCallbackEventReference

target

, .

, ICallbackEventHandler.
,

, .
,
.
,
JavaScript, . ,
, JavaScript
.
, .

,
.

JavaScript,
, . ,
clientCallback,
true, , ; false

argument

clientCallback

context

clientErrorCallback

useAsync

, :
// Page_Load
string rpc = ClientScript.GetCallbackEventReference(
this,
"document.forms[0].elements['cboEmployees'].value",

246

II

ASP.NET

"UpdateEmployeeViewHandler",
"null",
"null",
false);

, ICallbackEventHandler.
, GetCallbackEventReference .
, target (
this) . target
, ,
.
, ,
JavaScript:
document.forms[0].elements['cboEmployees'].value

,
. , , , .
(,
), ,
. , , ,
. , ,
, ,
, ,
.
, ASP.NET
,
. ?
? ,
.
,
. ,
,
. . ,
? ( TreeView,
.)

, - ,
(, ), -
, .
: , ,
.

JavaScript
, , . ,
:
document.forms[0].elements["yourDropDown"].value
document.all["yourDropDown"].value

247

Internet Explorer,
Mozilla. , DOM,
, Internet Explorer.

,
ICallbackEventHandler.
: RaiseCallbackEvent GetCallbackResult. ,
.
, GetCallbackResult.
public partial class ShowInfo : Page, ICallbackEventHandler
{
private string _results;
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
//
int empID = -1;
bool success = Int32.TryParse(eventArgument, out empID);
EmployeeInfo emp = GetEmployeeDetails(empID);
// : , .
// , ,
// , JavaScript
string[] buf = new string[6];
buf[0] = emp.ID.ToString();
buf[1] = emp.FirstName;
buf[2] = emp.LastName;
buf[3] = emp.Title;
buf[4] = emp.Country;
buf[5] = emp.Notes;
_results = String.Join(",", buf);
}
string ICallbackEventHandler.GetCallbackResult()
{
return _results;
}
}

, ICallbackEventHandler ,
, @Implements
. ,
.
RaiseCallbackEvent argument, . 6-4. GetCallbackResult ,
JavaScript- clientCallback .
, , RaiseCallbackEvent GetCallbackResult, .
, - -,

248

II

ASP.NET

. , ,
JavaScript, , , JavaScript.
, .
, Ajax.NET,
.NET
JavaScript. Atlas
ASP.NET, .
.

, , .
EmployeeInfo. API ,
,
.
, : , , . .
ICallbackEventHandler .
.

, Jet, . ,
. Ajax.NET Atlas
, ,
, ,
, ,
.
API Script Callbacks, , .
<script language="javascript">
function UpdateEmployeeViewHandler(response, context)
{
// ,
var o = response.split(',');
// ,
var e_ID = document.getElementById("e_ID");
var e_FName = document.getElementById("e_FName");
var e_LName = document.getElementById("e_LName");
var e_Title = document.getElementById("e_Title");
var e_Country = document.getElementById("e_Country");
var e_Notes = document.getElementById("e_Notes");
// ,
e_ID.innerHTML = o[0];
e_FName.innerHTML = o[1];
e_LName.innerHTML = o[2];
e_Title.innerHTML = o[3];
e_Country.innerHTML = o[4];

249

e_Notes.innerHTML = o[5];
}
</script>

. 6-3 ,
Internet Explorer 6.0 Firefox.

. 6-3. , ,
Internet Explorer Firefox

DOM

ASP.NET
, .
, ASP.NET,
, Internet Explorer Mozilla. ,
. ASP.NET ,

JavaScript. , , ,
.
,
, document.write. ,
, ,
DOM, .
JavaScript
.
, Internet Explorer,
Firefox Netscape Navigator. . ,
<span> e_ID.
Internet Explorer, Firefox Netscape Navigator:
var userID = ...;
e_ID.innerHTML = userID;

DOM Mozilla e_ID, DOM


. , Internet Explorer .

250

II

ASP.NET

.
, , .
document.getElementById,
W3C:
var userID = ...;
var e_ID = document.getElementById("e_ID");
e_ID.innerHTML = userID;W3C

,
W3C DOM. (, , ,
Internet Explorer,
, .)
API ASP.NET Script Callbacks, Ajax.NET
, , . ,
,
. Atlas, , Microsoft, ,
, , , .

. ASP.NET.


ASP.NET, TreeView GridView. , TreeView
.
GridView,
.

, . . .
, . , , ,
. :
<asp:SqlDataSource runat="server" ID="EmpSource"
ConnectionString="<%$ ConnectionStrings:LocalNWind %>"
SelectCommand="SELECT employeeid, lastname FROM employees" />
<asp:DropDownList ID="listEmployees" runat="server"
DataSourceID="EmpSource"
DataTextField="lastname" DataValueField="employeeid"
onchange="ShowOrders(this.options[this.selectedIndex].value);" />
<asp:DropDownList runat="server" ID="listOrders"
style="visibility:hidden" />

SqlDataSource listEmployees
, Northwind. onchange
,
. JavaScript ShowOrders,
. ShowOrders
Page_Load:

251

void Page_Load(object source, EventArgs e)


{
string rpc = ClientScript.GetCallbackEventReference(this,
"arg", "UpdateOrders", "null", "ShowError", false);
string func = "function ShowOrders(arg) { " + rpc + "; }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "ShowOrders", func, true);
}

Page_Load :
<script type="text/javascript">
function ShowOrders(arg) {
WebForm_DoCallback('__Page', arg, UpdateOrders, null, ShowError, false);
}
</script>

, GetCallbackEventReference , , ,
arg, .aspx:
this.options[this.selectedIndex].value

arg, , , . ,
,
.
.
.
JavaScript UpdateOrders:
function UpdateOrders(result)
{
if (!result) return;
var childDropDown = document.forms[0].elements['listOrders'];
if (!childDropDown) return;
childDropDown.length = 0;
var listOrders = document.getElementById("listOrders");
var rows = result.split('|');
for (var i = 0; i < rows.length; ++i)
{
var option = document.createElement("OPTION");
option.value = rows[i];
option.innerHTML = rows[i];
listOrders.appendChild(option);
}
listOrders.style.visibility = "visible";
}

. ,
. ,
display visibility,
. ( display, DOM .) . 6-4 .

252

II

ASP.NET

. 6-4. ,
, Internet Explorer 6.0 Netscape 7.2

,
. ASP.NET Script Callback
API,
. ,
Ajax.NET ( ) Atlas, ,
ASP.NET, .

. :
,
.
,
-. , JavaScript - , ,
. , ,
, .
.

Ajax.NET
Script Callback, ASP.NET,
, .
-, ,
. Internet Explorer
COM- XmlHttpRequest; Mozilla Opera
DOM- .
.

253

API, . ASP.NET
API Script Callback,
, , , , , .
ASP.NET, .
API Script Callback
. Ajax.NET.


Ajax Asynchronous JavaScript And XML ( JavaScript XML). ,
( JavaScript, DOM , CSS
XmlHttpRequest), Web-. Ajax-, ,
, .

.

Google, Google Maps, Google Suggest Gmail,
.
, Ajax,
Web-
. Ajax.NET, ASP.NET 1.x, ASP.NET 2.0,
.
Ajax.NET, http://ajax.schwarzinteractive.de/csharpsample/default.aspx.
Ajax http://en.wikipedia.org/wiki/ajax.

Ajax.NET ajax.dll, GAC, Bin . ,


web.config HTTP:
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx"
type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>

, URL, ajax/*.ashx, Ajax. ,


ajax.
2, HTTP. ,
,
. , .
Ajax, , ,
.
, . ,
, Ajax.NET.

254

II

ASP.NET

, , TestAjax.aspx. JavaScript . ,
Find,
JavaScript GetCustomerDetail.
, .
<%@ Page Language="C#" CodeFile="TestAjax.aspx.cs" Inherits="TestAjax" %>
<script type="text/javascript">
function GetCustomerDetail()
{
var customerID = document.getElementById("customerID");
var response = TestAjax.GetCustomerByID(customerID.value);
var oCustomer = response.value;
if (oCustomer.Type == "UnknownCustomer")
{
alert("Customer not found");
}
else
{
var fn = document.getElementById("firstName");
var ln = document.getElementById("lastName");
fn.innerHTML = oCustomer.FirstName;
ln.innerHTML = oCustomer.LastName;
}
}
</script>
<html>
<head runat="server">
<title>Testing Ajax</title>
</head>
<body>
<form id="form1" runat="server">
<h2>Enter a Customer ID (1, 2, 3, ...)</h2>
<asp:textbox id="customerID" runat="server" text="1" />
<input onclick="GetCustomerDetail()" type="button" value="Find">
<hr />
<asp:label id="firstName" runat="server" />&nbsp;
<asp:label id="lastName" runat="server" /> <br />
</form>
</body>
</html>

. 6-5 Opera 8.5.


? , . JavaScript .
: , JavaScript,
:
var response = TestAjax.GetCustomerByID(customerID.value);
var oCustomer = response.value;
if (oCustomer.Type == "UnknownCustomer") {
} else {
}

255

. 6-5. , Ajax, Opera 8.5

TestAjax.GetCustomerByID? oCustomer? :
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ajax;
using ProAspNet20;
public partial class TestAjax : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Utility.RegisterTypeForAjax(typeof(TestAjax));
Utility.RegisterTypeForAjax(typeof(ProAspNet20.Customer));
Utility.RegisterTypeForAjax(typeof(ProAspNet20.UnknownCustomer));
}
[AjaxMethod()]
public Customer GetCustomerByID(string customerID)
{
//
switch (customerID)
{
case "1":
return new Customer("John", "Doe");
case "3":
return new Customer("Jim", "Idontknowthisguy");
default:
return new UnknownCustomer();
}
}
}

, GetCustomerByID ,
[AjaxMethod]. Ajax Page_Load : ProAspNet20.Customer, ProAspNet20.UnknownCustomer TestAjax. ?
JavaScript, , ,
TestAjax. , [AjaxMethod],
JavaScript.

256

II

ASP.NET

Ajax;
XmlHttpRequest.
, Ajax, , , ASP.NET
Script Callback. , Ajax,
JavaScript, (. 6-6).

. 6-6. , Ajax, Opera 8.5


,
.

, Ajax, ,
<script>:
<script type="text/javascript"
src="/ProAspNetAdv/ajax/common.ashx" />
<script type="text/javascript"
src="/ProAspNetAdv/ajax/TestAjax, [assembly].ashx" />
<script type="text/javascript"
src="/ProAspNetAdv/ajax/ProAspNet20.Customer, [assembly].ashx" />
<script type="text/javascript"
src="/ProAspNetAdv/ajax/ProAspNet20.UnknownCustomer, [assembly].ashx" />

, .ashx ,
Web-.
, HTTP- Ajax
. , common.ashx
TestAjax.aspx :
var TestAjax =
{
GetCustomerByID:function(customerID,callback,context)
{
return new ajax_request(this.url +
'?_method=GetCustomerByID&_session=no',
'customerID=' + enc(customerID), callback, context);

257

},
url:'/ProAspNetAdv/ajax/TestAjax,App_Web_3obyp7mk.ashx'
}

JavaScript TestAjax : GetCustomerByID


url. , ,
[AjaxMethod], TestAjax.
ajax_request
API . ajax_request
WebForm_DoCallback.
JavaScript - Web-. ,
;
.

common.ashx API Ajax.NET,


, .ashx, ,
.NET JavaScript. .NET
JavaScript, . (,
, ) JavaScript.
.NET ,
Ajax.NET DataSet, DataTable, DataView, DataRow, Image,
. . Ajax ,
IAjaxObjectConverter.

Ajax.NET ASP.NET Script Callbacks


Ajax.NET ASP.NET Script Callbacks ,
XmlHttpRequest. API
.

. 6-5 ,
.
. 6-5. Script Callbacks Ajax.NET
ASP.NET Script Callbacks

Ajax.NET


,
.
GetCallbackEventReference,

Page_Load

, .

, .
, ,
,

.NET,
. , .
Page_Load
,
,
[AjaxMethod]


ICallbackEventHandler .

,

258

II

ASP.NET

, Ajax.NET . . -, ,
,
-,
.NET.
Script Callbacks Ajax.NET
.

, ,
Ajax.NET . JavaScript, ,
. ,
. ,
Ajax , ,
.
, .
Script Callback, , .

, ,
. , Ajax.NET
, Script Callback API
, .

. Ajax.NET ,
. Script Callbacks,
,
. ( )
. ,
.
LoadComplete.

PreRender. , , , .
, :
ICallbackEventHandler handler;
handler = FindControl(target) as ICallbackEventHandler;
if (handler != null)
{
handler.RaiseCallbackEvent(arguments);
string results = handler.GetCallbackResult();
Response.Write(results);
return;
}

, , ,
. , ,
. -

259

?
. , ASP.NET Script
Callbacks . ,
Ajax.NET , ,
,
, .
Atlas

Atlas Web-, Web- .


Microsoft Ajax. Atlas
. - API,
.
Web-, HTTP , .
, , ,
Atlas.
Ajax DOM . , Atlas
Ajax-. , Web-. Atlas
JavaScript,
, ,
JavaScript.
Professional Developer's Conference 2005, Atlas
Framework ,
, , ,
- API.
http://atlas.asp.net.

Web- Web-
, . . ,
. , .
,
, .
, ,
.
1990- Web-, ,
. , ,

260

II

ASP.NET


, , - .
Google Maps Web: ,
,
. , Web-.
, Web-, ASP.NET
.
Script Callbacks, API . ,
,
, :
, . ,
Ajax.NET,
. ,
. :
, DOM
,
. , , Atlas Framework,
Professional Developer's Conference 2005
ASP.NET 2.0.
Web-. , ,
, . Atlas technology
preview, ASP.NET.
, Ajax.NET.

ASP.NET:
, .

Page ,
, OnSubmit
.
ASP.NET
, .
.
JavaScript, .
,
PreRender. , ,
, .
,
.
Ajax.NET ,
, - , .NET
JavaScript.

Web Parts

, , , .
Web- .
, .
. , ,
,
, , , ,
.
Web-, , , , ?
, ,
?
Microsoft, ASP.NET 2.0
Web Parts.
.
ASP.NET 2.0 Web Parts,
, Web-.

Web Parts
ASP.NET Web Parts Framework ASP.NET ,
Web- .

, .
Web Parts, Web- Web-. ,
Web-.

Web Parts
. 7-1 Web- My MSN. , .
, ,
. , Add Content Change
Details.
ASP.NET,
Web Parts.

262

II

ASP.NET

. 7-1. My MSN, ,

Web Part

Web Part , . , . ;
Web Part , HTML- , , ,
(user) (custom).
Web Parts API , ,
.
Web Part ,
,
. , Web-,
, ,
. , Web Parts
, , , .
Web Part

Web Part Panel. Web Part ,


ASP.NET. Web Part , ,
, Web Parts,
, . Web Part

Web Parts

263

.
, .
Web Part ,
, , , .
URL, ,
URL, . Web Part
, HTML.
, ,
. HTML scraping,
, Web-.
Web Parts Microsoft SharePoint

Microsoft Windows SharePoint


. Web-,
SharePoint, Web Parts, ,
.
SharePoint ASP.NET ,
. SharePoint , . SharePoint,
, . ASP.NET,
, - SharePoint. , ASP.NET 2.0 ,

SharePoint.
: SharePoint ASP.NET ?
, , , , : Web Parts. Web Parts, SharePoint
ASP.NET ,
SharePoint. Web Parts ASP.NET 2.0 ,
ASP.NET Web Parts SharePoint.
SharePoint ASP.NET , . , SharePoint
ASP.NET 2.0 Web Part ASP.NET
SharePoint. , , SharePoint Service Pack 2.
ASP.NET (, , )
SharePoint ASP.NET 2.0. Web Parts, , .
SharePoint, ASP.NET Web Parts SharePoint Web Parts, ,
.

Web Parts Framework


, Web Parts,
Web Parts Framework, .
Web Parts
WebPart, .
. 7-1.

264

II

ASP.NET

. 7-1. Web Parts Framework

WebPartManager

Web Parts .
,
, .
WebPart ;

,
WebPart
Catalog Part.
Web Part, . ImportCatalogPart,
PageCatalogPart DeclarativeCatalogPart
CatalogPart
Web Part,

-, Web Parts. Editor Part ,

EditorPart

WebPart

WebPartZone
CatalogPart

CatalogZone
ConnectionsZone
EditorPart

EditorZone

Web Parts WebPartManager , : Web Parts (Web-), Catalog Parts (-) Editor Parts (-).

,
. ASP.NET
, .
, ,
, , ,
.
Web Part , , Editor
Part Web Part. , Web Part . Editor Part Web Part
,
, , : .
My MSN; ,
Select Your Cities
, (. 7-2). ,
, Web Part.
WebPart.
Web Parts ,
, , . Catalog Part,
.
, ,

Web Parts

265

.
Catalog Parts Editor Parts .

. 7-2. My MSN

Web Parts . WebPart, ,


Part. , EditorPart CatalogPart
Catalog Parts Editor Parts, Part. ,
,
Panel. ASP.NET- . . 7-3.

. 7-3.
ASP.NET 2.0 Panel
. CSS- overflow.
ASP.NET 1.x , .aspx.

WebPartManager

WebPartManager ,
, Web
Parts. , -
, . Web-
WebPartManager.
:
<asp:WebPartManager runat="server" id="MyWebMan" />

266

II

ASP.NET

- , . ,
.
. Normal,
Web
Parts .
Zones.
WebPartManager
, .
, ,
.
Web Parts, , , .
, WebPartManager , Web Parts .

, WebPartConnection.
, . Web
Part, , . - .
,
Web Parts ,
, . ,
, .
Web Parts
ASP.NET 2.0 . , WebPart WebPartZone. Web Parts
- WebParts, . ,
Design WebPartZone Web Parts .
Design Web Parts
, Web Parts. WebPartZone ;
PartStyle ( ), PartTitleStyle ( )
MenuVerbStyle ( , Web Part
). .

. EditorZone
-,
Web Parts; CatalogZone Web Parts,
; , ConnectionsZone
, Web Parts, .

Web Parts
, , ,
, Web Parts. , :
<%@ Page Language="C#" CodeFile="Parts.aspx.cs" Inherits="Parts" %>
<%@ Register TagPrefix="x" TagName="News" Src="News.ascx" %>

Web Parts

267

<%@ Register TagPrefix="y" TagName="Favorites" Src="Favorites.ascx" %>


<html>
<head><title>Simple Web Parts</title></head>
<body>
<form id="form1" runat="server">
<h1>Demonstrating WebParts zones</h1>
<asp:WebPartManager ID="WebMan" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server"
HeaderText="This is Zone #1"
PartChromeType="TitleAndBorder" BorderColor="#CCCCCC">
<PartStyle Font-Size="0.8em" ForeColor="#333333" />
<PartTitleStyle Font-Size="0.8em" Font-Names="verdana"
BackColor="#507CD1" ForeColor="White" />
<PartChromeStyle BackColor="#EFF3FB" BorderColor="#D1DDF1"
Font-Names="Verdana" ForeColor="#333333" />
<ZoneTemplate>
<x:News runat="server" id="News" />
<y:Favorites runat="server" id="Favs" />
</ZoneTemplate>
</asp:WebPartZone>
</form>
</body>
</html>

, .
WebPartManager, . Web- .
. <ZoneTemplate>
Web Parts. ,
. 7-4.

. 7-4. Web Parts


268

II

ASP.NET

Web Part , ,
, .ascx,
. (
12.)
, @Register.

.

Web Parts. ,
WebPart ,
. 7-3. ,

ASP.NET. ,
. .
Web Parts ?
, . Web Parts ,

.
, - , , .
,
.
,

. 7-4 Web Part,


. ,
. 7-5.

. 7-5. : Web Part


Minimize Restore

.
Minimize ( Restore) Close.
Close, Web Part . ,
, , Catalog Part.

Web Parts

269

; , . (chrome) Web Part


.
- . , ,
Web Parts.
Web Parts (. . 7-5). Web Parts
. ?
ASP.NET
, IWebPart.
,
,
.

Web Parts

Web Part, . -,
, , .
- AuthorizeWebPart
Web Parts,
. .

Web Parts
Web Part
. , ,
Web- ,
. ,
.
Web Parts
, . , ,
, .
Web Parts .
Web Part
, . , ,
(, , . .)
Web- (, , . .)
Web Part WebPart.
.
WebPart

Web Part: , WebPart,


,
( .ascx).
, WebPart, Web-
( )
Web Parts.

270

II

ASP.NET

- GenericWebPart, Web Parts Web Parts.


. 7-3, GenericWebPart
WebPart. .
, , GenericWebPart
.
GenericWebPart
, :

<ZoneTemplate>
<asp:Button runat="server" ID="Button1" Text="Hello" />
</ZoneTemplate>
<ZoneTemplate> ,
. , ,
. runat="server",
.

<ZoneTemplate>
<h1 runat="server" ID="H1">Hello</h1>
</ZoneTemplate>

Web Part
, , .
,
. , , ,
, . , WebPart,
Web Part.
! Web Parts
, ,
Visual Studio 2005. ,
.
, Web Parts,
, WebPart.
. , ,
Web Parts.
, , ,
Visual Studio 2005.
12.

WebPart

. 7-2 WebPart. ,
,
Web Parts. ,
WebControl Panel, BackColor, BackImageUrl ScrollBars.

Web Parts

271

. 7-2. WebPart

AllowClose

, Web Part

AllowConnect

, Web Part
AllowEdit
, Web Part

Editor Part
AllowHide
, Web Part
AllowMinimize
, Web Part
AllowZoneChange
, Web Part

AuthorizationFilter
, Web Parts
, Web Part

CatalogIconImageUrl URL , Web Part
Web Parts
ChromeState
Web Part:
ChromeType
, Web Part: , ,

ConnectErrorMessage , ,

Description
Web Part, , ,

Direction
:
DisplayTitle
, Web Part
ExportMode
, Web Part : ,
, ( )
HasSharedData
, Web Part -

HasUserData
, Web Part -

HelpMode
, Web Part
HelpUrl
URL Web Part
Hidden
, Web Part
ImportErrorMessage , , Web Part

IsClosed
, Web Part
IsShared
, Web Part

IsStandalone
, Web Part Web Parts
IsStatic
, Web Part ,

Subtitle
, Title Web Part
Title
Web Part
TitleIconImageUrl
URL ,

(. . .)

272

II

ASP.NET

. 7-2. ()

TitleUrl

URL Web Part. URL ,


Verbs

( ),
Web Part

WebBrowsableObject

Web Part, Editor Part

Zone

, Web Part

ZoneIndex

Web Part ,

WebPart ,
. ( ,
). WebPart
CreateEditorParts, Editor Part,
Web Part, Edit.
, WebPart ,
(. 7-3). ,
, WebPart
WebPartManager,
Web Parts.
. 7-3. WebPart

OnClosing

Web Part

OnConnectModeChanged

Web Part

OnDeleting

Web Part

OnEditModeChanged

Web Part

WebPart ,
Web Part.

Web Parts.
Web Parts

. 7-3, WebPart Part : IWebPart, IwebActionable IWebEditable,


,
Web Part.
Web Parts:
WebPart .
, WebPart,
, . Web Part , , ,

Web Parts

273

. ,
. ,
Web Part IWebPart, (. . 7-4).
Web Parts,
, . 7-2:
public interface IWebPart
{
string CatalogIconImageUrl { get; set; }
string Description { get; set; }
string Subtitle { get; }
string Title { get; set; }
string TitleIconImageUrl { get; set; }
string TitleUrl { get; set; }
}
public interface IWebEditable
{
EditorPartCollection CreateEditorParts();
object WebBrowsableObject { get; }
}
public interface IWebActionable
{
WebPartVerbCollection Verbs { get; }
}

WebBrowsableObject this ( Me Microsoft Visual Basic .NET),


Verbs . Title Description IWebPart ,
Part. . Subtitle IWebPart
.

Web Parts Web Parts .


,
Web Parts. Web Part
, Web Parts AuthorizeWebPart,
, .
AuthorizationFilter Web Part , .
AuthorizationFilter , . ,
. ,
- ,
.
<asp:WebPartManager runat="server" OnAuthorizeWebPart="AuthorizeWebPart" />

Web Part ,
,
:
void AuthorizeWebPart(object sender, WebPartAuthorizationEventArgs e)
{

274

II

ASP.NET

if (!String.IsNullOrEmpty(e.AuthorizationFilter))
{
if (e.AuthorizationFilter == "Admin")
e.IsAuthorized = true;
else
e.IsAuthorized = false;
}
}

WebPartAuthorizationEventArgs AuthorizationFilter,
Web Part. ,
IsAuthorized.
, , AuthorizeWebPart AuthorizationFilter ,
, Web Part .
! Web Part .
, ASP.NET,
.

Web Part StockViewer


Web Part , :
public class StockViewerWebPart : WebPart
{
// , ...
public override string Title
{
}
protected override void RenderContents (HtmlTextWriter writer)
{
}
}

, , Title, Web Part , RenderContents,


.
,
Web Part. StockViewer, ,
Web Part, ,
. StockViewer

.

StockViewer Title Subtitle, Web Part.


WebPart:
public override string Title
{

Web Parts

275

get
{
if (String.IsNullOrEmpty(base.Title))
return "Stock Viewer";
return base.Title;
}
set
{
base.Title = value;
}
}

Title Subtitle .
:
public override string Subtitle
{
get
{
if (String.IsNullOrEmpty(base.Subtitle))
return "Random quotes";
return base.Subtitle;
}
}

Web Part ,
.
StockViewer : Stocks RefreshRate.
, ,
. , Stocks
.
[Personalizable]
[WebBrowsable]
public string Stocks
{
get { return _stocks; }
set { _stocks = value; }
}
[Personalizable]
[WebBrowsable]
public int RefreshRate
{
get { return _refreshRate; }
set { _refreshRate = value; }
}

, .
, ,
. ,
Web Part .
?
Web Part

[Personalizable] ,

276

II

ASP.NET

, Web Parts
, Web Part. 4, Web Part ,
.
aspnetdb.mdf. ,
.
.
, , ( ,
get set) (-, Item, ). ,
, ,
IPersonalizable ,
, .
[WebBrowsable] ,
Editor Part, . ,
, . [WebBrowsable],
, .
, , Web Part, Stocks RefreshRate
StockViewer.
Web Part
[WebDescription] [WebDisplayName], Edit.
, , , .

, Web Part
(. 7-6). , , , . 7-7.

. 7-6. Web Part StockViewer,

RenderContents WebPart.
, StockViewer:
protected override void RenderContents (HtmlTextWriter writer)
{
if ((_stocks == null) || (_stocks.Length == 0))
{

Web Parts

277

writer.Write("<b>No stocks available.</b><hr>" +


"<i style=\"font-size:85%\">Specify some names
and create a list of stocks to monitor. " +
"For example, \"XYZ, FOO, BAR\"</i>");
}
else
{
CreateTableOfStocks(writer);
string msg = "No auto refresh";
if (RefreshRate >0)
msg = String.Format("{0} seconds delay", RefreshRate);
string text = String.Format(
"<br><div style=\"margin:5\">" +
"<span style=\"font-size:80%\">" +
"<span id=\"LastUpdated\">{0}</span> - " +
"Quotes supplied by <b>RandomQuotes Inc</b>, {1}. " +
"</span></div><br>",
DateTime.Now.ToString("hh:mm:ss"),
msg);
writer.Write(text);
}
}

. 7-7. Web Part StockViewer

CreateTableOfStocks:
void CreateTableOfStocks(HtmlTextWriter writer)
{
Table t = new Table();
//
CreateTableHeader(t);
//
string[] list = _stocks.Split(new char[] { ',' });

278

II

ASP.NET

for (int i = 0; i < list.Length; i++)


{
string stockID = list[i];
TableRow row = new TableRow();
c1 = new TableCell();
c1.Text = stockID;
row.Cells.Add(c1);
// ID
//
// ASP.NET
c2 = new TableCell();
c2.ID = "StockValue" + i.ToString();
c2.Text = GetCurrentValue(stockID);
row.Cells.Add(c2);
t.Rows.Add(row);
}
t.RenderControl(writer);
}


. .
, Stocks , .
Web Part . 7-7.

, ,
. , (, ).
, Web Part , . StockViewer .
RefreshRate. , .
. Web Part
, ,
. ASP.NET Script Callback Ajax.NET.
CreateTableOfStocks :
if (RefreshRate > 0)
{
if (!Page.ClientScript.IsStartupScriptRegistered(
this.GetType(), "RefreshQuotes"))
{
string js = GetRefreshScript();
Page.ClientScript.RegisterStartupScript(
this.GetType(), "RefreshQuotes", js, true);
}
}

JavaScript,

:
private string GetRefreshScript()
{

Web Parts

279

StringBuilder sb;
sb = new StringBuilder("\r\nfunction RefreshQuotes() {\r\n");
sb.AppendLine(Page.ClientScript.GetCallbackEventReference(
this, "null", "UpdateQuotes", "null"));
sb.AppendFormat(" window.setTimeout(\"RefreshQuotes()\", {0});",
RefreshRate*1000);
sb.AppendLine("\r\n}");
sb.AppendLine(GetUpdateQuotesScript());
sb.AppendLine("RefreshQuotes();");
return sb.ToString();
}

JavaScript:
function RefreshQuotes()
{
WebForm_DoCallback('WebMan$MyStocks', null, UpdateQuotes, null,
null, false);
window.setTimeout("RefreshQuotes()", 5000);
}


Web Part Web-.
ASP.NET Script Callback. StockViewer
,
. . , .
:
private string results;
void ICallbackEventHandler.RaiseCallbackEvent(string argument)
{
string buf = "," + _stocks;
string[] list = buf.Split(new char[] { ',' });
list[0] = DateTime.Now.ToString("hh:mm:ss");
for (int i=1; i<list.Length; i++)
{
list[i] = GetCurrentValue(list[i]);
}
results = String.Join(",", list);
return;
}
string ICallbackEventHandler.GetCallbackResult()
{
return results;
}

6, JavaScript, .
:
function UpdateQuotes(response, context) {
var quotes = response.split(',');

280

II

ASP.NET

for(i=1; i<quotes.length; i++)


{
var elem = document.getElementById("StockValue" +
(i-1).toString());
elem.innerHTML = quotes[i];
}
var now = document.getElementById("LastUpdated");
now.innerHTML = quotes[0];
}

, , :
_, 1, ..., N


, , , ,
.
: http://www.microsoft.com/mspress/companion/0-7356-2177-2/.

StockViewer .
(, Visual Studio 2005,
.)
<asp:WebPartManager ID="WebMan" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server"
HeaderText="This is Zone #1"
PartChromeType="TitleAndBorder">
<ZoneTemplate>
<x:StockViewerWebPart runat="server" id="MyStocks"
RefreshRate="5" Stocks="XYZ,MYCOMP,FOO,BAR"
Title="Stock Viewer" />
</ZoneTemplate>
</asp:WebPartZone>

RefreshRate ,
.
,
. . 7-8
Web Part.

. 7-8. StockViewer ,
RefreshRate

Web Parts

281

, StockViewer, ,
. ,
, GetCurrentValue.
, , StockViewer
, .

Web Parts
, WebPart Web Parts, , ,
. , , .
Web Part

. 7-4 , Web
Parts, .

:
<ZoneTemplate>
<x:News runat="server" id="News" />
<x:Favorites runat="server" id="Favs" />
</ZoneTemplate>

? . XML-
. , XML-
, HTML, , .
Favorites.
<%@ Control Language="C#" ClassName="MyFavorites"%>
<asp:XmlDataSource ID="XmlData" runat="server"
DataFile="/App_Data/webpartsdata.xml"
XPath="WebPartsData/Favorite" />
<asp:Repeater ID="Repeater1" DataSourceID="XmlData" runat="server">
<HeaderTemplate>
<h2>Your Favorites</h2>
<ul>
</HeaderTemplate>
<SeparatorTemplate>
<br /><br />
</SeparatorTemplate>
<ItemTemplate>
<li>
<a href='<%# XPath("url")%>'><b><%# XPath("title")%></b></a>
<br />
<span style="font-size:85%">
<%# XPath("description") %>
</span>
</li>
</ItemTemplate>
<FooterTemplate>

282

II

ASP.NET

</ul>
</FooterTemplate>
</asp:Repeater>

Web
Parts, , GenericWebPart.
WebPart , ,
IWebPart, , Web
Parts. , ,
Web Part
: ,
GenericWebPart, .

@Implements, ,
Web Part Favorites IWebPart:
<%@ Control Language="C#" ClassName="MyFavorites"%>
<%@ Implements Interface="System.Web.UI.WebControls.WebParts.IWebPart" %>
<script runat="server">
private string _title = "Favorite Links";
string IWebPart.Title {
get { return _title; }
set { _title = value; }
}
// IWebPart
</script>


.
Web Part, , , .
, - GenericWebPart. :
<x:News runat="server" id="News" Title="News of the day" />
<x:Favorites runat="server" id="Favs" />

Web Parts . Web Part News , GenericWebPart, Web


Part Favorites , IWebPart. . 7-9
, . 7-4, .
Web Parts
, Web Parts .
<ZoneTemplate> Web Parts ,
. ,

Web Parts.
<ZoneTemplate>
<asp:Calendar ID="Calendar1" runat="server" Title="Today" >

Web Parts

283

<TodayDayStyle BackColor="#FF8000" />


</asp:Calendar>
<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="0">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1" />
<asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2" />
</WizardSteps>
</asp:Wizard>
</ZoneTemplate>

, . 7-10.

. 7-9.
Web Parts

. 7-10. Wizard Calendar


Web Parts

284

II

ASP.NET

, Title
, Title.
- GenericWebPart.

Web-
Web Part
. , , ,
,
. , ,
Web Parts .
, ,
.
Web Part ,
, .
. , , Web Part,
,
.
,

Web- ,
Web Parts. . 7-4.
. 7-4. ,

EmptyZoneTextStyle

ErrorStyle

, ,
Web Part ;
Web Part
ErrorWebPart

FooterStyle

HeaderStyle

MenuCheckImageStyle

, Web Part

MenuLabelHoverStyle

, ,
,

MenuLabelStyle

, Web Part

MenuPopupStyle

Web Part

MenuVerbHoverStyle

MenuVerbStyle

PartChromeStyle

Web Parts,

PartStyle

Web Part,

PartTitleStyle

Web Part,

SelectedPartChromeStyle

Web Part Edit

TitleBarVerbStyle

Web Parts

285

Visual Studio 2005 AutoFormat


WebPartZone (. 7-11). , .

. 7-11. AutoFormat
Visual Studio 2005

, , Web Zone , . . 7-5.


. 7-5. Web Zone,

AllowLayoutChange

DragHighlightColor
EmptyZoneText
LayoutOrientation
Padding
ShowTitleIcons
WebPartVerbRenderMode

, Web
Parts , ;
true
Web Part
Design
, Design,
, Web Parts
, ( )
( ) Web Parts
, Web
Part
, Web
Part .

(verbs) Web Parts .


, Web Part.
- .

(. 7-12).

286

II

ASP.NET

. 7-12.
Web Part

Web Zone , , . Web Parts , .


.
Web Parts

, Web
Part : , , .
, /
Web Part AllowXXX,
. 7-2. . 7-6.
. 7-6. Web Parts

Close

Web Part . Web Part Catalog Part ( )

Connect

Web Parts,
( )

Delete

Web Part . Web Part ,


Edit

Web Part Editor Part


,

Export

Web Parts XML. , ExportMode Web Part WebPartExportMode.None

Help

Web Part , . ,
HelpUrl Web Part

Minimize

Web Part

Restore

Web Part

, , , Web Parts, , Web Parts


, .

Web Parts

287

, Close :
<CloseVerb Enabled="false" />

, , Web Part AllowXXX. , , , ,


Web Part true AllowClose. , ,
, , .
, :
<MinimizeVerb Enabled="true" />

Web Part AllowMinimize false


.
WebPartVerb, ,
Description ( ), Text ( ,
) ImageUrl ().
WebPartVerb Enabled Visible, .

Web Part .
IWebActionable,
Verbs. Web Part
, Verbs , , Part. Web Part
, IWebActionable
. ,
Refresh StockViewer:
private WebPartVerbCollection _verbs;
public override WebPartVerbCollection Verbs
{
get
{
if (_verbs == null)
{
ArrayList a = new ArrayList();
WebPartVerb verb = new WebPartVerb("Refresh",
new WebPartEventHandler(RefreshQuotesFromMenu));
verb.Text = "Refresh";
a.Add(verb);
_verbs = new WebPartVerbCollection(base.Verbs, a);
}
return _verbs;
}
}

WebPartVerbCollection.
Verbs .
, , . (

288

II

ASP.NET

WebPartVerbCollection .) WebPartVerb. ,
,
. , .
Refresh Web Part
RefreshQuotesFromMenu.
.
. 7-13 Web Part StockViewer Refresh
.

. 7-13. Refresh Web Part

,
,
.
Web Part

, Web Parts,
. ,

. ASP.NET 2.0 .
, . ,
aspnetdb.mdf App_Data
SQL Server, web.config. ( Web Parts 4.)

Web Parts . , .
,
, .
Web Part . : ( )
. . , SQL Server .
User (),
Web Parts
. , Web Part, User, , , Shared ( ),
, . Web Part User Shared

Web Parts

289

[Personalizable], .
:
[Personalizable(PersonalizationScope scope)]
[Personalizable(PersonalizationScope scope, bool isSensitive)]

User Shared,
,
. [Personalizable] (
StockViewer), :
User, . Shared, Web Parts
, Shared, ,
.
.
,
<asp:WebPartManager>, PreInit.
WebPartManager1.Personalization.InitialScope = PersonalizationScope.Shared;

, Web Parts,
User. Personalization ToggleScope, , Provider,
(. 4).
Web Part
. .
( aspnetdb.mdf),
. ,
:

WebPartManager1.Personalization.ResetPersonalizationState();
ResetPersonalizationState
, .

, , . , User, Web Part


. , Shared, ,
. Web Part
User, , Web Part
. [Personalizable]
.
! , ,
Shared. , .
, Web Part
,
.

290

II

ASP.NET

Web Parts
, Web Parts Web Parts. , Web Parts

. , Web Parts ,
Web Parts, Web Part Web Parts
.


, DisplayMode Web Parts:
WebPartManager1.DisplayMode = mode;

(, ), , ,
, .
Menu,
. .

. 7-7 Web Parts ASP.NET.


Browse, Web
Parts, - .
. 7-7.

Browse

Web Parts ;

Catalog

Catalog Parts, ,
Web Parts,
,

Connect

Web Part,
,

Design

Web Parts

Edit

Catalog Parts, ,
Web Parts. ( , Web Part )

Design,
Web Parts .
. Browse Design . Edit, Catalog Connect,

Web Parts

291

, ,
. ,
, SupportedDisplayModes
WebPartManager.
,

,
Web Parts, ,
. 7-14.

. 7-14.

.
, - SupportedDisplayModes
WebPartManager. ,
.
DisplayMode Web Parts, .
modeswitcher.ascx.
<%@ Control Language="C#" ClassName="ModeSwitcher" %>
<script runat="server">
WebPartManager wpm;
void Page_Load(object sender, EventArgs e)
{
wpm = WebPartManager.GetCurrentWebPartManager(Page);
if (!IsPostBack)
{
foreach (WebPartDisplayMode mode in wpm.SupportedDisplayModes)
{
if (mode.IsEnabled(wpm))
SupportedModes.Items.Add(mode.Name);
}
}
}

292

II

ASP.NET

public void SelectedIndexChanged(object sender, EventArgs e)


{
string selectedMode = SupportedModes.SelectedValue;
WebPartDisplayMode mode = wpm.SupportedDisplayModes[selectedMode];
if (mode != null)
wpm.DisplayMode = mode;
}
</script>
<asp:DropDownList ID="SupportedModes" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="SelectedIndexChanged" />

, , . ,
, , . ( 12.)

:
<%@ Page Language="C#" CodeFile="Portal.aspx.cs" Inherits="Portal" %>
<%@ Register tagprefix="x" tagname="Mode" src="ModeSwitcher.ascx" %>
<x:Mode runat="server" id="Switcher" />

, Web Parts
.


Web Parts
, ,
Web Parts.
Web Parts.

, Web Parts.
,
. AutoFormat
Visual Studio 2005 (. . 7-11). ,
.
<asp:WebPartZone ID="WebPartZone1" runat="server" HeaderText="Zone #1">
<ZoneTemplate>
<x:News runat="server" id="News" Title="News of the day" />
<x:Favorites runat="server" id="Favs" />
</ZoneTemplate>
</asp:WebPartZone>
<asp:WebPartZone ID="WebPartZone2" runat="server" HeaderText="Zone #2">
<ZoneTemplate>
<asp:Calendar ID="Calendar1" runat="server" Title="Today" />
<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="0">
<WizardSteps>

Web Parts

293

<asp:WizardStep ID="WizStep1" runat="server" Title="Step 1" />


<asp:WizardStep ID="WizStep2" runat="server" Title="Step 2" />
</WizardSteps>
</asp:Wizard>
<x:StockViewerWebPart runat="server" id="MyStocks"
Title="Stock Viewer"
RefreshRate="5"
Stocks="XYZ,MYCOMP,FOO,BAR" />
</ZoneTemplate>
</asp:WebPartZone>

, Web Parts,
Calendar Wizard () . ,
, - .
, Web Parts , , ,
, .
,
( ). ASP.NET 2.0
.
,
( LoginName), ( LoginStatus) ,
(. . 7-14).
<table width="100%" bgcolor="cyan">
<tr>
<td align="left">
<asp:LoginName runat="server" ID="LoginName1"
FormatString="Welcome, <b>{0}</b>" />
<asp:LoginStatus runat="server" id="LoginStatus1" />
</td>
<td align="right">
<x:ModeSwitcher runat="server" id="Switcher" />
</td>
</tr>
</table>
Web Parts

Web Parts ,
. Design.
.
, Web Part ,
. . 7-15 Today Zone #2 Zone #1. Web Parts
Zone #1 , Web Part.
Web Part, , , , . ,
Browse,
.

294

II

ASP.NET

. 7-15. Design Web Parts


,
DOM . Web Part
,
.
Web Part ( , ),
.
Internet Explorer. ,
Design ,
Internet Explorer, .

Editor Zone
,
Web Parts, .
EditorZone.
, . ASP.NET
:
Web Part, Web Part,
, . .

:
<asp:EditorZone runat="server">
<ZoneTemplate>

Web Parts

295

<asp:AppearanceEditorPart runat="server" />


<asp:LayoutEditorPart runat="server" />
<asp:PropertyGridEditorPart runat="server" />
</ZoneTemplate>
</asp:EditorZone>

, , . <ZoneTemplate> , .
Edit ,
.
,
Web Parts, Editor Parts, Catalog Parts .
.

Web Parts Edit. (


) . Edit Design,
, Design ( ).
Web Part,
Edit.
, . 7-16. ,
Web Part Edit,
.

. 7-16.
Web Part

296

II

ASP.NET

Editor Parts

. 7-8 Editor Parts.


.
.
. 7-8. Editor Parts

AppearanceEditorPart

, ,
,
,
, Web Part .
Editor Part

( ) , Web Part,
Web Part
Web Part.
, , WebPart,
[Personalizable] [WebBrowsable]

BehaviorEditorPart

LayoutEditorPart

PropertyGridEditorPart


, (OK), (Apply)
(Cancel). .
ASP.NET 2.0
.
! , Web Part (browsable) . ,
[Personalizable] [WebBrowsable]. .

Catalog Zone
, Web Parts .
Web Parts, . ,
Web Parts, .
Catalog.
Catalog

, .
, ,
<ZoneTemplate>. , , .
<asp:CatalogZone ID="CatalogZone1" runat="server">
<ZoneTemplate>
<asp:PageCatalogPart ID="PageCatPart1" runat="server" />
<asp:DeclarativeCatalogPart ID="DeclCatPart1" runat="server">
</asp:DeclarativeCatalogPart>

Web Parts

297

<asp:ImportCatalogPart ID="ImportCatalogPart1" runat="server" />


</ZoneTemplate>
</asp:CatalogZone>

,
; . 7-9.
. 7-9. Catalog Parts

DeclarativeCatalogPart

Web Parts,
,

ImportCatalogPart

Web Part,

PageCatalogPart

Web Parts,
,

. 7-17. Web Parts,


, .

. 7-17. Web Parts

Catalog Parts ,
CatalogZone.
.
.

298

II

ASP.NET

DeclarativeCatalogPart

DeclarativeCatalogPart Web Parts, . Web Parts


.aspx WebPartsTemplate,
:
<asp:DeclarativeCatalogPart runat="server">
<WebPartsTemplate>
<x:WeatherWebPart runat="server" zipcode="00015" />
<x:BookFinder runat="server" author="Dino Esposito" />
</WebPartsTemplate>
</asp:DeclarativeCatalogPart>

Web Parts, DeclarativeCatalogPart, ,


.
Web Parts, , . . 7-18 DeclarativeCatalogPart.

. 7-18. Web Parts,


Web Part ,
, Web Parts.
! Catalog Parts Editor Parts,
Catalog Edit , , Title. , . 7-18
DeclarativeCatalogPart Optional Web Parts.

Web Parts

299

Web Parts

ImportCatalogPart (. 7-19),
Web Part
.webpart. Web Part
.

. 7-19. Web Part

Web Part , ExportMode ,


None, .
, ExportMode All:
<asp:StockViewerWebPart runat="server" ExportMode="All" ... />

, ,
ExportMode NonSensitiveData. (, [Personalizable].) Web Parts
,
Export. ,
(. 7-20).

. 7-20.

300

II

ASP.NET

, Web Part,
Web Parts.
enableExport <webParts> web.config.
<webParts enableExport="true" />

, [Personalizable].
, , .
.webpart ,
. XML:
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart>
<metaData>
<type name="ProAspNet20.StockViewerWebPart, ProAspCompLib" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="AllowClose" type="bool">True</property>
<property name="ExportMode" type="exportmode">All</property>
</properties>
</data>
</webPart>
</webParts>

.webpart . Web Part


, .

Web Parts
Web Parts, , , .
. -.
Web Parts, , . Web Parts , . ,
,
.

Web Parts
Web Parts : .
. Web Parts. Web Part
Web Part.

Web Parts

301

Web Parts

, : .
Web Parts;
.
Web Parts:
<ZoneTemplate>
<x:EmployeesWebPart runat="server" id="emp" Title="Employee Info" />
<x:OrdersWebPart runat="server" id="ord" Title="Orders 1997" />
</ZoneTemplate>

, Web Parts Web-


. :
, .
Web Parts

Web Parts,
Web Parts <StaticConnections>:
<asp:WebPartManager runat="server" id="WebPartManager1">
<StaticConnections>
<asp:WebPartConnection ID="Conn1"
ProviderID="emp"
ProviderConnectionPointID="EmployeeIDProvider"
ConsumerID="ord"
ConsumerConnectionPointID="EmployeeIDConsumer" />
</StaticConnections>
</asp:WebPartManager>

;
. ProviderID
ConsumerID ,
ConsumerConnectionPointID ProviderConnectionPointID
.
.
Web Parts


Web Parts. :
<asp:ConnectionsZone ID="ConnectionsZone1" runat="server" />

, ,
. , Web
Parts Connect.
, Web Parts, ,
Connect.

302

II

ASP.NET

,
,
Web Parts . . 7-21.
, ,
.

. 7-21.
Web Parts , ,
, .

, Web Parts. ,
.
Web
Part Web Parts.
.
. ,
. , ,
.
- , , .


, Web Parts, WebPart.
EmployeesWebPart; . , . Web Part
.
OrdersWebPart; , . ,
.

Web Parts

303

Web Part, , .
:
interface IEmployeeInfo
{
int EmployeeID { get; set; }
}

EmployeesWebPart
ASP.NET, WebPart;
:
public class EmployeesWebPart : WebPart, IEmployeeInfo
{
private int _empID;
public int EmployeeID
{
get { return _empID; }
set { _empID = value; }
}

EmployeeID ,
.
[Personalizable(true)]
[WebBrowsable(true)]
public int EmployeeID
{
get { return _empID; }
set { _empID = value; }
}

. , , [ConnectionProvider]. ,
IEmployeeInfo:
[ConnectionProvider("EmployeeIDProvider",
"EmployeeIDProvider")]
public IEmployeeInfo GetEmployeeInfo()
{
return this;
}

304

II

ASP.NET

ProviderName
( ) ConsumerName ( ),
<asp:WebPartConnection>.
WebPart , ,
ConnectionProvider. ,
, ,
.

Web Part, , .
.
[ConnectionConsumer("EmployeeIDConsumer", "EmployeeIDConsumer")]
private void GetEmployeeInfo(IEmployeeInfo empInfo)
{
if (empInfo != null)
{
_empID = empInfo.EmployeeID;
FindEmployeeInfo();
}
else
throw new Exception("No connection data found.");
}

ASP.NET
, [ConnectionConsumer].

.

DataGrid,
Orders Northwind.


,
Web Parts (
, ,
).
<StaticConnections>
<asp:WebPartConnection
ProviderID="emp" ProviderConnectionPointID="EmployeeIDProvider"
ConsumerID="ord" ConsumerConnectionPointID="EmployeeIDConsumer" />
</StaticConnections>

Web Parts emp ord;


EmployeeIDProvider, ,
EmployeeIDConsumer.
,
, , .
, . 7-22.

Web Parts

305

. 7-22. ,
Web Parts

Web Part, , EmployeeID. ,


, .

Web Parts Framework ASP.NET


. Web Part , ,
.

, .
Web Parts ASP.NET,
.
Web Parts. , (
Minimize, Edit Close). , .
Web Parts Framework , Design,
Edit Catalog. Design Web Parts, . Edit ,
Web Parts. , . , Catalog Web Parts,
, .

306

II

ASP.NET

, Web
Parts, . . -,

.

ASP.NET SharePoint-,
, Web Parts.

Web Part , , .

Web Parts , .
,
Web Parts, Web Parts
.

Web Part ,
: ,
,
WebPart. , Web Part
.

Web Part ,
, , ,
, .

Web Parts , . , , .

ASP.NET Web- , ,
.
, , , Palm BlackBerry. Web Forms ASP.NET ,
.
machine.config,
.
ASP.NET . ,
Mobile Web Forms ,
,
.
ASP.NET
. , , , , PhoneCall.
ASP.NET,
Visual Studio .


ASP.NET ,
, runat server. .NET Framework . MobileControl, , ,
Control.
, . Web- MobilePage.



ASP.NET , .
,
, .

- ( ). ,

308

II

ASP.NET

,
.
HTML-
XHTML-. HTML 3.2 HTML 4.0 ,
, .
,
. ASP.NET
.
,
.

. ,
.

, ,
, -, . ASP.NET
, .

. . 8-1.
. 8-1. ,

Compact HTML 1.0

HTML 3.2
WML 1.x

XHTML

HTML 3.2,
,
.
cHTML. I-Mode
HTML,
, Pocket PC 2002, Palm BlackBerry
Wireless Markup Language ( )
.
,

Wireless Application Protocol (WAP).
WML
,
XML- HTML,
WAP 2.0

ASP.NET : , , , .
. 8-2.
Web Forms.

309

.
.
. 8-2. ASP.NET

AdRotator


, ASP.NET
Calendar
,
ASP.NET
Command
Button ASP.NET

CompareValidator
ASP.NET
CustomValidator
ASP.NET
DeviceSpecific

Form Panel
Form
HtmlForm ASP.NET,

Image
ASP.NET
Label
ASP.NET
Link

URL.
HyperLink ASP.NET
List
ASP.NET Repeater DataList,
.

ObjectList
ASP.NET DataGrid,

Panel
ASP.NET Panel
PhoneCall
, ,
, .
mailto HTML
RangeValidator
ASP.NET
RegularExpressionValidator ASP.NET
RequiredFieldValidator
ASP.NET
SelectionList
, .
, , .
,

StyleSheet
, .

TextBox
;

TextView
,

ValidationSummary
ValidationSummary ASP.NET,

310

II

ASP.NET

, PhoneCall TextView,
ASP.NET. , ASP.NET,
, . . 8-1
. , , .

. 8-1. ASP.NET


, -
ASP.NET.

ASP.NET
Web- ASP.NET MobilePage, ASP.NET Page.
MobilePage , .
(custom controls) . .

311

, ,
.
<%@ Page Language="C#" CodeFile="Hello.aspx.cs" Inherits="Hello" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<%@ Import Namespace="System.Web.Mobile" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<mobile:Form ID="Form1" runat="server">
Language is
<mobile:Label runat="server" font-bold="true" id="theBrowser" />
</mobile:Form>
</body>
</html>

Label,
. Load
,
. MobileCapabilities System.Web.Mobile,
System.Web.UI.MobileControls.
public partial class Hello : System.Web.UI.MobileControls.MobilePage
{
protected void Page_Load(object sender, EventArgs e)
{
MobileCapabilities mobCaps = (MobileCapabilities) Request.Browser;
theBrowser.Text = mobCaps.PreferredRenderingType;
}
}

, Openwave 7.0 (
http://odn.openwave.com), ,
. 8-2.

. 8-2. Openwave

312

II

ASP.NET


WML 1.1:
<wml>
<head>
<meta http-equiv="Cache-Control" content="max-age=0" />
</head>
<card>
<do type="accept"><noop /></do><p>
Language is <b>wml11</b></p>
</card>
</wml>

, Internet Explorer. HTML 3.2. . 8-3


Internet Explorer.

. 8-3. Internet Explorer

, , :
<html><body>
<form id="Form1" name="Form1" method="post" action="Hello.aspx?__ufps=149742">
<input type="hidden" name="__VIEWSTATE" value="/wEXA ... CVL">
<input type="hidden" name="__EVENTTARGET" value="">
<input type="hidden" name="__EVENTARGUMENT" value="">
<script language=javascript><!-function __doPostBack(target, argument){
var theform = document.Form1
theform.__EVENTTARGET.value = target
theform.__EVENTARGUMENT.value = argument
theform.submit()
}
// -->
</script>
Language is <b>html32</b>
</form>
</body></html>
.
,
.
.

MobilePage : Form
StyleSheet. , , .
,
.
. ,

313

.
, , .

ASP.NET
.
(pagination).
.
,
.

. ,
Paginate Form true. , ,
,
, Paginate -
false. Form ,
, PageCount, CurrentPage PagerStyle.

ControlToPaginate,
.

. , , ,
,
.
. , List,
, . -,
; ,
. . 8-4
()
, .

. 8-4.

314

II

ASP.NET

! ,
. 8-4, , , Next, .
cookie.

ASP.NET, ,
Web Forms.
, . ASP.NET 3
Programming Microsoft ASP.NET 2.0: Core Reference (Microsoft Press, 2005).


, , Adapter MobilePage.
machine.config, web.config ,
web.config, .
. :
,
.

. .

, Request,
. .

, .
Load .
,
, .


, , ,
.
, IPostBackDataHandler.
.

, , .

- . , , PreRender. .
.


, . .

,
.
.

315

. Unload , .


ASP.NET 1.x, , ,
. ASP.NET 2.0
,
.

, .
, ,
.
Microsoft Windows ASP.NET.
, ,
. .
, .

.
:


,
, , ,
, ,
.
.
IPageAdapter, API
.

form, , . ,

. ,
. , .

, . ,
, , .

(text writer) ,
. HtmlTextWriter.
,
.
,
.

ASP.NET 2.0
, cHTML, XHTML, HTML WML.

316

II

ASP.NET


ASP.NET , Panel Form,
. Form ; Panel,
, .
, ;
.
Panel

, . ,
. , .
<mobile:Form runat="server">
<mobile:Panel runat="server" Font-Bold="true" Alignment="Right">
<mobile:Label runat="server">Programming ASP.NET 2.0</mobile:Label>
</mobile:Panel>
<mobile:Panel runat="server" BackColor="yellow">
<mobile:Label runat="server">Dino Esposito</mobile:Label>
</mobile:Panel>
</mobile:Form>

ASP.NET,
MobilePage, Form StyleSheet. , ,
, . .
, Panel
.
Form

Form , . , Action Method. Action


, URL.
.
,
.
ActiveForm, .
, Link.
<mobile:Form id="Form2" runat="server">
<mobile:Label runat="server"
text="Second page of information" />
<mobile:Link runat="server" NavigateURL="#Form1" text="Back" />
</mobile:Form>

,
NavigateURL #.



ASP.NET List, ObjectList SelectionList.
List Repeater DataList; -

317

. SelectionList ,
.
ObjectList,
. , ,
.
List

List .
.
. , .
ItemCommand, ,
. ItemsAsLinks true,
. ItemCommand ,
URL. URL DataValueField,
DataTextField.
, . :
, ,
.
<mobile:Form id="IntroForm" runat="server">
<b>Where do you want to go today?</b>
<mobile:List runat="server" id="Cities" OnItemCommand="List_Click" >
<item Text="Rome" Value="10" />
<item Text="New York" Value="$500" />
<item Text="London" Value="200" />
<item Text="Paris" Value="350" />
<item Text="Sydney" Value="$1200" />
</mobile:List>
</mobile:Form>
<mobile:Form runat="server" id="ResultsForm">
<mobile:Label runat="server" id="Info"/>
</mobile:Form>

.
protected void List_Click(object sender, ListCommandEventArgs e)
{
string msg = String.Format("Going to {0} for {1}.",
e.ListItem.Text, e.ListItem.Value);
Info.Text = msg;
ActiveForm = ResultsForm;
}

. 8-5 .
List, ItemCommand .
! , $ .
WML . ASP.NET
,
: $$.

318

II

ASP.NET

. 8-5.

List
DataSource , IEnumerable. , , DataSourceID.
ASP.NET 9
Programming Microsoft ASP.NET 2.0: Core Reference (Microsoft Press, 2005).
, List
, Text , Value.
DataTextField DataValueField List. ,

, ItemDataBind.
void OnItemDataBind(object sender, ListDataBindEventArgs e) {
e.ListItem.Text = String.Format ("{0} ${1}",
DataBinder.Eval(e.DataItem, "city"),
DataBinder.Eval(e.DataItem, "price"));
}

, , , .
List
ASP.NET Repeater.
ObjectList

ObjectList
DataGrid ASP.NET. , .
, .
. LabelField , .
,
, .
, .

319

, <command>, ,
BackCommandText. , AutoGenerateField (
true) <fields>
, .
ObjectList
List. , ObjectList .

. , ObjectList
.
,
ObjectList .
ObjectList List

LoadItems.
ItemCount. 0, ,
. , LoadItems
.
SelectionList

SelectionList ,
.

. , , AutoPostBack true.
, SelectedIndexChanged.
SelectionList : ( ), -,
, , . (
) SelectType.
. , ; ,
.
, , ,
.
<mobile:Form runat="server" id="Form1">
Your skills? <br />
<mobile:SelectionList runat="server" id="list"
SelectType="checkbox" />
<mobile:Command runat="server" OnClick="Button_Click" Text="Go" />
</mobile:Form>
<mobile:Form runat="server" id="ResultsForm">
<mobile:Label runat="server" id="Results" />
</mobile:Form>

.
public partial class Select : System.Web.UI.MobileControls.MobilePage
{

320

II

ASP.NET

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack) {
ArrayList values = new ArrayList();
values.Add("ASP.NET");
values.Add("ADO.NET");
values.Add("SQL Server");
values.Add("XML");
list.DataSource = values;
list.DataBind();
}
}
protected void Button_Click(object sender, EventArgs e)
{
string buf = "";
foreach (MobileListItem item in list.Items)
buf += (item.Selected ? item.Text + ", " : "");
buf = buf.TrimEnd();
if (buf.EndsWith(","))
buf = buf.TrimEnd(',');
Results.Text = buf;
ActiveForm = ResultsForm;
}
}

. 8-6 . SelectionList, ,
.

. 8-6. SelectionList


ASP.NET TextControl, , .
Text,

321

. , TextControl,
Link, TextBox Label. Label ASP.NET,
Link HyperLink.
Command,
, PhoneCall.
TextBox

TextBox
Text .
, , .
.
<mobile:TextBox runat="server" id="theUser" OnTextChanged="Alert" />

TextBox OnTextChanged, ,
.
Command

Command ASP.NET Button LinkButton.


submit ( )
. Format Button Link;
Link, , URL
ImageUrl. ,
, Command
. (
.)
Command . ItemCommand
OnClick. ItemCommand, ,
. ,
CausesValidation ,
.
, TextBox
Command.
<mobile:Form runat="server">
Search for:
<mobile:TextBox runat="server" font-bold="true" id="theSubject" />
<mobile:Command runat="server" Text="GO" OnClick="OnSearch" />
</mobile:Form>
<mobile:Form runat="server" id="ResultsForm">
<mobile:Label runat="server" id="theResults" />
</mobile:Form>

, :
protected void OnSearch(object sender, EventArgs e)
{
string msg = "Results for '{0}'";

322

II

ASP.NET

msg = String.Format(msg, theSubject.Text);


theResults.Text = msg;
ActiveForm = ResultsForm;
}

ActiveForm Form , .
. 8-7.

. 8-7. TextBox Command

PhoneCall

PhoneCall .
, ( ),
, . .
<mobile:Form runat="server">
Phone numbers found for Joe:
<mobile:PhoneCall runat="server"
AlternateFormat="{0} at {1}"
AlternateURL="http://www.acme.com"
PhoneNumber="111-222-0000"
Text="ACME Corp" />
<mobile:PhoneCall runat="server"
AlternateFormat="{0} at {1}"
PhoneNumber="111-333-0000"
Text="Home" />
</mobile:Form>

AlternateFormat ,
, .
:
Text, PhoneNumber. , AlternateURL,

323

URL. Text ,
. . 8-8 PhoneCall
Openwave.

. 8-8. PhoneCall


BaseValidator, , ,
TextControl. Text ErrorMessage. Text , , ,
ErrorMessage. ErrorMessage
ValidationSummary.
.


CompareValidator ,
. ControlToValidate
, , , ValueToCompare,
ControlToCompare. , .

CustomValidator , .
ControlToValidate ,
ServerValidate.
, IsValid , , false
true.

RangeValidator ,
. MinimumValue
MaximumValue, . Type
.

324

II

ASP.NET

RegularExpressionValidator , . ControlToValidate,
ValidationExpression.

RequiredFieldValidator .
, ; ,
InitialValue (
) .

, ASP.NET
. ValidationSummary,
, ,
. BackLabel
, .
Command , ; TextBox SelectionList , . Text, SelectedIndex.
(, )
.
[ValidationProperty]. (
4 Programming Microsoft ASP.NET 2.0: Core Reference.)
, , .
SelectionList,
.
. SelectionList RequiredFieldValidator.
InitialValue ASP.NET 1.
<mobile:Form runat="server" id="Main">
<mobile:RequiredFieldValidator runat="server"
ErrorMessage="Must indicate a skill!"
ControlToValidate="skills" />
<b>Indicate your skills</b><br>
<mobile:SelectionList runat="server" id="skills"
SelectType="checkbox" />
<mobile:Command runat="server" OnClick="Submit" Text="Send" />
</mobile:Form>
<mobile:Form runat="server" id="ResultsForm">
<b>Recognized skills</b>
<mobile:Label runat="server" id="Results" />
</mobile:Form>

, ,
,
.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
ArrayList values = new ArrayList();

325

values.Add("ASP.NET");
values.Add("ADO.NET");
values.Add("XML");
values.Add("Windows Forms");
values.Add("SQL Server");
skills.DataSource = values;
skills.DataBind();
}
}
protected void Submit(object sender, EventArgs e)
{
if (!Page.IsValid) return;
string buf = "";
foreach (MobileListItem item in skills.Items)
buf += (item.Selected ? item.Text + ", " : "");
buf = buf.TrimEnd();
if (buf.EndsWith(","))
buf = buf.TrimEnd(',');
Results.Text = buf;
ActiveForm = ResultsForm;
}

IsValid MobilePage false, ,


.
ValidationSummary, . . 8-9.

. 8-9.


,
, .

326

II

ASP.NET

, ,
.
Pocket PC, ,
.
. .
.
, , , . ,
() , .
.
Web- 20 , ,
,
, .
, ,
. Web ,
,
, .


,
.
, , ,
, , , ,
.


. ,
. ,
. ,
, . ,
, , , ,
, ,
.
,
, : .
( ,
, ).
, ,
. -

327

,
,
, .
, , . ,
,
. , .
Visual Studio 2005

Visual Studio , Pocket PC 2003, SmartPhone 2003 Windows CE 5.0.


Web-
Web-. web.config,
.

. ,
ASP.NET ,
.
.

Visual Studio 2005


Internet Explorer.
.
Visual Studio Browse With . (. 8-10),
.
Visual Studio .

. 8-10.
Visual Studio
ASP.NET
, . , ASP.NET
,
. , , ,
, ASP.NET , .

328

II

ASP.NET


CustomerFinder .
.
, ObjectList . , ,
. , , ,
.
. ,
ASP.NET
.

List,
, 26 . Text ListItem
, Value , .
<mobile:form id="MainForm" runat="server">
<mobile:List id="Menu" runat="server" OnItemCommand="Menu_ItemCommand">
<Item Value="A,B,C,D,E,F" Text="A-F" />
<Item Value="G,H,I,J,K,L,M" Text="G-M" />
<Item Value="N,O,P,Q,R,S" Text="N-S" />
<Item Value="T,U,V,W,X,Y,Z" Text="T-Z" />
</mobile:List>
<mobile:Label id="Desc" runat="server" Text="Select Customers" />
<mobile:TextBox id="Initials" runat="server" Size="5" />
<mobile:Command id="FindButton" runat="server"
OnClick="FindButton_Click">Find</mobile:Command>
</mobile:form>

. ,
.
:
void Menu_ItemCommand(object sender, ListCommandEventArgs e)
{
string[] menuItems = e.ListItem.Value.Split(",".ToCharArray());
Session["AvailableInitials"] = menuItems;
LetterList.DataSource = menuItems;
LetterList.DataBind();
//
ActiveForm = SecondMenuForm;
}


. ,
Find .
List. ,
.

. , -

329

. . 8-11 ,
.

. 8-11.

ActiveForm
. ,
. , , ,
. ActiveForm
, ,
. ActiveForm
-.
-

,
Value ListItem. :
<mobile:form id="SecondMenuForm" runat="server">
<mobile:List id="LetterList" runat="server" />
<mobile:Label id="Desc" runat="server" Text="Select Customers" />
<mobile:TextBox id="CustName" runat="server" />
<mobile:Command id="FindCustomerButton" runat="server" text="Find" />
</mobile:form>

,
ADO.NET DataView, , .
ObjectList.
, ,
, (. 8-12).
, , ,
.

330

II

ASP.NET

. 8-12.

.
ObjectList, , :
DataView SelectCustomers(string filterString)
{
//
DataTable data = GetData();
DataView view = new DataView(data);
//
string cmdText = "";
string[] initials = filterString.Split(",".ToCharArray());
string opOR = "";
foreach(string s in initials) {
cmdText += String.Format("{0} {2} LIKE '{1}%' ",
opOR, s, "companyname");
opOR = " OR ";
}
//
view.RowFilter = cmdText;
return view;
}

- , .
DataSource ObjectList:
void LetterList_ItemCommand(object sender, ListCommandEventArgs e) {
DataView view = SelectCustomers(e.ListItem.Value);
CustomerList.DataSource = view;
CustomerList.DataBind();
ActiveForm = CustomerForm;
}

331

:
<mobile:form id="CustomerForm" runat="server" paginate="true">
<mobile:ObjectList id="CustomerList" runat="server"
Wrapping="nowrap" AutoGenerateFields="False"
LabelField="Company">
<Field Name="Company" DataField="companyname" Visible="False" />
<Field Name="Address" DataField="address" />
<Field Name="City" DataField="city" />
<Field Name="Country" DataField="country" />
<Field Name="Phone" DataField="phone" />
</mobile:ObjectList>
<mobile:Command id="BackMenuCommand" runat="server" text="Back" />
</mobile:form>

ObjectList ,
LabelField. ,
(. 8-13) <field>.
, LabelField, Company.
, , Visible false. Name
.

. 8-13.

, ObjectList, List, .
! WML Web- (card).
(deck). WML- ,
, .
, WAP, Web-
, .
, . , , . ,
ASP.NET , , .
1200 .

332

II

ASP.NET



.
,
,
. .
<DeviceSpecific>.

ASP.NET .aspx , . ,

,
, .
<DeviceSpecific> <Choice>.
<DeviceSpecific> . , .
web.config. :
<deviceFilters>
<filter name="isHTML32"
compare="PreferredRenderingType"
argument="html32" />
<filter name="isWML11"
compare="PreferredRenderingType"
argument="wml11" />
<filter name="prefersGIF"
compare="PreferredImageMIME"
argument="image/gif" />
</deviceFilters>

<filter> ,
<choice>. compare ,
, argument . ,
, , WML 1.1,
, , :
<mobile:Form runat="server">
<mobile:Label runat="server" text="Some text">
<DeviceSpecific>
<choice filter="isWML11" font-italic="true" />
</DeviceSpecific>
</mobile:Label>
</mobile:Form>

, web.config . ,
<DeviceSpecific>. ,
.

333

,
. ,
. PhoneCall?
, .
, List ObjectList,
.
, ,
List, PhoneCall.
<mobile:List id="CustomerList" runat="server" OnItemCommand="ItemCommand">
<DeviceSpecific>
<Choice>
<ItemTemplate>
<mobile:PhoneCall runat="server"
Text='<%# Eval("companyname") %>'
PhoneNumber='<%# Eval("phone") %>'>
</mobile:PhoneCall>
</ItemTemplate>
</Choice>
</DeviceSpecific>
</mobile:List>

Filter, ,
, .

Web- , . ASP.NET ,

. , ,
, .

ASP.NET
.
. , Web-, .
, ASP.NET
.
. - -
. ,
, Back.
, .
, ASP.NET
, .

334

II

ASP.NET

, . ,
, , web.config
. , ,
.
<configuration>
<system.web>
<mobileControls sessionStateHistorySize="15" />
</system.web>
</configuration>

Session, , , .
, ViewStateExpire. ; ,
OnViewStateExpire MobilePage
.
, Web- ASP.NET,
, ,
. EnableViewState @Page;
,
EnableViewState .

, , ,
. , MobilePage
,
Web-.
.
ClientViewState ,
.
.
,
.

MobilePage HiddenVariables.
, .
, .

. cookie
. cookie , . ASP.NET
. ,
, URL, , , ,

335

, URL .
, URL
.
, cookie- .

, , ,
. ,
, . ,
, .
, .
,
, ASP.NET,
.
,
, . , ASP.NET
,
.

ASP.NET
.

,
,
.


.
,
.

List, ObjectList SelectionLis ASP.NET.

, .

. ASP.NET
, .

, ,
. Web
. Web
, , ,
, HTML-. , ,
, Adobe Photoshop.
Web Web-
,
. , ,
, ,
, .
.
, ,
, .
(
) (,
).
Web. .NET
Framework , ,
GDI+, ASP.NET ,
. , ,
GDI+ .NET
Framework.

Web-
HTML
<img>, URL . ,
URL, ,
Web- URL. URL
, , GIF JPEG. Web- ,
.
, Web <img> ,
Web-.
Web.

337

<img>

HTML- <img> Web-. , , , , . HTML- :


<img id="control ID"
alt="alternate text"
align="top | middle | bottom | left | right"
border="border width"
height="image height"
src="URL"
width="image width" />

ASP.NET <img> HtmlImage. ,


Image, ,
. HtmlImage
System.Web.UI.HtmlControls, Image System.Web.UI.WebControls.

, <img>, ASP.NET
. ,
, , ,
, . , .
Image:
<img src='<%# , URL %>' />

runat=server?
? , ASP.NET 2.0
DataBoundLiteralControl, .
DataBind, #-,
<img>.
<img> URL , , . URL
, .
URL
.

<img> , , ,
, Web-.
, URL
HTTP-. <img> .aspx, Web- .

338

I I

ASP.NET

,
. , .

,
Web- . ,
, <b>, . <img>,
,
URL. URL
, , , MIME.
, URL ,
, MIME- ,
<img>. ,
, .
,
, .aspx.
! , ,
URL <img>.
(, )
, <img>
HTTP, .

, , Content-Type . ,
, . ,
IIS , JPEG:
HTTP/1.1 200 OK
Server: Microsoft-IIS/6.0
Date: Thu, 24 Nov 2005 14:30:12 GMT
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: image/jpeg
Content-Length: 28521

ASP.NET Content-Type HttpResponse. ContentType


text/html;
MIME- HTTP. , ,
,
- .
, ContentType , JPEG:
Response.ContentType = "image/jpeg";

, ,
ASP.NET:
<%@ Page Language="C#" %>
<html>

339

<body>
<form runat="server">
<img src="image.aspx" />
</form>
</body>
</html>

image.aspx :
protected void Page_Load(object sender, EventArgs e)
{
string fileName = Server.MapPath(@"/proaspnet/images/slotmachine.jpg");
Response.ContentType = "image/jpeg";
Response.WriteFile(fileName);
}

.
. src
<img> URL .aspx.
,
.
! ASP.NET
. HTTP,
. ,
HTTP, .


,
, , , . ,
system.web , ASP.NET,
,
(. 6). ,
Microsoft Visual Studio 2005.

,
, Build Action Embedded
Resource (. 9-1). , , (DLL).
, Web-, Build Action,
.
: _
._..
, _
. ,
. 9-1, ProAspCompLib.SlotMachine.jpg (. 9-2).

340

I I

ASP.NET

. 9-1.

. 9-2. .NET Reflector

, , , , . ,
,
.
,
. ? ; ,
.
URL,
<img>.
HTTP. , ;
image.axd. <img>, , :
<img src="image.axd?asm=...&res=..." />

341

src URL , , .
.
, ,
, . ,
, , .

, ;
, XSLT. , ,
. ?
Assembly ( System.Reflection) GetManifestResourceNames GetManifestResource
Stream. ,
, .
, ResourceNames
, system.web:
Assembly dll = Assembly.LoadWithPartialName("system.web");
string[] resources = dll.GetManifestResourceNames();
ResourceNames.DataSource = resources;
ResourceNames.DataBind();

. 9-3 .

. 9-3. , system.web

, GetManifestResourceStream:
private System.Drawing.Image LoadImageFromResources(string imageID)
{
Assembly dll = Assembly.LoadWithPartialName("system.web");
Bitmap img = new Bitmap(dll.GetManifestResourceStream(imageID));
return img;
}
protected void buttonSave_Click(object sender, EventArgs e)
{

342

I I

ASP.NET

string resourceName = ResourceNames.SelectedValue;


System.Drawing.Image img = LoadImageFromResources(resourceName);
if (img != null)
{
string path = string.Format(@"c:\{0}", resourceName);
StreamWriter bin = new StreamWriter(path);
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
img.Dispose();
ms.WriteTo(bin.BaseStream);
ms.Close();
bin.Close();
//
string js = "alert('Done.');";
ClientScript.RegisterStartupScript(this.GetType(),
"Alert", js, true);
}
}

GetManifestResourceStream , . API - .NET Framework,


. ( ,
ASP.NET ;
C:\ .)
! ASP.NET 2.0 ,
. GetWebResourceUrl ClientScriptManager [WebResource],

, .
13, .

,
. ,
, . ,
, -
BLOB (binary large objects). BLOB ,
. ,
BLOB Microsoft SQL Server, Oracle
.


,
, ADO.NET. , ,
BLOB , . ,
(, ),
. , ,
.

343

BLOB
(data reader) ADO.NET. ,
DataSet. ,
DataSet ,
Web- . BLOB
, .
, BLOB, ,
SQL Server.
Oracle.
BLOB

BLOB- ADO.NET,
SQL-, ExecuteScalar
.
, .
HTTP, , ASP.NET:
public class DbImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext ctx)
{
// , ID, URL,
//
int id = -1;
bool result = Int32.TryParse(ctx.Request.QueryString["id"], out id);
if (!result)
ctx.Response.End();
string connString = "...";
string cmdText = "SELECT photo FROM employees WHERE employeeid=@id";
// BLOB
byte[] img = null;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("@id", id);
conn.Open();
img = (byte[])cmd.ExecuteScalar();
conn.Close();
}
//
if (img != null)
{
ctx.Response.ContentType = "image/jpeg";
ctx.Response.BinaryWrite(img);
}
}
public bool IsReusable
{
get { return true; }
}
}

344

I I

ASP.NET

. , , -,
photo JPEG, -,
, -, URL,
, id.
id ,
. , ,
, ,
. , SQL , .
.
BinaryWrite
HttpResponse.
! Northwind (
), . SQL Server 2000
photo Employees OLE-.
, , Northwind
Microsoft Access SQL Server. ,
, , , 78 , .
, OLE-.
BLOB,
Northwind photo
Employees :

Response.OutputStream.Write(img, 78, img.Length);


, BinaryWrite,
, .

. 9-4 , BLOB-.
,
. URL, Image:
string url = String.Format("dbimage.axd?id={0}",
EmpList.SelectedValue);
Image1.ImageUrl = url;

2, HTTP
web.config .
dbimage.axd, ,
, :
<httpHandlers>
<add path="dbimage.axd" verb="*"
type="ProAspNet20.Components.DbImageHandler,
ProAspCompLib"/>
</httpHandlers>

345

. 9-4. ,
BLOB-

BLOB-

, INSERT UPDATE,
. SQL-, . BLOB
, ,
, SQL Server Image,
.
. 9-5 , Web SQL Server.

. 9-5.
Web-,
SQL Server

. 9-1.

346

I I

ASP.NET

. 9-1.

ImageID

Bits

BLOB- Image,

Description

ImageSize
MIME


, MIME-

Uploader

UploadTime

FileUpload, . ASP.NET 2.0 HtmlInputFile ASP.NET 1.x.


, EncType,
multipart/form-data. ASP.NET 2.0 ,
HtmlInputFile FileUpload, ,
.
<asp:FileUpload ID="theFile" runat="server" />

PostedFile , . HttpPostedFile,
ContentLength, ContentType InputStream.
MIME- , , .
, MyPics
MyBlobs, SQL Server:
protected void UploadButton_Click(object sender, EventArgs e)
{
// "theFile" ,
// FileUpload
int sizeOfFile = theFile.PostedFile.ContentLength;
int recordsAffected = -1;
// SQL-
string connString =
ConfigurationManager.ConnectionStrings["MyBlobs"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
string cmdText = "INSERT INTO MyPics " +
"(bits, description, uploader, uploadtime, imagesize, mime) " +
"VALUES (@imageBits, @description, @uploader, @uploadTime, " +
"@imageSize, @mimeType)";
SqlCommand cmd = new SqlCommand(cmdText, conn);
//
cmd.Parameters.AddWithValue("@imageBits",
GetImageBits(theFile.PostedFile.InputStream, sizeOfFile));

347

cmd.Parameters.AddWithValue("@description",
theDesc.Text);
cmd.Parameters.AddWithValue("@uploader",
theUploader.SelectedItem.Value);
cmd.Parameters.AddWithValue("@uploadTime",
DateTime.Now);
cmd.Parameters.AddWithValue("@imageSize",
sizeOfFile);
cmd.Parameters.AddWithValue("@mimeType",
theFile.PostedFile.ContentType);
//
conn.Open();
recordsAffected = cmd.ExecuteNonQuery();
conn.Close();
}
//
string msg = (recordsAffected != -1
? "Successfully done!" : "Something went wrong...");
string js = String.Format("alert('{0}');", msg);
ClientScript.RegisterStartupScript(this.GetType(), "Alert", js, true);
return;
}
private byte[] GetImageBits(Stream fs, int size)
{
byte[] img = new byte[size];
fs.Read(img, 0, size);
return img;
}

InputStream HttpPostedFile.
, SQL-,
BLOB-.
. ( ,
, ) .
ASP.NET ,
, . ,
ASP.NET.


, ,
, .
,
; ,
,
.

, , ,
.
.aspx .axd, <img>,

348

I I

ASP.NET

. ,
.
, .
, ,
.
Web- .
, , . ,
,
, .
, IIS , ASP.NET.
,
.
BLOB, .
,
,
.

ExecuteScalar, BLOB, , .
, , -
, . ,
ExecuteScalar reader . BLOB- ,
.
ADO.NET
, ExecuteReader.
CommandBehavior.
SequentialAccess, reader , . ,
, .

. reader
, , , .
, ,
.
BLOB GetBytes
reader .
bytesRead = reader.GetBytes(colIndex, startPos, buf, 0, bufSize);
while (bytesRead == bufSize)
{
//
ProcessBytes(buf);
//

349

startPos += bufSize;
bytesRead = reader.GetBytes(colIndex, startPos, buf, 0, bufSize);
}
//
ProcessBytes(buf);

GetBytes
. GetBytes,
BLOB-.
SQL Server

SQL Server Image,


8 2 . SQL Server
T-SQL, UPDATETEXT, READTEXT
WRITETEXT, .
, ,
, ,
. ,
, 1 , , , .
1 , SQL Server.
. , .
, .
Web- ,
SQL Server, . SQL Server
, TDS
(Tabular Data Stream ),
, BLOB-.
Oracle

Oracle
BFILE LOB. 4 ,
,
. . , BFILE , .
BFILE
, .
, ,
. BFILE ,
.
, LOB.

- . , , .

.

350

I I

ASP.NET

4 .
6 .
Microsoft,
BLOB.
, . ,
, .
,
, ,
.
, ,
,
, ? , , , , BLOB-, .
? , .
, (
). , ( ),
, .


, . Web-,
, ,
, .

, .
,
.
, , . ,
. Web-

, Microsoft Office.
ASP.NET , ,
. GDI+.

GDI+
GDI+ Microsoft Windows XP, 32 64- , Windows 2000 Windows 2003. GDI+,
, GDI (Graphics Device
Interface ),
Windows. .NET Framework
GDI+ Web, Windows Forms Web-.
GDI+ : .

351

, , ;
,
, , .
, , ;
.
Web-, ,
JPEG GIF.
Graphics

Win32 GDI
. , .
, ,
. Win32
GDI. ,
, . ,
API .
, GDI+,
. Graphics .
,
ASP.NET Graphics.FromImage.
Graphics,
.NET. , Graphics,
.
! Graphics,
, Dispose.
GDI+, GDI+.

Bitmap

Bitmap GDI+,
. GDI+
, . Bitmap. ,
Bitmap
.bmp; ,
BMP JPG, .
Graphics, .
, Web- . , Bitmap , :
Bitmap bmp = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bmp);

,
Graphics, Bitmap.
Bitmap ,
PNG, JPEG, BMP GIF. , Bitmap ,

352

I I

ASP.NET

,
.

. , ,
FillRectangle,
, RectangleF:
g.FillRectangle(brush, area);

brush -, . GDI+ , , . ,
:
//
Pen p = new Pen(Color.Black);
g.DrawRectangle(p, 0, 0, width, height);
//
Brush brInterior = new SolidBrush(Color.SkyBlue);
g.FillRectangle(brInterior, 1, 1, width-2, height-2);

, GDI+ . DrawRectangle, .
GDI+
. (
) LinearGradientBrush.
:
//
Rectangle area = new Rectangle(0, 0, width, height);
LinearGradientBrush brInterior;
brInterior = new LinearGradientBrush(area, Color.SkyBlue,
Color.AntiqueWhite, LinearGradientMode.Horizontal);
g.FillRectangle(brInterior, area);
brInterior.Dispose();

, ,
. Blend,
0 1.
//
//
float[] relativeIntensities = {0.0f, 0.6f, 1.0f};
float[] relativePositions = {0.0f, 0.1f, 1.0f};
// Blend
Blend blend = new Blend();
blend.Factors = relativeIntensities;
blend.Positions = relativePositions;
brInterior.Blend = blend;

353

,
.
:
float[] relativeIntensities = {0.0f, 1.0f};
float[] relativePositions = {0.0f, 1.0f};

,
. ,
, , 60 %
10 % .
, ,
. ,
. :
//
Image img = Image.FromFile("pattern.bmp");
TextureBrush brInterior = new TextureBrush(img);
g.FillRectangle(brInterior, area);
brInterior.Dispose();

DrawString Graphics ,
, , , , . , ,
, ( ) , ,
,
. StringFormat,
.
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
//
Font f = new Font("Tahoma", 16);
g.DrawString("Hello, world", f, new SolidBrush(Color.White),
new Rectangle(0, 0, width, height), sf);

GDI+ , , , .
.


ASP.NET . ASP.NET
ASPNET NETWORK SERVICE. ,
ASP.NET ,
, .
, , ,
ASPNET NETWORK SERVICE , Access denied.

354

I I

ASP.NET

, ,
ASP.NET
. ASP.NET GDI+
. ,
.

GDI+ , : JPEG, GIF, BMP PNG.


ImageFormat. Bitmap
,
Save:
bmp.Save(outputStream, ImageFormat.Gif);

,
. GDI+,
. ,
, Win32. , , ,
, , JPEG.
.

, . ,
,
.
Bitmap, Graphics , .
MIME-.
:
<html>
<body>
<img id="picture" src="dynimage.ashx?url=images/pic1.jpg" />
</body>
</html>

ASP.NET, , <img>.
HTTP dynimage.ashx.
, , .
ProcessRequest .
public void ProcessRequest (HttpContext context)
{
object o = context.Request["url"];
if (o == null)
{
context.Response.Write("No image found.");
context.Response.End();
return;
}
string file = context.Server.MapPath((string)o);
string msg = "Courtesy of 'Programming Microsoft ASP.NET 2.0

355

Applications--Advanced Topics'";
if (File.Exists(file))
{
Bitmap bmp = AddCopyright(file, msg);
context.Response.ContentType = "image/jpeg";
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
bmp.Dispose();
}
else
{
context.Response.Write("No image found.");
context.Response.End();
}
}

, . -, , -
JPEG.
Bitmap AddCopyright(string file, string msg)
{
//
Bitmap bmp = new Bitmap(file);
Graphics g = Graphics.FromImage(bmp);
//
StringFormat strFmt = new StringFormat();
strFmt.Alignment = StringAlignment.Center;
//
// ( )
SolidBrush btmForeColor = new SolidBrush(Color.PaleGreen);
SolidBrush btmBackColor = new SolidBrush(Color.Black);
//
//
Font btmFont = new Font("Verdana", 7);
SizeF textSize = new SizeF();
textSize = g.MeasureString(msg, btmFont);
//
float x = ((float) bmp.Width-textSize.Width-3);
float y = ((float) bmp.Height-textSize.Height-3);
float w = ((float) x + textSize.Width);
float h = ((float) y + textSize.Height);
RectangleF textArea = new RectangleF(x, y, w, h);
g.FillRectangle(btmBackColor, textArea);
//
g.DrawString(msg, btmFont, btmForeColor, textArea);
btmForeColor.Dispose();
btmBackColor.Dispose();
btmFont.Dispose();
g.Dispose();
return bmp;
}

356

I I

ASP.NET

. 9-6. ,
. ,
Save Picture As, .

. 9-6.

GDI+ , .
, , , , .
:
.
Web-, ,
.
, GetThumbnailImage Bitmap:
Bitmap GetThumbnail(string file)
{
Bitmap bmp = new Bitmap(file);
Bitmap newImg = (Bitmap) bmp.GetThumbnailImage(bmp.Width/3, bmp.Height/3, null,
IntPtr.Zero);
return newImg;
}

, ,
, .
,
, .
, , . 9-7.

357

. 9-7.

, JPEG

JPEG 88 ,
.
.
, , zip-. ,
-
. JPEG
,
. JPEG-
24 , 16 .
. JPEG
, .
,
.
, , . , 15:1 , -
, .
JPEG- GDI+, , , MimeType .
// JPEG
string mimeType = "image/jpeg";
ImageCodecInfo[] encoders;
ImageCodecInfo jpegEncoder = null;
// GDI+
encoders = ImageCodecInfo.GetImageEncoders();
for(int j=0; j < encoders.Length; j++) {
if(encoders[j].MimeType == mimeType)
jpegEncoder = encoders[j];
}

, ,
, :
//
EncoderParameter paramRatio;
paramRatio = new EncoderParameter(Encoder.Quality,ratio);

358

I I

ASP.NET

, ,
. . ,
.
//
EncoderParameters jpegParams;
jpegParams = new EncoderParameters(1); //
jpegParams.Param[0] = paramRatio;
//
Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream, jpegEncoder, jpegParams);
bmp.Dispose();

HTTP.

: , ASP.NET,
GDI+.
ASP.NET ,
. , , ,
.
ASP.NET.

,
,
. , <img>
, :
<table>
<tr><td><img runat="server" id="bar"></td></tr>
<tr><td><img runat="server" id="pie"></td></tr>
</table>

Load <img> ,
URL. . ,
:
void Page_Load(object sender, EventArgs e)
{
bar.Src = "chart.ashx?Type=bar&Data=Sales";
pie.Src = "chart.ashx?Type=pie&Data=Sales";
}

, , .
, <appSettings> web.config.

HTTP chart.ashx : Type, ( ), Data, -

359

<appSettings> web.config,
.
HTTP
( 4) ,
.
.
:
public abstract class ChartDataProvider
{
public abstract DataTable GetData();
public abstract string DataLabelField { get; }
public abstract string DataField { get; }
}

, DataTable
, . , SalesChartDataProvider,
DataTable Employee Sales. Employee , Sales .
<appSettings>
:
<appSettings>
<add key="Sales" value="SalesChartDataProvider,ProAspCompLib" />
</appSettings>

key Data ,
.
,
,
. , ,
, .

.

, HTTP
chart.ashx. ProcessRequest:
public void ProcessRequest(HttpContext context)
{
//
string type = "bar";
string dataProvider = String.Empty;
object arg1 = context.Request["Type"];
object arg2 = context.Request["Data"];
if (arg1 != null)
type = (string) arg1;
if (arg2 == null)
context.Response.End();
else
dataProvider = (string) arg2;

360

I I

ASP.NET

//
string info = ConfigurationManager.AppSettings[dataProvider];
string[] typeInfo = info.Split(',');
string cls = typeInfo[0];
string asm = typeInfo[1];
ObjectHandle handle = Activator.CreateInstance(asm, cls);
ChartDataProvider prov = (ChartDataProvider)handle.Unwrap();
//
Bitmap bmp;
Graphics g;
if (type == "bar")
{
bmp = new Bitmap(700, 200);
g = Graphics.FromImage(bmp);
DrawBarChart(g, prov);
}
else
{
bmp = new Bitmap(300, 300);
g = Graphics.FromImage(bmp);
DrawPieChart(g, prov);
}
//
context.Response.ContentType = "image/png";
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
bmp.Dispose();
g.Dispose();
}

, . ,
<appSettings> , .
,
.
Activator.CreateInstance.
! Activator.CreateInstance,
, , ObjectHandle, .
ObjectHandle
AppDomain. ,
, .NET Remoting.
Unwrap.

Graphics, ,
, . ,
PNG.

361

, , .
. ,
. ,
.
// DataTable ("data")
float total = Convert.ToSingle(data.Compute("Sum(sales)", ""));
//
float sweep = Convert.ToSingle(value) / total * 360;

FillPie, DrawEllipse. Graphics:


g.FillPie(new SolidBrush(wedgeColor), rectChart, angle, sweep);
g.DrawEllipse(new Pen(Color.DarkGray, 1), rectChart);

, . ,
.
.
, :
for(int j=ShadowDepth; j>0; j--)
{
for(int i=0; i<data.Rows.Count; i++)
{
// ,
//
float sweep = Convert.ToSingle(data.Rows[i]["Sales"])/total*360;
//
wedgeColor = colors[i];
//
Rectangle shadowArea = new Rectangle(area.Location, area.Size);
shadowArea.Offset(j, j);
g.FillPie(new HatchBrush(HatchStyle.Percent50, wedgeColor),
shadowArea, angle, sweep);
//
g.FillPie(new SolidBrush(wedgeColor), area, angle, sweep);
g.DrawEllipse(new Pen(Color.DarkGray, 1), area);
//
//
Point center = GetPoint(angle + sweep/2, area.Width, area.Height);
center.X = (int) ((area.Right - area.Left) / 2 + center.X) / 2;
center.Y = (int) ((area.Bottom - area.Top) / 2 + center.Y) / 2;
centers[i] = center;

362

I I

ASP.NET

//
angle += sweep;
}
}

, . ,
. ,
, ,
. .
? ,
. ,
, , , ,
,
. , , .
, ,
. .
, ,
:
// width ,
int radius = width / 2;
// . angle
double rad = Math.PI * 2 * angle / 360;
//
Point pt = new Point();
pt.X = (int) (radius * Math.Cos(rad)) + radius;
pt.Y = (int) (radius * Math.Sin(rad)) + radius;

,
. , :
pt.X = (int) ((rcChart.Right - rcChart.Left) / 2 + pt.X) / 2;
pt.Y = (int) ((rcChart.Bottom - rcChart.Top) / 2 + pt.Y) / 2;
centers[i] = pt;

,
. ,
.
, , . .
for(int i=0; i<dt.Rows.Count; i++)
{
g.DrawString(data.Rows[i]["Employee"].ToString(),
new Font("Tahoma", 8),
new SolidBrush(Color.Black),
centers[i].X, centers[i].Y);
}

. 9-8.

363

. 9-8.

, , ,
. :
.
, x y .
:
//
g.DrawString(String.Format("{0:c}", data.Rows[i]["Sales"]),
new Font("Tahoma", 8), new SolidBrush(Color.Blue),
xBarPos, yCaptionPos);
//
Rectangle rcBar = new Rectangle(xBarPos, yBarPos, barWidth, barHeight);
//
Rectangle rcShadow = new Rectangle(rectBar.Location, rectBar.Size);
rectShadow.Offset(j, -j);
//
g.FillRectangle(new HatchBrush(HatchStyle.Percent50, Color.Orange),
rectShadow);
//
g.FillRectangle(new LinearGradientBrush(rectBar, Color.Orange, Color.Yellow,
LinearGradientMode.Horizontal), rectBar);
//
Font fnt = new Font("Tahoma", 8, FontStyle.Bold);

364

I I

ASP.NET

g.DrawString(dt.Rows[i]["Employee"].ToString(), fnt,
new SolidBrush(Color.Blue), xBarPos, yBarBottom);

. 9-9.

. 9-9.
.aspx HTTP.
, .
, .
, <img>. , .

, Web.
,
Web .
, Web, HTTP
, <img>. URL,
.
<img> .aspx, HTTP,

. HTTP- .
ASP.NET
GDI+.
GDI+ Windows XP, 32 64- Windows. .NET Framework GDI+
-,
.

, . , ,
,

365

BLOB- . .
, , ASP.NET.

Web- <img>,
URL .


, , , <img>
, , .aspx
HTTP.

HTTP
, .


MIME- , .

BLOB- .


, GDI+.

10

Web- , , - .
, ,
, , . ,

, .
ASP.NET 2.0 API,
, , , . ASP.NET
.
, ,
TreeView Menu.
, , ,
,
.
, .


ASP.NET,
, . ,

.
, ,
XML-.
, .



. ,

,
URL .
.
ASP.NET , .

10

367

,
XML-; web.sitemap.

, , XmlSiteMapProvider.
<siteMap>
<providers>
<add name="AspNetXmlSiteMapProvider"
siteMapFile="web.sitemap"
type="System.Web.XmlSiteMapProvider, System.Web, ... " />
</providers>
</siteMap>

, siteMapFile,
, .
, XML-,
. , XmlSiteMapProvider
, .sitemap. ,

.
web.sitemap

web.sitemap
.
, .
, .
<siteMap>
<siteMapNode title=" " url="default.aspx">
<siteMapNode title="" url="intro.aspx" />
<siteMapNode title="" url="ack.aspx">
<siteMapNode title="" url="ref.aspx" />
</siteMapNode>
<siteMapNode title="" url="toc.aspx">
<siteMapNode title=" " url="ch01.aspx" />
<siteMapNode title=" HTTP" url="ch02.aspx" />
</siteMapNode>
<siteMapNode title="" url="appendix.aspx">
<siteMapNode title=" " url="samples.aspx">
</siteMapNode>
</siteMapNode>
</siteMap>

XML- <siteMap> <siteMapNode>.


<siteMapNode>,
, .
<siteMapNode>, , . URL,
, ,
. , ,

368

I I

ASP.NET

, API .
API , ,
,
.
<siteMapNode> . 10-1.
. 10-1. <siteMapNode>

description

. ,
SiteMapPath,
, ,
,
,

,

URL

provider
resourceKey
roles
siteMapFile
title
url

roles ( site map security


trimming ).
, . 10-1, , .
.sitemap <siteMapNode> <siteMap>.

, ,
.
XML-
, , , . 4, ,
SiteMapProvider StaticSiteMapProvider.
, . , provider
<siteMapNode>,
, .
<siteMap>
<siteMapNode title="Intro" url="intro.aspx" >
<siteMapNode title="Acknowledgements" url="ack.aspx" />
<siteMapNode title="References" url="ref.aspx" />
</siteMapNode>
<siteMapNode provider="SimpleTextSiteMapProvider" />
</siteMap>

,
, :
<system.web>
<siteMap defaultProvider="XmlSiteMapProvider">

10

369

<providers>
<add name="SimpleTextSiteMapProvider"
type="SimpleTextSiteMapProvider, Samples"
siteMapFile="MySiteMap.txt" />
</providers>
</siteMap>
</system.web>

<siteMapNode>, SimpleTextSiteMapProvider,
, MySiteMap.txt. , :
XmlSiteMapProvider SimpleTextSiteMapProvider.


. ,
, -, , , -,
,
. .

,
web.sitemap, .

.sitemap .
<siteMapNode> ,
, ,
.sitemap, :
<siteMap>
<siteMapNode title="My Book" url="default.aspx">
<siteMapNode siteMapFile="introduction.sitemap" />
<siteMapNode siteMapFile="chapters.sitemap" />
<siteMapNode siteMapFile="appendix.sitemap" />
</siteMapNode>
</siteMap>


web.sitemap ,
. , , . siteMapFile
.
,
XmlSiteMapProvider.
, .

Web-, , ,
.
? . ,

370

I I

ASP.NET

,
ASP.NET , . ,
,
,
.
,
. . , URL
.
,
. ( 15
Programming Microsoft ASP.NET 2.0: Core Reference.)
ASP.NET

.sitemap, , , ASP.NET
forbidden resource. ,
, , , ,
IIS. , ASP.NET (NETWORK
SERVICE ASPNET)
. ,
.
,
. , ,
.

Title, Description,
.
. ,
enableLocalization:
<siteMap enableLocalization="true">
</siteMap>

, .
( $- 5.)
, ,
.
:
<siteMap enableLocalization="true">
<siteMapNode
url="~/homepage.aspx"
title="$Resources:MyLocalizations,HomePage" />
</siteMap>

10

371

$Resources,
.resx, .
MyLocalizations.resx HomePage,
title. , .
.
<siteMapNode> ,
.resx :
[_].[]

, :
<siteMap enableLocalization="true">
<siteMapNode
resourceKey="Home"
url="~/homepage.aspx"
description=" default "
title=" default " />
</siteMap>

, .sitemap, .resx. web.sitemap.resx. ,


Home.description Home.title.
, description title. , .sitemap (
, ), .
.resx
. , ,
, , fr.resx, fr .

,
, ? , Url , Title Description.
URL ,
:
<siteMap defaultProvider="XmlSiteMapProvider">
<providers>
<add name="DefaultSiteMap"
type="System.Web.XmlSiteMapProvider"
siteMapFile="default.sitemap" />
<add name="FrenchSiteMap"
type="System.Web.XmlSiteMapProvider"
siteMapFile="fr.sitemap" />
<add name="ItalianSiteMap"
type="System.Web.XmlSiteMapProvider"
siteMapFile="it.sitemap" />

372

I I

ASP.NET

</providers>
</siteMap>


, . ,
.
! .resx
, XML- .sitemap.
, , .


. , .
, , , .
ASP.NET
SiteMap.

SiteMap
System.Web SiteMap
. -
.
. . ,

SiteMap.
SiteMap

SiteMap . 10-2.
SiteMapResolve,
CurrentNode.
, . ,
, .
. 10-2. SiteMap

CurrentNode

SiteMapNode,

Enabled

Provider

SiteMapProvider

Providers


SiteMapProvider,

RootNode

SiteMapNode,

CurrentNode, SiteMap .
, null, ,
.

10

373

SiteMapNode

SiteMapNode . ,
, ,
. . 10-3.
. 10-3. SiteMapNode

ChildNodes

Provider
ReadOnly
ResourceKey
Roles
RootNode
Title

/ ,
/

,
/

, ,
/

, ,

,
/ ,
/ ,

Url

/ URL ,

Description
HasChildNodes
Item
Key
NextSibling
ParentNode
PreviousSibling

. 10-1
<siteMapNode> .sitemap.
SiteMapNode

. 10-4 SiteMapNode.
. 10-4. SiteMapNode

Clone

GetAllNodes

GetDataSourceView

GetHierarchicalDataSourceView

IsAccessibleToUser

, ,

IsDescendantOf

, ,

, SiteMapNode .

374

I I

ASP.NET


CurrentNode SiteMap. ,
:
if (SiteMap.CurrentNode.HasChildNodes)
{
foreach(SiteMapNode node in SiteMap.CurrentNode.ChildNodes)
{
//
}
}

CurrentNode SiteMap
SiteMapResolve, ,
.

, ,
. , .
, . ?
( , ASP.NET
.)
.
, , , . ? ,
, ASP.NET
API,
.

, ASP.NET,
. showpost.aspx.
SiteMapResolve,
URL:
void Page_Load(object sender, EventArgs e)
{
SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(ResolveNode);
}
SiteMapNode ResolveNode(object sender, SiteMapResolveEventArgs e)
{
//
SiteMapNode tempNode = SiteMap.CurrentNode.Clone(true);
//
int postID = GetPostID();
// ,
tempNode.Url += "?ID=" + postID;
return tempNode;

10

375

}
string GetPostID()
{
return HttpContext.Current.QueryString["ID"].ToString();
}

, URL showpost.aspx
.
, SiteMapPath.

SiteMapPath

, ,
(. 10-1). ASP.NET
(site map path).
SiteMapPath, .

. 10-1.

ASP.NET
, URL,
.
SiteMapPath

SiteMapPath
- . SiteMap.
SiteMapPath . 10-5.
. 10-5. SiteMapPath

CurrentNodeStyle
CurrentNodeTemplate

NodeTemplate
ParentLevelsDisplayed
PathDirection

PathSeparator
PathSeparatorStyle
PathSeparatorTemplate

NodeStyle

(. . .)

376

I I

ASP.NET

. 10-5. ()

Provider

,
(/)
RenderCurrentNodeAsLink ,

RootNodeStyle

RootNodeTemplate

ShowToolTips
,

SiteMapProvider
,
SkipLinkText
, ,

, SiteMapPath,
SiteMapNodeItem.
ItemCreated. - ,
ItemDataBound.

SiteMapPath URL SiteMapNode , .


URL, ,
.
SiteMapPath, . .aspx
:
<asp:SiteMapPath ID="SiteMapPath1" runat="server"
RenderCurrentNodeAsLink="True" PathSeparator=" : " >
<PathSeparatorStyle Font-Bold="True" />
<NodeStyle Font-Bold="True" />
<RootNodeStyle Font-Bold="True" />
</asp:SiteMapPath>

, .
, . 10-1.
SiteMapPath SiteMap. , SiteMapResolve,
, ,
. ,
. .

, . SiteMapPath,

10

377

. ,
. :
void Page_Load(object sender, EventArgs e)
{
RenderCustomSiteMapPath(TreeView1);
}
void RenderCustomSiteMapPath(TreeView tv)
{
for (SiteMapNode node=SiteMap.CurrentNode;
node != null;
node=node.ParentNode)
{
TreeNode tn = new TreeNode(node.Title, node.Title,
"", node.Url, "");
tv.Nodes.AddAt(0, tn);
}
}

, URL
. , C#,
for - SiteMapNode.
ParentNode.
null, , ,
.
, .
TreeView, , , .
. 10-2.

. 10-2. ,
TreeView

SiteMapDataSource
SiteMapPath ,
URL,
. ,
-
.
. ?
, .

378

I I

ASP.NET

ASP.NET 2.0 , (data source


control), ,
, , . ,
, ;
,
, , . ,
, XML-. ,
, : , ,
. 9 Programming Microsoft ASP.NET 2.0: Core
Reference (Microsoft Press, 2005) ,
, .

SiteMapDataSource, ,
.
, TreeView Menu, .
SiteMapDataSource

SiteMapDataSource,
, HierarchicalDataSourceControl IDataSource, . SiteMapDataSource
. 10-6.
. 10-6. SiteMapDataSource

Provider

,
.

ShowStartingNode

, ,
.
true

SiteMapProvider

, .

StartFromCurrentNode , ,
.
false
StartingNodeOffset

StartingNodeUrl

URL

SiteMapDataSource , . , ,
SiteMapProvider .
, Provider,
.

10

379

SiteMapDataSource

SiteMapDataSource Data Microsoft Visual Studio 2005. , , Web-, . ,


, , .
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

,
SiteMapProvider. SiteMapDataSource
, , TreeView, DataSourceID
TreeView
SiteMapDataSource, :
<asp:TreeView ID="TreeView1" runat="server"
DataSourceID="SiteMapDataSource1" ImageSet="WindowsHelp">
</asp:TreeView>

.
, SiteMapDataSource,
,
, .

: StartFromCurrentNode, StartingNodeOffset StartingNodeUrl. , StartFromCurrentNode StartingNodeUrl , StartingNodeUrl , StartFromCurrentNode


false, .
, URL. ,
. :
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server"
StartFromCurrentNode="true"
StartingNodeOffset="-1" />

,
.

SiteMapDataSource .
,
, URL .

SiteMap SiteMapDataSource

,
, SiteMap SiteMapDataSource,
. SiteMap
API .
SiteMapDataSource ,

, ,
TreeView Menu. ,

380

I I

ASP.NET

, , , ,
, .



, , .
,
. ,
.
ASP.NET 2.0
. , , .
TreeView Menu.
, ( , )

. ,
, ,
, .
SiteMapDataSource. ,
,
. 10-3.

. 10-3. , TreeView

TreeView .
SiteMapDataSource
.
! ASP.NET 2.0 ,
, , .

TreeView
, TreeView ASP.NET 2.0.
, ,
, , , , ,
, .

10

381

TreeView ,

. TreeNode
.
TreeView

TreeView, ,
, . : , . TreeView
. 10-7.
. 10-7. TreeView

CollapseImageToolTip
CollapseImageUrl
ExpandImageToolTip
ExpandImageUrl


URL

URL



URL
( )
, , ,

, (leaf, parent, root)

, , ,

, ,

ImageSet
NoExpandImageUrl
NodeIndent
NodeWrap
ShowCheckBoxes
ShowExpandCollapse
ShowLines

, TreeView . -, ,
/ , -, ,

. ,
, .
. 10-8 ,
TreeView .
. 10-8. TreeView

AutoGenerateDataBindings ,
CheckedNodes
TreeNode, ,

DataBindings
TreeNodeBinding,

(. . .)

382

I I

ASP.NET

. 10-8. ()

EnableClientScript

,
/.
true
,
TreeView

TreeNode,

,
. (/)
,
. true
TreeNode,

ExpandDepth
MaxDataBindDepth
Nodes
PathSeparator
PopulateNodesFromClient
SelectedNode
SelectedValue

TreeView . ?

? :
?
TreeView
DataSourceID DataSource. , , XML . (
IEnumerable TreeView .) TreeView
,
DataBindings. TreeNodeBinding <asp:TreeNodeBinding>.
Nodes,
, .
TreeNode <asp:TreeNode>.
, , ,
ASP.NET (. 6).
. 10-9 TreeView.
. 10-9. TreeView

HoverNodeStyle
LeafNodeStyle
LevelStyles

,

Style,

,


NodeStyle
ParentNodeStyle
RootNodeStyle
SelectedNodeStyle

10

383

TreeNodeStyle. Style,
, . : NodeStyle,
RootNodeStyle, ParentNodeStyle LeafNodeStyle, .
LevelStyles, ,
. SelectedNodeStyle HoverNodeStyle.
TreeView : ExpandAll FindNode.
,
TreeNode , .
.

: TreeView SiteMapDataSource
. TreeView .
, , ,
.
TreeView SiteMapDataSource
, , .
TreeView ImageSet.
. TreeViewImageSet
system.web. ,
, . 10-3, Simple2, , . 10-4,
. (,
AutoFormat.)

. 10-4.

384

I I

ASP.NET

,
:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Type t = typeof(TreeViewImageSet);
DropDownList1.DataSource = Enum.GetValues(t);
DropDownList1.DataBind();
}
}
void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Type t = typeof(TreeViewImageSet);
string imageSet = DropDownList1.SelectedValue;
TreeView1.ImageSet = (TreeViewImageSet) Enum.Parse(t, imageSet);
}
! , , SiteMapDataSource, ,
. ,
.

Menu
Windows-.
ASP.NET 2.0 ,
Windows-. , , ASP.NET 2.0
Menu.
Menu ,
,
. , Menu
, , , .aspx- .
Menu MenuItem,
.
, , , .
, .
ASP.NET 2.0 : .
. , , ,
.
Menu

, , Menu
.
(. 10-10).

10

385

. 10-10. Menu

DynamicBottomSeparatorImageUrl

DynamicEnableDefaultPopOutImage

DynamicHorizontalOffset
DynamicItemFormatString
DynamicPopOutImageTextFormatString

DynamicPopOutImageUrl
DynamicItemTemplate
DynamicTopSeparatorImageUrl
DynamicVerticalOffset
ScrollDownImageUrl

ScrollDownText
ScrollUpImageUrl

ScrollUpText
StaticBottomSeparatorImageUrl
StaticDisplayLevels
StaticEnableDefaultPopOutImage

StaticItemFormatString
StaticItemTemplate
StaticPopOutImageTextFormatString

StaticPopOutImageUrl
StaticSubMenuIndent
StaticTopSeparatorImageUrl

URL ,

, , ,

( )

,
,

URL ,
,
,

URL ,

( )
URL , , ,
,
,
ScrollDownImageUrl
URL , , , ,

,
ScrollUpImageUrl
URL ,

,

,
, ,


,

,
,

URL ,
,

( )

URL ,

386

I I

ASP.NET

URL .
, ,
.
. . 10-11
Menu, .
. 10-11. Menu

DataBindings

MenuItemBinding,

DisappearAfter

( ),

,

Items

MenuItemCollection,

ItemWrap

,
,

MaximumDynamicDisplayLevels
Orientation

PathSeparator

SelectedItem

SelectedValue

ASP.NET,
. Items Menu , MenuItem <Items> <asp:MenuItem>.
<asp:MenuItem>.
Menu ; , ,
. Menu ,
, DataSourceID,
DataSource. DataBindings
.
, TreeView Menu ,
. ,
SiteMapDataSource. ,
-, , ,
, -,
.

, ,
, , . . 10-12
, Menu.

10

387

. 10-12. Menu

DynamicHoverStyle

DynamicMenuItemStyle

DynamicMenuStyle

DynamicSelectedStyle

LevelMenuItemStyles

Style,

LevelSelectedStyles

Style,

LevelSubMenuStyles

Style,

StaticHoverStyle

StaticMenuItemStyle

StaticMenuStyle

StaticSelectedStyle

MenuItemStyle.
Style ,
. :
StaticMenuStyle, StaticMenuItemStyle. LevelMenuItemStyles
LevelSubMenuStyles , . StaticSelectedStyle LevelSelectedStyles, HoverNodeStyle.
Menu , FindItem,
. FindItem , . -, . -
PathSeparator.
MenuItemClick MenuItemDataBound. ,
, .

Menu ,
TreeView:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"
DynamicHorizontalOffset="2" StaticSubMenuIndent="10px">
</asp:Menu>

. 10-5 , ,
.
, Menu TreeView
, Internet Explorer Mozilla.

388

I I

ASP.NET

. 10-5.
, ,
. , .
, Page PreInit
( , )
, .
(skin), , .
ASP.NET, -
3 5 Programming Microsoft ASP.NET 2.0: Core
Reference.

,
. ASP.NET 2.0
User. ,
ASP.NET 1.x, , User
.
15
Programming Microsoft ASP.NET 2.0: Core Reference.
, ,
. ,
, ,
.
,
, , ,
TreeView Menu. ,
, .

,
web.config. , , , ,
.
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>

10

389

<add name="XmlSiteMapProvider"
description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider "
siteMapFile="Web.sitemap"
securityTrimmingEnabled="true" />
</providers>
</siteMap>

roles <siteMapNode> ,
. , .
, Editor:
<siteMapNode title="Introduction" roles="Editor">
</siteMapNode>

. 10-6 10-7 ,
.

. 10-6. Editor

. 10-7. Reader
( Introduction )
, ,
roles, . ,
, '*'.

390

I I

ASP.NET

Web- , , .
.
? ? , .
ASP.NET 2.0
SiteMapPath, TreeView Menu.
,
, .
,
, XML-
, ,
.

,
.

XML- web.sitemap,
.

,
, XML-
.

,
.
SiteMapPath.

SiteMap.

SiteMapDataSource ,
, TreeView Menu.

,
, , TreeView Menu ,
.

III

ASP.NET

11. ASP.NET ................................................. 392


12. ASP.NET ......................................... 418
13. ASP.NET ................. 446
14. ,
................................................................................. 487
15.
.......................................................................................... 533

11


ASP.NET

ASP.NET 1.0
. ASP.NET 2.0
,
.
9 Programming Microsoft ASP.NET 2.0: Core Reference (Microsoft Press, 2005),
10 11
GridView, DetailsView FormView ASP.NET 2.0. ,
, , .

ASP.NET .
. ASP.NET.


ASP.NET ,
, ,
ASP.NET. , ,
. , .
ASP.NET 2.0 : Repeater DataList.
, ,
, ,
.


, DropDownList, ListBox,
CheckBoxList BulletedList, .
, List,
DataList.
DropDownList , ;
, , ,
.
CheckBoxList ,
,

ASP.NET

11

393

. HTML-,
.
, , , , <b>. , ,
.

.
ASP.NET,

.

, , ,
. , IEnumerable.
.
ASP.NET , , ;
Repeater DataList. ,
,
, ITemplate, . ( *.ascx)
.
, , , ,
.
,
, ,
, . ,
(
) , ITemplate. ( .)


-
- GridView, DetailsView, FormView
DataGrid. ,
, .
. -
.

DataGrid GridView , Repeater


DataList, . , ,

394

III

ASP.NET

. .
Repeater ,
, DataList.
, Repeater
DataList, , . . 11-1
, .
. 11-1. ,

;
,
,

, , DetailsView FormView . DetailsView ,


.
FormView .
,
.
, Repeater, .

Repeater
Repeater ,
, . ASP.NET .
.
HTML ASP.NET.

Repeater
Repeater Control ,
INamingContainer. , , Control,
. 11-2.

ASP.NET

11

395

. 11-2. Repeater

AlternatingItemTemplate
DataMember
DataSource
DataSourceID

,
,
IEnumerable
,



RepeaterItemCollection RepeaterItem,


FooterTemplate
HeaderTemplate
Items
ItemTemplate
SeparatorTemplate

, , .
Items , . Repeater
, .
, RepeaterItem,
.
RepeaterItem ( , ),
. RepeaterItem
, . 11-3.
. 11-3. RepeaterItem

DataItem

, . RepeaterItem,
, ,
null
0-
ListItemType, . Header, Footer,
Item, AlternatingItem Separator

ItemIndex
ItemType

, ListItemType
, Repeater. ,
RepeaterItem:
public enum ListItemType
{
Header,
Footer,
Item,
AlternatingItem,
SelectedItem,
EditItem,

396

III

ASP.NET

Separator,
Pager
}

, DataItem RepeaterItem , , . ,
, null.
Repeater

ASP.NET, ,
Repeater ,
DataBind, ASP.NET 2.0 , . DataBind Repeater,
, .
.
ASP.NET, Repeater
, . , Repeater
.

DataBind HTML-
. , , Repeater
: ItemCreated, ItemCommand ItemDataBound (. 11-4). , DataBinding, Control,
, . 11-4.
. 11-4. Repeater

ItemCommand
ItemCreated

Repeater
Repeater . DataItem
null
Repeater .
DataItem , , ,

ItemDataBound

ItemCreated ItemDataBound RepeaterItem.


Repeater.
Repeater

, Repeater, . CreateControlHierarchy.
Repeater, ,
, .
CreateControlHierarchy
.
Repeater :
//
if (headerTemplate != null)
CreateItem(ListItemType.Header);

ASP.NET

11

397

int _counter = 0;
RepeaterItem _repItem;
//
foreach(object _dataItem in DataSource)
{
if (useSeparator && _counter > 0)
CreateItem(ListItemType.Separator);
if (_counter % 2)
_repItem = CreateItem(_counter, ListItemType.Item, _dataItem);
else
_repItem = CreateItem(_counter, ListItemType.AlternatingItem,
_dataItem);
Items.Add(_repItem);
_counter ++;
}
//
if (footerTemplate != null)
CreateItem(ListItemType.Footer);

Repeater , .

ItemTemplate AlternatingItemTemplate.
, . ,
.
CreateItem RepeaterItem
. ItemCreated Items.
ItemDataBound.

Repeater
, HTML, .
ASP.NET ,
( ),
( ).
Repeater ItemTemplate. ;
ItemTemplate, Repeater .

. , , DataGrid:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<table>
<thead>
<td> <b>ID</b> </td>
<td> <b>First Name</b> </td>
<td> <b>Last Name</b> </td>
</thead>
</HeaderTemplate>

398

III

ASP.NET

<ItemTemplate>
<tr>
<td bgcolor="white">
<%# Eval("EmployeeID") %></td>
<td bgcolor="white">
<%# Eval("FirstName")%></td>
<td bgcolor="white">
<%# Eval("LastName") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td bgcolor="#eeeeee">
<%# Eval("EmployeeID") %></td>
<td bgcolor="#eeeeee">
<%# Eval("FirstName")%></td>
<td bgcolor="#eeeeee">
<%# Eval("LastName") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

. 11-1 , Repeater.
DataGrid, .

. 11-1. Repeater

Repeater SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalNWind %>"
SelectCommand="SELECT employeeid, firstname, lastname FROM employees">
</asp:SqlDataSource>

Repeater HTML-,
. ,
Repeater HTML- . , <table> ,
.

ASP.NET

11

399

ITemplate

Repeater ITemplate,
, , ,
, .
, HTML-. ?
, ,
, ITemplate. InstantiateIn:
void InstantiateIn(Control container);

,
, Controls , , , ,
DataBinding.

, .
LoadTemplate Page.
.ascx:
Repeater1.ItemTemplate = Page.LoadTemplate("item_template.ascx");

.NET,
, . LoadTemplate , ,
HeaderTemplate FooterTemplate. ,
.ascx, ,
. 11-1.
<%@ Control Language="C#" %>
<tr>
<td bgcolor="white">
<%# Eval("EmployeeID")%>
</td>
<td bgcolor="white">
<%# Eval("FirstName") %>
</td>
<td bgcolor="white">
<%# Eval("LastName") %>
</td>
</tr>

, ASP.NET 2.0 Eval . ASP.NET 1.x,


:
<%# DataBinder.Eval((RepeaterItem) Container.DataItem, "LastName") %>

RepeaterItem , , .

, , , , ITemplate.

400

III

ASP.NET

.ascx LoadTemplate.
:
public class MyItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
// <tr>
TableRow row = new TableRow();
// <td> employeeID
TableCell empID = new TableCell();
empID.DataBinding += new EventHandler(BindEmpID);
row.Cells.Add(_empID);
// <td> lastname
TableCell lname = new TableCell();
lname.DataBinding += new EventHandler(BindLastName);
row.Cells.Add(_lname);
// <td> firstname
TableCell fname = new TableCell();
fname.DataBinding += new EventHandler(BindFirstName);
row.Cells.Add(fname);
//
container.Controls.Add(row);
}
public void BindEmpID(object sender, EventArgs e)
{
TableCell cell = (TableCell) sender;
RepeaterItem container = (RepeaterItem) cell.NamingContainer;
object data = DataBinder.GetPropertyValue(container.DataItem, "EmployeeID");
cell.Text = data.ToString();
}
public void BindLastName(object sender, EventArgs e)
{
TableCell cell = (TableCell) sender;
RepeaterItem container = (RepeaterItem) cell.NamingContainer;
object data = DataBinder.GetPropertyValue(container.DataItem, "LastName");
cell.Text = data.ToString();
}
public void BindFirstName(object sender, EventArgs e)
{
TableCell cell = (TableCell) sender;
RepeaterItem container = (RepeaterItem) cell.NamingContainer;
object data = DataBinder.GetPropertyValue(container.DataItem, "FirstName");
cell.Text = data.ToString();
}
}

ASP.NET

11

401

, , Repeater. sender
, , TableCell. NamingContainer
Repeater.
Repeater .
ASP.NET 2.0
, , ,
IEnumerable. , ,
,
. , DataTable, DataSet, DataView ?
, ,
DataBinder.GetPropertyValue (. ).
get.
, .

Repeater
, Repeater HTML-, ASP.NET
. : HTML- . Repeater
,
.
, , Northwind Microsoft SQL Server.
, .
,
Repeater,
. .

.
Repeater, ,
, . , Repeater
, , . . ( ) ,
.
, <hr>. ,
, .

, , . 11-2,
.
<asp:repeater runat="server" id="Repeater1">
<HeaderTemplate>
<div style="background-color:yellow;">Customers</div>
</HeaderTemplate>

402

III

ASP.NET

<ItemTemplate>
<span style="display:none;">
<%# m_checkBox = (CheckBox) FindCheckBox(Container) %>
</span>
<asp:checkbox runat="server" id="ExpandButton" />
<%# ShowHeader(Container.DataItem) %><br>
<%# ShowInfoBar(Container.DataItem) %>
<%# ShowAddressBar(Container.DataItem) %>
</ItemTemplate>
<SeparatorTemplate>
<hr style="border:dashed 1px black;height:1px;" />
</SeparatorTemplate>
</asp:repeater>

. 11-2. Northwind,
Repeater

,
. <hr>,
. <ItemTemplate>.
.

<span>,
. ,
, , <%# %>. . 11-2,
. ,
- .
ShowHeader, ShowInfoBar ShowAddressBar ,
. , ShowHeader ,

ASP.NET

11

403

, ShowInfoBar , ShowAddressBar ,
.
HTML-, .
protected string ShowHeader(object dataItem)
{
// ,
string color = (m_checkBox.Checked ? "blue" : "black");
// HTML-
string output = "<b style='color:{0};'>{1}&nbsp;-&nbsp;{2}</b>";
//
output = String.Format(output, color,
DataBinder.GetPropertyValue(dataItem, "customerid"),
DataBinder.GetPropertyValue(dataItem, "companyname"));
//
return output;
}

,
, .
, . FindCheckBox. m_checkBox ,
.
<ItemTemplate>
<span style="display:none;">
<%# m_checkBox = (CheckBox) FindCheckBox(Container) %>
</span>
</ItemTemplate>

<span>, m_checkBox, , .
private CheckBox FindCheckBox(Control container)
{
// ,
CheckBox ctl = (CheckBox) container.FindControl("ExpandButton");
if (ctl == null)
return null;
//
ctl.Checked = (Page.Request[ctl.UniqueID]=="on");
//
return ctl;
}

, , .
Repeater.
.

404

III

ASP.NET

, FindControl Page ,
.

,
, ? ItemCommand.
:
<ItemTemplate>
<asp:Button runat="server" id="ExpandButton" CommandName="Expand" />
<%# ShowHeader(Container.DataItem) %><br>
<asp:panel runat="server" id="ExtraInfo" visible="false">
<%# ShowInfoBar(Container.DataItem) %>
<%# ShowAddressBar(Container.DataItem) %>
</asp:panel>
</ItemTemplate>

ExpandButton CommandName, . , , ,
. ,
ItemCommand:
void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
Panel p = (Panel) e.Item.FindControl("ExtraInfo");
p.Visible = !p.Visible;
}

FindControl Panel,
. , Visible, (. 11-3).

. 11-3.

ASP.NET

11

405

DataList
DataList , , Repeater,
. ,
Repeater, DataList
. DataList,
, Repeater.
Repeater, DataList ,
.
, DataList Repeater,
. , ,
,
.
, DataList DataGrid
, , . , DataList
, Repeater, . DataList , Repeater.

DataList
DataList , Repeater, , .
. ,
, ,
, . , DataList , HTML-
. ,
HTML-.
, DataList HTML-,
, <table> <td>.
, , DataList
.
DataList :
public class DataList : BaseDataList, INamingContainer, IRepeatInfoUser

BaseDataList INamingContainer
IRepeatInfoUser. ,
. CheckBoxList RadioButtonList.
DataList

. 11-5 DataList,
, Control WebControl.

ShowFooter ShowHeader true, , FooterTemplate HeaderTemplate


() null.

406

III

ASP.NET

. 11-5. DataList

AlternatingItemStyle
AlternatingItemTemplate
CellPadding

/
/

CellSpacing

Controls
DataKeyField
DataKeys

DataMember

DataSource

DataSourceID

EditItemIndex

EditItemStyle
EditItemTemplate
ExtractTemplateRows

/
/

FooterStyle
FooterTemplate
GridLines

/
/

HeaderStyle
HeaderTemplate
HorizontalAlign
Items

/
/

ItemStyle
ItemTemplate
RepeatColumns
RepeatDirection

/
/
/

RepeatLayout



( )

( )



.
DataKeyField
, , .
DataSource.
DataSet, DataMember ,
,

,
0- ,


,
, , DataList
HTML-, .
HTML-, .
false


, ,
. RepeatLayout
RepeatLayout.Flow, GridLines




, ,
:
, ,
: .

ASP.NET

11

407

. 11-5. ()

SelectedIndex
SelectedItem
SelectedItemStyle

SelectedItemTemplate
SeparatorStyle

SeparatorTemplate
ShowFooter

/
/

ShowHeader


, ,

, ,

DataList Repeater,
. DataList
: .
SelectedIndex SelectedItem properties, EditItemIndex.
DataList

. 11-6 , DataList,
, Control WebControl
(, Load DataBinding).
. 11-6. , DataList

CancelCommand


Cancel

DeleteCommand


Delete

EditCommand


Edit

ItemCommand

ItemCreated

DataList

ItemDataBound

DataList

SelectedIndexChanged

DataList

UpdateCommand


Update

ItemCreated ItemDataBound
. ItemCommand,
, EditCommand
DeleteCommand. SelectedIndexChanged, ,
Select.

408

III

ASP.NET


. ,
DataList, , Edit Delete.
, ,
.

DataList Update
Cancel, . , DataList ,
. CancelCommandName,
DeleteCommandName, EditCommandName, SelectCommandName UpdateCommandName.


, Repeater ,
, - .
DataList . ,
, , . , .
RepeatColumns, RepeatDirection RepeatLayout.
.

RepeatLayout RepeatLayout: Table


( ) Flow. Flow, DataList
<span>,
<br>, .
HTML-.
Flow.
<span id="DataList1">
<span> </span>
<br>
<span> </span>
<br>
<span> </span>
<span> </span>
</span>

Table HTML- . DataList :


<table id="DataList1">
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>

ASP.NET

11

409

<td> </td>
</tr>
</table>

.
: , ,
, :
<table id="DataList1">
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>

ExtractTemplateRows true, DataList


. ,
- . , ,
, Table ( <asp:Table>). , HTML <table> ASP.NET HtmlTable (<table runat="server">),
. ,
Table . DataList .
, .
<ItemTemplate>
<asp:table runat="server">
<asp:tablerow runat="server">
<asp:tablecell runat="server">
<%# Eval("Name") %>
</asp:tablecell>
</asp:tablerow>
</asp:table>
</ItemTemplate>

ExtractTemplateRows ,
, .
,
, ColumnSpan RowSpan.
ExtractTemplateRows true,
RepeatColumns, RepeatDirection RepeatLayout DataList.

,
ExtractTemplateRows. , , .

410

III

ASP.NET

, .
Repeater,
. , Repeater. ,
DataList , ,
. DataList
HTML- ,
, .
, . ,
. ExtractTemplateRows true,
.
<asp:datalist runat="server" id="list" extracttemplaterows="true">
<AlternatingItemStyle backcolor="palegoldenrod" />
<headerstyle backcolor="brown" forecolor="white"
font-size="larger" font-bold="true" horizontalalign="center" />
<HeaderTemplate>
<asp:table runat="server">
<asp:tablerow runat="server">
<asp:tablecell runat="server">Customer</asp:TableCell>
<asp:tablecell runat="server">Contact</asp:TableCell>
</asp:tablerow>
</asp:table>
</HeaderTemplate>
<ItemTemplate>
<asp:table runat="server">
<asp:tablerow runat="server" font-bold="true">
<asp:tablecell runat="server">
<%# Eval("CustomerID") %>
</asp:tablecell>
<asp:tablecell runat="server">
<%# Eval("ContactName") %>
</asp:tablecell>
</asp:tablerow>
<asp:tablerow runat="server">
<asp:tablecell runat="server" columnspan="2">
<%# Eval("Address") + " - " +
Eval("City") %>
</asp:tablecell>
</asp:tablerow>
</asp:table>
</ItemTemplate>
</asp:datalist>

, DataList Table
, TableRow.
, ,
.
DataList ,
(, ).
. 11-4.

ASP.NET

11

411

. 11-4. DataList ,


<asp:table> ( Table).
, <table> runat, , -
. <table> runat
ASP.NET ( , HtmlTable),
, .

DataList
RepeatColumns.
. , ,
, , , , .
<asp:datalist runat="server" id="list" RepeatColumns="3">
</asp:datalist>

. 11-5 RepeatColumns .

. 11-5. DataList

412

III

ASP.NET

, , . , ,
, .

DataList
, Repeater, DataList SelectedItemTemplate EditItemTemplate.
, :
, .
SelectedItemTemplate

, ,
Select. -
, ,
.
<SelectedItemTemplate>.
SelectedItem, DataListItem.
DataKeys , DataKeyField.
, , SelectedIndexChanged. , , , , .
, DataKeyField.
//
//
int key = (int) list.DataKeys[list.SelectedIndex];
GetChildData(key);

0-
SelectedIndex. 1 ,
. , SelectedIndex
.
.
EditItemTemplate

EditItemTemplate , .
EditItemStyle, EditItemIndex 0-
. , SelectedIndex,
, , , .
, Edit,
DataList EditCommand. ,
EditItemIndex ( 0-). 1. DataList EditItemTemplate.
, ,
UpdateCommand.

ASP.NET

11

413

, FindControl, ,
.

DataList
,
DataList .

,
, Select.
, , , Select ,
,
. , ,
SelectedItemStyle, SelectedIndex. -
,
, , , ItemCommand, .
SelectedIndex, .
, . DataList,
companyname Customers:
SELECT DISTINCT substring(companyname, 1, 1) AS Initial FROM customers

:
<asp:datalist runat="server" id="Picker"
repeatlayout="flow" repeatdirection="horizontal"
OnItemCommand="ItemCommand">
<ItemTemplate>
<asp:button ID="Button1" runat="server"
backcolor='<%# GetBackColor(Container.DataItem) %>'
forecolor='<%# GetForeColor(Container.DataItem) %>'
text='<%# Eval("Initial")%>'
commandname='<%# Eval("Initial")%>' />
</ItemTemplate>
</asp:datalist>

ItemCommand ,
, , , . . 11-6.
DataList:
<asp:datalist runat="server" id="Customers"
RepeatLayout="flow"
DataKeyField="customerid">
<SelectedItemStyle backcolor="cyan" width="100%" />
<HeaderTemplate>
<div><big><b><%# SetHeader() %></b></big></div>
</HeaderTemplate>
<ItemTemplate>
<span id='<%# Eval("customerid") %>'>
<span style="display:none;">

414

III

ASP.NET

<%# m_checkBox = (CheckBox) FindCheckBox(Container) %>


</span>
<asp:checkbox runat="server" id="ExpandButton" />
<asp:linkbutton ID="Link1" runat="server"
commandname="select"
text='<%# Eval("companyname") %>' />
<br>
</span>
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:datalist>

. 11-6. DataList

,
Repeater. Select (linkbutton)
. ,
:
<SelectedItemStyle backcolor="cyan" width="100%" />

.
, SelectedIndexChanged
, .

DataList
, .
, ,

ASP.NET

11

415

. ,
, , . 11-4, . DataList
.
.
, ,
. , , , . DataGrid GridView ,
DataList . ,
, .

DataList
, ,
. ,
. ,
DataList
.
private void OnPreviousPage(object sender, EventArgs e)
{
CurrentPageIndex -= 1;
RefreshPage();
}
private void OnNextPage(object sender, EventArgs e)
{
CurrentPageIndex += 1;
RefreshPage();
}

( CurrentPageIndex) DataList. RefreshPage


,
, , . CurrentPageIndex
,
. ,

.
RefreshPage DataTable:
private void RefreshPage()
{
DataTable data = GetData();
AdjustPageIndex(data.Rows.Count);
CurrentPage.Text = (CurrentPageIndex +1).ToString();
list.DataSource = GetPage(data, CurrentPageIndex);
list.DataBind();
}
private DataTable GetData()

416

III

ASP.NET

{
//
DataTable data = (DataTable) Session["MyData"];
// ,
if (data == null)
data = LoadData();
return data;
}

GetPage , . DataTable, DataList:


private DataTable GetPage(DataTable dt, int pageIndex)
{
if (dt==null)
{
CurrentPageIndex = 0;
dt = LoadData();
}
int firstIndexInPage = (CurrentPageIndex*PageSize);
DataRowCollection rows = dt.Rows;
DataTable target = dt.Clone();
for (int i=0; i<PageSize; i++)
{
int index = i+firstIndexInPage;
if (index < rows.Count)
target.ImportRow(rows[i+firstIndexInPage]);
else
break;
}
return target;
}

, . Clone , , . ImportRow
DataTable . ,
, ,
ADO.NET .
ASP.NET 2.0 DataList ObjectDataSource
, , . ObjectDataSource 9 Programming Microsoft
ASP.NET 2.0: Core Reference (Microsoft Press, 2005).


, ASP.NET, Repeater DataList.

. .
.

ASP.NET

11

417

Repeater , ;
, . DataList - , -
. Repeater DataList , ASP.NET.
;
.
DataList , Repeater,
, .

, , ,
.
.
, , .

ASP.NET , , , ,
.

ASP.NET : Repeater DataList.

, , .

-, GridView, DetailsView, FormView DataGrid,


, .
,
.

Repeater ,
, , .

Repeater , ,
ITemplate.

DataList ,
, .

DataList .

12


ASP.NET

ASP.NET:
. (custom)
(, Control WebControl)
. ,
, , .

: HTML-,
,
.
.
(user) , .
, HTML- ,
.
-,
, UserControl ASP.NET.


, Web-,
, .
. ActiveX- Microsoft Visual Basic,
,
,
.
,
Web-. - ASP.NET,
. , ASP.NET 1.0 pagelets ( .
page ). ,
, Web-. ,

ASP.NET

12

419

.ascx,
.
ASP.NET. , ,
.
, .
,
, , .

UserControl
.ascx,
ASP.NET.
( ), . ASP.NET,

,
. , . (
, , ,
<script runat="server">.)

( )
. ASP.NET IIS
, .ascx. ,
.aspx ,
.

(serverside includes, SSI).
SSI ,
HTML-, .
, ,
ASP.NET.

UserControl .NET Framework, ASP.NET .ascx-.


TemplateControl,
Page UserControl ( Web- ).
public class UserControl : TemplateControl

UserControl , INamingContainer. ,

, , .
, Control:
LoadControl, LoadTemplate ParseControl.

420

III

ASP.NET

.ascx , . ParseControl

.

. 12-1 UserControl, ,
TemplateControl.
. 12-1. UserControl

Application
Attributes

HttpApplicationState,
,
Cache,
ControlCachePolicy,
.
, , ControlCachePolicy. ASP.NET 1.x

,
HttpRequest,
HttpResponse,
HttpServerUtility,
HttpSessionState,
TraceContext,

Cache
CachePolicy

IsPostBack
Request
Response
Server
Session
Trace

, UserControl ,
ASP.NET, IsPostBack,
, ASP.NET.
,
, (ID, ClientID UniqueID), . ,
Controls.

UserControl , ,
. DataBind, FindControl LoadTemplate,
. 12-2.
. 12-2. UserControl

DesignerInitialize

,
RAD-

UserControl
,
.
.ascx, .aspx

InitializeAsUserControl
MapPath

ASP.NET

12

421

DesignerInitialize InitializeAsUserControl
.NET Framework.
, InitializeAsUserControl
, . , , Page_Load Page_Init,
, Load Init . , ,
. 123.
. 12-3. , UserControl
()

Page_AbortTransaction
(OnTransactionAbort)
Page_CommitTransaction
(OnTransactionCommit)
Page_DataBinding
Page_Error
Page_PreInit

Page_Init
Page_InitComplete
Page_PreLoad
Page_Load
Page_LoadComplete
Page_PreRender
Page_PreRenderComplete
Page_SaveStateComplete
Page_Unload




. ASP.NET 1.x


. ASP.NET 1.x

. ASP.NET 1.x


. ASP.NET 1.x




.
.


,
.
,
. , .
, <html>, <body> <form>.
,
-,
<html> <body>, ,
. <form>, ,
, runat.
<form runat="server">,

422

III

ASP.NET

. HTML- ( <form>
runat), .
HTML, , .ascx.
, . ,
@Page, @Control.
@Control

@Control @Page .
, ,
. 12-4.
. 12-4. @Control

AutoEventWireup
ClassName

CodeBehind

CodeFile

CodeFileBaseClass

CompilationMode
CompilerOptions
Debug

Description
EnableTheming
EnableViewState

Explicit

Inherits
Language
Strict

,
. true
, .

ASP.NET 1.x.
, ,

ASP.NET 2.0 ,
, . ASP.NET 1.x

.
,
CodeFile. ASP.NET 1.x
, . ASP.NET 1.x

,
,
. true,
, 1

, .
ASP.NET 1.x
,
.
true
, Visual Basic .NET Option Explicit. .
false
, .
UserControl
,
, Visual Basic .NET Option Strict.
.
false

ASP.NET

12

423

. 12-4. ()

Src

TargetSchema

.
.
ASP.NET 1.x

WarningLevel

, ,

,
. ,
. ,
.
@Control
(, Visual Basic.NET, C#).

(intermediate language).


ClassName, . , ,
.


, Web Forms .

URL. IIS 6.0 Web-,
Web-. 14 Programming Microsoft ASP.NET 2.0: Core Reference
(Microsoft Press, 2005).
:
. ,
.
, @OutputCache .aspx

. ,

.ascx @OutputCache.

: Duration VaryByParam. , 60 .
<% @OutputCache Duration="60" VaryByParam="None" %>

,
, ,
GET.

424

III

ASP.NET

!
, . ,
. ,

.
, .
, .
- ,
, , .
(-
), .


Web-. ,
, . , <script
runat="server">, , .
,
, .
.ascx:
<%@ Control Language="C#" %>
<script runat="server">
//
//
</script>
<!-- -->

,
. ,
, .
, , . ,
.
TabStrip
.

TabStrip
TabStrip
, .
, -, . ,
TabStrip, . 12-1.
Repeater HTML-,
.

ASP.NET

12

425

. 12-1. TabStrip

,
. .
, .
. , , , ,
, ,
(/) , , URL.
<%@ Control Language="C#" CodeFile="Tabstrip.ascx.cs" %>
<asp:Repeater runat="server" id="__theTabStrip">
<headertemplate>
<table cellpadding="0" cellspacing="0" border="0" ><tr>
</headertemplate>
<itemtemplate>
<td>
<asp:button runat="server" id="__theTab"
text='<%# Container.DataItem %>' />
</td>
</itemtemplate>
<footertemplate>
</tr></table>
</footertemplate>
</asp:Repeater>
<asp:panel runat="server" id="__theSep" width="100%" backcolor="gray" />

:
public ArrayList Tabs = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
__theTabStrip.DataSource = Tabs;

426

III

ASP.NET

__theTabStrip.DataBind();
}

Tabs , .
. Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
menu.Tabs.Add("Welcome");
menu.Tabs.Add("Developer");
menu.Tabs.Add("Download");
menu.Tabs.Add("Contact Us");
}

,
, Web-.

, runat.
,
. : .
expo, tabstrip. (,
.)
<expo:tabstrip runat="server" id="menu" />

asp
, ASP.NET system.
web. ,
. .ascx?
@Register

@Register ,
Web-.
. 12-5.
. 12-5. @Register

Assembly

, ,
.

Namespace

Src


, .
.ascx

TagName

,
( tabstrip);

ASP.NET

12

427

. 12-5. ()

TagPrefix

,
( expo);

@Register ,
.
:
<%@ Register tagprefix="..." namespace="..." assembly="..." %>

@Register :
<%@ Register tagprefix="..." tagname="..." src="..." %>

(tagprefix) ,
, , , .
ASP, ClassName. ,
, (_). , ,
ClassName TabStrip, ASP.TabStrip, ,
ClassName , ASP.tabstrip_ascx (
, tabstrip.ascx).
. .
,
,
.
.


, . , URL
URL . ,
Images ,
, :
<img src="images/logo.gif" />

, ,
, , .
, , (..),
(~).
:
<img src="~/images/logo.gif" />

TabStrip
:
<%@ Register TagPrefix="expo" TagName="TabStrip" Src="tabstrip.ascx" %>

428

III

ASP.NET

. ,
ASP.NET. ( .ascx
) , .
. ( , ,
, ,
.)
web.config

ASP.NET 1.x , ASP.NET 2.0 , ,


<controls> web.config.
<controls>
<add tagPrefix="expo" tagName="Tabstrip" src="tabstrip.ascx" />
</controls>

<controls> <pages>, , 3, .

.


,
public, . ,
:
public Color BackColor
{
get
{
object o = ViewState["BackColor"];
if (o == null)
return Color.Silver;
return (Color)o;
}
set { ViewState["BackColor"] = value; }
}
public Color ForeColor
{
get
{
object o = ViewState["ForeColor"];
if (o == null)
return Color.White;
return (Color)o;
}
set { ViewState["ForeColor"] = value; }
}

ASP.NET

12

429

public
, -.
ViewState .
.NET Framework,
.
get set. ( ),
- . , ,
. .
,
. ,
, Cache, Session
ViewState . ViewState
, Web-.


, , Text
, .
public string Caption
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}


. Caption Text
TextBox1 - .
. ,
.

,
. Tabs. CurrentTabIndex,
, .
public int CurrentTabIndex
{
get
{
object o = ViewState["CurrentTabIndex"];
if (o == null)
return 0;
return (int) o;
}
}

, get, set
. ,
, ,
. ,
.
, .

430

III

ASP.NET

, CurrentTabIndex
.
! , CurrentTabIndex:
, , .
null, .
ASP.NET.

BackColor ForeColor
TabStrip SelectedBackColor SelectedForeColor,
.
, .
:
<expo:tabstrip runat="server" id="menu" selectedbackcolor="cyan" />

. ,
, , .
ASP.NET .
, ,
, :
void Page_Load(object sender, EventArgs e)
{
// Tabs ,
// .
// , IsPostBack
menu.Tabs.Add("Welcome");
menu.Tabs.Add("Developer");
menu.Tabs.Add("Download");
menu.Tabs.Add("Contact Us");
if (!IsPostBack)
{
// ,
//
// ,
// ,
}
//
menu.SelectedBackColor = Color.Green;
menu.SelectedForeColor = Color.White;
menu.BackColor = Color.LightGray;
menu.ForeColor = Color.Black;
}


ID. ,
, ,
.
,
, ( 5):
<itemtemplate>
<td>

ASP.NET

12

431

<asp:button runat="server" id="__theTab"


BorderWidth="1px"
BorderStyle="solid"
BorderColor='<%# GetBorderColor(Container) %>'
text='<%# Container.DataItem %>'
font-bold='<%# (Container.ItemIndex == CurrentTabIndex) %>'
backcolor='<%# GetBackColor(Container) %>'
forecolor='<%# GetForeColor(Container) %>' />
</td>
</itemtemplate>

GetXXX TabStrip;
,
.
protected Color GetBackColor(object elem)
{
RepeaterItem item = (RepeaterItem)elem;
if (item.ItemIndex == CurrentTabIndex)
return SelectedBackColor;
return BackColor;
}
protected Color GetForeColor(object elem)
{
RepeaterItem item = (RepeaterItem)elem;
if (item.ItemIndex == CurrentTabIndex)
return SelectedForeColor;
return ForeColor;
}
protected Color GetBorderColor(object elem)
{
RepeaterItem item = (RepeaterItem)elem;
if (item.ItemIndex == CurrentTabIndex)
return SelectedBackColor;
return Color.Black;
}

TabStrip,
Tabs, / . Tabs ,
, .
. ,
,
, . , .
( .) :
?
, ,
. :
, , , . -
,
. ,
.

432

III

ASP.NET

. ,
.
13 14,
.

TabStrip
. ,
. Select, ,
. :
public void Select(int index)

0-
, .
.
public
{
//
//
if

void Select(int index)


, .
,
(index <0 || index >Tabs.Count)
index = 0;

// .
// ,
// CurrentTabIndex
ViewState["CurrentTabIndex"] = index;
//
__theSep.BackColor = SelectedBackColor;
//
BindData();
}


, , . , Select ,
CurrentTabIndex, ,
.
ViewState, .

. ,
, ,
, - (. 12-2):
<asp:textbox runat="server" id="tabIndex" />
<asp:linkbutton runat="server" text="Select tab" onclick="OnSelectTab" />

OnSelectTab Select
:
void OnSelectTab(object sender, EventArgs e)
{

ASP.NET

12

433

int index = -1;


Int32.TryParse(tabIndex.Text, out index);
menu.Select(index);
}

. 12-2. -

Select CurrentTabIndex. , ,
Select.


TabStrip , ,
, . -
, , .
, ,
, URL. ,
.
SelectionChanged

:

Select. SelectionChanged:
public event SelectionChangedEventHandler SelectionChanged;

, .
. , ,
. ( ,
, , , .) ASP.NET
EventHandler. :
public delegate void EventHandler(object sender, EventArgs e);

EventHandler ,
object EventArgs void. , . , ,
.

434

III

ASP.NET


, , , EventHandler . ,
,
:
public delegate void SelectionChangedEventHandler(
object sender, SelectionChangedEventArgs e);

, ,
EventHandler , , ,
. (
SelectionChanged)
, .
public class SelectionChangedEventArgs : EventArgs
{
public int SelectedIndex // 0-based index of the selected tab
}

SelectionChangedEventArgs EventArgs,
, 0-
. ,
SelectionChanged.
.NET Framework 2.0
.
EventHandler EventHandler<T>.
public event EventHandler<SelectionChangedEventArgs> SelectionChanged;

. ASP.NET 2.0 , , , .


, . (protected,
virtual).
,
.NET Framework. protected virtual, ,
.NET Framework.
// ,
//
protected virtual void OnSelectionChanged(SelectionChangedEventArgs e)
{
// SelectionChanged -.
// ,
if (SelectionChanged != null)
SelectionChanged(this, e);
}

, : ,
- , . -

ASP.NET

12

435

, , ,
.
, , . C# ,
. Visual Basic.NET
, RaiseEvent, .
, OnEventName,
, ,
, .

, ,
. Select:
public void Select(int index)
{
// ,
if (index <0 || index >Tabs.Count)
index = 0;
//
__theSep.BackColor = SelectedBackColor;
//
BindData();
//
SelectionChangedEventArgs ev = new SelectionChangedEventArgs();
ev.SelectedIndex CurrentTabIndex;
OnSelectionChanged(ev);
}

,
Repeater ItemCommand.
Select.
private void ItemCommand(object sender, RepeaterCommandEventArgs e)
{
//
Select(e.Item.ItemIndex);
}

, , ,
.

.NET, ,
, ,
. . , C#
-
:
// YourHandler
menu.SelectionChanged += new SelectionChangedEventHandler(YourHandler);

436

III

ASP.NET

Visual Basic.NET AddHandler:


' YourHandler
AddHandler menu.SelectionChanged, AddressOf YourHandler

ASP.NET , ,
OnXXX, XXX -.
<expo:TabStrip runat="server" id="menu"
SelectedBackColor="cyan"
OnSelectionChanged="SelectionChanged" />

SelectionChanged:
void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
msg.Text = "Selected tab #" + e.Position.ToString();
}
ASP.NET 2.0
TabStrip MultiView,
, ASP.NET. MultiView -, ,
.

.
TabStrip MultiView.




.
, , SQL- .


, , ,
.
, , , IEnumerable
, , ADO.NET.
ButtonList, TabStrip, .
ButtonList

ButtonList : Repeater,
. Repeater , .
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="ButtonList.ascx.cs" Inherits="ButtonList" %>

ASP.NET

12

437

<asp:repeater runat="server" id="__theMenu">


<HeaderTemplate>
<table border="0" cellspacing="0" cellpadding="0"><tr>
</HeaderTemplate>
<ItemTemplate>
<td valign="bottom">
<asp:button runat="server" id="TheButton"
style="border:solid 1px gray" />
</td>
</ItemTemplate>
<FooterTemplate>
</tr></table>
</FooterTemplate>
</asp:repeater>
<asp:panel runat="server" id="__theSep" width="100%" />

.ascx . , , .
ButtonList

ButtonList (. 12-6),
,
Repeater.
. 12-6. ButtonList

ButtonWidth
CurrentButtonIndex
DataSource
DataTextField
DataValueField

( )
0- ( )

,
, ,

DataSource , , .
,
. . Button
, . ,
DataValueField , . , . , DataSource,
.
DataSource ASP.NET
Cache. ,
ButtonList .
public object DataSource
{

438

III

ASP.NET

get
{
object o = Cache[ID];
if (o == null)
{
RefreshDataEventArgs ev = new RefreshDataEventArgs();
OnRefreshData(ev);
o = ev.DataSource;
}
return o;
}
set { Cache[ID] = value; }
}

DataSource ,
. , ,
, .
ASP.NET, , , -
.
. , ,
Cache, ,
, . DataSource null , , ,
-, .
public event EventHandler<RefreshDataEventArgs> RefreshData;

RefreshDataEventArgs :
public class RefreshDataEventArgs : EventArgs
{
public object DataSource;
}

, , , ,
.
DataTextField:
public string DataTextField
{
get
{
object o = ViewState["DataTextField"];
if (o == null)
return String.Empty;
return (string) o;
}
set { ViewState["DataTextField"] = value; }
}

, . , null

ASP.NET

12

439

( ,
).
ButtonList , Repeater. ,
BindData,
ButtonList, , :
private void BindData() {
__theMenu.DataSource = DataSource;
__theMenu.DataBind();
}

BindData : Page_Load ,
:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}

, ButtonClicked. ,
. .

( ),
,
Repeater:
private void HookUpEvents() {
__theMenu.ItemCommand += new RepeaterCommandEventHandler(ItemCommand);
__theMenu.ItemCreated += new RepeaterItemEventHandler(ItemCreated);
__theMenu.ItemDataBound += new RepeaterItemEventHandler(ItemBound);
}

ItemCreated
, , . ,
.
protected void ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item &&
e.Item.ItemType != ListItemType.AlternatingItem)
return;
//
RepeaterItem item = e.Item;
bool isSelected = IsSelectedItem(item);
Button btn = (Button) item.FindControl("TheButton");
//
if (isSelected) {
btn.BackColor = SelectedBackColor;
btn.ForeColor = SelectedForeColor;
btn.Height = Unit.Pixel(SELECTEDBUTTONHEIGHT);

440

III

ASP.NET

btn.Width = Unit.Pixel(ButtonWidth*150/100);
}
else
{
btn.BackColor = BackColor;
btn.ForeColor = ForeColor;
btn.Height = Unit.Pixel(BUTTONHEIGHT);
btn.Width = Unit.Pixel(ButtonWidth);
}
}

, ,
. ( , ,
TabStrip, .) ItemCreated, Repeater
Item AlternatingItem.
ItemCreated, . , ,
ItemDataBound.
protected void ItemBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item &&
e.Item.ItemType != ListItemType.AlternatingItem)
return;
// ,
RepeaterItem item = e.Item;
Button btn = (Button) item.FindControl("TheButton");
//
btn.Text = DataBinder.GetPropertyValue(item.DataItem,
DataTextField).ToString();
btn.CommandName = DataBinder.GetPropertyValue(item.DataItem,
DataValueField).ToString();
}

DataBinder. ,
( )
ADO.NET . DataBinder,
DataTextField DataValueField
.
, Repeater ItemCommand.
protected void ItemCommand(object sender, RepeaterCommandEventArgs e)
{
//
CurrentButtonIndex = e.Item.ItemIndex;
// ButtonClicked
ButtonClickedEventArgs ev = new ButtonClickedEventArgs();
ev.ButtonCommand = e.CommandName;

ASP.NET

12

441

ev.ButtonIndex = CurrentButtonIndex;
OnButtonClicked(ev);
//
BindData();
}

RepeaterCommandEventArgs ,
, . ButtonClickedEventArgs
.

, ButtonList , ,
.
:
<%@ Register TagPrefix="expo"
TagName="ButtonList" Src="buttonlist.ascx" %>

,
TagName TagPrefix.
ButtonList ButtonClicked:
<expo:buttonlist runat="server" id="initialStrip"
onbuttonclicked="ButtonClicked" />
<expo:buttonlist runat="server" id="yearStrip"
onbuttonclicked="ButtonClicked" />


.
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindInitials();
BindYears();
}
}
private void BindInitials()
{
DataTable data = GetData_Initials();
initialStrip.DataSource = data;
initialStrip.DataTextField = "Initial";
initialStrip.DataValueField = "Initial";
initialStrip.DataBind();
}
private void BindYears()
{
DataTable data = GetData_Years();
yearStrip.DataSource = data;
yearStrip.DataTextField = "Year";
yearStrip.DataValueField = "Year";

442

III

ASP.NET

yearStrip.DataBind();
}
private DataTable GetData_Years()
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(m_cmdYears,
m_connString);
adapter.Fill(data);
return data;
}
private DataTable GetData_Initials()
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(m_cmdInitial,
m_connString);
adapter.Fill(data);
return data;
}

, , BindInitials
BindYears NorthWind:
--
SELECT DISTINCT substring(companyname, 1, 1) AS Initial FROM customers
-- ,
SELECT DISTINCT year(orderdate) AS Year FROM orders

,
initialStrip; yearStrip .
initialStrip.DataSource = data;
initialStrip.DataTextField = "Initial";
initialStrip.DataValueField = "Initial";
initialStrip.DataBind();

. 12-3.
, ButtonClicked , .
// "ProAspNet.CS.Ch10"
void ButtonClicked(object sender, ButtonClickedEventArgs e)
{
string t1 = "Customer names that fall under the <b>{0}.</b> " +
"tab named <b>'{1}'</b>.";
string t2 = "Order information that falls under the <b>{0}.</b> " +
"tab named <b>'{1}'</b>."
//
//
//
if

label.
ButtonList
,
(sender.Equals(initialStrip))
msg1.Text = String.Format(t1, 1 + e.ButtonIndex,
e.ButtonCommand);

ASP.NET

12

443

else
msg2.Text = String.Format(t2, 1 + e.ButtonIndex,
e.ButtonCommand);
}

. 12-3. ButtonList

DataSource Cache,
, - RefreshData,
,
. , . 12-3.
protected void RefreshData(object sender, RefreshDataEventArgs e)
{
if (sender.Equals(initialStrip))
e.DataSource = GetData_Initials();
else
e.DataSource = GetData_Years();
}


ASP.NET, .
new, LoadControl.
LoadControl

LoadControl TemplateControl.
Control , .
Control ctl = LoadControl("ButtonList.ascx");

Control,
, . ClassName @Control ,
.
, .
@Reference.
, ,
LoadControl, Control, PartialCachingControl.

444

III

ASP.NET

@Reference

,
, .
ButtonList,
buttonlist.ascx:
<%@ Reference Control="buttonlist.ascx" %>

.
ClassName, ASP.buttonlist_ascx,
ASP.XXX, XXX ClassName.
@Reference , ( ) .
: Page Control. URL
Web-,
. .ascx,
:
ButtonList btn = (ButtonList) LoadControl("buttonlist.ascx");

@Register
,
. @Reference ,
.

, , Web-.
,
.
,
.

, .
, Web-,
, .
, ,
- ,
. , .
,
, .
.
.
, , .
. . , , ,

ASP.NET

12

445

,
- .

Web-,
, , .

.ascx, , .

ASP.NET,
, , .

ASP.NET
<html>, <body>
<form>, @Page @Control.

.
, .

13


ASP.NET

Microsoft
, . ASP.NET , ,
.

. , Microsoft Visual Studio 2005 ,
, ,
Properties,
, .
, . ,
Visual Studio,
. , , , ,
. ,
, (. 1). ,
,
.
ASP.NET
. ,
Visual Studio 2005.

(GAC) ; \Bin .
, . ,
, , .
, , ,
. ,
, .
,
, -

ASP.NET

13

447

Control WebControl. ,
, (,
, )
.
, , . ,
.

.
! ASP.NET
, HTML, .
, ,
, HTML-
. ,
,
, , Windows Forms.
( ), ,
DHTML,
.


, , ,
HTML, JavaScript.
, HTML,
.



Control ASP.NET.
,
,
.

ASP.NET, ,
, . . 13-1
, ASP.NET
.
.
. 13-1. , ASP.NET

BaseDataBoundControl

2.0

BaseDataList

1.x


. WebControl
,
, , .
WebControl

(. . .)

448

III

ASP.NET

. 13-1. ()

CompositeControl

2.0

.
WebControl

CompositeDataBoundControl

2.0



.
DataBoundControl

DataBoundControl

2.0

, ; . BaseDataBoundControl

HierarchicalDataBoundControl

2.0

,
;

.
BaseDataBoundControl

ListControl

1.x


, CheckBoxList DropDownList. ASP.NET 1.x,
ASP.NET 2.0 . DataBoundControl

WebControl

1.x


, , ,

,
Control, Repeater, Substitution, MultiView, Placeholder
LiteralControl. ASP.NET -

Control ,
. , ,
, , ASP.NET 2.0 ,
. , . 13-1,
,
.
, ,
, , ASP.NET.
. , , . 13-1, ,
; .
, ,
, , , ,
, .

ASP.NET

13

449

HyperLink
,
HyperLink.
<a>, URL. ( ) ,
, . ,
,
HyperLink. .

, HyperLink, , ,
, .
, , . , ,
.
, ,
(, )?
(Button,
HyperLink, ImageButton, LinkButton, AdRotator) , , ,
.
, , . , ,
LinkButton.
OnClick:
protected virtual void OnClick(EventArgs e)
{
//
//
base.OnClick(e);
}

HyperLink?
. - .
HyperLink

: URL
, ,
, .
using System;
using System.Web.UI.WebControls;
namespace ProAspNet20.Advanced.CS.Components
{
public class Hyperlink : System.Web.UI.WebControls.HyperLink
{
public string RedirectPage
{
get
{
object o = ViewState["RedirectPage"];

450

III

ASP.NET

if (o == null)
return "redir.aspx";
else
return (string)o;
}
set { ViewState["RedirectPage"] = value; }
}
public new string NavigateUrl
{
get { return base.NavigateUrl; }
set
{
string url = "{0}?page={1}";
url = String.Format(url, RedirectPage, value);
base.NavigateUrl = url;
}
}
}
}

RedirectPage
NavigateUrl. RedirectPage URL ,
, . .
public partial class Redir : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//
string url = String.Empty;
object o = Request["Page"];
if (o != null)
{
url = (string) o;
if (String.IsNullOrEmpty(url)
return;
}
// ,
//
Response.Redirect(url);
}
}

, HyperLink
-, Page,
URL. , - .
URL NavigateUrl. . , URL
http://www.asp.net, :
redir.aspx?page=http://www.asp.net

ASP.NET

13

451

redir.aspx, http://www.asp.net.
( ) , -
virtual. HyperLink Text
, , Target NavigateUrl. virtual,
, . C#
new, Microsoft Visual Basic .NET Shadows.
public new string NavigateUrl
{
get { return base.NavigateUrl; }
set
{
string url = "{0}?page={1}";
url = String.Format(url, RedirectPage, value);
base.NavigateUrl = url;
}
}

new ,
, .
NavigateUrl ,
, ,
new, .


:

.
, .
.


ASP.NET
. -, , Control WebControl,
. , , . INamingContainer,
IPostBackDataHandler, IPostBackEventHandler ASP.NET 2.0
ICallbackEventHandler.
. 13-1.

, Control WebControl.
Control WebControl

Control , ,
. , , , , ID, UniqueID,
Parent, ViewState Controls.

452

III

ASP.NET

WebControl Control , .
ForeColor, BackColor, Font, Height Width.
ASP.NET.
ASP.NET
.
, WebControl.
, ,
Control. ,
, . ,
Control, .
, ,
ASP.NET 2.0 CompositeControl, ASP.NET 1.x,
, Control.
UserControl.

, . , .


INamingContainer , ,
ASP.NET , , , .
UniqueID ,
, .
, -,
. INamingContainer
,
, . ( .)

IPostBackDataHandler , , ,
. , , . ,
TextBox ,
, .
IPostBackDataHandler. LoadPostData . ,
, ,
( RaisePostDataChanged). ,
TextBox: , TextChanged.

IPostBackEventHandler , , ( ).
ASP.NET ,
, , UniqueID
(, , ).

ASP.NET

13

453

IPostBackEventHandler, ASP.
NET RaisePostBackEvent.
, ,
. , Button Click.


ICallbackEventHandler , (. 6). 7 Web Part, ICallbackEventHandler,


.


. , , , ,
.
-.
Render

,
Render.
. Render :
protected override void Render(HtmlTextWriter writer)

HTTP- (HtmlTextWriter) , . ,
HtmlTextWriter .
HtmlTextWriter , , , , , .
,
,
.
, . :
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<input type=text id=\"TextBox1\" />");
}

,
TextBox1.
.
,
, HTML,
, , .
,
, .
,
.

, .

454

III

ASP.NET

, CreateChildControls Control.
Controls.
CreateChildControls:
protected override void CreateChildControls()
{
//
Controls.Clear();
//
CreateControlHierarchy();
//
ClearChildViewState();
}

ClearChildViewState Control, , .
CreateControlHierarchy . ,
ASP.NET CreateControlHierarchy;
. , . ,
, .
protected void CreateControlHierarchy()
{
//
Label lbl = new Label();
lbl.Text = "Some text";
Controls.Add(lbl);
// ,
//
Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
//
TextBox txt = new TextBox();
txt.Text = String.Empty;
Controls.Add(txt);
// ,
ChildControlsCreated = true;
}

CreateControlHierarchy Controls
,
. ChildControlsCreated,
Control, , .
, Render,
INamingContainer,
ASP.NET ,
.

ASP.NET

13

455

ASP.NET 2.0
CompositeControl. Visual Studio 2005
, .
,
Web- . ASP.NET 1.x , Render ,
.

EnsureChildControls. ,
, . ? ChildControlsCreated
CreateChildControls,
. , .
protected virtual void EnsureChildControls()
{
if (!ChildControlsCreated)
{
try {
CreateChildControls();
}
finally {
ChildControlsCreated = true;
}
}
}

SimpleGaugeBar
, ASP.NET, , ,
. , SimpleGaugeBar,
.

:
, . ,
, ,
, . . 13-2
SimpleGaugeBar.
. 13-2. SimpleGaugeBar

FormatString

, .
. :
{0} / {1}

GridLines

Maximum

, .
100

Segments

, .
4

(. . .)

456

III

ASP.NET

. 13-2. ()

Value

, .
0

Value , Maximum.
:
Value ({1}) Maximum ({2}). HTML-
. :
GaugeBar1.FormatString = "{0} ({1})";
GaugeBar2.FormatString = "Maximum is {1}. Value is <b>{0}</b>";

SimpleGaugeBar .

HTML-. Value Maximum . . 13-1 ,


SimpleGaugeBar Visual Studio 2005.

. 13-1. SimpleGaugeBar Visual Studio

, , ,
,
Segments. ,
.
public class SimpleGaugeBar : CompositeControl
{
private int _dividerCell;
public SimpleGaugeBar()
{
}
// ,
public float Value
{
get
{
object o = ViewState["Value"];
if (o == null)
return 0;
return (float) o;
}
set
{
ViewState["Value"] = value;
if (value > Maximum)
ViewState["Value"] = Maximum;
}

ASP.NET

}
//
public float Maximum
{
get
{
object o = ViewState["Maximum"];
if (o == null)
return 100;
return (float) o;
}
set { ViewState["Maximum"] = value; }
}
//
public int Segments
{
get
{
object o = ViewState["Segments"];
if (o == null)
return 4;
return (int) o;
}
set
{
ViewState["Segments"] = value;
if( value < 1)
ViewState["Segments"] = 1;
}
}
//
public string FormatString
{
get
{
object o = ViewState["FormatString"];
if (o == null)
return "<b>{0}</b> / <b>{1}</b>";
return (string) o;
}
set { ViewState["FormatString"] = value; }
}
//
public bool GridLines
{
get
{
object o = ViewState["GridLines"];
if (o == null)
return true;
return (bool) o;
}
set { ViewState["GridLines"] = value; }
}
}

13

457

458

III

ASP.NET

ViewState.
, , .
!
. ,
,
.
-.

, .
. , , .
.
, .
, ,
, ,
. HTML-
, 52 % .
.
<table><tr>
<td bgcolor=orange width=25%></td>
<td bgcolor=orange width=25%></td>
<td>
<table><tr>
<td bgcolor=orange width=2%></td>
<td bgcolor=white width=98%></td>
</tr></table>
</td>
<td bgcolor=white width=25%></td>
</tr></table>

. 13-2 ,
.

. 13-2. SimpleGaugeBar

ASP.NET

13

459

, , , , . 13-2, . ,
, BackColor ForeColor, , Width Height.
, Visual Studio.
, .


HTML. , HTML,
,
.
.
HTML-

HTML,
, , .
, , ,
HTML, ,
. .
:
output.WriteFullBeginTag("table");
output.WriteFullBeginTag("tr");
output.WriteFullBeginTag("td");
output.Write(text);
output.WriteEndTag("td");
output.WriteEndTag("tr");
output.WriteEndTag("table");

,
:
output.Write("<table><tr><td>");
output.Write(text);
output.Write("</td></tr></table>");

, . , ,
.
, ASP.NET HTML- , .
: ,
, , .
ASP.NET
.
, . , ,
Label writer.

460

III

ASP.NET


, .
, ,
, RenderContents .
Render, :
protected override void Render(HtmlTextWriter output)
{
// ,
// .
PrepareControlForRendering();
//
base.RenderContents(output);
}

PrepareControlForRendering .
SimpleGaugeBar , .
protected override void CreateChildControls()
{
Controls.Clear();
CreateControlHierarchy();
ClearChildViewState();
}
protected virtual void CreateControlHierarchy()
{
// -
Table outer = new Table();
TableRow outerRow = new TableRow();
outer.Rows.Add(outerRow);
//
TableCell rulerCell = new TableCell();
outerRow.Cells.Add(rulerCell);
BuildGaugeBar(rulerCell);
//
TableCell textCell = new TableCell();
if (!_textStyle.DisplayTextAtBottom)
{
outerRow.Cells.Add(textCell);
BuildLabel(textCell);
}
//
Controls.Add(outer);
//
if (!_textStyle.RenderInsideTable && _textStyle.DisplayTextAtBottom)
BuildLabel(null);

ASP.NET

13

461

}
void BuildGaugeBar(TableCell container)
{
// :
Table t = new Table();
TableRow ruler = new TableRow();
t.Rows.Add(ruler);
//
BuildRuler(ruler);
//
if (_textStyle.RenderInsideTable)
BuildLabelIntoTable(t);
//
container.Controls.Add(t);
}

SimpleGaugeBar
, , (. . 13-2). , Label.
TextStyle,
, .
,
. , ,
Segments,
Value Maximum. , ,
. -
, . 13-3.
.
void BuildRuler(TableRow ruler)
{
// ,
float val = GetValueToRepresent();
float valueToRepresent = 100f * val / Maximum;
int numOfSegments = GetNumOfSegments();
int segmentWidth = 100 / numOfSegments;
bool finished = false;
for (int i = 1; i <= numOfSegments; i++)
{
if (valueToRepresent < i * segmentWidth)
{
if (finished)
{
//
TableCell stillToDo = new TableCell();
ruler.Cells.Add(stillToDo);
stillToDo.Width = Unit.Percentage(segmentWidth);
}
else
{

462

III

ASP.NET

// ,
_dividerCell = i - 1; // 0-
TableCell cell = new TableCell();
ruler.Cells.Add(cell);
cell.Width = Unit.Percentage(segmentWidth);
cell.Height = Unit.Percentage(100);
//
Table child = new Table();
child.Width = Unit.Percentage(100);
child.Height = Unit.Percentage(100);
cell.Controls.Add(child);
child.CellPadding = 0;
child.CellSpacing = 0;
TableRow childRow = new TableRow();
child.Rows.Add(childRow);
float fx = (100 *
(valueToRepresent - segmentWidth *
(i - 1)) / segmentWidth);
if (valueToRepresent > (i - 1) * segmentWidth)
{
TableCell left = new TableCell();
childRow.Cells.Add(left);
left.Width = Unit.Percentage(fx);
}
TableCell right = new TableCell();
childRow.Cells.Add(right);
right.Width = Unit.Percentage(100 - fx);
finished = true;
}
}
else
{
//
TableCell done = new TableCell();
ruler.Cells.Add(done);
done.Width = Unit.Percentage(segmentWidth);
}
}
}

. 13-3. - SimpleGaugeBar

.
, .

ASP.NET

13

463

BuildLabel
, BuildLabelIntoTable
, .
void BuildLabel(TableCell container)
{
// ,
float buf = GetValueToRepresent();
//
string msg = GetTextToRepresent();
Label lbl = new Label();
if (container is TableCell)
container.Controls.Add(lbl);
else
Controls.Add(lbl);
lbl.Text = String.Format(msg, buf, Maximum);
}
//
void BuildLabelIntoTable(Table t)
{
// ,
float buf = GetValueToRepresent();
int numOfSegments = GetNumOfSegments();
//
string msg = GetTextToRepresent();
if (_textStyle.DisplayTextAtBottom)
{
//
TableRow label = new TableRow();
t.Rows.Add(label);
TableCell lblCell = new TableCell();
label.Cells.Add(lblCell);
lblCell.ColumnSpan = numOfSegments;
lblCell.Text = String.Format(msg, buf, Maximum);
}
}
,
: GetValueToRepresent GetTextToRepresent.
Value FormatString.
SimpleGaugeBar,
. , ,
GetValueToRepresent GetTextToRepresent.

,
. ,
.
.

SimpleGaugeBar WebControl
, BackColor, Font BorderStyle.
?

464

III

ASP.NET

, . :
, .
Style TableItemStyle. ,
, .
SimpleGaugeBar TextStyle,
:
private TextItemStyle _textStyle;
[PersistenceMode(PersistenceMode.InnerProperty)]
public TextItemStyle TextStyle
{
get
{
if (_textStyle == null)
_textStyle = new TextItemStyle();
if (IsTrackingViewState)
((IStateManager)_textStyle).TrackViewState();
return _textStyle;
}
}

TextStyle
_textStyle. , ,
. .
, [PersistenceMode], ,
. Visual Studio 2005
.aspx .
TextItemStyle.
public class TextItemStyle : TableItemStyle, IStateManager
{
private bool _renderInsideTable;
private bool _displayTextAtBottom;
public TextItemStyle()
{
_displayTextAtBottom = true;
_renderInsideTable = false;
}
//
public bool RenderInsideTable
{
get { return _renderInsideTable; }
set { _renderInsideTable = value; }
}
public bool DisplayTextAtBottom
{

ASP.NET

13

465

get { return _displayTextAtBottom; }


set { _displayTextAtBottom = value; }
}
}

IStateManager, , . ,
.
,
, BinaryFormatter.
, ,
. IStateManager
SimpleGaugeBar:
bool IStateManager.IsTrackingViewState
{
get { return base.IsTrackingViewState; }
}
void IStateManager.TrackViewState()
{
base.TrackViewState();
}
object IStateManager.SaveViewState()
{
object[] state = new object[2];
state[0] = base.SaveViewState();
object[] extraData = new object[2];
extraData[0] = _renderInsideTable;
extraData[1] = _displayTextAtBottom;
state[1] = (object)extraData;
return state;
}
void IStateManager.LoadViewState(object state)
{
if (state == null)
return;
object[] myState = (object[])state;
base.LoadViewState(myState[0]);
object[] extraData = (object[])myState[1];
_renderInsideTable = (bool)extraData[0];
_displayTextAtBottom = (bool)extraData[1];
}

IStateManager , . 13-3.
SaveViewState , .
, SaveViewState
. (
, Pair Triplet), ,
. LoadViewState
.

466

III

ASP.NET

. 13-3. IStateManager

IsTrackingViewState

LoadViewState

SaveViewState


.
LoadViewState

TrackViewState

Visual Studio 2005


(. 13-4). , SimpleGaugeBar Properties. , ,
.aspx <TextStyle>.

. 13-4. Visual Studio 2005

,
.
.
protected override void Render(HtmlTextWriter output)
{
PrepareControlForRendering();
base.RenderContents(output);
}

PrepareControlForRendering ,
.
protected virtual void PrepareControlForRendering()
{
if (Controls.Count < 1)
return;

ASP.NET

//
Table outer = (Table)Controls[0];
Table t = (Table)outer.Rows[0].Cells[0].Controls[0];
//
t.CopyBaseAttributes(this);
//
t.CellPadding = 0;
t.CellSpacing = 0;
//
for (int i = 0; i < Segments; i++)
{
TableCell cell = t.Rows[0].Cells[i];
if (GridLines)
{
cell.BorderColor = BorderColor;
cell.BorderStyle = BorderStyle;
cell.BorderWidth = BorderWidth;
}
if (i < _dividerCell)
cell.BackColor = ForeColor;
if (i >= _dividerCell)
cell.BackColor = BackColor;
if (i == _dividerCell)
{
Table inner = (Table)cell.Controls[0];
if (inner.Rows[0].Cells.Count > 1)
{
inner.Rows[0].Cells[0].BackColor = ForeColor;
inner.Rows[0].Cells[1].BackColor = BackColor;
}
else
inner.Rows[0].Cells[0].BackColor = BackColor;
}
}
//
if (!_textStyle.DisplayTextAtBottom)
outer.Rows[0].Cells[1].ApplyStyle(TextStyle);
else if (_textStyle.RenderInsideTable &&
_textStyle.DisplayTextAtBottom)
{
//
TableRow row = t.Rows[1];
row.ApplyStyle(TextStyle);
}
else
{
//
Label lbl = (Label)Controls[1];
lbl.ApplyStyle(TextStyle);
}
}

13

467

468

III

ASP.NET

PrepareControlForRendering , , .
.

SimpleGaugeBar
Visual Studio 2005
Web Forms. .
<expo:SimpleGaugeBar id="GaugeBar1" runat="server"
Width="500px" Height="15px"
FormatString="<b>{0}</b> out of <b>{1}</b>"
Segments="10"
Value="65">
<TextStyle Font-Bold="True" Font-Names="Verdana" Font-Size="8pt" />
</expo:SimpleGaugeBar>

, , Properties; , ,
Visual Studio.
,
SimpleGaugeBar.
private void Button1_Click(object sender,
EventArgs e)
{
GaugeBar1.Maximum = 200;
GaugeBar1.Value = 55;
}

Maximum ,
Value. .
- ,
, ,
.



ASP.NET 1.x Panel
<div>. , HTML ,
. ASP.NET 2.0
, .
Panel
. /. ,
,
.
, , , ,
.

ASP.NET

13

469



Panel, , .
: / ,
Panel. :
<table>
<tr>
<td>Caption</td>
<td>Drop-down button</td>
</tr>
<tr>
<td colspan="2">Standard contents</td>
</tr>
</table>

Panel
, Panel:
<asp:Panel runat="server">
<!-- -->
</asp:Panel>


Controls Panel. , CreateChildControls
, .
ASP.NET Controls Panel Render.
. ,
, , /
, .
.

System.Web.UI.WebControls.Panel
, :
namespace ProAspNet20.Advanced.CS.Components
{
public class Panel : System.Web.UI.WebControls.Panel, INamingContainer
{
}
}

, Panel,
. 13-4.
EnableDropDown,
false, , .
true, , /.

470

III

ASP.NET

. 13-4. Panel

Caption
CaptionBackColor
CaptionForeColor
EnableClientScript



, / .
false
, /. false
,
. true

EnableDropDown
ShowExpanded

,
, ,
EnableClientScript. false,
.
,
, . .
.
. 13-5.

. 13-5. Panel

, ButtonUrl,
.
Caption , ;
CaptionBackColor CaptionForeColor. , .

Panel
, EnableDropDown.
public bool EnableDropDown
{
get
{
object o = ViewState["EnableDropDown"];
if (o == null)

ASP.NET

13

471

return false;
return (bool) o;
}
set { ViewState["EnableDropDown"] = value; }
}


? / , ShowExpanded?
, , . ?
, , , .
ASP.NET 2.0,
,
-. ,
, ,
- .
, .
, ,
. , ,
. ,
. , ,
, .
- ViewState.

, :
private bool _panelDisplayed;
protected override object SaveControlState()
{
Pair p = new Pair();
p.First = base.SaveControlState();
p.Second = _panelDisplayed;
return p;
}
protected override void LoadControlState(object savedState)
{
if (savedState == null)
return;
Pair p = (Pair) savedState;
base.LoadControlState(p.First);
_panelDisplayed = (bool)p.Second;
}

Panel
, , . ,
,
. ,
SaveControlState LoadControlState.

472

III

ASP.NET

SaveControlState , ,
, LoadControlState ,
.
Pair
Triplet , ,
Object. SaveControlState Pair
.
, .
. LoadControlState
.

. , , -. LoadControlState
SaveControlState .
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
_panelDisplayed = ShowExpanded;
}


Init, RegisterRequiresControlState Page.
, Panel _panelDisplayed, .
Load , IsPostBack
false. _panelDisplayed
.

ASP.NET 2.0 .
, HTML-
.
(CSS) . 5 Programming Microsoft ASP.NET 2.0:
Core Reference.
ASP.NET : CSS . (skin)
,
. , .
,
Panel.
<%@ Register TagPrefix="expo" Namespace="ProAspNet20.CS.Components"
Assembly="ProAspCompLib" %>

ASP.NET

13

473

<expo:Panel runat="server" Width="300px" BorderWidth="1px"


Font-Bold="True" Font-Names="Verdana" Font-Size="Small"
HorizontalAlign="Left" BackColor="#FFFF80"
CaptionBackColor="Teal">
</expo:Panel>

. ,
, . ,
? [Themeable].
. ,
:
[Themeable(false)]
public bool EnableDropDown
{
}

, EnableDropDown, EnableClientScript ShowExpanded


.
? ,
CaptionBackColor, ?
. .
,
, .
. , ,
. , .


,
:
.
ASP.NET.
writer ,
, ,
ASP.NET.
Panel <div>
.
Panel , .
writer, , ,
.
CreateChildControls.

Panel
Render.
. Render Controls Panel ,

474

III

ASP.NET

<asp:panel>.
Panel.
,
. 13-5, .
Controls CreateChildControls.
, Panel.
protected override void CreateChildControls()
{
if (EnableDropDown)
{
base.CreateChildControls();
CreateControlHierarchy();
}
else
base.CreateChildControls();
}

EnableDropDown false, Panel. CreateChildControls


,
CreateControlHierarchy.
CreateControlHierarchy ,
Controls , . .
ASP.NET . ,
.

CreateControlHierarchy ,
, Controls
. :
protected virtual void CreateControlHierarchy()
{
//
Table t = new Table();
//
TableRow row1 = new TableRow();
t.Rows.Add(row1);
//
TableCell cell1 = new TableCell();
row1.Cells.Add(cell1);
cell1.Text = Caption;
// ( )
TableCell cell2 = new TableCell();
row1.Cells.Add(cell2);
cell2.HorizontalAlign = HorizontalAlign.Right;

ASP.NET

13

475

//
TableRow row2 = new TableRow();
t.Rows.Add(row2);
//
TableCell body = new TableCell();
body.ID = "Body";
row2.Cells.Add(body);
body.ColumnSpan = 2;
//
Control[] children = new Control[Controls.Count];
Controls.CopyTo(children, 0);
foreach (Control ctl in children)
body.Controls.Add(ctl);
// Controls
Controls.Clear();
Controls.Add(t);
}

, Controls
.
Control . Controls . . 13-6
, ASP.NET.

. 13-6.

, . ,

. , ,
, HTML (
ASP.NET). ASP.
NET (, ,
), , ASP.NET .

476

III

ASP.NET

, Controls.
.
CreateControlHierarchy, , .
, ,
. ImageButton, , Image, /
. EnableClientScript
.

. , :
WebControl img;
if (!EnableClientScript)
{
img = new ImageButton();
((ImageButton)img).Click += new ImageClickEventHandler(OnClick);
}
else
{
img = new System.Web.UI.WebControls.Image();
//
}
// cell2 (. )
cell2.Controls.Add(img);
// /
ShowChildControls(_panelDisplayed);
//
ShowImageButton(_panelDisplayed);

/
Click OnClick, , .
URL ?
ShowImageButton /
ImageUrl ImageButton Image. , ImageButton Image, ,
.
void ShowImageButton(bool display)
{
// , ,
//
if (Controls.Count != 1)
return;
//
Table t = (Table)Controls[0];
TableRow r = t.Rows[0];
TableCell icon = r.Cells[1];

ASP.NET

13

477

// Image ImageButton
// EnableClientScript
// (ImageButton Image)
Image img =(Image) icon.Controls[0];
string imageName = "ProAspNet20.Advanced.CS.Components.Expand.bmp";
if (display)
imageName = "ProAspNet20.Advanced.CS.Components.Collapse.bmp";
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(
this.GetType(), imageName);
}

ShowImageButton ,
-, ,
.
(. 9).
,
Visual Studio, ,
Build Action Embedded Resources. ,
. assemblyinfo.cs ( assemblyinfo.vb)
:
[assembly: WebResource("ProAspNet20.Advanced.CS.Components.Expand.bmp",
"image/jpg")]
[assembly: WebResource("ProAspNet20.Advanced.CS.Components.Collapse.bmp",
"image/jpg")]

,
GetWebResourceUrl ClientScript .
. URL,
ImageUrl ,
, src <img>. 6, URL HTTP WebResource.
axd. HTTP ,
MIME-, [WebResource].
ASP.NET 2.0 , App_Code Web-,
. Visual Studio 2005
. ,
,
.

, Panel,
, Microsoft Windows XP.
. 13-7 , / .

. 13-7. /

478

III

ASP.NET

ASP.NET 2.0 , ,
. ASP.NET 1.x
, .

. ,
.
,
CreateChildControls,
, . .
CreateControlHierarchy , /.
Render, , :
protected override void Render(HtmlTextWriter writer)
{
PrepareControlForRendering();
base.Render(writer);
}
protected virtual void PrepareControlForRendering()
{
// ,
if (Controls.Count != 1)
return;
//
if (!EnableDropDown)
return;
Table t = (Table) Controls[0];
t.CopyBaseAttributes(this);
if (ControlStyleCreated)
t.ApplyStyle(ControlStyle);
//
t.CellPadding = 1;
t.CellSpacing = 0;
//
TableRow row1 = t.Rows[0];
row1.BackColor = CaptionBackColor;
row1.ForeColor = CaptionForeColor;
}

PrepareControlForRendering , . protected virtual, .


Controls
.
.

ASP.NET

13

479

,
Visual Studio 2005. , BackColor Panel, Table,
Panel. ,
, .
PrepareControlForRendering ,
.


Panel ,
, . , /. , ,
- , ,
.
.

. , . HTML ,
, .
, ,
.

Panel
ImageButton, Image : submit, ,
. ImageButton
, .

, ,
, . ImageButton
OnClick:
ImageButton img = new ImageButton();
img.Click += new ImageClickEventHandler(OnClick);

:
void OnClick(object sender, ImageClickEventArgs e)
{
// /
_panelDisplayed = !_panelDisplayed;
//
ShowChildControls(_panelDisplayed);
ShowImageButton(_panelDisplayed);
}

480

III

ASP.NET

, ASP.NET,
INamingContainer
ImageButton Controls.
, , ASP.NET
, Click .
/ , , .
ShowChildControls.
void ShowChildControls(bool display)
{
//
if (Controls.Count != 1)
return;
//
Table t = (Table)Controls[0];
TableRow r = t.Rows[1];
TableCell body = r.Cells[0];
body.Style["display"] = (display ? "" : "none");
}

,
, .
.
DOM style display, ,
. none, .
, .
, Firefox Netscape
6.0 .
DOM : display visibility.
HTML.
, visibility ,
, visibility
.

PanelClick

, ,
(, -)
Click .
Panel
.
PanelClick , ,
. :
public event EventHandler<PanelClickEventArgs> PanelClick;

ASP.NET

13

481

,
PanelClickEventArgs:
public class PanelClickEventArgs : EventArgs
{
public bool BeingClosed;
}

PanelClickEventArgs EventArgs
, ,
, BeingClosed, ,
.
PanelClick
Click ImageButton:
void OnClick(object sender, ImageClickEventArgs e)
{
PanelClickEventArgs args = new PanelClickEventArgs();
args.BeingClosed = _panelDisplayed;
OnPanelClick(args);
// /
// ( )
}
protected virtual void OnPanelClick(PanelClickEventArgs args)
{
if (PanelClick != null)
PanelClick(this, args);
}

- ( , Panel)
PanelClick, Panel Click
ImageButton.

Click Panel
? ,
(event bubbling).
ASP.NET , , ,
. , , ,
, .
, , ,
, , RaiseBubbleEvent:
protected virtual void OnPanelClick(PanelClickEventArgs args)
{
if (PanelClick != null)
PanelClick(this, args);
base.RaiseBubbleEvent(this, args);
}

482

III

ASP.NET

RaiseBubbleEvent Control ASP.NET.


- .
, OnBubbleEvent:
protected override bool OnBubbleEvent(object source, EventArgs e)
{
bool handled = false;
if (e is PanelClickEventArgs)
{
PanelClickEventArgs args = (PanelClickEventArgs) e;
if (args.BeingClosed)
{
// .
// , .
// true,
handled = true;
}
}
return handled;
}

EventArgs .
. , OnBubbleEvent, : true,
. false (
, ), .
,
,
. ,
, , ,
. ? ,
, , ,
. . ,
, .


Panel . ,
, .
. , .
ImageButton ,
.
Image ,
, , .

EnableClientScript true, / ,
:
// Image
Image img = new Image();

ASP.NET

13

483

img.Attributes["onmouseover"] = "this.style.cursor = \"hand\";";


img.Attributes["onmouseout"] = "this.style.cursor = \"\";";
img.Attributes["onclick"] = "__toggle()";
// cell2
cell2.Controls.Add(img);

Image ,
onmouseover onmouseout, . ,
JavaScript,
: __toggle.
ShowImageButton, ,
CreateControlHierarchy URL .
.
//
string imageName = "ProAspNet20.Advanced.CS.Components.Expand.bmp";
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(
this.GetType(), imageName);

JavaScript __toggle
. -,
. ,
.
if (!Page.ClientScript.IsClientScriptBlockRegistered("__toggle"))
{
string js = BuildScript(body);
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "__toggle", js, true);
}

, , ,
. IsClientScriptBlockRegistered ,
, RegisterClientScriptBlock . <script>.
ASP.NET 2.0
. ASP.NET 1.x
-, .
, ,
JavaScript .
JavaScript , RegisterClientScriptBlock ,
<script>. false,
, .

,
, JavaScript.
,

484

III

ASP.NET

StringBuilder. , .NET Framework


, +.
private string BuildScript(TableCell body)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("function __toggle() {");
sb.AppendFormat("var body = document.getElementById(\"{0}\");\r\n",
body.ClientID);
sb.AppendLine("var display = body.style.display;");
sb.AppendLine("if (display == \"\") {");
sb.AppendLine("body.style.display = \"none\";");
sb.AppendLine("} else {");
sb.AppendLine("body.style.display = \"\";");
sb.AppendLine("}");
sb.AppendLine("}");
return sb.ToString();
}

JavaScript, , :
<script type="text/javascript">
<!-function __toggle() {
var body = document.getElementById("Panel1_Body");
var display = body.style.display;
if (display == "") {
body.style.display = "none";
} else {
body.style.display = "";
}
}
// -->
</script>

, ,
. HTML DOM.
, BuildScript
TableCell.
. Panel, , Body,
Panel1_Body. ? , ?

,
. , Body Panel1
Panel2.
, .
, , -

ASP.NET

13

485

DOM
.
INamingContainer,
, ,
. :
cell.ID = "Body";

Panel Panel1, Panel1$Body. ID


Body, UniqueID Panel1$Body.
ID- , ClientID. UniqueID , $
(_).
, HTML- , ClientID
.
! ClientID
Controls . ,
BuildScript ,
Controls, ClientID Body Panel1_Body
, .

ASP.NET ,
. ,
,
. . ,
, ,
.
,
,
: HTML-
. ,
.

, .
. ,
.
, .

,
.

, ,

486

III

ASP.NET

, ,
.


: , HTML- .
.

, .
,
.

. ,
.

14

, ,
,
. . 11,
Repeater DataList.
2 Programming Microsoft ASP.NET 2.0: Core Reference
(Microsoft Press, 2005).
ASP.NET ,
, ,
. ,
, . , ,
. ,
,
, , .

. , ,
,
, , .
13 ,
,
, . ,
,

. ,
, .

,
, , ,
, ,
. ASP.NET 1.x , , ,
IEnumerable ( ) IListSource. ASP.NET 2.0
. ,

488

III

ASP.NET

,
, , . ASP.NET, ,
ASP.NET 1.x, , .
9 Programming Microsoft ASP.NET 2.0: Core
Reference (Microsoft Press, 2005).
, , ASP.NET . , .
, .aspx
. , , , .
, , ,
.
( , )
,
.
ASP.NET 2.0 , ,
:
, .
,
, ,
.
, .

,
.
,
, , :
, .


.
, .
, ,
, , , , .
SimpleGaugeBar, ,
, . , Value FormatString
, , , .

, . RadioButtonList, CheckBoxList ASP.NET 2.0

14

489

BulletedList.
,
, .
,
: ,
, .
, .
,
.

, , .
, . , ,
DataGrid.
BarChart
.
HTML-,
.
,
.
! ASP.NET 1.x ,
. , ,
, . ASP.NET 2.0
, ,
. ASP.NET : GridView, FormView DetailsView.
,
, .
, , .


ASP.NET 2.0 , ,
. 141. , BaseDataBoundControl.
BaseDataBoundControl .
, : DataSource
DataSourceID ,
:
public virtual object DataSource { get; set; }
public virtual string DataSourceID { get; set; }

. ,
. ?
,
BaseDataBoundControl .

490

III

ASP.NET

. 14-1. ,

DataSource , IEnumerable (, ) IListSource (, DataTable).


, ASP.NET 1.x:
ctl.DataSource = dataTable;
ctl.DataBind();

DataSource DataBind ( , , ).
.
DataSourceID
, .
, (
, )
. , .
, .
ASP.NET ,
. , ,
. ,
ASP.NET 1.x.
, ,
ASP.NET 2.0 .
BaseDataBoundControl. , ,
DataSource DataSourceID , . DataSource:
// DataSource
set (object value)

14

491

{
if (value != null)
ValidateDataSource(value);
_dataSource = value;
OnDataPropertyChanged();
}

,
.
OnDataPropertyChanged. DataSourceID:
// DataSourceID
set (string value)
{
ViewState["DataSourceID"] = value;
OnDataPropertyChanged();
}

DataSourceID , OnDataPropertyChanged. OnDataPropertyChanged?


RequiresDataBinding, BaseDataBoundControl
.
RequiresDataBinding true,
.
BaseDataBoundControl.
BaseDataBoundControl

BaseDataBoundControl
, DataBind (
Control),
.
Init PreRender. - , OnInit RequiresDataBinding true. , ,
, , , . OnPreRender
, .
, EnsureDataBound.
RequiresDataBinding , true, DataBind.
, DataBind Control
BaseDataBoundControl. :
public override void DataBind()
{
PerformSelect();
}

, PerformSelect BaseDataBoundControl
, .
.
BaseDataBoundControl, ValidateDataSource,
DataSource.

492

III

ASP.NET

DataBoundControl

ValidateDataSource PerformSelect BaseDataBoundControl DataBoundControl. :


protected override void ValidateDataSource(object dataSource)
{
if (dataSource != null)
{
if (!(dataSource is IListSource) &&
!(dataSource is IEnumerable) &&
!(dataSource is IDataSource))
throw new InvalidOperationException(...);
}
}

, DataSource null
: IListSource, IEnumerable IDataSource. IDataSource
, . , , :
, DataSourceID, ,
DataSource , .
PerformSelect:
protected override void PerformSelect()
{
// - ,
//
DataSourceView view = GetData();
// SELECT ;
// _arguments ,
// , SELECT
_arguments = CreateDataSourceSelectArguments();
view.Select(_arguments, OnDataSourceViewSelectCallback);
//
}

, , . SELECT
, SqlDataSource ObjectDataSource.

( DataSource DataSourceID),
, -.
, , ,
, -
, IDataSource.
, - GetData. DataSource
, -,
ReadOnlyDataSource.
DataSourceView Select, , . , Select

14

493

.
.
, ,
- .
,
SELECT, INSERT, DELETE UPDATE. DataBoundControl
SELECT . ,
, , DataSource DataSourceID.
, ,
?
HierarchicalDataBoundControl
DataBoundControl, , -.

PerformDataBinding

,
SELECT ,
PerformDataBinding:
protected virtual void PerformDataBinding(IEnumerable data)
{
// data
// ,
}

PerformDataBinding DataBoundControl
. ,
.
ASP.NET 2.0 , , , ,
. , DataBoundControl, PerformDataBinding.
, , ,
.
. 14-1 , .
, ,
DataMember, ASP.NET 1.x, , DataSource. ,
. ASP.NET 2.0 : DataSource
BaseDataBoundControl, DataMember DataBoundControl.

,

SimpleGaugeBar,
. Value Maximum,
. SimpleGaugeBar

494

III

ASP.NET

, ,
. CompositeControl,
SimpleGaugeBar ,
.


SimpleGaugeBar .
,
ASP.NET. , DataSource
DataSourceID , ,
, .
, (
).
, :


, ;

, -
;

,
- ;

,
.

, , , .
, DropDownList ,
.
DataTextField DataValueField
DropDownList.

. . , , DataXxxField, Xxx
.

, ,
, : IEnumerable (),
IListSource ( ADO.NET), IDataSource ( ,
). , , DataTable.
? , ,
BLOB-?
, -

. ,

14

495

, . , DropDownList , Text Value.


, , (ListItem),
, Text Value ( ).
, , , ,
.
. , , . ,
IStateManager,
.
,
.

,
,
, , . , , LoadViewState SaveViewState, ,
IStateManager, .
, SimpleGaugeBar, 13,
LoadViewState SaveViewState
. , ,
, IStateManager. ,
(
IStateManager). :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
SimpleGaugeBar1.TextStyle.BackColor = Color.Yellow;
}

BackColor .
, TextStyle (. 13),
.
protected void Page_Load(object sender, EventArgs e)
{
// ,
//
SimpleGaugeBar1.TextStyle.BackColor = Color.Yellow;
}

,
IsPostBack,
,
.

496

III

ASP.NET

PerformDataBinding

,
DataBoundControl, PerformDataBinding.
. ,
.
,
.
,
(, ),
DataBoundControl.
, , BaseDataBoundControl,
PerformSelect ValidateDataSource. ,
, /
.

GaugeBar
, ,
SimpleGaugeBar GaugeBar. , DataBoundControl,
.
public class GaugeBar : DataBoundControl
{
}

, , ASP.NET 2.0 CompositeDataBoundControl, ,


. .

GaugeBar 12 SimpleGaugeBar.
,
, .
GaugeBar , Value FormatString.
. DataXxxField,
Value FormatString. , DataValueField DataTextField,
,
Value FormatString. -, DataValueField DataTextField
.
public virtual string DataValueField
{
get
{
object o = ViewState["DataValueField"];
if (o == null)
return String.Empty;
return (string) o;

14

497

}
set { ViewState["DataValueField"] = value; }
}
public virtual string DataTextField
{
get
{
object o = ViewState["DataTextField"];
if (o == null)
return String.Empty;
return (string) o;
}
set { ViewState["DataTextField"] = value; }
}

, ViewState . GaugeBar
, : DataSource, DataSourceID DataMember.
GaugeBar

GaugeBar , .
. ,
, , .
GaugeBar GaugeBarDataItem ( , )
:
public class GaugeBarDataItem : IStateManager
{
private string _text;
private float _value;
private bool _marked;
public GaugeBarDataItem()
{
}
public GaugeBarDataItem(float value, string text)
{
_text = text;
_value = value;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public float Value
{
get { return _value; }
set { _value = value; }

498

III

ASP.NET

}
public bool IsTrackingViewState
{
get { return _marked; }
}
public void LoadViewState(object state)
{
if (state != null)
{
Pair p = (Pair)state;
_value = (float)p.First;
_text = (string)p.Second;
}
}
public object SaveViewState()
{
return new Pair(_value, _text);
}
public void TrackViewState()
{
_marked = true;
}
}

, Text Value,
, IStateManager, ,
.
SaveViewState Pair (
), Text Value. Pair, ViewState, LoadViewState,
Pair Text Value.
GaugeBar
GaugeBarDataItem . DataItem:
private GaugeBarDataItem _dataItem;
private GaugeBarDataItem DataItem
{
get
{
if (_dataItem == null)
{
_dataItem = new GaugeBarDataItem();
if (base.IsTrackingViewState)
_dataItem.TrackViewState();
}
return _dataItem;
}
}

, ViewState,
DataItem _dataItem.

14

499


. DataItem
_dataItem null
GaugeBarDataItem.
, ,
. , ,
DataItem null

.


, ,
.
DataItem ? , , ?
// NB: , GaugeBarDataItem
//
public virtual GaugeBarDataItem DataItem
{
get
{
object o = ViewState["DataItem"];
if (o == null)
return new GaugeBarDataItem();
return (string) o;
}
set { ViewState["DataItem"] = value; }
}

, ,
.
, .
BinaryFormatter,
.NET,
, , .
. , ,

.
, : ViewState
, ,
, , . (
), ; IStateManager ,
. ,
- , .

, , ,

500

III

ASP.NET

SaveViewState LoadViewState. Control


ViewState:
protected override object SaveViewState()
{
// ViewState
object baseState = base.SaveViewState();
// DataItem
object itemState = DataItem.SaveViewState();
// TextStyle
object styleState = TextStyle.SaveViewState();
//
return new Triplet(baseState, itemState, styleState);
}

SaveViewState GaugeBar :
, DataItem TextStyle. SaveViewState
, SaveViewState IStateManager DataItem TextStyle. SaveViewState
,
Pair Triplet.
, SaveViewState, LoadViewState,
.
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
Triplet t = (Triplet) savedState;
base.LoadViewState(t.First);
DataItem.LoadViewState(t.Second);
TextStyle.LoadViewState(t.Third);
}
else
{
base.LoadViewState(null);
}
}

LoadViewState IStateManager
, (, ) .
, DataItem.LoadViewState
DataItem,
_dataItem.

ASP.NET 2.0
PerformDataBinding. ,
. , -

14

501

IEnumerable, PerformDataBinding,
, (
ADO.NET, , ,
).
PerformDataBinding GaugeBar:
protected override void PerformDataBinding(IEnumerable data)
{
// data , .
// MoveNext
if (data == null)
return;
IEnumerator e = data.GetEnumerator();
e.MoveNext();
//
float displayValue = 0;
string displayText = String.Empty;
// Value
if (!String.IsNullOrEmpty(DataValueField))
displayValue = (float) DataBinder.GetPropertyValue(
e.Current, DataValueField);
// FormatString
if (!String.IsNullOrEmpty(DataTextField))
displayText = (string) DataBinder.GetPropertyValue(
e.Current, DataTextField);
// DataItem
DataItem.Value = displayValue;
DataItem.Text = displayText;
}

IEnumerable, PerformDataBinding, .
. ,
.
// data IEnumerable
IEnumerator e = data.GetEnumerator();
e.MoveNext();
// e.Current

e.Current , , , , . , , ,
DataRow, Value, :
displayValue = ((DataRow) e.Current)[DataValueField];

DataBinder
. GetPropertyValue DataBinder,
, , ,
:
displayText = (string) DataBinder.GetPropertyValue(
e.Current, DataTextField);

502

III

ASP.NET

GetPropertyValue , .
,

DataItem. BuildLabel
(
13).
void BuildLabel(TableCell container)
{
// ,
float buf = GetValueToRepresent();
//
string msg = GetTextToRepresent();
Label lbl = new Label();
if (container is TableCell)
container.Controls.Add(lbl);
else
Controls.Add(lbl);
lbl.Text = String.Format(msg, buf, Maximum);
}

BuildLabel Label. , ,
. Value
FormatString .
,
, . ,
, .
float GetValueToRepresent()
{
float f = 0;
if (DataItem.Value >=0)
f = DataItem.Value;
else
f = Value;
return f;
}
string GetTextToRepresent()
{
string msg = "";
if (!String.IsNullOrEmpty(DataItem.Text))
msg = DataItem.Text;
else
msg = FormatString;
return msg;
}

SimpleGaugeBar
(. 13) .

14

503

Load ,
GaugeBar,
DataTable:
protected void Page_Load(object sender, EventArgs e)
{
// GaugeBar .
// DataTable
Random rnd = new Random();
DataTable dt = new DataTable();
dt.Columns.Add("Numbers", typeof(float));
dt.Columns.Add("Label", typeof(string));
DataRow row = dt.NewRow();
row[0] = rnd.Next(0,100);
row[1] = "{0} out of {1}";
dt.Rows.Add(row);
dt.AcceptChanges();
// DataTable GaugeBar
GaugeBar1.DataValueField = "Numbers";
GaugeBar1.DataTextField = "Label";
GaugeBar1.DataSource = dt;
GaugeBar1.DataBind();
}

DataTable , Numbers float Label


string. . ,
PerformDataBinding .
GaugeBar DataItem:
GaugeBar1.DataItem.Value = 12;
GaugeBar1.DataItem.Text = "{0} %";

, DataBind .


, , . ,
. , CheckBoxList
CheckBox, DropDownList <option>
<select>.
ASP.NET 2.0 ListControl . 14-1 ,
ASP.NET 1.x. ListControl DataBoundControl . , ,
.


. 14-1, ListControl : DropDownList, CheckBoxList,

504

III

ASP.NET

RadioButtonList, ListBox BulletedList. BulletedList ASP.NET 2.0. , DataBoundControl.


.
ListControl

. 14-1 , ListControl
.
. 14-1. ,

AppendDataBoundItems

, Items ,

AutoPostBack

CausesValidation

DataTextField

DataTextFormatString

DataValueField

Items

.
AppendDataBoundItems
. ListItem

SelectedIndex

SelectedItem

ListItem,

SelectedValue

Text

SelectedValue

ValidationGroup

, AutoPostBack, CausesValidation ValidationGroup,


.
ListItem. DataItem,
, , .
Items, ListItemCollection.
, Items ; PerformDataBinding.
AppendDataBoundItems true ( ),
ListItem .

.
ListControl.
, , , ,
. ,
. ,
, HyperLink, URL .

14

505

public class SimpleHyperLinkList : ListControl


{
private HyperLink _controlToRepeat;
private HyperLink ControlToRepeat
{
get
{
if (_controlToRepeat == null)
_controlToRepeat = new HyperLink();
return _controlToRepeat;
}
}
protected override void Render(HtmlTextWriter writer)
{
for (int i=0; i<Items.Count; i++)
{
HyperLink ctl = ControlToRepeat;
ctl.ApplyStyle(ControlStyle);
ctl.Text = Items[i].Text;
ctl.NavigateUrl = Items[i].Value;
ctl.RenderControl(writer);
writer.Write("<br />");
}
}
}

SimpleHyperLinkList ControlToRepeat Render. ControlToRepeat


,
. , .
Render ,
HyperLink. Text HyperLink . RenderControl
HyperLink. writer, ,
. 14-2.

. 14-2. SimpleHyperLinkList

, SimpleHyperLinkList.

506

III

ASP.NET

ListControl, ListItem,
. ,
, , .
,
, SimpleHyperLinkList,
.

HyperLinkList

ListControl. HyperLinkList :
public class HyperLinkList : DataBoundControl, IRepeatInfoUser
{
}

IRepeatInfoUser
, (
).

HyperLinkList ,
: DataTextField, DataTooltipField DataUrlField.
public virtual string DataTextField
{
get
{
object o = ViewState["DataTextField"];
if (o == null)
return String.Empty;
return (string) o;
}
set { ViewState["DataTextField"] = value; }
}
public virtual string DataTooltipField
{
get
{
object o = ViewState["DataTooltipField"];
if (o == null)
return String.Empty;
return (string) o;
}
set { ViewState["DataTooltipField"] = value; }
}
public virtual string DataUrlField
{
get
{
object o = ViewState["DataUrlField"];

14

507

if (o == null)
return String.Empty;
return (string) o;
}
set { ViewState["DataUrlField"] = value; }
}

( , URL)
.
HyperLinkList

, , . :
, URL.
public class HyperLinkItem
{
private string _text;
private string _url;
private string _tooltip;
public HyperLinkItem()
{
}
public HyperLinkItem(string url, string text, string tooltip)
{
_text = text;
_url = url;
_tooltip = tooltip;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public string Tooltip
{
get { return _tooltip; }
set { _tooltip = value; }
}
public string Url
{
get { return _url; }
set { _url = value; }
}
}

, Url, Tooltip Text,


, .
HyperLinkItem n- .
HyperLinkItem.

508

III

ASP.NET

ASP.NET 2.0 ,
, . IStateManager.
class HyperLinkItemCollection : Collection<HyperLinkItem>, IStateManager
{
private bool _marked;
public HyperLinkItemCollection()
{
_marked = false;
}
public bool IsTrackingViewState
{
get { return _marked; }
}
public void TrackViewState()
{
_marked = true;
}
public void LoadViewState(object state)
{
if (state != null)
{
Triplet t = (Triplet) state;
// , ,
// ,
Clear();
string[] rgUrl = (string[])t.First;
string[] rgText = (string[])t.Second;
string[] rgTooltip = (string[])t.Third;
for (int i = 0; i < rgUrl.Length; i++)
Add(new HyperLinkItem(rgUrl[i], rgText[i], rgTooltip[i]));
}
}
public object SaveViewState()
{
int numOfItems = Count;
object[] rgTooltip = new string[numOfItems];
object[] rgText = new string[numOfItems];
object[] rgUrl = new string[numOfItems];
for (int i = 0; i < numOfItems; i++)
{
rgTooltip[i] = this[i].Tooltip;
rgText[i] = this[i].Text;
rgUrl[i] = this[i].Url;
}
return new Triplet(rgUrl, rgText, rgTooltip);
}
}

14

509

,
DataItem GaugeBar, Items ( ).
private HyperLinkItemCollection _items;
public virtual HyperLinkItemCollection Items
{
get
{
if (_items == null)
{
_items = new HyperLinkItemCollection();
if (base.IsTrackingViewState)
_items.TrackViewState();
}
return _items;
}
}

SaveViewState.
URL, .
, Triplet.
LoadViewState .
, HyperLinkItemCollection , .
HyperLinkList:
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
object itemState = Items.SaveViewState();
return new Pair(baseState, itemState);
}
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
Pair p = (Pair) savedState;
base.LoadViewState(p.First);
Items.LoadViewState(p.Second);
}
}

SaveViewState LoadViewState HyperLinkList , . Items


, .


PerformDataBinding. , . PerformDataBinding
,

510

III

ASP.NET

, .
protected override void PerformDataBinding(IEnumerable dataSource)
{
base.PerformDataBinding(dataSource);
string urlField = DataUrlField;
string textField = DataTextField;
string tooltipField = DataTooltipField;
if (dataSource != null)
{
foreach (object o in dataSource)
{
HyperLinkItem item = new HyperLinkItem();
item.Url = DataBinder.GetPropertyValue(o, urlField, null);
item.Text = DataBinder.GetPropertyValue(o, textField, null);
item.Tooltip = DataBinder.GetPropertyValue(o, tooltipField, null);
Items.Add(item);
}
}
}

, HyperLinkItem,
Items.
IRepeatInfoUser

HyperLinkList SimpleHyperLinkList, ,
.

. ASP.NET CheckBoxList, RepeatDirection,
RepeatLayout RepeatColumns. ,
. . 14-2
; .
. 14-2. IRepeatInfoUser

RepeatColumns

RepeatDirection

RepeatLayout

,
. , .
public virtual RepeatDirection RepeatDirection
{
get
{
object o = ViewState["RepeatDirection"];
if (o != null)
return (RepeatDirection) o;

14

511

return RepeatDirection.Vertical;
}
set { ViewState["RepeatDirection"] = value; }
}
public virtual int RepeatColumns
{
get
{
object o = ViewState["RepeatColumns"];
if (o != null)
return (int) o;
return 0;
}
set { ViewState["RepeatColumns"] = value; }
}
public virtual RepeatLayout RepeatLayout
{
get
{
object o = ViewState["RepeatLayout"];
if (o != null)
return (RepeatLayout) o;
return RepeatLayout.Table;
}
set { ViewState["RepeatLayout"] = value; }
}

,
, Render .
protected override void Render(HtmlTextWriter writer)
{
if (Items.Count > 0)
{
RepeatInfo ri = new RepeatInfo();
Style controlStyle = (base.ControlStyleCreated
? base.ControlStyle : null);
ri.RepeatColumns = RepeatColumns;
ri.RepeatDirection = RepeatDirection;
ri.RepeatLayout = RepeatLayout;
ri.RenderRepeater(writer, this, controlStyle, this);
}
}

RepeatInfo ASP.NET 1.x


.
RenderRepeater ( this),
IRepeatInfoUser.
. . 14-3.
. 14-3. IRepeatInfoUser

HasFooter
HasHeader

,
,

(. . .)

512

III

ASP.NET

. 14-3. ()

HasSeparators

RepeatedItemCount

GetItemStyle RenderItem.
, , . , :
bool IRepeatInfoUser.HasFooter
{
get { return false; }
}
bool IRepeatInfoUser.HasHeader
{
get { return false; }
}
bool IRepeatInfoUser.HasSeparators
{
get { return false; }
}
int IRepeatInfoUser.RepeatedItemCount
{
get { return this.Items.Count; }
}
Style IRepeatInfoUser.GetItemStyle(ListItemType itemType, int repeatIndex)
{
return null;
}
void IRepeatInfoUser.RenderItem(ListItemType itemType,
int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
HyperLink ctl = ControlToRepeat;
int i = repeatIndex;
ctl.ID = i.ToString();
ctl.Text = Items[i].Text;
ctl.NavigateUrl = Items[i].Url;
ctl.ToolTip = Items[i].Tooltip;
ctl.RenderControl(writer);
}

RenderItem
.
(, HyperLink ),
. ,

14

513

, . RenderControl. . 14-3.

. 14-3. HyperLinkList
( RepeatColumns 3)

,

, , CompositeDataBoundControl.
:


, CreateChildControls;

,
.

ASP.NET 1.x
, : CompositeDataBoundControl.

,

ASP.NET 2.0 , , . CreateChildControls. ,
.
. HTTP-, , .

, , CreateChildControls.
Control, :
protected override void CreateChildControls()

514

III

ASP.NET

CompositeDataBoundControl . . :
protected override void CreateChildControls()
{
Controls.Clear();
object o = ViewState["_!ItemCount"];
if ((o == null) && RequiresDataBinding)
EnsureDataBound();
else
{
int numOfItems = (int) o;
object[] rg = new object[numOfItems];
CreateChildControls(rg, false);
base.ClearChildViewState();
}
}

Controls,
, _!ItemCount. ,
. , ,
.
, ,
, . ASP.NET
, ,
, . ,
.
, GaugeBar,
. ,
, , Items
DataItem. ,
DataGrid, DataList GridView,
.
.
GridView
. ,
, GridView, ,
. ,
. ,
,
, - , .
, ASP.NET . ,
.
, , CreateChildControls
, .

14

515

CreateChildControls.
CompositeDataBoundControl, .
CreateChildControls

CreateChildControls, CompositeDataBoundControl:
protected abstract int CreateChildControls(
IEnumerable dataSource, bool dataBinding);

. :
. , .
PerformDataBinding ( CompositeDataBoundControl), :
protected internal override void PerformDataBinding(IEnumerable data)
{
base.PerformDataBinding(data);
Controls.Clear();
base.ClearChildViewState();
TrackViewState();
int numOfItems = CreateChildControls(data, true);
base.ChildControlsCreated = true;
ViewState["_!ItemCount"] = numOfItems;
}

, PerformDataBinding
CreateChildControls true, ,
.
CreateChildControls?
,
( CreateControlHierarchy) CreateChildControls
, . ,
BarChart.
CreateChildControls PerformDataBinding, CreateChildControls:
// o , ViewState
int numOfItems = (int) o;
object[] rg = new object[numOfItems];
CreateChildControls(rg, false);


. ,
( CreateControlHierarchy)
, . ,
BarChart,
.
CreateChildControls false, .
ASP.NET ,
. ,
,

516

III

ASP.NET

, , Label,
,
.
, Label Text.
, , ,
,

. , ,
.
XXXItem

, ASP.NET
, , ,
. Items, . ,
, .
,
. . ,
DataGrid DataGridItem .
BarChart, ,
TableRow , ,
. , ,
.
, BarChart.

BarChart
BarChart CompositeDataBoundControl
, . 14-4. Items.
. 14-4. BarChart

DataTextField

,


,

,
BarChart.
.
Items BarChartItem
,

DataTextFormatString
DataValueField
DataValueFormatString
Items

Maximum
SubTitle
Title

14

517

. 14-4 , , BarChart.

. 14-4. BarChart

, BarChart ,
. 14-5.
. 14-5. BarChart

BarStyle
LabelStyle
SubTitleStyle
TitleStyle
ValueStyle

,



,

Render,
, .
BarChartItem

BarChart CreateChildControls:
protected override int CreateChildControls(
IEnumerable dataSource, bool dataBinding)
{
return CreateControlHierarchy(dataSource, dataBinding);
}

CreateChildControls
CreateControlHierarchy, .
int CreateControlHierarchy(IEnumerable dataSource, bool dataBinding)
{

518

III

ASP.NET

// ( )
if (dataSource == null)
{
RenderEmptyControl();
return 0;
}
//
Table t = new Table();
Controls.Add(t);
//
CreateTitle(t);
//
CreateSubTitle(t);
//
int totalItems = CreateAllItems(t, dataSource, dataBinding);
return totalItems;
}

, , . CreateAllItems
,
.
int CreateAllItems(Table t, IEnumerable data, bool useDataSource)
{
//
int itemCount = 0;
// ( null, )
Items.Clear();
//
foreach (object o in data)
{
// -
BarChartItemType itemType = BarChartItemType.Item;
BarChartItem item = CreateBarChartItem(t,
itemType, o, useDataSource);
// Items
_items.Add(item);
//
itemCount++;
}
//
// ( )
return itemCount;
}

BarChartItem
Items. BarChartItem .

14

519

, Items.Clear, _items.Add. Items :


private BarChartItemCollection _items;
public virtual BarChartItemCollection Items
{
get
{
if (_items == null)
_items = new BarChartItemCollection();
return _items;
}
}

Items _items.
Items.Clear .
_items, .
BarChartItem . :
public class BarChartItem : TableRow
{
private object _dataItem;
private BarChartItemType _itemType;
public BarChartItem(BarChartItemType itemType)
{
_itemType = itemType;
}
public object DataItem
{
get {return _dataItem;}
set {_dataItem = value;}
}
public BarChartItemType ItemType
{
get {return _itemType;}
}
}

TableRow, , .
DataItem ItemType. DataItem
. , BarChart
DataTable, DataItem DataRow, . ItemType
: Title, SubTitle Item.
:
public enum BarChartItemType
{
Title,
SubTitle,

520

III

ASP.NET

Item
}

Items BarChartItem BarChartItemCollection:


public class BarChartItemCollection : Collection<BarChartItem>
{
}

, IStateManager
,
, .

, ,
PerformDataBinding .
, , ,
.
CreateBarChartItem DataItem. ? . 14-4 ,
: .
BarChartItem CreateBarChartItem(Table t, BarChartItemType itemType,
object dataItem, bool useDataSource)
{
//
BarChartItem item = new BarChartItem(itemType);
//
TableCell labelCell = CreateLabelCell(item);
TableCell valueCell = CreateValueCell(item);
//
t.Rows.Add(item);
//
if (useDataSource)
{
//
item.DataItem = dataItem;
//
BindLabelCell(labelCell, dataItem);
BindValueCell(valueCell, dataItem);
}
//
return item;
}

CreateLabelCell CreateValueCell .
:
private TableCell CreateLabelCell(BarChartItem item)
{

14

521

//
TableCell cell = new TableCell();
item.Cells.Add(cell);
return cell;
}
private TableCell CreateValueCell(BarChartItem item)
{
//
TableCell cell = new TableCell();
item.Cells.Add(cell);
//
Label lblGraph = new Label();
Label lblText = new Label();
cell.Controls.Add(lblGraph);
cell.Controls.Add(new LiteralControl("<br>"));
cell.Controls.Add(lblText);
return cell;
}

, , .
CreateBarChartItem if .
, DataItem
,
BarChart:
private void BindLabelCell(TableCell cell, object dataItem)
{
if (!String.IsNullOrEmpty(DataTextField))
{
string txt = DataBinder.GetPropertyValue(
dataItem, DataTextField, DataTextFormatString);
cell.Text = txt;
}
}
private void BindValueCell(TableCell cell, object dataItem)
{
//
Label lblGraph = (Label) cell.Controls[0];
object o = null;
if (!String.IsNullOrEmpty(DataValueField))
o = DataBinder.GetPropertyValue(dataItem, DataValueField);
else
return;
float val = Convert.ToSingle(o);
float valueToRepresent = 100 * val / Maximum;
lblGraph.Width = Unit.Percentage(valueToRepresent);
//
Label lblText = (Label) cell.Controls[2];

522

III

ASP.NET

lblText.Text = DataBinder.GetPropertyValue(
dataItem, DataValueField, DataValueFormatString);
}


.
, .
,
. , ,
,
Render .

BarChart

BarChart : BarChartCreated BarChartDataBound. , DataGrid, . BarChart , , DataGrid.


public event EventHandler<BarChartItemEventArgs> BarChartItemCreated;
public event EventHandler<BarChartItemEventArgs> BarChartItemDataBound;
protected virtual void OnBarChartCreated(BarChartItemEventArgs e)
{
if (BarChartItemCreated != null)
BarChartItemCreated(this, e);
}
protected virtual void OnBarChartItemDataBound(BarChartItemEventArgs e)
{
if (BarChartItemDataBound != null)
BarChartItemDataBound(this, e);
}

BarChartItemCreated ,
, , BarChartItemDataBound . ,
.
:
public class BarChartItemEventArgs : EventArgs
{
private BarChartItem _item;
public BarChartItemEventArgs(BarChartItem item)
{
_item = item;
}
public BarChartItem Item
{
get { return _item; }
}
}

14

523

CreateBarChartItem.
BarChartItem CreateBarChartItem(Table t, BarChartItemType itemType,
object dataItem, bool useDataSource)
{
//
BarChartItem item = new BarChartItem(itemType);
//
TableCell labelCell = CreateLabelCell(item);
TableCell valueCell = CreateValueCell(item);
BarChartItemEventArgs argsCreated = new BarChartItemEventArgs(item);
OnBarChartItemCreated(argsCreated);
if (useDataSource)
{
BarChartItemEventArgs argsData = new BarChartItemEventArgs(item);
OnBarChartItemDataBound(argsData);
}
}
BarChart

, . ,
BarChart :
<expo:BarChart runat="server" id="BarChart1"
Maximum="100" SubTitle="Subtitle" Title="Title"
OnBarChartDataBound="BarChart1_BarChartDataBound" >
</expo:BarChart>

. Page_Load
. ,
SQL Server 2000, ,
, , 1997 . Northwind.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable data = ExecuteQuery(1997);
BarChart1.Maximum = 150000;
BarChart1.Title = "Northwind Sales";
BarChart1.SubTitle = "(Year 1997)";
BarChart1.DataSource = data;
BarChart1.DataTextField = "Employee";
BarChart1.DataValueField = "Sales";
BarChart1.DataBind();
}

, . 14-4,
.
BarChartDataBound :
void BarChart1_BarChartDataBound(object sender,
ProAspNet20.Advanced.BarChartItemEventArgs e)

524

III

ASP.NET

{
//
Decimal sales = (Decimal) DataBinder.GetPropertyValue(
e.Item.DataItem, "sales");
//
string tip = sales.ToString();
e.Item.Attributes["title"] = tip;
// , sales > 50000
if (sales > 50000)
e.Item.Cells[1].BackColor = Color.LightGreen;
}

,
. ,
$50 000, (. 14-5).

. 14-5. BarChart,


, , : DataBinding DataBound. ASP.NET 1.x,
.
ASP.NET 2.0, .


BarChart ,
.
. , BarChart.
? ,
, .

14

525

, , .
,
. ,
GaugeBar : {0}/{1}.
, :
// Value,
// Maximum
String.Format(FormatString, Value, Maximum);

HTML, , ,
, , .
.

ASP.NET :
ITemplate . 12,
,
. , . , ,
PlaceHolder,

Controls PlaceHolder:
placeHolder.Controls.Add(Page.LoadControl("usercontrol.ascx"));

,
Init. LoadControl . , . ,
, ,
. , ,
. ,
. ,
.
ITemplate
,
.ascx.
-

- ,
.
,
. ,
- TitleTemplate:
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(TitleTemplateContainer))]
public ITemplate TitleTemplate
{

526

III

ASP.NET

get { return _titleTemplate; }


set { _titleTemplate = value; }
}

_titleTemplate,
:
private ITemplate _titleTemplate = null;

- : PersistenceMode TemplateContainer. , -.
. 14-6.
. 14-6.

Attribute

HTML-


HTML;

, ;
;

EncodedInnerDefaultProperty
InnerDefaultProperty

InnerProperty

InnerProperty, Microsoft Visual Studio 2005 ,


, .
<expo:BarChart runat="server" ID="BarChart1" ... >
<TitleTemplate>
</TitleTemplate>
</expo:BarChart>

InnerDefaultProperty,
, InnerProperty
.
.
TemplateContainer ,
. , ,
Controls . , TemplateContainer, .

,
INamingContainer. ,

. TitleTemplate:
public class TitleTemplateContainer : WebControl, INamingContainer
{
private BarChart _parent;

14

527

public TitleTemplateContainer(BarChart parent)


{
_parent = parent;
}
public string Title
{
get { return _parent.Title; }
}
public string SubTitle
{
get { return _parent.SubTitle; }
}
public BarChart BarChart
{
get { return _parent; }
}
}

,
, : , BarChart.
(
) .
, ,
,
, (, Title
SubTitle). , .
, ,
, .
Container.
-

. 14-6 BarChart, .
, Visual Studio 2005. Microsoft
IntelliSense TitleTemplate,
.
.
. :
<TitleTemplate>
<img src="Title.gif" />
<%# Container.Title %>
</TitleTemplate>

BarChart, , Title, . :
<TitleTemplate>
<%# Container.Title %>

528

III

ASP.NET

<small>(<%# DateTime.Now.ToString() %>)</small>


</TitleTemplate>

. 14-6. Visual Studio 2005 -

. 14-7 ,
, Title
. ,
, TitleStyle.

. 14-7. BarChart ,

14

529

Container , , . , ,
<%# ...%>,
, ASP.NET.

, -
. , :


ITemplate, ;

PersistenceMode;

TemplateContainer.

.
,
- . , ,
, . ,
TitleTemplate , ,
CreateTitle. :
private void CreateTitle(Table t)
{
//
BarChartItem item = new BarChartItem(BarChartItemType.Title);
t.Rows.Add(item);
//
TableCell cell = new TableCell();
cell.ColumnSpan = BarChart.ColumnsCount;
item.Cells.Add(cell);
//
if (TitleTemplate != null)
{
_titleTemplateContainer = new TitleTemplateContainer(this);
TitleTemplate.InstantiateIn(_titleTemplateContainer);
cell.Controls.Add(_titleTemplateContainer);
}
else
cell.Text = Title;
// DataBind, #-
item.DataBind();
}

, .
, Text Title.

530

III

ASP.NET

InstantiateIn ITemplate.
, Controls .
: DataBind. ,
. , <%# ... %> .
, ,

ASP.NET 1.x
: ,
IEnumerable. , DataView
,
ADO.NET, DataTable DataSet. IListSource.
,
DataMember. IEnumerable , ,
ASP.NET,
. , , GetResolvedDataSource,
, system.web:
static IEnumerable GetResolvedDataSource(
object dataSource, string dataMember);

, , DataSourceHelper; System.Web.UI. ASP.NET 1.x


, ,
. :
.
, ASP.NET 2.0 .
, ,
PerformDataBinding, IEnumerable , .

. ,
.
, .
.
ASP.NET, , . ASP.NET 1.x

. . ,

14

531

, .
.
ASP.NET 2.0 .
,
.
,
, , . : BaseDataBoundControl,
DataBoundControl, ListControl CompositeDataBoundControl.
ASP.NET 1.x,
.
, (, ), ,
, , , , , .
,
Visual Studio. ,
, .

, , ,
, ,
.


DataSource DataSourceID. , IEnumerable, ,
.

, , DataBoundControl, PerformDataBinding.

PerformDataBinding , .


, , .
( ,
) .

,
.

ListControl , ,
.
,
DataBoundControl , .

532

III

ASP.NET

IRepeatInfoUser
.

CompositeDataBoundControl ,
, , .


,
.

15

:
. ,

,
, , Microsoft Visual Studio 2005,
WYSIWYG (what-you-see-is-what-you-get , ).

Microsoft ASP.NET
, ,
.
Control. ,
Web- , ,
Properties.
, ,
-,
. .
, , . Control,
,
. ,
, ,
,
.

.NET
Microsoft .NET Framework , ,
, IComponent. ,
Control, , Site,
, ISite. .
, , .

534

III

ASP.NET

IComponent Component,
System.ComponentModel. .
,
. .NET Framework
,
.
ASP.NET Component,
IComponent .

,
IComponent IDisposable
Dispose.
. , Dispose
, . , ,
IComponent, .NET Framework
.
,
, , ISite. ,
. ISite
. 15-1.
. 15-1. ISite

Component

,
ISite

Container

, IContainer,
, ISite

DesignMode

Name

,
. Microsoft Windows Forms, ASP.NET. , ASP.NET Control
IComponent ,
.
, ; ,
, .
ASP.NET .
, .
ISite IServiceProvider,
GetService,
.

15

535


, Visual Studio 2005,
. .NET Framework
, .
.

. -, , ,
,
. -,
.
, ,
, . ,
, ,
. ASP.NET, . ,
, .
,
. Visual Studio 2005.


.
.
System.ComponentModel.
, :
, .
. 15-2.
. 15-2.

, .NET. ,
, ASP.NET 2.0

,

, ,
( ) .

ASP.NET , ,
, .NET Framework.
ASP.NET , , , Control; -,
ControlDesigner. ,
IDesigner, , , ,
IComponent.

536

III

ASP.NET

-
- , .
, . , ,
, , .
, ,
.
, .
, , -

, .

ASP.NET , -, , ,
Visual Studio 2005.
, .

Attribute, : BrowsableAttribute, DefaultValueAttribute. , Attribute .
, .
, .
ASP.NET
. ( , ,
ASP.NET).
, Visual Studio 2005. ( ,
, Visual Studio.)

,
. 15-3
. ,
.
. 15-3.

Bindable

Browsable

,
Properties

Category

, .
Properties

DefaultEvent

, , .

DefaultProperty

, Properties ,
.

15

537

. 15-3. ()

DefaultValue

,
. ,

Description

.
Properties,

Editor

Themeable

,
. ASP.NET 1.x

ToolboxData

, Visual Studio
.aspx,
Web-.

TypeConverter

,
.

Properties Visual Studio 2005.


. 15-1. Visual
Studio Solution.

. 15-1. Properties Visual Studio 2005

,
Visual Studio 2005. ASP.NET, ,
Visual Studio 2005 .
, ,
. ,
, .

538

III

ASP.NET

C# , Visual Basic .
C#:
[Bindable(true)]
public int Count
{
}

Visual Basic:
<Bindable(True)> _
Public Property Count As Integer
End Property

, Visual Basic , ,
, (_), ,
.
. :
[Bindable(true)]
[Browsable(true)]
public int Count
{
}

:
[Bindable(true), Browsable(true)]
public int Count
{
}
Bindable

Bindable ,
. , , ,
, DataBindings.
Visual Studio 2003. , Bindable
false,
.
Properties Visual Studio 2005 DataBindings.
Expressions, .
Bindable, ,
. false.
Browsable

Properties, , Browsable, false.


, .
false , , ,

15

539

( DataItem
GaugeBar, 14).
[Browsable(false)]
public GaugeBarDataItem DataItem
{
}

, , , Properties .
Category Description

Category Description
. ,
Properties ,
.
, Properties
(. . 15-1).
. Properties.
: Accessibility,
Appearance, Behavior, Data, Layout Misc. ,
. Misc.
[Category("Appearance")]
[Description("Gets and sets whether notches should be displayed")]
public bool GridLines
{
}

, Category Description,
, :
[LocalizableDescription("Local_GridLines_Desc")]
public bool GridLines
{
}

, Category / Description,
, .
DefaultValue

DefaultValue , .
. Web-, Visual Studio 2005 Properties. Visual
Studio 2005 DefaultValue,
, Properties ,
, ,
.
Themeable

ASP.NET 2.0 , , .
(CSS) . ,

540

III

ASP.NET

, . ASP.NET, ,
, ,
.
. ,
,
.
, ,
, .
[Themeable(false)]
public float Maximum
{
}

Maximum GaugeBar
.
. .
Editor

Editor ,
. Editor,
. , ,
Properties. UITypeEditor.
.
TypeConverter

TypeConverter ,
.
.
,
, Visual Studio 2005 , , .
.


: DefaultEvent, DefaultProperty ToolboxData.
DefaultProperty , Properties,
, DefaultEvent ,
, . 15-2.
[ToolboxData("<{0}:BarChart runat=\"server\"></{0}:BarChart>")]
[DefaultProperty("Title")]
[DefaultEvent("BarChartCreated")]
public class BarChart : CompositeDataBoundControl
{
}

15

541

. 15-2. ,

ToolboxData ,
. ,
, ,
. {0} ,
.

,
-. , Color (. 15-3).

. 15-3. Color

:
.

542

III

ASP.NET

. . 15-4 , BorderStyle BarChart,


14.

. 15-4. BorderStyle

Visual Studio 2005 .

,
,
Visual Studio 2005. , .
, .aspx.
. 15-4.
. 15-4. ,

ControlBuilder

ParseChildren

ASP.NET
:

TemplateContainer

,
(. 14)

. -. , .

, . ,
, ControlBuilder.

15

543

ControlBuilder
Controls . ,
, . ,
.
ControlBuilder, . , ,
, .


, Properties, .
(, , ), , , .
Width :
<expo:GaugeBar runat="server" ID="GaugeBar1" width="200px" />

width (200px), Width .


Unit. 200px ?
,
, .
UnitConverter Unit
Unit .


, ,
GaugeBar, 14, Filter
. ,
, - .
- , Microsoft Internet Explore 5.0 .
Style .
Internet
Explorer, .

, GaugeBar -
,
. .
Filter GaugeBar

GaugeBar
Filter, :
private FilterSettings _gaugeFilters = null;
[Category("Appearance")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Description("Defines the filter settings of the gauge")]
public FilterSettings Filter
{
get

544

III

ASP.NET

{
if (_gaugeFilters == null)
_gaugeFilters = new FilterSettings();
return _gaugeFilters;
}
}

Filter , . DesignerSerializationVisibility, . Filter


:
public class FilterSettings
{
private GaugeFilterType _type;
private Color _glowColor;
private int _glowStrength;
private int _alphaOpacity;
public FilterSettings()
{
_type = GaugeFilterType.None;
_glowStrength = 5;
_alphaOpacity = 25;
}
[Description("Gets and sets the type of the filter to use")]
[NotifyParentProperty(true)]
public GaugeFilterType FilterType
{
get { return _type; }
set { _type = value; }
}
[Description("Gets and sets the color of the border")]
[NotifyParentProperty(true)]
public Color GlowColor
{
get { return _glowColor; }
set { _glowColor = value; }
}
[Description("Indicates the width of the border")]
[NotifyParentProperty(true)]
public int GlowStrength
{
get { return _glowStrength; }
set { _glowStrength = value; }
}
[Description("Indicates the percentage of opacity desired")]
[NotifyParentProperty(true)]
public int AlphaOpacity
{
get { return _alphaOpacity; }
set { _alphaOpacity = value; }
}
}

15

545

. ,
, . ,
, ,
.
Filter ?
. 15-5 , Visual Studio 2005 , .

. 15-5.
Visual Studio 2005

, Properties , ,
ToString. ,
?
: . .

, . .NET Framework,
, , Unit,
. , .aspx. ,
. , , ,
Font
.
FilterSettings Visual
Studio 2005, ,
, . , TypeConverter, .

, . , , CanConvertTo CanConvertFrom.

546

III

ASP.NET

, .
, ,
. String, ,
. (, Integer ,
.)
, ConvertTo ConvertFrom. , FilterSettings
.
,
.
.
FilterSettings.
public class GaugeFilterSettingsConverter : TypeConverter
{
private const int NumOfMembers = 4;
public GaugeFilterSettingsConverter()
{
}
// String
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
// String
public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType == typeof(string))
return true;
if (destinationType == typeof(InstanceDescriptor))
return true;
return base.CanConvertTo(context, destinationType);
}
// FilterSettings
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
// , value FilterSettings
if (value != null)
{
if (!(value is FilterSettings))
throw new ArgumentException(
"Invalid FilterSettings object", "value");
}

15

// null,
if (destinationType == typeof(string))
{
if (value == null)
return String.Empty;
//
FilterSettings filter = (FilterSettings) value;
TypeConverter cvInt;
cvInt = TypeDescriptor.GetConverter(typeof(int));
TypeConverter cvColor;
cvColor = TypeDescriptor.GetConverter(typeof(Color));
//
string[] parts = new string[NumOfMembers];
parts[0] = filter.FilterType.ToString();
parts[1] = cvInt.ConvertTo(filter.AlphaOpacity, typeof(int));
parts[2] = cvInt.ConvertTo(filter.GlowStrength, typeof(int));
parts[3] = cvColor.ConvertTo(filter.GlowColor, typeof(string));
return String.Join(culture.TextInfo.ListSeparator, parts);
}
return base.ConvertTo(context, culture, value, destinationType);
}
// FilterSettings
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
//
if (value == null)
return new FilterSettings();
//
if (value is string)
{
//
string data = (string) value;
if (data.Length == 0)
return new FilterSettings();
//
string[] parts = data.Split(culture.TextInfo.ListSeparator[0]);
if (parts.Length != NumOfMembers)
throw new ArgumentException(
"Invalid FilterSettings object", "value");
// FilterSettings
FilterSettings filter = new FilterSettings();
// 0 , FilterType
Type t = typeof(GaugeFilterType);
filter.FilterType = (GaugeFilterType) Enum.Parse(t, parts[0]);
// 1 AlphaOpacity (integer)
TypeConverter cvInt;
cvInt = TypeDescriptor.GetConverter(typeof(int));

547

548

III

ASP.NET

filter.AlphaOpacity = (int) cvInt.ConvertFrom(context, culture,


parts[1]);
// 2 GlowStrength (integer)
filter.GlowStrength = (int) cvInt.ConvertFrom(context, culture,
parts[2]);
// 3 GlowColor (Color)
TypeConverter cvColor;
cvColor = TypeDescriptor.GetConverter(typeof(Color));
filter.GlowColor = (Color) cvColor.ConvertFrom(context,
culture, parts[3]);
return filter;
}
return base.ConvertFrom(context, culture, value);
}
}

GaugeFilterSettingsConverter FilterSettings , CanConvertTo


CanConvertFrom. FilterSettings
. , , .
,
Color Integer:
TypeConverter cvInt = TypeDescriptor.GetConverter(typeof(int));
TypeConverter cvColor = TypeDescriptor.GetConverter(typeof(Color));

: ,
,
:
parts[2] = cvInt.ConvertTo(filter.GlowStrength, typeof(int));
parts[3] = cvColor.ConvertTo(filter.GlowColor, typeof(string));

,
FilterSettings ,
:
filter.GlowStrength = cvInt.ConvertFrom(context, culture, parts[2]);
filter.GlowColor = cvColor.ConvertFromString(context, culture, parts[3]);

,
FilterSettings:
[TypeConverter(typeof(GaugeFilterSettingsConverter))]
public class FilterSettings
{
}

Properties Filter, . :
// 0=, 25=, 5=, -256=
0,25,5,-256

15

549

.
, , .
ExpandableObjectConverter

Visual Studio 2005, ,


Font ,
Size Name. ,
Font.
?
ExpandableObje
ctConverter. TypeConverter : GetProperties GetPropertiesSupported.
,
, Font (. 15-6).

. 15-6. Filter

, ,
NotifyParentProperty, . ,
Text:
[Description("Gets and sets the type of filter to use")]
[NotifyParentProperty(true)]
public GaugeFilterType FilterType
{
get { return _type; }
set { _type = value; }
}

. 15-7 ,
GaugeBar .
, :
<expo:GaugeBar runat="server" ID="GaugeBar1"
Width="200px"
Height="20px"
BackColor="LightCyan"

550

III

ASP.NET

Value="22"
BorderStyle="Solid"
BorderWidth="1px"
BorderColor="MediumAquamarine"
ForeColor="MediumAquamarine"
GridLines="True"
FormatString="<b>{0}</b>%"
Filter-AlphaOpacity="4"
Filter-FilterType="Glow"
Filter-GlowColor="Blue"
Filter-GlowStrength="5" >
</expo:GaugeBar>

. 15-7. GaugeBar
Internet Explorer

, : -. , , DesignerSerializationVisibility,
Filter.

, . 15-5, ,
. ,
HTML- .
DesignerSerializationVisibility ,
. 15-6.
. 15-5.

DesignerSerializationVisibility , ( , ) ,
Properties,

15

551

. 15-5. ()

NotifyParentProperty

,
.
, ExpandableObjectConverter
,

,

PersistChildrenAttribute

PersistenceMode

. 15-6. DesignerSerializationVisibility

Content

(, Filter) .

. .
, FilterType GlowColor Filter.
FilterType Filter-FilterType

: .
, Filter .
, Filter

Hidden
Visible

PersistChildren false , WebControl, true , Control.


. . ,
<ItemTemplate> ItemTemplate. , PersistChildren false,
HTML-
; . PersistenceMode ,
. , ,
.
. 15-7.
. 15-7. PersistenceMode

Attribute

EncodedInnerDefaultProperty
HTML
InnerDefaultProperty

InnerProperty

552

III

ASP.NET

-, PersistenceMode ,
, Properties.
- (. 14).
[TemplateContainer(typeof(TitleTemplateContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate TitleTemplate
{
get { return _titleTemplate; }
set { _titleTemplate = value; }
}

, TitleTemplate
.


Properties . , , ,
,
.
Visual Studio ,
.
UITypeEditor. , -,
,
.
Windows Forms,
.
, , Properties.
Filter.
Filter

, .
[Editor(typeof(GaugeFilterSettingsEditor), typeof(UITypeEditor))]
public FilterSettings Filter
{
}

Editor ,
, GaugeFilterSettingsEditor. . .NET Framework ,
.
UITypeEditor .

. , URL,
, . .

15

553

Editor, (. 15-8). ,
,
.

. 15-8. Filter ,

UITypeEditor
System.Windows.Forms. , -
. UITypeEditor,
.

,
UITypeEditor .

. ,
, Windows Forms .
:
using System.Drawing.Design;
using System.Windows.Forms;

Windows Forms , ,
Web, .
GetEditStyle EditValue. : DropDown Modal,
,
Properties. GaugeFilterSettingsEditor.
public class GaugeFilterSettingsEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(
ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(

554

III

ASP.NET

ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
// Windows Forms
//
//
return value;
}
}

GetEditStyle UITypeEditorEditStyle.DropDown, . UITypeEditorEditStyle.Modal,


.
EditValue . . ,

. ,
EditValue, .
DropDown, Properties IWindowsFormsEditorService. ,
.
public override object EditValue(
ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
object o = provider.GetService(typeof(IWindowsFormsEditorService));
IWindowsFormsEditorService srv = (IWindowsFormsEditorService) o;
if (srv != null)
{
//
MyControl myCtl = new MyControl(value);
srv.DropDownControl(myCtl);
}
}

, GetPaintValueSupported PaintValue.
. , Properties,
, Graphics.
PaintValue GDI+.


, , . ,
, . 15-9.

15

555

. 15-9. ,


-, .
-

Visual Studio 2005 , ICollection, CollectionEditor.


, . 15-9.
, , .
, .
. , ToString , .
HyperLinkItemCollection

, 14, -
Items, , .
HyperLinkItem. - HyperLinkItemCollection :
public class HyperLinkItemCollection : Collection<HyperLinkItem>
{
}

HyperLinkItem : Text, Url Tooltip. Items Properties,


, . 15-10. ,
Web-, .

. 15-10.
HyperLinkItemCollection

556

III

ASP.NET


. ,
, , ,
.
, .
ASP.NET 2.0 Control DesignMode.
, true,
, false .
Render if.
if (DesignMode)
{
}
else
{
}

.
.


-,
Visual Studio 2005.

-.
, Visual Studio 2005 ( ) .
RenderControl.
, . ,
, , , , ,
. ,
.
,
( ASP.NET 2.0)
, -:
, .
,
,
.
ControlDesigner

ControlDesigner , ASP.NET. -

15

557

.
, :
// ctl ,
StringWriter sw = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
ctl.RenderControl(writer);
return sw.ToString();

Visual Studio 2005 Web-.


GetDesignTimeHtml. HTML-,
.
GetDesignTimeHtml, ControlDesigner. ,
ControlDesigner GetDesignTimeHtml.
,

, .
, .
, , : ", " (
). ASP.NET 2.0
,
.
. . 15-11 ,
, .
, ,
DataBoundControlDesigner. ControlDesigner
,
GetDesignTimeHtml.
DataBoundControlDesigner DataBind, GetDesignTimeDataSource,
.
, ,
; , ASP.NET 1.x.

. 15-11. ,
, ASP.NET 2.0

558

III

ASP.NET


ControlDesigner, System.Web.UI.Design.
, . ControlDesigner
, .
ASP.NET HtmlControlDesigner,
Windows.
HTML

, HTML-. ,
WYSIWYG, Render.
HTML- .
CreateChildControls, ,
. , ,
, HTML-. ASP.NET 2.0
CompositeControl . CompositeControl,
, Render.
Render CompositeControl,
,
:
protected internal override void Render(HtmlTextWriter writer)
{
if (base.DesignMode)
this.EnsureChildControls();
base.Render(writer);
}


, , ,
GetDesignTimeHtml.
.

ControlDesigner
, .
HTML- .


GetDesignTimeHtml HTML-,
.
, Render, ,

.

15

559

GetEmptyDesignTimeHtml HTML,
. ,
.

GetErrorDesignTimeHtml HTML-, ,
.
.

AllowResize CreatePlaceHolderDesignTimeHtml.
,
.
.
, ,
, , .
CreatePlaceHolderDesignTimeHtml HTML-, ,
. ,
,
(. 15-12):
protected override string GetErrorDesignTimeHtml(Exception e)
{
return CreatePlaceHolderDesignTimeHtml("There was an error");
}

. 15-12.

, , HTML-,
.
HTML-

GaugeBar. : GetDesignTimeHtml,
Initialize OnClick, AutoFormats.
, .
GetDesignTimeHtml
.
public class GaugeBarDesigner : ControlDesigner
{

560

III

ASP.NET

private GaugeBar _controlInstance;


private bool _addNote;
private float _originalValue;
public override void Initialize(IComponent component)
{
//
_controlInstance = (GaugeBar) component;
base.Initialize(component);
}
public override string GetDesignTimeHtml()
{
if (_controlInstance.Value < 0)
{
// ,
_originalValue = _controlInstance.Value;
// .
// ,
// ASPX-
_controlInstance.Value = GetRandomNumber();
_addNote = true;
}
else
_addNote = false;
// ,
//
if (_addNote)
{
string template = "...";
string message = "The <b>Value</b> property has no valid " +
"value set. <br/>The displayed value has " +
"been randomly generated to help " +
"you form an idea about the control. <hr/>" +
"<small>Courtesy of <b>Programming " +
"Microsoft ASP.NET 2.0 Applications" +
"Advanced Topics</b></small>";
string markup = String.Format(template,
base.Component.GetType().Name,
base.Component.Site.Name,
base.GetDesignTimeHtml(),
message);
//
_controlInstance.Value = _originalValue;
//
return markup;
}

15

561

//
return base.GetDesignTimeHtml();
}
protected override void OnClick(DesignerRegionMouseEventArgs e)
{
base.OnClick(e);
//
UpdateDesignTimeHtml();
}
public override DesignerAutoFormatCollection AutoFormats
{
get
{
DesignerAutoFormatCollection autoFormats;
autoFormats = new DesignerAutoFormatCollection();
autoFormats.Add(new SimpleAutoFormat());
autoFormats.Add(new PercentageAutoFormat());
return autoFormats;
}
}
private int GetRandomNumber()
{
Random rnd = new Random();
return (int) rnd.Next(0, (int)_controlInstance.Maximum);
}
}

. 15-13 GaugeBar Visual Studio 2005.


,
Value.

. 15-13. GaugeBar Visual Studio

562

III

ASP.NET

Value

GaugeBar Value. , ,
.
, , Value
, GaugeBar .
, ,
. ( ,
.)
HTML- :
, .
.
, , , StringBuilder String.Format.
,
, HTML-, CreatePlaceHolderDesignTimeHtml, .
HTML- HTML-,
: , ,
.
component Initialize
GaugeBar, Visual Studio 2005 .
. Value ,
, ,
. , , , Web- ASP.NET.
Value,
.
, ,
.
. 15-14 GaugeBar
, Value . , , 1, Properties.
.
ASP.NET 2.0
, . ,

.
protected override void OnClick(DesignerRegionMouseEventArgs e)
{
base.OnClick(e);
UpdateDesignTimeHtml();
}

UpdateDesignTimeHtml ,
, .

15

563

DesignerRegionMouseEventArgs ,
.

. 15-14. GaugeBar
Value

AutoFormats

Properties AutoFormat (. . 15-14). ,


AutoFormats .
AutoFormats ,
, .
, DesignerAutoFormat.
.
DesignerAutoFormatCollection autoFormats;
autoFormats = new DesignerAutoFormatCollection();
autoFormats.Add(new SimpleAutoFormat());
autoFormats.Add(new PercentageAutoFormat());

:
public class SimpleAutoFormat : DesignerAutoFormat
{
public SimpleAutoFormat() : base("(Default formatting)")
{
}
public override void Apply(System.Web.UI.Control control)
{
GaugeBar _gaugeBar = control as GaugeBar;
if (_gaugeBar != null)
{
_gaugeBar.FormatString = "{0} out of {1}";

564

III

ASP.NET

_gaugeBar.Segments = 4;
_gaugeBar.TextStyle.BackColor = Color.Transparent;
_gaugeBar.TextStyle.Font.Name = "verdana";
_gaugeBar.TextStyle.Font.Size = FontUnit.Point(8);
_gaugeBar.TextStyle.DisplayTextAtBottom = true;
_gaugeBar.TextStyle.RenderInsideTable = false;
}
}
}

, ,
. Apply , .
, AutoFormats,
Visual Studio 2005, . 15-15.

. 15-15. Auto Format


GaugeBar

, Designer, :
[Designer(typeof(GaugeBarDesigner))]
public class GaugeBar : DataBoundControl
{
}

,
Web-,
.
ASP.NET 1.x ControlDesigner
, . ASP.NET 2.0 ,
(, CompositeControlDesigner DataBoundDesigner)
. , ASP.NET 2.0
. , .

15

565

, .NET Framework,
, ASP.NET . Visual
Studio 2005, . .
,
Properties. ASP.NET , , .
ASP.NET . -,
,
.
, , .
,
.
, . , ,
Properties ,
. ExpandableObjectConverter.

, .
,
. Windows Forms ,
Properties .
,
.
,
.
, HTML-,
.
, . ,
.
.

:
.


: -, .

,
Properties.

566

III

ASP.NET

, Properties,
ASP.NET; PersistenceMode , .

, TypeConverter
,
.aspx.


, .
UITypeEditor.

, ,
Visual Studio 2005. , .

ControlDesigner . .

Active Directory, , 144


Ajax.NET, , 252, 257
API
CodeDOM, 42
Data Protection (DPAPI), 106
XMLDOM, 41
, 25
IIS (ISAPI), 3, 51
, 122
AppDomain, 2
ASP.NET
, 10
, 29
, 3
ISAPI, 52
, 6, 8
, 6
, 84
, 3
IIS 5.0, 4
IIS 6.0, 4
MMC, 129
Atlas, , 259
AzMan, , 148

IIS (Internet Information Server), 3, 51


IIS 7.0, 54
ISAPI (Internet Server Application
Programming Interface), 3
, 51
, 3
, 53
, 53
, 54
, 53

Catalog Part, , 264, 265


Catalog Zone, 297
CodeDOM, , 42
cookie
, 166

Web
-
, 293
, 284
, 284
-, 4
-, 51
-, , 189
Web Part, , 262
, 278
, 275
, 286
, 294
, 287
, 281
, 290
, 276

D
DOM (Document Object Model), 124, 227, 249

E
Editor Part, 297
Editor Zone, , 295

G
GDI+, 350

J
JavaScript, 224

M
Microsoft SharePoint Web Parts, 263

R
reader, , 348

S
Script Callbacks, , 239

568

Web Part, ()
, 282
, 269
, 288
, 268
Web Parts, , 261
, 302
, 302
, 301
, 302
Web Parts Framework, 263
Web Zone, , 264


, 225
, 100

, 315
, 138
, 30

Bindable, 537
Browsable, 537
Category, 538
ControlBuilder, 541
DefaultEvent, 539
DefaultProperty, 539
DefaultValue, 538
Description, 538
DesignerSerializationVisibility, 543, 549
Editor, 539, 551
NotifyParentProperty, 548
ParseChildren, 541
PersistChildren, 550
PersistenceMode, 526, 550, 564
TemplateContainer, 526, 541
Themeable, 539
ToolboxData, 539
TypeConverter, 539
, 535, 537
, 535
, 549


aspnetdb.mdf, 143, 159
, 99

aspnet_isapi, 3
asp.dll, 52
ISAPI, 51
, 203205
, 230
, 233

, 227
, 225, 226
, 225

, 323
, 224, 258
, 481

, 240, 247
, 243, 252
, 203
, 208
AppSettings, 209
ConnectionStrings, 209
Resources, 33, 209
, 19
, 203
, 21, 207209

, 70, 433
AsyncCallback, 70
BeginEventHandler, 179
EndEventHandler, 179
EventHandler, 433
TimeoutHandler, 198
WaitCallback, 185

, 367
, 85
, 19

, 363
, 361
, 358

, 534
, 555
, 555

@Control, 422, 443


@Implements, 247
@OutputCache, 99, 423
@Page, 8, 18, 178, 227, 422
@Reference, 443, 444
@Register, 268, 426
@WebHandler, 62

HTTP
cache-control, private, 99
Content-Type, 338

HTTP ()
UserAgent, 225
, 75
Web Parts, 264

, 95

Oracle, 349
SQL Server, 349
, 342347
BLOB, 342
, 337
, 339
, 338

IAsyncResult, 177, 194


ICallbackEventHandler, 246, 453
ICollection, 554
IComponent, 532, 533
IDataSource, 492
IDesigner, 534
IDisposable, 533
IEnumerable, 487, 490, 530
IHttpAsyncHandler, 55, 70, 176, 185
IHttpHandler, 6, 8, 55, 175
IHttpHandlerFactory, 8
IHttpModule, 72
IListSource, 487, 490, 530
INamingContainer, 394, 419, 452,
480, 485, 526
IPostBackDataHandler, 452
IPostBackEventHandler, 452
IRepeatInfoUser, 510, 531
IServiceProvider, 533
ISite, 532, 533
IStateManager, 495, 498, 499
ITemplate, 399
IWebActionable, 272
IWebEditable, 272
IWebPart, 272

, 152, 366
, 369
, 370, 371
, 387
, 370, 388
, 380
, 374
, 369
, 369

569

Assembly, 341
BarChartItem, 519
BaseDataBoundControl, 447, 489, 491, 492
BaseDataList, 447
BaseValidator, 323
BinaryFormatter, 499
Bitmap, 351
BrowserCapabilities, 225
BuildProvider, 36
CatalogPart, 265
CatalogZone, 266
ClientScriptManager, 229
CollectionEditor, 554
CompareValidator, 323
CompositeControl, 447
CompositeControlDesigner, 563
CompositeDataBoundControl, 447, 513, 531
ConfigurationSection, 128
ConnectionsZone, 266
Control, 418, 447, 448, 451, 532, 533
ControlBuilder, 542
ControlDesigner, 534, 555557, 564
CustomValidator, 323
DataBinder, 501
DataBoundControl, 447, 492, 496, 531
DataBoundControlDesigner, 556
DataBoundDesigner, 563
DataSourceHelper, 530
DataSourceView, 492
DeclarativeCatalogPart, 299
EditorPart, 265
EditorZone, 266
EventArgs, 434
ExpandableObjectConverter, 548, 564
ExpressionBuilder, 208, 211
FastObjectFactory, 17
GenericWebPart, 270
Graphics, 351
HierarchicalDataBoundControl, 447
HtmlTextWriter, 453
HttpApplication, 6, 8, 50, 72
HttpApplicationFactory, 6
HttpCapabilitiesBase, 225, 226
HttpResponse, 338
HttpRuntime, 8, 13
ImportCatalogPart, 300
ListControl, 447, 531
ListItemCollection, 504
MobileCapabilities, 225
MobilePage, 310, 312, 334
Page, 8, 260
PageHandlerFactory, 6, 8, 50
PageParser, 215
PageParserFilter, 215

570

()
Panel, 265
ProviderBase, 139, 174
RangeValidator, 323
RegularExpressionValidator, 324
RepeaterItem, 395
RequiredFieldValidator, 324
SessionStateModule, 50
SiteMap, 372, 373, 379
SiteMapProvider, 368
StaticSiteMapProvider, 368
StringBuilder, 484
TemplateControl, 419, 443
TextControl, 320
TextWriter, 45
TypeConverter, 548, 564
UITypeEditor, 551, 564
UserControl, 418420
VirtualFile, 47
VirtualPathProvider, 46
WebConfigurationManager, 122
WebControl, 418, 447, 452
WebPart, 268, 269, 270
WebPartConnection, 266
WebPartManager, 265, 267
WebPartZone, 266
window, 236
XmlHttpRequest, 240
XmlSiteMapProvider, 367
, 141
, 9
, 20
, 17
, 10
, 227
, 224

Modules, 76
Zones, 266
, 38

, 27
, 26

, 542, 544

, 419
, 526
GDI, 351
, , 135

, 314
, 3, 98, 423
, 3, 423
, 98

()
, 347
, 78
, 358
, 98

Web Parts, 262, 270


, 290
, 36
, 151

AddOnPreRenderCompleteAsync, 179, 180


AllowResize, 558
BeginProcessRequest, 177
CanConvertFrom, 544
CanConvertTo, 544
ClearChildViewState, 454
ConvertFrom, 545
ConvertTo, 545
CreateChildControls, 454, 513517, 557
CreateControlHierarchy, 454, 474, 517
CreatePlaceHolderDesignTimeHtml, 558
DataBind, 491
Dispose, 533
DrawRectangle, 352
DrawString, 353
EditValue, 552
EndProcessRequest, 177
EnsureDataBound, 491
ExecuteScalar, 348
FillRectangle, 352
GetCallbackEventReference, 245
GetCodeExpression, 211
GetDesignTimeHtml, 556558
GetEditStyle, 552
GetEmptyDesignTimeHtml, 558
GetErrorDesignTimeHtml, 558
GetManifestResourceNames, 341
GetManifestResourceStream, 341
GetProperties, 548
GetPropertiesSupported, 548
GetPropertyValue, 501
GetResolvedDataSource, 530
InstantiateIn, 529
IsClientScriptBlockRegistered, 232, 483
LoadControl, 419, 443
LoadTemplate, 419
LoadViewState, 495, 509
OnBubbleEvent, 482
OnPreRender, 491
ParseControl, 420
PerformDataBinding, 493, 496, 509, 515, 530

()
PerformSelect, 491, 492
ProcessRequest, 6, 55, 175
RaiseBubbleEvent, 482
RegisterAsyncTask, 178, 198, 202
RegisterClientScriptBlock, 230, 483
RegisterStartupScript, 233
Render, 453
RenderItem, 512
SaveViewState, 495, 509
ValidateDataSource, 491, 492
, 165

, 139
, 139
, 136, 174
, 140
, 140
, 137
HTTP, 50
, 72, 73
, 74
, 76

, 108, 116, 366


, 122

HTTP, 50, 63
, 69
, 55, 56
, 60
, 64, 68
, 20
, 240, 247

Cache, 438
HTTP-, 453

Properties, 551
, 236

App_Browsers, 30
App_Code, 30
App_Data, 32
App_GlobalResources, 32
App_LocalResources, 33

571

()
App_Themes, 34
App_WebReferences, 34
Bin, 29
, 19
, 289
, 369

, 208
$AppSettings, 209
$ConnectionStrings, 209
$Profile, 213
$Resources, 209
, 210
, 36
, 8, 21
, 21, 23
, 25

, 25
, 21

, 355
, 328
, 334
, 333
, 334
, 328

ActiveDirectoryMembershipProvider, 144
AuthorizationStoreRoleProvider, 146, 147
BufferedWebEventProvider, 154
DpapiProtectedConfigurationProvider, 162
EventLogWebEventProvider, 155
InProcSessionStateStore, 151
MailWebEventProvider, 155
OutOfProcSessionStateStore, 151
ProfileProvider, 149
RoleProvider, 146
RsaProtectedConfigurationProvider, 160
SessionStateStoreProviderBase, 150
SqlMembershipProvider, 142
SqlPersonalizationProvider, 157, 159
SqlRoleProvider, 146
SqlSessionStateStore, 151
TemplatedMailWebEventProvider, 156
TraceWebEventProvider, 157
WebEventProvider, 154
WindowsTokenRoleProvider, 146, 147
XmlSiteMapProvider, 153
, 46
, 141

(), 159
, 152, 367

572

()
, 26, 34, 35
ForceCopyBuildProvider, 37
IgnoreFileBuildProvider, 37
, 37, 40
, 289
Web Parts, 158, 159
, 164
, 164
, , 170, 172
, 146
Web, 154
, 150
, 142
, 126

dllhost.exe, 51
inetinfo.exe, 51
, w3wp.exe, 5
, 5
, 375


DataList, 414
, 313
, 393

<anonymousIdentification>, 95
<appSettings>, 88, 120
<assemblies>, 27
<authentication>, 95
<authorization>, 97
<browserCaps>, 97
<buildProviders>, 44
<caching>, 98
<Choice>, 332
<clientTarget>, 100
<codeSubDirectories>, 31
<compilation>, 26, 28
<configProtectedData>, 88, 121
<configSections>, 88
<configuration>, 84
, 87
<connectionStrings>, 88, 121
<customErrors>, 100
<deployment>, 101
<deviceFilters>, 332
<DeviceSpecific>, 332
<EncryptedData>, 126
<filedeps>, 12
<globalization>, 101
<healthMonitoring>, 102, 156
<hostingEnvironment>, 103
<httpCookies>, 103

()
<httpHandlers>, 57, 63
<httpModules>, 76
<httpRuntime>, 104, 176
<identity>, 105
<location>, 89, 92
<machineKey>, 106
<mailSettings>, 156
<mappings>, 44
<membership>, 106
<pages>, 107
<processModel>, 109
<profile>, 111
<protectedData>, 125
<roleManager>, 112
<section>, 88
<sectionGroup>, 88
<securityPolicy>, 113
<sessionPageState>, 113
<sessionState>, 114
<siteMap>, 116, 367
<siteMapNode>, 367369
, 368
<system.diagnostics>, 88
<system.runtime.remoting>, 88
<system.web>, 88, 92, 134
<trace>, 116
<trust>, 117
<urlMappings>, 118
<webControls>, 118
<webServices>, 119
<xhtmlConformance>, 120
<ZoneTemplate>, 295, 297
, 127
, 551
, 332

, 532

, 27
, 12
, 10

AppendDataBoundItems, 504
AuthorizationFilter, 273
ClientID, 485
ClientTarget, 227
DataItem, 498, 499
DataMember, 493
DataSource, 437, 489492, 531
DataSourceID, 489, 490, 531
Filter, 542
ID, 485
Items, 504, 516, 519

()
Paginate, 313
RequiresDataBinding, 491
Site, 532
UniqueID, 485
-
, 527
, 525
, 433
AuthorizeWebPart, 269, 273
BeginRequest, 74
DataBinding, 208
EndRequest, 74
ItemCommand, 317
PreRender, 260
PreRenderComplete, 81, 178, 180
ViewStateExpire, 334

, 175
, 186
, 193
, 188
, 180, 184
, 220
, 311
, 314
, 28
, 213
, 77
, 12
, 13

submit-, 233
, 235
, 234

aspnet_compiler, 22, 24
aspnet_regiis.exe, 127
resgen.exe, 32
WSAT (Web Site Administration Tool), 130
xsd.exe, 32

, 139
HTTP, 6, 50, 68
, 6

.ashx, 8
.asmx, 2, 8, 35
global.asax, 13
machine.config, 85, 134
web.config, 85
web.sitemap, 367, 369
, 2
, 84
HTTP, 2
, 2
,
, 15

ISAPI, 53
, 543
, 215
(), 97
Web Parts, 269, 273
, 368
, 543
, 332

573

, 116

<body>, 19, 421


<form>, 19, 20, 230, 421
<head>, 19, 20
<html>, 421
<img>, 336, 365
<script>, 228
<SelectedItemTemplate>, 412
<ZoneTemplate>, 270

393, 397
Repeater, 397
, 399
, 400
, 529
DataList, 412
, 524

RSA, 126
RSA, 162
, 125

, 258

, 90
, 92

, 533
BulletedList, 489, 504
CheckBoxList, 488, 503
Command, 321

574

()
DataGrid, 318, 489
DataList, 405415
DataTable, 490
DetailsView, 489
DropDownList, 503
FileUpload, 346
Form, , 316
FormView, 394, 489
GridView, 489
HtmlInputFile, 346
List, 317
ListBox, 504
ListControl, 503, 504
Menu, 384 387
ObjectList, 318
Panel, 316
PhoneCall, 322, 333
RadioButtonList, 488, 504
Repeater, 394404, 437439
, 394
SelectionList, 319
SiteMapDataSource, 377379, 383, 384
SiteMapPath, 375
TextBox, 321
TreeView, 380384
ValidationSummary, 324
, 534
, 392
, 534
, 307
, 307
, 309

()

, 394
, 524
418, 419, 424
, 443
, 433
, 428
, 424
, 426
, 424
, 427, 428
, 436
, 421
, 393

, 378, 488
, 534
, 392, 488
, 489
, 530
, 489
, 513
, 488
, 447
, 418, 424, 446
, 447
, 459, 473
, 468
, 451
, 392
, 393
, 327

Вам также может понравиться