Está en la página 1de 56

Mark Anders Answers your ASP.NET/.

NET Questions
November 3rd, 2000

Question: Under the new ASP.NET validation framework, how do the validation controls determine when to use client script vs. server-side code? or e!ample, re"ular e!pression support is weak or non-e!istent in #rowsers like $E and Netscape %. &ould ASP.NET default to server side in those cases? $s this a confi"ura#le settin"? &hat is the performance hit 'to the server( and the #etween pa"e dela) time when the AP$ now includes this t)pe of *d)namic* per pa"e validation? + or more information on ASP.NET validation controls, #e sure to read, orm -alidation with ASP.NET - $t .oesn/t 0et An) Easier12 Answer, 3ur client side validation re4uires #oth EcmaScript '5Script( 6.7 and the 8S.38. $n 9eta6, if the UserA"ent is $E: or #etter, and the pa"e/s ;lientTar"et is Auto 'the default( we/ll render client script. 3r, if ;lientTar"et is Up<evel, we/ll render client script without re"ard for the UserA"ent. &e are lookin" at makin" this more fle!i#le in 9eta 7. $/m not sure $ understand the performance part of )our 4uestion, #ut $/ll "ive this a shot. $f we do render client script, it/s #asicall) =ust a do>en or so lines of client script in the pa"e plus a 5Script include file. The 5Script file is 6?@ in si>e, and the #rowser will routinel) cache this file unless the user has disa#led his #rowser cache. An)wa), the si>e of the rendered pa"e is most affected #) the first download of the script file, and then not all that much. The difference in the renderin" of the validation control is minimal too. The main #enefit of the client script is improved user interaction with the pa"e. 3n post#ack we alwa)s perform the validation on the server, re"ardless of whether the client has alread) done so. This is essential to prevent an unscrupulous user from spoofin" the client script, and it helps ensure the validation lo"ic is trul) identical for all users. .oes this cover it? Aou should hit a pa"e that does validation 'like from the 4uickstarts( and do a view source on it. Aou/ll see the include for the 5Script file, and a little client script #lock near the end that declares an a arra) of validator controls for the 5Script file to act on.
November 3rd, 2000

Question, &ill there need to #e much rewritin" of our "ood old ASP code? &e have lots of "reat ASP code and would not #e happ) to have to tinker with it when we install ASP.NET.

Answer, There are a couple of aspects to this 4uestion. irst, when )ou install ASP.NET on a machine, it does not affect e!istin" ASP pa"es or applications at all. &e/ve desi"ned ASP.NET to run side #) side with e!istin" ASP. That/s the primar) reason that )ou/ll notice that ASP.NET files have the e!tension .asp!. Second, we/ve desi"ned ASP.NET to #e as compati#le with ASP as possi#le, so that )ou can take e!istin" pa"es and run them under ASP.NET simpl) #) chan"in" the e!tension to .asp!. The caveat to this, and $ don/t want to make li"ht of it, is that we were not a#le to make ASP.NET 6BBC compati#le with ASP. There are a variet) of reasons for this. or e!ample, one of the main ones is that we no lon"er use late #ound script lan"ua"es - ASP.NET pa"es are compiled. There are man) thin"s that can #e done s)ntacticall) in and script lan"ua"es that can/t #e supported with compiled ones, especiall) when multiple lan"ua"es are used. So in summar), installin" ASP.NET will not #reak e!istin" code, and, dependin" on how )our code is written, )ou ma) #e a#le to move them over with little or no work.
November 3rd, 2000

Question, This 4uestion re"ards we# services. <et/s sa) $ have a we#service that validates form values. .oes a customer need to #e runnin" $$S in order to su#scri#e? ;an the) #e runnin" Apache that does not run ASP? Answer, $f )ou create a we# service that validates form values usin" ASP.NET, for a customer to use this, that is, for them to call )our we# service, there are no re4uirements as to the technolo"ies the) need to use at all. The) could indeed run Apache or an)thin" else. The) could run on an) platform. &e# Services are completel) open and that/s wh) companies such as $98 are supportin" them. + or a "ood technie discussion on &e# Services, check out, &ill &e# Services Take 3ff?2
November 3rd, 2000

Question, $ would assume with the compiled code advanta"e ASP.NET offers, the response time for a "iven pa"e would #e 4uicker than a re"ular ASP pa"e. Are there an) metrics )et affirmin" this issue. $n other words, have ASP.NETDASP pa"es with identical functionalit) #een measured #) response times? Answer, Aes, we/ve done a lot of #enchmarkin" and have compared =ust that. At this point, $ can/t actuall) tell )ou how much faster it is. &e have not even released the 9eta, )et, and we are continuin" to work on performance. $t also depends on the e!act scenario that )ou are usin". Eowever, $ can sa) that ASP.NET is nota#l) faster than ASP, and

compiled pa"es is onl) part of the reason. &e/ve spent a tremendous amount of workin" on performance from da) one. $n fact, the second developer on the ASP.NET team 'wa) #ack in 6FFG( was a performance dev, whose sole =o# it was to work on makin" it faster1

Commonly Asked ASP.NET Questions... Answered!


Question: ASP.NET is in private #eta testin" ri"ht now. &hen will it #e pu#lic #eta testin"? &hen can $ "et m) hands on ASP.NET and start writin" m) own ASP.NET pa"es? Answer: *&e are workin" hard now at finishin" up a pu#lic #eta that will #e availa#le for pu#lic download. ETA is still around H weeks 'earl) Septem#er( thou"h 'there are a lot of pieces in it(. *&e did hand out #its to the I,BBB people who attended last week/s P.; conference, however, which is wh) some people have copies now -- and wh) )ou are startin" to see discussions a#out it on discussion forums like this.* -- Scott 0uthrie, ASP.NET orum J ASP8essa"e#oard.com UPDATE!!! The .NET Runtime SD is A!ai"a#"e $or a""! %ou &an down"oad the #its at: htt'://msdn.mi&roso$t.&om/net/ Question: &hat platform's( will ASP.NET run on? Answer: *3nce released, )ou will #e a#le to run ASP.NET on either $$S? or $$S: 'we will not re4uire a new version of $$S to install it(. 9ecause we run side-#)-side with ASP 'meanin" #oth can run concurrentl) on the same #o! -- so )our e!istin" apps won/t #reak at all(, there shouldn/t #e an) real adoption #lockers to installin" it. *Aou can use -SH to edit ASP.NET Applications. 3r )ou can use notepad. 3r )ou can use -SI 'which has &AS$&A0 .esi"ners and .e#u""ers for -9, ;K and ;LL that tar"et ASP.NET(.* -- Scott 0uthrie, ASPN0 <istServ J ASP<ists.com Question: &hat lan"ua"es will developers #e a#le to use to create ASP.NET pa"es?

Answer: *Note that ASP.NET -- like ASP -- still defaults to *-9* as )our lan"ua"e unless )ou specif) another one. ... ASP.NET now allows )ou to use an) lan"ua"e )ou want to pro"ram pa"esDservicesDcomponents. *&e will have three lan"ua"es supported out of the #o! -- -9, ;K and 5Script. &e will also have appro!imatel) 6F other lan"ua"es read) in the ne!t month or two that will #e supported #) other companies. These lan"ua"es include, ;o#ol, Perl, P)thon, Eiffel, SmallTalk, <isp, Scheme, 3#=ective ;amel, etc. * rom a development standpoint, it reall) makes sense to pick a lan"ua"e that )ou feel most comforta#le with -- and then reall) #ecome a master at pro"rammin" with it. The "reat thin" is that we now have a common runtimeDde#u""in" environment that lets )ou consume an) .NET ramework AP$ from it 'Event<o"s, Perf ;ounters, .ata Access, etc(. So the lan"ua"e )ou choose is reall) a *lifest)le* choice -- whatever )ou feel most comforta#le and productive with.* -Scott 0uthrie, ASPN0 <istServ J ASP<ists.com Question: &ill a &indows FM version #e availa#le for ASP.NET? Answer: *3ur current plan is to support a *personal tier* version of ASP.NET that runs on &inF! 'includin" &indows FG as well as &indows 8E(. This isn/t reall) a we# server thou"h -- #ut rather a local development environment that will let )ou #uild apps that onl) )our local machine can use. *Althou"h )ou will #e a#le to use ASP.NET on &inF!, $ NwouldN recommend up"radin" to &in7! at some point 'note that ASP.NET works "reat on &in7k professional -- )ou don/t need a server(. $t will #e more ro#ust than &inF! -- and will support the full version of the product.* -- Scott 0uthrie, ASPN0 <istServ J ASP<ists.com Question: &ill there #e an) tools to port ASP applications to ASP.NET applications? Answer: *3ur "oal will #e to have portin" utilities availa#le to help identif)Dupdate code in e!istin" applications that needs to #e modified in order to work with ASP.NET. *... ASP.NET will run side-#)-side with e!istin" ASP. As such, )ou will #e a#le to incrementall) move )our apps forward at whatever time schedule )ou like. This -- com#ined with the portin" utilities -- will

hopefull) make up"radin" a non-painful process.* -- Scott 0uthrie, ASP.NET orum J ASP8essa"e#oard.com Question: Eow will ASP.NET handle session mana"ement? Answer: *ASP.NET does not rel) on SO< Server or <.AP for session mana"ement. 9asicall) we provide two new additional features, 6.( ;ookieless Session, This is where we *mun"e* the sessionid into UP<s as opposed to client-side cookies to keep track of Session$.s 'ena#lin" )ou to now use session state even with #rowsers that have cookie support disa#led(. &e automaticall) do the mun"in" for )ou 'no code chan"es re4uired( to make this happen for #oth static and d)namic content 'so )ou can link off to a static html pa"e which then in turn links off to another d)namic pa"e -- and the session is maintained(. 7.( E!ternal Session State Support. This is where we store session values into an e!ternal state store instead of the ASP.NET worker process. This "uaretees that state is stored accross worker process restarts 'providin" "reat relia#ilit)( as well as accross multiple machines 'providin" #uilt-in we# farm support(. &e ship support for two session stores out of the #o!, 6( the *ASP.NET state store* which is a dedicated NT Service that can run on an) #o! -- and which ships with the ASP.NET #its. 7( support for storin" session data directl) into SO< Server. This later option is more scala#le -- #ut does re4uire )ou to #u) SO< Server in order to make it work. *Note that the a#ove two state options are completel) ortho"anal from each other -- ie, )ou can use them to"ether or separatel). Also, our e!ternal state store support is plu""a#le -- meanin" that we e!pect other third parties 'as well as people like 8S ;ommerce Server( to plu" in their own store support into the model. *&ith re"ard to performance, we are NmuchN faster than than e!istin" pre-ASP.NET state solutions when doin" out of proc state. &e are levera"in" ASP.NET/s new 8TA #ased thread pool to do as)nc readDwrite operations that ena#le us to avoid #lockin" worker threads when retrievin" and updatin" the state 'instead usin" iocompletions to reuse threads(. This should improve s)stem throu"hput si"nificantl) and was not possi#le #efore with ASP 'since it used an STA thread pool and as such couldn/t do as)nc operations(.* -- Scott 0uthrie, ASPN0 <istServ J ASP<ists.com

ASP .NET

Question: What are the differences between C# and VB.NET, and which language should I use to create my !".NET Web #ages$ %"rint this & '( Answer: With !".NET, de)elo#ers can choose to create the ser)er*side code for their Web #ages in a myriad of languages. The most common languages that de)elo#ers will choose, will li+ely be VB.NET or C#. ,There are a number of other languages one can choose to use, from "erl.NET to -!cri#t.NET to C.B./.NET.0 .f the many !".NET articles and code e1am#les that e1ist on the Web, it seems that while a slim ma2ority of them are shown VB.NET, a good number are written in C#. What language is the 3best3 language choice$ If you are a VB wi4ard, should you ta+e the time to learn C# or continue to use VB.NET$ re C# !".NET #ages 3faster3 than VB.NET !".NET #ages$ These are 5uestions that you may find yourself as+ing, es#ecially when you6re 2ust starting to del)e into .NET. &ortunately the answer is sim#le7 there is no 3best3 language. ll .NET languages use, at their root, functionality from the set of classes #ro)ided by the .NET &ramewor+. Therefore, e)erything you can do in VB.NET you can do in C#, and )ice*a*)ersa. The only differences among languages is merely a syntactical one. If you are more familiar with -a)a, -!cri#t, or C8C99, you may find C#6s synta1 more familiar than VB.NET6s. If you6)e been doing VB for the #ast fi)e years, there6s no reason to thin+ you ha)e to now switch to a new langauge ,although you should always loo+ to be learning new things0. What if you ha)e an !".NET Web #age written in C# that you want to con)ert to VB.NET, or )ice*a*)ersa$ s aforementioned, the languages only differ in their synta1, so this translation, while not usually tri)ial, is still fairly striaghtforward, and can be accom#lished systemmatically. &or information on the syntactical differences between the two languages, be sure to read7 &rom VB.NET to C# and Bac+ gain. :a##y "rogramming, with whate)er language you choose;

FAQ: ASP.NET- I

What is the .NET Framework? The .NET Framework is an environment for building, deploying, and running Web Services and other applications. t consists of three main parts! the "ommon #anguage $untime, the Framework classes, and %S&.NET.

What kind of appli ations we an !"ild "sin# the .NET Framework? The .NET Framework enables you to create great Web applications. 'owever, it can also help you build the same applications you build today. f you write any Windows software (using %T#)"*+, +F", +icrosoft(r, -isual .asic(r,, or even standard +icrosoft(r, Win/0(r,,, .NET offers many advantages to the way you currently build applications. *f course, if you do develop Web sites, then the .NET Framework has a lot to interest you1starting with %S&.NET.

$ow is ASP.NET different than ASP %.&? %S&.NET is a completely new %S&. t was written entirely from the ground up (homage to Scott 2uthrie and +ark %nders for their ingenious idea, in "3 (pronounced 4see sharp4,. %S&.NET makes use of compilable programming languages, such as -isual .asic.Net, "3, even "*.*#5 (making it truely language1neutral,, to write Web %pplications. The applications are compiled on the server, and pages are served in 'T+# for the specific browser that has issued the re6uest

What do I need to r"n ASP.NET? To run %S&.NET, you must have the .NET Framework S78. This beta software should only be installed on non1production test machines. The S78 will run on Windows(r, 0999 and Windows NT(r, :.9 (including the NT*& for %S&.NET support,, Windows ;<, or Windows +E. nternet E=plorer >.> and 7ata %ccess "omponents 0.? are re6uired.

'o I need to (is"al St"dio.Net in de)elop ASP.NET appli ations? The command line compilers for -., "3 and @Script will ship with %S&.NET in addition to -S.Net. This means that you don4t have to purchase)install -S.Net in order to write components with %S&.NET. Aou can simply install the BS78B version of %S&.NET that will be available publicly on the +icrosoft.com website and go from there. %S&.NET and the .NET Frameworks will not cost money. Aou will be able to download them, install them, and use them on both development and deployment servers for free

Is ASP.NET ross-!rowser ompati!le? %S&.NET will provide multiple types of 'T+# depending on the browser. 4Cp#evel4 browsers ( E:.9D, will get 'T+#:.9 and "lient1Side @avaScript E.9. %ll other browsers (47own#evel4, will get 'T+#/.0 and no @avaScript. That is as of .eta E

What platform*s+ will ASP.NET r"n on? *nce released, you will be able to run %S&.NET on either S> or S: (we will not re6uire a new version of S to install it,. .ecause we run side1by1side with %S& (meaning both can run concurrently on the same bo= 11 so your e=isting apps won4t break at all,, there shouldn4t be any real adoption blockers to installing it. Aou can use -S? to edit %S&.NET %pplications. *r you can use notepad. *r you can use -SF (which has WAS WA2 7esigners and 7ebuggers for -., "3 and "D D that target %S&.NET,

(e# Ser!i&es )re*uent"y Asked Questions


Co#yright < =asser !hohoud !ubmit new 5uestions to shohoudy>de)1#ert.com

1. What is a Web Service?


!im#ly #ut, a Web ser)ice is an a##lication that e1#oses a #rogrammatic interface using standard, Internet*friendly #rotocols. Web ser)ices are designed to be used by other #rograms or a##lications rather than by humans. "rograms in)o+ing a Web ser)ice are called clients. !. " o)er :TT" is the most commonly used #rotocol for in)o+ing Web ser)ices. &or more information, read cha#ter ? of my boo+ online.

2. Why would I create/use a Web Service?


By e1#osing data and functionality using standard #rotocols, Web ser)ices ma+e it easy to build so#histicated a##lications that integrate many features and content. There are three main uses of Web ser)ices. Application integration Web ser)ices within an intranet are commonly used to integrate business a##lications running on dis#arate #latforms. &or e1am#le, a .NET client running

on Windows @AAA can easily in)o+e a -a)a Web ser)ice running on a mainframe or Bni1 machine to retrie)e data from a legacy a##lication. Business integration Web ser)ices allow trading #artners to engage in e*business le)eraging the e1isting Internet infrastructure. .rgani4ations can send electronic #urchase orders to su##liers and recei)e electronic in)oices. Coing e*business with Web ser)ices means a low barrier to entry because Web ser)ices can be added to e1isting a##lications running on any #latform without changing legacy code. Commercial Web ser)ices focus on selling content and business ser)ices to clients o)er the Internet similar to familiar Web #ages. Bnli+e Web #ages, commercial Web ser)ices target a##lications not humans as their direct users. Continental irlines e1#oses flight schedules and status Web ser)ices for tra)el Web sites and agencies to use in their a##lications. /i+e Web #ages, commercial Web ser)ices are )aluable only if they e1#ose a )aluable ser)ice or content. It would be )ery difficult to get customers to #ay you for using a Web ser)ice that creates business charts with the customersD data. Customers would rather buy a charting com#onent ,e.g. C.E or .NET com#onent0 and install it on the same machine as their a##lication. .n the other hand, it ma+es sense to sell real*time weather information or stoc+ 5uotes as a Web ser)ice. Technology can hel# you add )alue to your ser)ices and e1#lore new mar+ets, but ultimately customers #ay for contents and8or business ser)ices, not for technology. &or more information, read cha#ter ? of my boo+ online.

3. How do I create a Web service with .NET?


.NET ma+es it almost tri)ial to create a basic Web ser)ice. Fead this short online tutorial on creating .NET Web ser)ices.

4. How do I i vo!e a Web service with .NET?


In)o+ing a Web ser)ice is also )ery easy with .NET. Fead this short online tutorial on how to in)o+e a Web ser)ice from .NET.

". How do I call a Web service #ro$ %& ' or classic (S)?
=ou can use the Eicrosoft !. " tool+it which is downloadable here. This tool+it #ro)ides an easy, C.E*based ob2ect model for calling Web ser)ices from C.E*enabled languages such as Visual Basic and VB!cri#t. :ereDs a VB G e1am#le that calls the Weather Web ser)ice on this site7 .im soap As Soap;lient Set soap Q New Soap;lient soap.mssoapinit R *http,DDwww.<earnMml&S.comDservicesDweatherPetriever.asm!? &S.<* 8s"9o! soap.0etTemperature'*7B6I6*(

'. Where ca I #i d live Web services?


ThereDs a list of Web ser)ices on this site. ll ser)ices on this list ha)e been )erified to intero#erate with .NET unless otherwise s#ecified. ThereDs also a long list of Web ser)ices at www.1methods.com. In addition, www.salcentral.com offers a directory of Web ser)ices. .f course, BCCI ,Bni)ersal Cescri#tion Cisco)ery and Integration0 is the ultimate directory of Web ser)ices. ll commercial Web ser)ices should be registered with BCCI so if youDre loo+ing for a business oriented Web ser)ice, search BCCI at uddi.microsoft.com. EarthConnect.net is an e1am#le of a li)e, commercial Web ser)ice that #ro)ides financial information. EarthConnectDs Web ser)ices #ro)ide delayed and real*time stoc+ 5uotes using .NET HE/ Web ser)ices. They #ro)ide an !CI and lots of e1am#le clients in different languages. =ou can sign u# to use their ser)ices at htt#788www.EarthConnect.net.

*. Where ca I #i d other Web service resources?


.f course thereDs my monthly Web ser)ices newsletter aimed at software architects and de)elo#ers using .NET. The best #lace to as+ 5uestions and get hel# on Web ser)ices is the highly s#eciali4ed Web ser)ices mailing list ,as#ngwebser)ices0 at htt#788www.as#friends.com8as#friends8as#ngwebser)ices.as#. The C.TNET discussion list is also a good source for Web ser)ice information. Be sure to search the archi)es for both of these lists before as+ing your 5uestions. There are also the Eicrosoft Web ser)ices and !. " !CI newsgrou#s on msnews.microsoft.com. s far as Web sites go, chec+ out Web !er)ices rchitect, and Web!er)ices.org. Both of these sites offer high*le)el, u#*to*date information and news related to the Web ser)ices industry. If youDre loo+ing for .NET resources, a good #lace to start is CotNet@JK.com and LotCotNet.com. &or !" and !".NET information, chec+ out as#alliance.com, as#friends.com, and learnas#.com.

+. What are ,-. Sche$a?


E1tensible Ear+u# /anguage ,HE/0 is the basic format for re#resenting data on the Web ser)ices #latform. In addition to being sim#le to create and #arse, HE/ was chosen because it is neither #latform nor )endor s#ecific. Being neutral is more im#ortant than being technically su#erior7 !oftware )endors are much more li+ely to ado#t a neutral technology rather than one that was in)ented by a com#etitor. HE/ #ro)ides a sim#le way of re#resenting data, but it says nothing about the standard set of data ty#es a)ailable and how to e1tend that set. &or e1am#le, what e1actly is an integer$ Is it ?G, M@, or GJ bits$ !uch details are im#ortant to enable intero#erability. The WMC HE/ !chema ,H!C0 is a standard that s#ecifies some built*in ty#es and language to define additional ty#es. The Web ser)ices #latform uses H!C as its ty#e system. When you build Web ser)ices in your #rogramming language ,e.g. VB.NET or C#0, the data ty#es you use must be translated to H!C ty#es to conform to the Web ser)ices standards. The tools you use might automate this translation for you, but you are li+ely to ha)e to twea+ the result a bit to meet your needs. Cha#ter @ of my boo+ is all about HE/ !chema and how to translate custom ty#es ,e.g. classes0 to H!C ty#es.

/. What is S0() a d why should I use it?


.nce youD)e built a Web ser)ice, you and8or others will want to in)o+e it. The !im#le .b2ect ccess "rotocol #ro)ides the standard F"C mechanism used for in)o+ing Web ser)ices. cle)er acronym, !. " is actually a bit of a misnomer7 It im#lies that the underlying Web ser)ice re#resentation is an ob2ect when in fact it does not ha)e to be. =ou can write your Web ser)ice as a series of functions in C and still in)o+e it using !. ". The !. " s#ecification #ro)ides standards for the format of a !. " message and how !. " should be used o)er :TT". !. " also builds on HE/ and H!C to #ro)ide standard rules for encoding data as HE/. Cha#ter M of my boo+ discusses !. " and e1#lains the com#onents of !. " messages.

11.

What is WS2.?

:ow do you e1#lain to others the functions that your Web ser)ice e1#oses and the #arameters each function acce#ts$ =ou might do it informally by writing u# a document that #ro)ides this information or you might e)en tell it )erbally to someone who needs to in)o+e your Web ser)ice. The informal a##roach has at least one serious #roblem7 When a de)elo#er sits down to build a client for your Web ser)ice, their de)elo#ment tool ,e.g. Visual !tudio0 cannot offer them any hel# because that tool has no idea about the Web ser)iceDs functions and #arameters. "ro)iding a formal descri#tion in a machine*readable format would sol)e this #roblem. The Web !er)ice Cescri#tion /anguage is an HE/* based grammar for describing Web ser)ices, their functions, #arameters, and return )alues. Being HE/*based, W!C/ is both machine and human readable, which is a big #lus. !ome modern de)elo#ment tools can generate a W!C/ document describing your Web ser)ice as well as consume a W!C/ document and generate the necessary code to in)o+e the Web ser)ice. Cha#ter J of my boo+ e1#lains the W!C/ grammar and shows you e1am#les of W!C/ documents generated by )arious tools.

11.

What is 322I a d what is it 4ood #or?

=ou can start by reading my online BCCI tutorial. lso chec+ out E!CNDs BCCI #age. When youDre ready to register your Web ser)ice with BCCI, read this article that outlines the #rocess. If you 2ust want to 5uic+ly and easily register your ser)ice with BCCI, you can sim#ly use 5BCCI at www.5BCCI.com. If you want to #rogrammatically search or register with BCCI, download the !CI here. The !CI is actually three things7 C.E* based !CI that you can use from VB G, a .NET*based !CI, and BCCI Ce)elo#er Edition which you can install and use as your own #ri)ate BCCI on your intranet. .f course youDll need to chec+ out EicrosoftDs test and #roduction BCCI registries.

12. How do I use a 5ro6y server whe i vo!i 4 a Web service?


If you are using the !. " Tool+it, you need to set some connector #ro#erties to use a #ro1y ser)er7 .im soap As Soap;lient Set soapQNew Soap;lient soap.;onnectorPropert)'*Pro!)Server*( Q Spro!)servernameT

soap.;onnectorPropert)'*Pro!)Port*( Q SGBGBT soap.;onnectorPropert)'*UsePro!)*( Q True .NET is a little easier, you 2ust need to create a !ystem.Net.Web"ro1y ob2ect and use it to set the "ro1y #ro#erty7 .im ws As localhost.8)Service'( ws.Pro!)QNew S)stem.Net.&e#Pro!)'Shttp,DDpro!)server,GBGBT(

14. I7$ havi 4 5roble$s i vo!i 4 $y Web service8 where do I start?


good #lace to start is finding out what e1actly is being sent on the wire between the client and the ser)ice and what is coming bac+. n easy way to do this is to use "ro1yTrace, a tool created by !imon &ell and dowloadable for free from htt#788www.#oc+etsoa#.com8tc#trace8#t.as#. "ro1yTrace acts as an :TT" #ro1y so the client sends it re5uests and forwards those re5uests to the ser)ice. It then recei)es res#onses from the ser)ice and forwards those res#onses to the client. But it also dis#lays the contents of re5uest and res#onse messages in an easy to read window. To use "ro1yTrace, sim#ly run it then configure the Web ser)ice client to use it as a #ro1y ,see :ow do I use a #ro1y ser)er abo)e0. =ou ha)e got to get this tool and use it to troubleshoot Web ser)ice #roblems. It has sa)ed me many hours and hel#ed me gain insight into how Web ser)ices wor+.

1".

Where ca I lear $ore about Web services?

This site has a lot of information. ThereDs my u#coming Web ser)ices boo+ which is a)ailable online. ThereDs also the monthly .NET Web ser)ices newsletter which you can read online here. lso chec+ out my training courses a)ailable on site and as #ublic scheduled classes.
What platforms does ASP.NET r"n on? "urrently, it4s supported on Windows 0999 and Windows G&. %S&.NET integrates with nternet nformation Server ( S, and thus re6uires that S be installed. t runs on server and non1server editions of Windows 0999 and G& as long as S is installed. +icrosoft originally planned to support %S&.NET on Windows NT :.9, but had to reconsider due to time and technical constraints. ,an two different pro#rammin# lan#"a#es !e mi-ed in a sin#le ASP. file? No. %S&.NET uses parsers to strip the code from %S&G files and copy it to temporary files containing derived Page classes, and a given parser understands only one language. Wh/ an0t I p"t 123 Pa#e 4an#"a#e56,776 28 at the top of an ASP. file and write m/

ser)er-side s ripts in ,77? .ecause the parsers %S&.NET uses to e=tract code from %S&G files only understand "3, -isual .asic.NET, and @Script.NET. 'owever, if you use code1behind to get your code out of the %S&G file and into a separately compiled source code file. Aou can write server1side scripts in any language supported by a .NET compiler. ,an I "se ode-!ehind with 9lo!al.asa- files? Aes. 'ere4s a simple 2lobal.asa= file that doesn4t use code1behind!

<%@ Import Namespace="System.Data" %> <script language="C#" runat="server"> void pplication!Start "# $ DataSet ds = ne% DataSet "#& ds.'ead(ml "Server.)ap*at+ "",lo-alData..ml"##& pplication/",lo-alData"0 = ds& 1 <2script>

'ere4s the e6uivalent file written to use code1behind!

<%@

pplication In+erits=")y pp" %>

%nd here4s the MyApp class that it references!

using System.3e-& using System.Data& pu-lic class )y pp 4 5ttp pplication $ pu-lic void pplication!Start "# $ DataSet ds = ne% DataSet "#& ds.'ead(ml "",lo-alData..ml"#& pplication/",lo-alData"0 = ds& 1 1

So that %S&.NET can find the MyApp class, compile it into a 7## (csc 2t4li-rary filename.cs, and place it in the application root4s bin subdirectory. ,an /o" o)erride method56post6 in a 1form r"nat56ser)er68 ta# !/ writin# 1form method56#et6 r"nat56ser)er68? Aes. ,an an ASP. file ontain more than one form marked r"nat56ser)er6?

No. Is it possi!le to see the ode that ASP.NET #enerates from an ASP. file? Aes. Enable debugging by including a HIJ &age 7ebugKBtrueB IL directive in the %S&G file or a Hcompilation debugKBtrueBL statement in Web.config. Then look for the generated "S or -. file in a subdirectory underneath MISystem$oot IM+icrosoft.NETMFrameworkMvE.9.nnnnMTemporary %S&.NET Files. 'oes ASP.NET s"pport ser)er-side in l"des? Aes. Server1side includes work the same in %S&.NET as they do in %S&. 'oes ASP.NET s"pport ser)er-side o!:e t ta#s? Aes. The following tag creates an instance of a custom type named ShoppingCart and assigns it session scope (that is, it creates a uni6ue ShoppingCart instance for each and every session created on the server,!

<o-6ect id=")yS+oppingCart" class="S+oppingCart" scope="session" runat="server" 2>

+anaged types created this way are identified by class name. Cnmanaged types ("*+ classes, are identified by "#S 7 or &rog 7. $ow do I omment o"t statements in ASP. files? <%77 <asp48utton 9e.t="Clic: )e" ;nClic:=";nClic:" runat="server" 2> 77%>

,an I "se "stom .NET data t/pes in a We! form? Aes. &lace the 7## containing the type in the application root4s bin directory and %S&.NET will automatically load the 7## when the type is referenced. $ow do I de!"# an ASP.NET appli ation that wasn0t written with (is"al St"dio.NET and that doesn0t "se ode-!ehind? Start the 7bg"lr debugger that comes with the .NET Framework S78, open the file containing the code you want to debug, and set your breakpoints. Start the %S&.NET application. 2o back to 7bg"lr, choose 7ebug &rocesses from the Tools menu, and select aspnetNwp.e=e from the list of processes. ( f aspnetNwp.e=e doesn4t appear in the list, check the BShow system processesB bo=., "lick the %ttach button to attach to aspnetNwp.e=e and begin debugging. .e sure to enable debugging in the %S&G file before debugging it with 7bg"lr. Aou can enable tell %S&.NET to build debug e=ecutables by placing a

<%@ *age De-ug="true" %>

statement at the top of an %S&G file or a

<compilation de-ug="true" 2>

statement in a Web.config file. What e)ent handlers an I in l"de in 9lo!al.asa-? %pplication start and end event handlers

%pplicationNStart %pplicationNEnd

Session start and end event handlers SessionNStart

SessionNEnd

&er1re6uest event handlers (listed in the order in which they4re called, %pplicationN.egin$e6uest

%pplicationN%uthenticate$e6uest %pplicationN%uthoriOe$e6uest %pplicationN$esolve$e6uest"ache %pplicationN%c6uire$e6uestState %pplicationN&re$e6uest'andlerE=ecute %pplicationN&ost$e6uest'andlerE=ecute %pplicationN$elease$e6uestState %pplicationNCpdate$e6uest"ache %pplicationNEnd$e6uest

Non1deterministic event handlers %pplicationNError

%pplicationN7isposed

2lobal.asa= can also include handlers for events fired by custom 'TT& modules. The event handlers listed above are intrinsic to %S&.NET. Is it possi!le to prote t )iew state from tamperin# when it0s passed o)er an "nen r/pted hannel? Aes. Simply include an @ Page directive with an Enable-iewState+acKBtrueB attribute in each %S&G file you wish to protect, or include the following statement in Web.config!

<pages ena-le<ie%State)ac="true" 2>

This configuration directive appends a hash (officially called the message authentication code, or +%", to view state values round1tripped to the client and enables %S&.NET to detect altered view state. f %S&.NET determines that view state has been altered when a page posts back to the server, it throws an e=ception. The hash is generated by appending a secret key (the validationKey value attached to the Hmachine8eyL element in +achine.config, to the view state and hashing the result. %n attacker can4t modify view state and fi= up the hash without knowing the secret key, too. Is it possi!le to en r/pt )iew state when it0s passed o)er an "nen r/pted hannel? Aes. Set Enable-iewState+ac to true and either modify the Hmachine8eyL element in +achine.config to look like this!

<mac+ine=ey validation=">D?S" ... 2>

*r add the following statement to Web.config!

<mac+ine=ey validation=">D?S" 2> ,an a "ser !rowsin# m/ We! site read m/ We!. onfi# or 9lo!al.asa- files? No. The Hhttp'andlersL section of +achine.config, which holds the master configuration settings for %S&.NET, contains entries that map %S%G files, "*NF 2 files, and selected other file types to an 'TT& handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. 'ere are the relevant statements in +achine.config!

<add ver-="@" pat+="@.asa." type="System.3e-.5ttpAor-idden5andlerB ... 2> <add ver-="@" pat+="@.conCig" type="System.3e-.5ttpAor-idden5andlerB ... 2>

'o We! ontrols s"pport ,as adin# St/le Sheets? Aes. %ll Web controls inherit a property named CssClass from the base class System.Web.U .WebControls.WebControl. The following e=ample defines a "SS class named np!t and uses it to modify a "e#t$o# control to display te=t in red E91point -erdana type!

<+tml> <+ead> <style> .Input $ Cont4 DEpt verdana& color4 red& 1 <2style> <2+ead> <-ody> <Corm runat="server"> <asp49e.t8o. CssClass="Input" 'un t="server" 2> <2Corm> <2-ody> <2+tml> Are ASP.NET ser)er ontrols ompati!le with Nets ape Na)i#ator? +ost are. Some controls, such as %abel, emit simple 'T+# tags that are compatible with virtually all browsers. *thers, such as Calendar, emit a mi= of 'T+# and client1side @avaScript. Fortunately, that @avaScript is simple enough to work with any browser that supports client1side scripting. The e=ception is the validation controls, which emit comple= @avaScript that integrates intimately with the browser4s 7'T+# 7ocument *bPect +odel (7*+,. .ecause the 7*+s used by Navigator and E are so different, the %S&.NET validation controls don4t work with Navigator. They can still validate input on the server, but they don4t even attempt to validate on the client in Navigator. What namespa es are imported !/ defa"lt in ASP. files? The following namespaces are imported by default. *ther namespaces must be imported manually using J mport directives.

System

System."ollections System."ollections.SpecialiOed System."onfiguration System.Te=t System.Te=t.$egularE=pressions System.Web System.Web."aching System.Web.Security System.Web.SessionState System.Web.C System.Web.C .'tml"ontrols System.Web.C .Web"ontrols

What assem!lies an I referen e in an ASP. file witho"t "sin# 3 Assem!l/ dire ti)es? %S&.NET links to the following assemblies by default!

+scorlib.dll System.dll System.7ata.dll System.7rawing.dll System.Web.dll System.Web.Services.dll System.Gml.dll

This list of BdefaultB assemblies is defined in the HassembliesL section of +achine.config. Aou can modify it by editing +achine.config or including an section in a local Web.config file. $ow does settin# a We! ontrol0s A"toPost;a k propert/ to tr"e a"se a pa#e to post !a k to the ser)er? With a sprinkle of @avaScript and a dash of 7ynamic 'T+# (7'T+#,. Enter this into a Web form!

<asp49e.t8o. ID="FserName" 'un t="server" 2>

uto*ost8ac:="true"

%nd the control returns this!

<input name="FserName" type="te.t" id="FserName" onc+ange="!!do*ost8ac:"GFserNameGBGG#" language="6avascript" 2> . . . <script language="6avascript"> <H77 Cunction !!do*ost8ac:"event9argetB event rgument# $ var t+eCorm = document.ctrlE& . .

. t+eCorm.su-mit"#& 1 22 77> <2script>

The HinputL tag includes an on&hange attribute that activates a @avaScript function named ''doPost$a&( on the client when the control loses the input focus following a te=t change. ''doPost$a&( programmatically posts the page back to the server by calling the S!bmit method of the 7'T+# obPect that represents the )orm *the)orm+. I sometimes see ASP.NET apps that in l"de AS$. files. What are AS$. files? %S'G files contain 'TT& handlers1software modules that handle raw 'TT& re6uests received by %S&.NET. The following code institutes a simple 'TT& handler!

<%@ 3e-5andler Ianguage="C#" Class="5ello"%> using System.3e-& pu-lic class 5ello 4 I5ttp5andler $ pu-lic void *rocess'eJuest "5ttpConte.t conte.t# $ string name = conte.t.'eJuest/"Name"0& conte.t.'esponse.3rite ""5elloB " K name#& 1 pu-lic -ool Is'eusa-le $ get $ return true& 1 1 1

f this code is placed in an %S'G file named 'ello.ash= and re6uested using the C$# http!))...)hello.ash=QNameK@eff, it returns B'ello, @effB in the 'TT& response. %S'G files provide developers with a convenient way to deploy 'TT& handlers without customiOing "*NF 2 files or modifying the S metabase. ,an I reate ASP.NET ser)er ontrols of m/ own? Aes. Aou can modify e=isting server controls by deriving from the corresponding control classes or create server controls from scratch by deriving from System.Web.U .Control. %lthough a full treatment of custom controls is beyond the scope of this F%R, here4s a simple custom control that writes B'ello, worldB to a Web page!

using System& using System.3e-& using System.3e-.FI& namespace 3intellect $ pu-lic class 5elloControl 4 Control $ protected override void 'ender "5tml9e.t3riter

%riter#

$ 1 %riter.3rite ""5elloB 3orldH"#&

% custom control emits 'T+# by overriding the virtual ,ender method it inherits from Control and using the provided Html"e#tWriter to write its output. What does the S/stem.We!.<I.Pa#e.=e#ister,lientS ript;lo k method do> and do I need it when I write "stom ASP.NET ser)er ontrols? ,egisterClientS&ript$lo&( enables a custom control to register a block of client1side script that the control returns to a browser. Why does it e=istQ So the same script block doesn4t get returned multiple times if the page contains multiple instances of a control that emits client1side script. 'ere4s the source code for a custom control called Alert$!tton that renders itself an as Hinput typeKBsubmitBL tag with an on&li&( attribute that displays a message using a @avaScript alert!

using using using using

System& System.3e-& System.3e-.FI& System.9e.t&

namespace 3intellect $ pu-lic class lert8utton 4 Control $ protected string !9e.t& protected string !)essage& pu-lic string 9e.t $ get $ return !9e.t& 1 set $ !9e.t = value& 1 1 pu-lic string )essage $ get $ return !)essage& 1 set $ !)essage = value& 1 1 protected override void ;n*re'ender "?vent rgs e# $ *age.'egisterClientScript8loc: " "!!do lert"B "<script language=L"6avascriptL">Ln" K "<H77Ln"K "Cunction !!do lert "message#Ln" K "$Ln" K " alert "message#&Ln" K "1Ln" K "77>Ln"K "<2script>" #&

1 %riter#

protected override void 'ender "5tml9e.t3riter

$ "#& value=L""#&

String8uilder -uilder = ne% String8uilder -uilder. ppend ""<input type=L"su-mitL"

-uilder. ppend "!9e.t#& -uilder. ppend ""L" onclic:=L"6avascript4!!do lert "LG"#& -uilder. ppend ")essage#& -uilder. ppend ""LG#&L" 2>"#& 1 1 1 %riter.3rite "-uilder.9oString "##&

f the control4s register tag prefi= is win, then the following statement declares an Alert$!tton control that, when clicked, displays B'ello, worldB in a message bo=!

<%in4 lert8utton 9e.t="Clic: )e" )essage="5elloB %orld" 'un t="server" 2>

The control uses ,egisterClientS&ript$lo&( to register the client1side script block that it returns. That script block contains the ''doAlert function referenced by the HinputL tag4s on&li&( attribute. t4s returned only once no matter %lert.uttons a page contains. ,egisterClientS&ript$lo&( should always be called from the control4s -nPre,ender method so %S&.NET can control the script4s position in the output. What0s the differen e !etween Page.RegisterClientScriptBlock and Page.RegisterStartupScript? ,egisterClientS&ript$lo&( is for returning blocks of client1side script containing functions. ,egisterStart!pS&ript is for returning blocks of client1script not packaged in functions1in other words, code that4s to e=ecute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs. ,an a alendar ontrol !e "stomi?ed so that it limits "sers to sele tin# ertain da/s of the week> and onl/ dates that fall on or after toda/0s date?

Aes. The secret is to customiOe the control by processing .ay,ender events, which are fired as the calendar renders each and every cell. 'ere4s an e=ample that limits selections to future Fridays and Saturdays!

<asp4Calendar ;nDay'ender=";nDay'ender" 'un t="server" 2> . . . void ;nDay'ender ";-6ect senderB Day'ender?vent rgs e# $ e.Day.IsSelecta-le = "e.Day.Date.Day;C3ee: == Day;C3ee:.Ariday MM e.Day.Date.Day;C3ee: == Day;C3ee:.Saturday# NN e.Day.Date >= Date9ime.No%& 1

The .ay,ender/ventArgs passed to a .ay,ender event handler has a property named .ay that identifies the day being rendered. This e=ample sets .ay0s sSele&table property to true or false depending on whether the day currently being rendered represents a legitimate selection. Setting sSele&table to false prevents the control from placing a hyperlink in the corresponding cell, effectively making that cell unselectable. Is it ne essar/ to lo k appli ation state !efore a essin# it?

*nly if you4re performing a multistep update and want the update to be treated as an atomic operation. 'ere4s an e=ample!

pplication.Ioc: "#& pplication/"ItemsSold"0 pplication/"ItemsSold"0 pplication/"ItemsIeCt"0 pplication/"ItemsIeCt"0 pplication.FnIoc: "#&

= K = 7

"int# D& "int# D&

.y locking application state before updating it and unlocking it afterwards, you ensure that another re6uest being processed on another thread doesn4t read application state at e=actly the wrong time and see an inconsistent view of it.

The ASP.NET appli ation a he doesn0t ha)e 4o k and <n4o k methods as appli ation state does. 'oes this mean I ne)er need to lo k it? No. t means you have to come up with your own mechanism for locking. System."hreading.,eaderWriter%o&( is the perfect tool for the Pob. %ssuming rwlo&( is an instance of ,eaderWriter%o&(, here4s how you4d lock the application cache during an update!

r%loc:. cJuire3riterIoc: "9imeout.InCinite#& Cac+e/"ItemsSold"0 = "int# Cac+e /"ItemsSold"0 K D& Cac+e/"ItemsIeCt"0 = "int# Cac+e /"ItemsIeCt"0 7 D& r%loc:.'elease3riterIoc: "#&

%nd here4s how you4d read B temsSoldB and B tems#eftB values from the cache!

r%loc:. cJuire'eaderIoc: "9imeout.InCinite#& int sold = "int# Cac+e/"ItemsSold"0& int leCt = "int# Cac+e /"ItemsIeCt"0& r%loc:.'elease'eaderIoc: "#&

%s with application state, locking the application cache is only necessary when performing multistep updates that are to be treated as atomic operations. If I "pdate session state> sho"ld I lo k it> too? Are on "rrent a esses !/ m"ltiple re@"ests e-e "tin# on m"ltiple threads a on ern with session state? "oncurrent accesses aren4t an issue with session state, for two reasons. *ne, it4s unlikely that two re6uests from the same user will overlap. Two, if they do overlap, %S&.NET locks down session state during re6uest processing so that two threads can4t touch it at once. Session state is locked down when the HttpAppli&ation instance that4s processing the re6uest fires an A&1!ire,e1!estState event and unlocked when it fires a ,elease,e1!estState event. ASP.NET0s appli ation a he s"pports e-piration poli ies and a he remo)al all!a ks. E-piration poli ies are !ased on time dependen ies and file dependen ies. Are data!ase dependen ies s"pported> too? In other words> an I ha)e an item a"tomati all/ remo)ed from the a he in response to a data!ase "pdate?

n %S&.NET version E, no. n version 011well, Pust wait (hint, hint,. 'o ASP.NET forms a"thenti ation ookies pro)ide an/ prote tion a#ainst repla/ atta ks? 'o the/> for e-ample> in l"de the lient0s IP address or an/thin# else that wo"ld distin#"ish the real lient from an atta ker? No. f an authentication cookie is stolen, it can be used by an attacker. t4s up to you to prevent this from happening by using an encrypted communications channel ('TT&S,. %uthentication cookies issued as session cookies, do, however, include a time1out valid that limits their lifetime. So a stolen session cookie can only be used in replay attacks as long as the ticket inside the cookie is valid. The default time1out interval is /9 minutes. Aou can change that by modifying the timeo!t attribute accompanying the HformsL element in +achine.config or a local Web.config file. &ersistent authentication cookies do not time1out and therefore are a more serious security threat if stolen. ;/ defa"lt> a persistent forms a"thenti ation ookie iss"ed !/ ASP.NET is )alid for A& /ears. Is it possi!le to shorten that? Aes. Cnfortunately, there is no configuration setting you can tweak to customiOe the lifetime of a persistent authentication cookie, but you can customiOe it programmatically. 'ere4s a snippet of code that returns a persistent authentication cookie from a forms login page and limits the cookie4s lifetime to F days!

string url = Aorms ut+entication.,et'edirectFrl ""?lmo"B true#& Aorms ut+entication.Set ut+Coo:ie ""?lmo"B true#& 5ttpCoo:ie coo:ie = 'esponse.Coo:ies/Aorms ut+entication.AormsCoo:ieName0& coo:ie.?.pires = Date9ime.No% K ne% 9imeSpan "OB EB EB E#& 'esponse.'edirect "url#&

To set the cookie4s lifetime to something other than F days, simply modify the "imeSpan value. I wrote an $TTP handler and re#istered it in the 1http$andlers8 se tion of a lo al We!. onfi# file> !"t the handler ne)er #ets alled. What o"ld !e wron#? n addition to being mapped to a file type (or specific file name, in a "*NF 2 file, an 'TT& handler has to be registered in the S metabase. For e=ample, if you register an 'TT& handler with the Web.config file shown below, you also have to map S.igen to %spnetNisapi.dll in the S metabase. *therwise, %S&.NET doesn4t see the re6uest and can4t forward it to the handler.

<conCiguration> <system.%e-> <+ttp5andlers> <add ver-="@" pat+="@.igen" type="Image,enB Image,enIi-" 2> <2+ttp5andlers> <2system.%e-> <2conCiguration>

$ow do I send e-mail from an ASP.NET appli ation? )ail)essage message = ne% )ail)essage "#& message.Arom = "%e-master@%intellect.com"& message.9o = "?veryone@%intellect.com"& message.Su-6ect = "Sc+eduled *o%er ;utage"& message.8ody = ";ur servers %ill -e do%n tonig+t."& Smtp)ail.SmtpServer = "local+ost"& Smtp)ail.Send "message#&

MailMessage and SmtpMail are classes defined in the .NET Framework "lass #ibrary4s System.Web.Mail namespace. 7ue to a security change made to %S&.NET Pust before it shipped, you need to set SmtpMail0s SmtpServer property to BlocalhostB even though BlocalhostB is the default. n addition, you must use the S configuration applet to enable localhost (E0F.9.9.E, to relay messages through the local S+T& service. $ow do I read an ima#e from a data!ase "sin# A'B.NET and displa/ it in a We! pa#e? The following %S&G file reads and displays an image from the &ubs database that comes with +icrosoft SR# Server.

<%@ <%@ <%@ <%@

Import Import Import Import

Namespace="System.Data.SJlClient" %> Namespace="System.Dra%ing" %> Namespace="System.Dra%ing.Imaging" %> Namespace="System.I;" %>

<+tml> <-ody> <2-ody> <+tml> <script language="C#" runat="server"> void *age!Ioad"o-6ect senderB System.?vent rgs e# $ )emoryStream stream = ne% )emoryStream "#& SJlConnection connection = ne% SJlConnection ""server=local+ost&data-ase=pu-s&uid=sa&p%d="#& try $ connection.;pen "#& SJlCommand command = ne% SJlCommand ""select logo Crom pu-!inCo %+ere pu-!id=GEO>PG"B connection#& -yte/0 image = "-yte/0# command.?.ecuteScalar "#& stream.3rite "imageB EB image.Iengt+#& 8itmap -itmap = ne% 8itmap "stream#& 'esponse.Content9ype = "image2giC"& -itmap.Save "'esponse.;utputStreamB ImageAormat.,iC#& 1 Cinally $ connection.Close "#& stream.Close "#& 1 1 <2script> Some We! ser)i e lasses deri)e from S/stem.We!.We!Ser)i esC others do not. What0s the deal? WebServi&e contributes properties named Appli&ation2 Session2 Conte#t2 Server2 and User to derived classes enabling Web services to access the %S&.NET obPects of the same name. f you don4t use these obPects in your Web service1for e=ample, if you don4t use application state or session state1then you don4t have to derive from WebServi&e, either. ncidentally, if you want to use %S&.NET session state in a Web method, use the following WebMethod attribute to enable session state for that method!

/3e-)et+od "?na-leSession="true"#0

What are (S'IS,B files? -S7 S"* files are 7 S"* files that support dynamic discovery of Web services. f you place the following -S7 S"* file in a directory on your Web server, for e=ample, it returns references to all %S+G and 7 S"* files in the host directory and any subdirectories not noted in He=cludeL elements!

<Q.ml version="D.E" Q> <dynamicDiscovery .mlns="urn4sc+emas7dynamicdiscovery4disco.REEE7E>7DO"> <e.clude pat+="!vti!cnC" 2> <e.clude pat+="!vti!pvt" 2> <e.clude pat+="!vti!log" 2> <e.clude pat+="!vti!script" 2> <e.clude pat+="!vti!t.t" 2> <2dynamicDiscovery>

'ow does dynamic discovery workQ %S&.NET maps the file name e=tension -S7 S"* to an 'TT& handler that scans the host directory and subdirectories for %S+G and 7 S"* files and returns a dynamically generated 7 S"* document. % client who re6uests a -S7 S"* file gets back what appears to be a static 7 S"* document. Note that -S7 S"* files are disabled in the release version of %S&.NET. Aou can reenable them by uncommenting the line in the Hhttp'andlersL section of +achine.config that maps S.vsdisco to System.Web.Servi&es..is&overy..is&overy,e1!estHandler and granting the %S&NET user account permission to read the S metabase. 'owever, +icrosoft is actively discouraging the use of -S7 S"* files because they could represent a threat to Web server security. $ow does a We! ser)i e lient all We! methods as/n hrono"sl/? Web service pro=y classes generated by Wsdl.e=e contain asynchronous as well as synchronous versions of the Web service4s methods. Suppose a Web service implements the following Add method!

/3e-)et+od0 pu-lic int dd "int aB int -# $ return a K -& 1

% pro=y generated by Wsdl.e=e has $eginAdd and /ndAdd methods for calling Add asynchronously. %ssuming &al& is an instance of the pro=y class, here4s how a client calls Add asynchronously!

22 Initiate an async call I sync'esult res = calc.8egin dd "RB RB nullB null#& . . . 22 ,et t+e results int sum = calc.?nd dd "res#&

f the call hasn4t completed when /ndAdd is called, /ndAdd blocks until it does. f desired, a client can ask to be notified when an asynchronous call returns by providing a reference to an Asyn&Callba&( delegate wrapping a callback method. n the ne=t e=ample, /ndAdd won4t block because it isn4t called until the client is certain the method call has returned!

syncCall-ac: c- = ne% syncCall-ac: " ddCompleted#& I sync'esult res = calc.8egin dd "RB RB c-B null#& . . . pu-lic void ddCompleted "I sync'esult res# $ int sum = calc.?nd dd "res#& 1

%nother option is to use the sCompleted property of the Asyn&,es!lt interface returned by $eginAdd to determine whether the call has completed and avoid calling /ndAdd until it does!

I sync'esult res = calc.8egin dd "RB RB nullB null#& . . . iC "res.IsCompleted# $ int sum = calc.?nd dd "res#& 1 else $ 22 9ry again later 1 I wrote ode that "ses the SmtpDail and DailDessa#e lasses to send e-mail from an ASP.NET appli ation. The ode worked fine in !eta E> !"t it throws an e- eption in the release )ersion of ASP.NET. What0s wron#? &lease see F%R B'ow do send e1mail from an %S&.NET applicationQB (http!))www.wintellect.com)resources)fa6s)default.asp=Qfa6NidKETpageK:3:, $ow do I "pload files to We! pa#es in ASP.NET? Cse the Html np!tFile class, which you can declare an instance of with an Hinput typeKBfileB runatKBserverB)L tag. The following e=ample is a complete %S&G file that lets a user upload an image file and a comment descibing the image. The -nUpload method writes the image and the comment to a table named &ictures in a SR# Server database named +y&ictures.

<%@ Import Namespace="System.Data.SJlClient" %> <Corm enctype="multipart2Corm7data" runat="server"> <ta-le> <tr> <td>Aile name<2td> <td><input type="Cile" id="Fpload" runat="server"

2><2td> <2tr> <tr> <td>Comment<2td> <td><asp49e.t8o. ID="Comment" 'un t="server" 2><2td> <2tr> <tr> <td><2td> <td><asp48utton 9e.t="Fpload" ;nClic:=";nFpload" 'un t="server" 2><2td> <2tr> <2ta-le> <2Corm> <script language="C#" runat="server"> void ;nFpload ";-6ect senderB ?vent rgs e# $ 22 Create a -yte/0 Crom t+e input Cile int len = Fpload.*ostedAile.ContentIengt+& -yte/0 pic = ne% -yte/len0& Fpload.*ostedAile.InputStream.'ead "picB EB len#& 22 Insert t+e image and comment into t+e data-ase SJlConnection connection = ne% SJlConnection ""server=local+ost&data-ase=mypictures&uid=sa&p%d="#& try $ connection.;pen "#& SJlCommand cmd = ne% SJlCommand ""insert into *ictures " K ""*ictureB Comment# values "@picB @te.t#"B connection#& cmd.*arameters. dd ""@pic"B pic#& cmd.*arameters. dd ""@te.t"B Comment.9e.t#& cmd.?.ecuteNonSuery "#& 1 Cinally $ connection.Close "#& 1 1 <2script>

$ow do I reate an ASP. pa#e that periodi all/ refreshes itself? +ost browsers recogniOe the following +ET% tag as a signal to automatically refresh the page every nn seconds!

<meta +ttp7eJuiv="'eCres+" content="nn">

'ere4s an %S&G file that displays the current time of day. *nce displayed, it automatically refreshes every > seconds!

<%@ *age Ianguage="C#" %> <meta +ttp7eJuiv="'eCres+" content="T"> <+tml> <-ody> <%

'esponse.3rite "Date9ime.No%.9oIong9imeString "##& %> <2-ody> <2+tml> $ow an an ASP.NET appli ation determine whether ookies are ena!led in a !rowser? 7etermining whether cookies are enabled re6uires a round trip to the browser and back. f you can live with an e=tra round trip, the basic strategy is to return a cookie in an 'TT& response and redirect to a page that checks for the cookie. 'ere4s a page that does Pust that!

<+tml> <-ody> <Corm runat="server"> <asp48utton 9e.t="9est Coo:ie Support" ;nClic:=";n9est" 'un t="server" 2> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> void ;n9est ";-6ect senderB ?vent rgs e# $ 5ttpCoo:ie coo:ie = ne% 5ttpCoo:ie ""Aoo"B "8ar"#& 'esponse.Coo:ies. dd "coo:ie#& 'esponse.'edirect "";t+er*age.asp."#& 1 <2script>

%nd here4s the page that it redirects to (*ther&age.asp=,. This page uses the presence or absence of the cookie to determine whether cookies are enabled and displays the result!

<%@ *age Ianguage="C#" %> <+tml> <-ody> <% 5ttpCoo:ie coo:ie = 'eJuest.Coo:ies/"Aoo"0& iC "coo:ie H= null NN coo:ie.<alue == "8ar"# 'esponse.3rite ""Coo:ies are ena-led"#& else 'esponse.3rite ""Coo:ies are not ena-led"#& %> <2-ody> <2+tml> Is it possi!le to pre)ent a !rowser from a hin# an ASP. pa#e? Aou bet. @ust call Set3oStore on the HttpCa&hePoli&y obPect e=posed through the ,esponse obPect4s Ca&he property, as demonstrated here!

<%@ *age Ianguage="C#" %> <+tml> <-ody> <% 'esponse.Cac+e.SetNoStore "#& 'esponse.3rite "Date9ime.No%.9oIong9imeString "##& %> <2-ody> <2+tml>

Set3oStore works by returning a Ca&he4Control5 private2 no4store header in the 'TT& response. n this e=ample, it prevents caching of a Web page that shows the current time. $ow do I reate a 'ata9rid with 'elete !"ttons and pop "p a messa#e !o- askin# the "ser for onfirmation !efore deletin# a re ord? The %S&G file below demonstrates the proper techni6ue. t populates a .ata6rid with content from the Titles table of the &ubs database that comes with +icrosoft SR# Server. The .ata6rid4s leftmost column contains a row of 7elete buttons. The -n.elete,e&ord method simulates a record deletion by writing the Title field of the record to be deleted to a #abel control. The -nAtta&hS&ript method, which is called once for each row in the .ata6rid in response to temCreated events, attaches to each button an -nCli&( attribute that activates a bit of client1side @avaScript. That script displays a confirmation dialog and prevents the page from posting back to the server (thus preventing -n.elete,e&ord from being called, if the user clicks "ancel rather than *8.

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SJlClient" %> <+tml> <-ody> <Corm runat="server"> <asp4Data,rid ID=")yData,rid" uto,enerateColumns="Calse" Cell*adding="R" 8order3idt+="D" 8orderColor="lig+tgray" Aont7Name="<erdana" Aont7SiUe="Vpt" ,ridIines="vertical" 3idt+="WE%" ;nItemCreated=";n ttac+Script" ;nItemCommand=";nDelete'ecord" 'un t="server"> <Columns> <asp48uttonColumn 9e.t="Delete" 5eaderStyle75oriUontal lign="center" ItemStyle75oriUontal lign="center" 8utton9ype="*us+8utton" CommandName="Delete" 2> <asp48oundColumn 5eader9e.t="Item ID"

DataAield="title!id" 2> <asp48oundColumn 5eader9e.t="9itle" DataAield="title" 2> <asp48oundColumn 5eader9e.t="*rice" DataAield="price" DataAormatString="$E4c1" 5eaderStyle75oriUontal lign="center" ItemStyle75oriUontal lign="rig+t" 2> <2Columns> <5eaderStyle 8ac:Color="teal" AoreColor="%+ite" Aont78old="true" 2> <ItemStyle 8ac:Color="%+ite" AoreColor="dar:-lue" 2> < lternatingItemStyle 8ac:Color="-eige" AoreColor="dar:-lue" 2> <2asp4Data,rid> <asp4Ia-el ID=";utput" 'un t="server" 2> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> void *age!Ioad ";-6ect senderB ?vent rgs e# $ iC "HIs*ost8ac:# $ SJlData dapter adapter = ne% SJlData dapter ""select @ Crom titles %+ere price H= E"B "server=local+ost&data-ase=pu-s&uid=sa&p%d="#& DataSet ds = ne% DataSet "#& adapter.Aill "ds#& )yData,rid.DataSource = ds& )yData,rid.Data8ind "#& 1 1 void ;n ttac+Script ";-6ect senderB Data,ridItem?vent rgs e# $ iC "e.Item.Item9ype == IistItem9ype.Item MM e.Item.Item9ype == IistItem9ype. lternatingItem# $ 3e-Control -utton = "3e-Control# e.Item.Cells/E0.Controls/E0& -utton. ttri-utes. dd ""onclic:"B "return conCirm "L" re you sureQL"#&"#& 1 1 void ;nDelete'ecord ";-6ect senderB Data,ridCommand?vent rgs e# $ iC "e.CommandName == "Delete"# $ ;utput.9e.t = "Deleted L"" K e.Item.Cells/R0.9e.t K "L""& 1 1 <2script> $ow do I lo ali?e an ASP.NET appli ation so that it formats dates and times !ased on the re@"estor0s lo ale? 7eploy the following 2lobal.asa= file in the application4s virtual root!

<%@ Import Namespace="System.9+reading" %> <%@ Import Namespace="System.,lo-aliUation" %> <script language="C#" runat="server">

void pplication!8egin'eJuest ";-6ect senderB ?vent rgs e# $ try $ iC "'eJuest.FserIanguages.Iengt+ > E# $ 9+read.Current9+read.CurrentCulture = CultureInCo.CreateSpeciCicCulture "'eJuest.FserIanguages/E0#& 1 1 catc+ " rgument?.ception# $ 22 Do not+ing iC CreateSpeciCicCulture Cails 1 1 <2script>

Appli&ation'$egin,e1!est e=ecutes at the beginning of each and every re6uest. This e=ample reads the re6uestor4s preferred language from the ,e1!est obPect4s User%ang!age property (which is populated with information found in the re6uest4s %ccept1#anguage header,, creates a C!lt!re n)o obPect from it, and assigns the C!lt!re n)o obPect to the C!rrentC!lt!re property of the thread that4s processing the re6uest. F"# methods that are culture1aware (such as .ate"ime."oShort.ateString, will format dates, times, currency values, and numbers accordingly. What does Asp,ompat56tr"e6 mean and when sho"ld I "se it? %sp"ompat is an aid in migrating %S& pages to %S&G pages. t defaults to false but should be set to true in any %S&G file that creates apartment1threaded "*+ obPects11that is, "*+ obPects registered Threading+odelK%partment. That includes all "*+ obPects written with -isual .asic ?.9. %sp"ompat should also be set to true (regardless of threading model, if the page creates "*+ obPects that access intrinsic %S& obPects such as ,e1!est and ,esponse. The following directive sets %sp"ompat to true!

<%@ *age

spCompat="true" %>

Setting %sp"ompat to true does two things. First, it makes intrinsic %S& obPects available to the "*+ components by placing unmanaged wrappers around the

e6uivalent %S&.NET obPects. Second, it improves the performance of calls that the page places to apartment1threaded "*+ obPects by ensuring that the page (actually, the thread that processes the re6uest for the page, and the "*+ obPects it creates share an apartment. %sp"ompatKBtrueB forces %S&.NET re6uest threads into single1threaded apartments (ST%s,. f those threads create "*+ obPects marked Threading+odelK%partment, then the obPects are created in the same ST%s as the threads that created them. Without %sp"ompatKBtrue,B re6uest threads run in a multithreaded apartment (+T%, and each call to an ST%1based "*+ obPect incurs a performance hit when it4s marshaled across apartment boundaries. 7o not set %sp"ompat to true if your page uses no "*+ obPects or if it uses "*+ obPects that don4t access %S& intrinsic obPects and that are registered Threading+odelKFree or Threading+odelK.oth. I0)e de)eloped a "stom Windows Forms ontrol that I0d like to "se in a We! Form. I0)e heard that ASP.NET an "se Windows Forms ontrols. Is that tr"e? If so> how do I reate a Windows Forms ontrol in a We! Form? Aou can embed Windows Forms controls in Web pages using HobPectL tags similar to those that declare %ctiveG controls. To demonstrate, here4s the source code for a very simple slider control1one that derives from the F"#4s Track.ar class!

namespace 3intellect $ pu-lic class 3e-Slider 4 System.3indo%s.Aorms.9rac:8ar $1 1

"ompile this source code into a 7## with the following command (assuming the source code file is named "ontrols.cs,!

csc 2t4li-rary controls.cs

"opy the resulting 7## ("ontrols.dll, to the virtual directory of your choice on your Web server. Now create a te=t file named Slider.asp= in the same directory and

add the following 'T+#!

<+tml> <-ody> <Corm> <o-6ect id="Slider" classid="+ttp4Controls.dll#3intellect.3e-Slider" %idt+="PX" +eig+t="RTP"> <param name=")inimum" value="E"> <param name=")a.imum" value="DE"> <param name="<alue" value=">"> <param name=";rientation" value="<ertical"> <param name="8ac:Color" value="gains-oro"> <2o-6ect> <2Corm> <2-ody> <2+tml>

The HobPectL tag declares an instance of the control and names it Slider. t also uses HparamL tags to initialiOe some of the control4s properties. *pen the %S&G file in your browser and the slider control should be displayed. E downloads the control implementation from the Web server, so you don4t have to install "ontrols.dll on the client. The client must, however, have the .NET Framework installed. nternet E=plorer >.9E or higher is re6uired on the client, too. If I "se the slider ontrol in the pre)io"s e-ample in a We! pa#e> what m"st I do to allow a ser)er-side e)ent handler to determine the position of the slider0s th"m!? The trick is to intercept the form submit event fired before the form posts back to the server and add the thumb position to the form4s postback data. 'ere4s a modified version of the %S&G file in the previous e=ample that does Pust that. The ons!bmit attribute in the HformL tag calls the @avaScript function S!bmitForm before the form posts back to the server. S!bmitForm writes the slider4s thumb position to a hidden HinputL control named NNT'C+.&*S. The browser submits the NNT'C+.&*S control4s value to the server, and the server1side event handler e=tracts the value from the re6uest. n this e=ample, the event handler writes the thumb position to the Web page.

<+tml> <-ody> <Corm id=")yAorm" onsu-mit="6avascript4return Su-mitAorm "#&" runat="server"> <input type="+idden" name="!!95F)8*;S" value="" > <o-6ect id="Slider" classid="+ttp4Controls.dll#3intellect.3e-Slider" %idt+="PX" +eig+t="RTP"> <param name=")inimum" value="E"> <param name=")a.imum" value="DE"> <param name="<alue" value=">"> <param name=";rientation" value="<ertical"> <param name="8ac:Color" value="gains-oro"> <2o-6ect> <-r><-r> <input type="su-mit" value="9est" onserverclic:="S+o%9+um-*os" runat="server"> <-r><-r>

<span id=";utput" runat="server" 2> <2Corm> <2-ody> <2+tml> <script language="YavaScript"> Cunction Su-mitAorm "# $ )yAorm.!!95F)8*;S.value = )yAorm.Slider.value& return true& 1 <2script> <script language="C#" runat="server"> void S+o%9+um-*os ";-6ect senderB ?vent rgs e# $ ;utput.Inner9e.t = "Zou c+ose " K 'eJuest/"!!95F)8*;S"0& 1 <2script> If I "se the slider ontrol in the pre)io"s e-ample in a We! pa#e> the slider0s th"m! snaps !a k to its defa"lt position ea h time the pa#e posts !a k to the ser)er. Is there a wa/ to make the th"m! sta/ p"t? The %S&G file below shows one way to do it. The HparamL tag that controls the slider4s thumb position is no longer embedded in the page4s 'T+#U instead, it4s output programmatically with $esponse.Write. That enables the page to emit a HparamL tag containing a default value if the page is fetched outside of a postback, or a HparamL tag containing the NNT'C+.&*S value submitted in the re6uest if the page is being returned following a postback. t4s not pretty, but it works.

<%@ *age Ianguage="C#" %> <+tml> <-ody> <Corm id=")yAorm" onsu-mit="6avascript4return Su-mitAorm "#&" runat="server"> <input type="+idden" name="!!95F)8*;S" value=""> <o-6ect id="Slider" classid="+ttp4Controls.dll#3intellect.3e-Slider" %idt+="PX" +eig+t="RTP"> <param name=")inimum" value="E"> <param name=")a.imum" value="DE"> <% iC "'eJuest/"!!95F)8*;S"0 == null# 'esponse.3rite ""<param name=L"<alueL" value=L">L">LrLn"#& else 'esponse.3rite ""<param name=L"<alueL" value=L"" K 'eJuest/"!!95F)8*;S"0 K "L">LrLn"#& %> <param name=";rientation" value="<ertical"> <param name="8ac:Color" value="gains-oro"> <2o-6ect> <-r><-r> <input type="su-mit" value="9est" onserverclic:="S+o%9+um-*os" runat="server"> <-r><-r> <span id=";utput" runat="server" 2>

<2Corm> <2-ody> <2+tml> <script language="YavaScript"> Cunction Su-mitAorm "# $ )yAorm.!!95F)8*;S.value = )yAorm.Slider.value& return true& 1 <2script> <script language="C#" runat="server"> void S+o%9+um-*os ";-6ect senderB ?vent rgs e# $ ;utput.Inner9e.t = "Zou c+ose " K 'eJuest/"!!95F)8*;S"0& 1 <2script> $ow an I reate a 'ata9rid that displa/s a ol"mn of ima#es o!tained from a data!ase? The following %S&G file demonstrates how!

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SJlClient" %> <+tml> <-ody> <Corm runat="server"> <asp4Data,rid ID=")yData,rid" 'un t="server" uto,enerateColumns="Calse" Cell*adding="R" 8order3idt+="D" 8orderColor="lig+tgray" Aont7Name="<erdana" Aont7SiUe="Vpt" ,ridIines="vertical" 3idt+="DEE%"> <Columns> <asp49emplateColumn 5eader9e.t="*+oto" 5eaderStyle75oriUontal lign="center"> <Item9emplate> <center> <img src=G<%# "Nort+%indImage,ra--er.as+.Qid=" K Data8inder.?val "Container.DataItemB "?mployeeID"# %>G> <2center> <2Item9emplate> <2asp49emplateColumn> <asp48oundColumn 5eader9e.t="Iast Name" 5eaderStyle75oriUontal lign="center" DataAield="IastName" 2> <asp48oundColumn 5eader9e.t="Airst Name" 5eaderStyle75oriUontal lign="center" DataAield="AirstName" 2> <asp48oundColumn 5eader9e.t="9itle" 5eaderStyle75oriUontal lign="center" DataAield="9itle" 2> <2Columns> <5eaderStyle 8ac:Color="teal" AoreColor="%+ite" Aont78old="true" 2> <ItemStyle 8ac:Color="%+ite" AoreColor="dar:-lue" 2> < lternatingItemStyle 8ac:Color="-eige" AoreColor="dar:-lue" 2> <2asp4Data,rid> <2Corm> <2-ody>

<2+tml> <script language="C#" runat="server"> void *age!Ioad ";-6ect senderB ?vent rgs e# $ iC "HIs*ost8ac:# $ SJlConnection connection = ne% SJlConnection ""server=local+ost&data-ase=nort+%ind&uid=sa&p%d="#& try $ connection.;pen "#& SJlCommand command = ne% SJlCommand ""select employeeidB lastnameB CirstnameB title Crom employees"B connection#& SJlData'eader reader = command.?.ecute'eader "#& )yData,rid.DataSource = reader& )yData,rid.Data8ind "#& 1 Cinally $ connection.Close "#& 1 1 1 <2script>

This %S&G file contains a 7ata2rid that displays data from the Employees table of SR# Server4s Northwind database. Each row rendered by the 7ata2rid represents one employee, and each row4s leftmost column contains the employee4s picture. The picture comes from the table4s &hoto field. The image is rendered by the H temTemplateL tag, which emits an HimgL tag accompanied by a src attribute that points to a file named Northwind mage2rabber.ash=. nside the %S'G file is an 'TT& handler that retrieves an image from the database. % 6uery string appended to the C$# tells the handler which image to retrieve. 'ere4s Northwind mage2rabber.ash=4s source code!

<%@ 3e-5andler Ianguage="C#" Class="Image,ra--er" %> using using using using using using System& System.3e-& System.Dra%ing& System.Dra%ing.Imaging& System.Data.SJlClient& System.I;&

pu-lic class Image,ra--er 4 I5ttp5andler $ pu-lic void *rocess'eJuest "5ttpConte.t conte.t# $ string id = "string# conte.t.'eJuest/"id"0& iC "id H= null# $ )emoryStream stream = ne% )emoryStream "#& SJlConnection connection = ne% SJlConnection ""server=local+ost&data-ase=nort+%ind&uid=sa&p%d="#& 8itmap -itmap = null& Image image = null& try $ connection.;pen "#& SJlCommand cmd = ne% SJlCommand ""select p+oto Crom employees %+ere

employeeid=G" K

id K "G"B connection#& -yte/0 -lo- = "-yte/0# cmd.?.ecuteScalar "#& stream.3rite "-lo-B OVB -lo-.Iengt+ 7 OV#& -itmap = ne% 8itmap "stream#& 22 S+rin: t+e imageB -ut maintain its aspect ratio int %idt+ = XV& int +eig+t = "int# "%idt+ @ ""dou-le# -itmap.5eig+t 2 "dou-le# image = -itmap.,et9+um-nailImage "%idt+B +eig+tB Int*tr.[ero#&

-itmap.3idt+##& nullB

conte.t.'esponse.Content9ype = "image26peg"& image.Save "conte.t.'esponse.;utputStreamB ImageAormat.Ypeg#& 1 Cinally $ iC "image H= null# image.Dispose "#& iC "-itmap H= null# -itmap.Dispose "#& stream.Close "#& connection.Close "#& 1 1 1 pu-lic -ool Is'eusa-le $ get $ return true& 1 1

The Pro&ess,e1!est method, which is called every time the %S'G file is re6uested, retrieves the image from the database and returns it to the client as a @&E2. For good measure, it also shrinks the image down to thumbnail siOe using mage.6et"h!mbnail mage. Northwind mage2rabber.ash= discards the first F< bytes of each image because the Northwind database4s &hoto field doesn4t store raw imagesU it stores .+& bitmaps prefi=ed by F< bytes of unrelated header information.

Is it possi!le to write an ASP.NET handler that works like an ISAPI filter-that is> that sees re@"ests and responses and perhaps modifies them> too? Aou can do it by writing an 'TT& module1a class that implements HttpMod!le1and registering it in Web.config. 'ere4s a simple 'TT& module written in "3 that appends B'ello, worldB to every response!

using System& using System.3e-& pu-lic class )y)odule 4 I5ttp)odule $ pu-lic void Init "5ttp pplication application# $ application.?nd'eJuest K= ne% ?vent5andler

" pplication!?nd'eJuest#& 1 void pplication!?nd'eJuest ";-6ect sourceB ?vent rgs e# $ 5ttp pplication application = "5ttp pplication# source& 5ttpConte.t conte.t = application.Conte.t& conte.t.'esponse.3rite ""5elloB %orld"#& 1 pu-lic void Dispose "# $ 1

'ere4s how you register it if +y+odule is in an assembly named "ustom+odules!

<conCiguration> <system.%e-> <+ttp)odules> <add name=")y)odule" type=")y)oduleB Custom)odules" 2> <2+ttp)odules> <2system.%e-> <2conCiguration>

%n 'TT& module can handle the per1re6uest events fired by HttpAppli&ation instances, and it can fire events of its own that can be processed in 2lobal.asa=. To deploy the module, simply drop the 7## containing +y+odule into the application root4s bin subdirectory. $ow an ASP.NET apps transmit data from one pa#e to another? *ne way to transfer data from page to page is to have the sending page encode the data in a 6uery string and the receiving page read the data from the re6uest. 'ere4s the source code for a page named &age*ne.asp= that encodes a string typed by the user in a 6uery string and passes it to &ageTwo.asp=!

<H77 *age;ne.asp. 77> <+tml> <-ody> <Corm runat="server"> <asp49e.t8o. ID="Input" 'un t="server" 2> <asp48utton 9e.t="Ne.t*age" ;nClic:=";nNe.t*age" 'un t="server" 2> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> void ;nNe.t*age ";-6ect senderB ?vent rgs e# $ 'esponse.'edirect ""*age9%o.asp.QInput=" K Input.9e.t#& 1 <2script>

%nd here4s the page it redirects to, which echoes what the user typed!

<H77 *age9%o.asp. 77> <%@ *age Ianguage="C#" %> <+tml> <-ody> <% 'esponse.3rite ""Zou typed L"" K 'eJuest/"Input"0 K "L""#& %> <2-ody> <2+tml>

%nother way to pass data from one page to another11a techni6ue that has the added benefit of keeping the data on the server and not e=posing it to the user11is to pass the data in session state, as demonstrated here!

<H77 *age;ne.asp. 77> <+tml> <-ody> <Corm runat="server"> <asp49e.t8o. ID="Input" 'un t="server" 2> <asp48utton 9e.t="Ne.t*age" ;nClic:=";nNe.t*age" 'un t="server" 2> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> void ;nNe.t*age ";-6ect senderB ?vent rgs e# $ Session/"Input"0 = Input.9e.t& 'esponse.'edirect ""*age9%o.asp."#& 1 <2script> <H77 *age9%o.asp. 77> <%@ *age Ianguage="C#" %> <+tml> <-ody> <% 'esponse.3rite ""Zou typed L"" K Session/"Input"0 K "L""#& %> <2-ody> <2+tml>

f you use Server."rans)er rather than ,esponse.,edire&t to transfer control to another page, you can use public fields in the sending page4s code1behind class to transmit data. The following e=ample demonstrates how!

<H77 *age;ne.asp. 77> <%@ *age In+erits="*age;neClass" %> <+tml> <-ody> <Corm runat="server"> <asp49e.t8o. ID="Input" 'un t="server" 2> <asp48utton 9e.t="Ne.t*age" ;nClic:=";nNe.t*age" 'un t="server" 2> <2Corm> <2-ody> <2+tml> 22 *age;neClass.cs using System& using System.3e-.FI& using System.3e-.FI.3e-Controls& pu-lic class *age;neClass 4 *age $ pu-lic string !Input& protected 9e.t8o. Input& pu-lic void ;nNe.t*age ";-6ect senderB ?vent rgs e# $ !Input = Input.9e.t& Server.9ransCer ""*age9%o.asp."#& 1 1 <H77 *age9%o.asp. 77> <%@ *age Ianguage="C#" %> <+tml> <-ody> <% *age;neClass prevpage = "*age;neClass# Conte.t.5andler& 'esponse.3rite ""Zou typed L"" K prevpage.!Input K "L""#& %> <2-ody> <2+tml> $ow do I displa/ an ASP. or $TD4 pa#e in a new !rowser window in ASP.NET? The following tag creates a hyperlink that, when clicked, opens an %S&G file in a new window!

<asp45yperIin: 9e.t="3intellect +ome page" NavigateFrl="+ttp422%%%.%intellect.com2deCault.asp." 9arget="!ne%" 'un t="server" 2> $ow do I initiali?e a Te-t;o- whose Te-tDode is 6password6 with a password? Initiali?in# the Te-t;o-0s Te-t propert/ doesn0t seem to work.

This won4t work!

<asp49e.t8o. 9e.t="im-atman" 9e.t)ode="*ass%ord" ID="*ass%ord" 'un t="server" 2>

.ut this will!

<asp49e.t8o. 9e.t)ode="*ass%ord" ID="*ass%ord" 'un t="server" 2> <script language="C#" runat="server"> void *age!Ioad ";-6ect senderB ?vent rgs e# $ *ass%ord. ttri-utes. dd ""value"B "im-atman"#& 1 <2script>

The latter code fragment manually adds a valueKBimbatmanB attribute to the HinputL tag output by the "e#t$o# control, causing the specified te=t to appear in the "e#t$o#. Aou can also initialiOe a password "e#t$o# by including a -alue attribute in the control tag, as demonstrated below!

<asp49e.t8o. <alue="im-atman" 9e.t)ode="*ass%ord" ID="*ass%ord" 'un t="server" 2> I know I an write "stom ser)er ontrols !/ deri)in# from ,ontrol or We!,ontrol. ;"t an I modif/ the !eha)ior of e-istin# ontrols !/ deri)in# from them and modif/in# their o"tp"t? Aou bet. 'ere4s a custom control named 3!m"e#t$o# that derives from "e#t$o# and adds an on(eydown attribute to the HinputL tag that "e#t$o# outputs. That attribute references a local @avaScript function that filters out non1numeric keys, producing a "e#t$o# that accepts only numbers. For good measure, 3!m"e#t$o# senses the browser type and renders differently to nternet E=plorer and Netscape

Navigator, enabling it to work in either browser. t also overrides "e#t$o#4s Te=t property and implements a set accessor that throws an e=ception if a non1numeric string is written to it.

using System& using System.3e-.FI& using System.3e-.FI.3e-Controls& namespace 3intellect $ pu-lic class Num9e.t8o. 4 9e.t8o. $ string I?ClientScript8loc: = "<script language=L"6avascriptL">Ln" K "<H77Ln" K "var :eys = ne% rray "VB WB D>B >>B >XB >TB " K ">PB >OB >WB XTB XP#&Ln" K "Cunction is=ey<alid ":eyCode#Ln" K "$Ln" K " return "":eyCode >= XV NN :eyCode <= TO# MM " K "is u.=ey ":eyCode##&Ln" K "1Ln" K "Cunction is u.=ey ":eyCode#Ln" K "$Ln" K " Cor "i=E& i<:eys.lengt+& iKK#Ln" K " iC ":eyCode == :eys/i0#Ln" K " return true&Ln" K " return Calse&Ln" K "1Ln" K "77>Ln" K "<2script>"& string NetscapeClientScript8loc: = "<script language=L"6avascriptL">Ln" K "<H77Ln" K "Cunction is=ey<alid ":eyCode#Ln" K "$Ln" K " return "":eyCode >= XV NN :eyCode <= TO# MM " K ":eyCode == V MM :eyCode == D>#&Ln" K "1Ln" K "77>Ln" K "<2script>"&

pu-lic override string 9e.t $ get $ return -ase.9e.t& 1 set $ 22 )a:e sure value is numeric -eCore storing it Convert.9oIntPX "value#& -ase.9e.t = value& 1 1 e# protected override void ;n*re'ender "?vent rgs $

string -ro%ser = Conte.t.'eJuest.8ro%ser.9ype.9oFpper "#&

int version = Conte.t.'eJuest.8ro%ser.)a6or<ersion& iC "-ro%ser.Inde.;C ""I?"# > 7D NN version >= X# *age.'egisterClientScript8loc: ""Num9e.t8o.Script"B I?ClientScript8loc:#& else iC "-ro%ser.Inde.;C ""N?9SC *?"# > 7D NN version >= X# *age.'egisterClientScript8loc: ""Num9e.t8o.Script"B NetscapeClientScript8loc:#& 1 protected override void 'ender "5tml9e.t3riter %riter# $ string -ro%ser = Conte.t.'eJuest.8ro%ser.9ype.9oFpper "#& int version = Conte.t.'eJuest.8ro%ser.)a6or<ersion& iC "-ro%ser.Inde.;C ""I?"# > 7D NN version >= X# %riter. dd ttri-ute ""on:eydo%n"B "6avascript4return is=ey<alid "%indo%.event.:eyCode#"#& else iC "-ro%ser.Inde.;C ""N?9SC *?"# > 7D NN version >= X# %riter. dd ttri-ute ""on:eydo%n"B "6avascript4return is=ey<alid "event.%+ic+#"#& 1 1 1 -ase.'ender "%riter#&

'ere4s an %S&G file you can use to test the control. t assumes that the control is compiled into an assembly named NumTe=t.o="ontrol.

<%@ 'egister 9ag*reCi.="%in" Namespace="3intellect" ssem-ly="Num9e.t8o.Control" %> <+tml> <-ody> <Corm runat="server"> <%in4Num9e.t8o. runat="server" 2> <2Corm> <2-ody> <2+tml> Is it possi!le to asso iate hidden )al"es--sa/> )al"es from an identit/ field in a data!ase ta!le--with items in a 'ata9rid? Aou bet. @ust declare a $o!ndCol!mn in the .ata6rid and set its 7isible property to false, like so!

<asp48oundColumn DataAield="ItemID" <isi-le="Calse" 2>

The column won4t show up in the .ata6rid, but you4ll be able to read data from it following a postback Pust as if it were visible. $ow do I onfi#"re a 'ata9rid to show a ol"mn of row n"m!ers: F> E> %> G> and so on? The easiest way to do it is to use a "emplateCol!mn. The following %S&G file demonstrates how. The "emplateCol!mn displays the value of a rown!m field that is incremented each time a row is output.

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SJlClient" %> <+tml> <-ody> <Corm runat="server"> <asp4Data,rid ID=")yData,rid" uto,enerateColumns="Calse" 'un t="server"> <Columns> <asp49emplateColumn 5eader9e.t="Num-er" ItemStyle75oriUontal lign="center"> <Item9emplate> <%# ro%numKK %> <2Item9emplate> <2asp49emplateColumn> <asp48oundColumn 5eader9e.t="9itle" DataAield="title" 2> <2Columns> <5eaderStyle 5oriUontal lign="center" 2> <2asp4Data,rid> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> int ro%num = D& void *age!Ioad ";-6ect senderB ?vent rgs e# $ iC "HIs*ost8ac:# $ SJlData dapter adapter = ne% SJlData dapter " "select title Crom titles %+ere price H= E"B "server=local+ost&data-ase=pu-s&uid=sa" #& DataSet ds = ne% DataSet "#& adapter.Aill "ds#& )yData,rid.DataSource = ds& )yData,rid.Data8ind "#& 1 1 <2script> Is it possi!le to all Fill on a 'ataAdapter and fill two 'ataTa!les in a 'ataSet with a sin#le all? Aou bet. 'ere4s a sample that demonstrates how by performing a double 6uery and binding each of the resulting .ata"ables to a different .ata6rid.

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SJlClient" %> <+tml> <-ody> <Corm runat="server"> <asp4Data,rid ID="Data,ridD" 'un t="server" 2> <asp4Data,rid ID="Data,ridR" 'un t="server" 2> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> void *age!Ioad ";-6ect senderB ?vent rgs e# $ iC "HIs*ost8ac:# $ SJlData dapter adapter = ne% SJlData dapter " "select @ Crom titles& select @ Crom aut+ors"B "server=local+ost&data-ase=pu-s&uid=sa" #& DataSet ds = ne% DataSet "#& adapter.Aill "ds#& Data,ridD.DataSource = ds.9a-les/E0& Data,ridD.Data8ind "#& Data,ridR.DataSource = ds.9a-les/D0& Data,ridR.Data8ind "#& 1 1 <2script> I0m tr/in# to "se Ser)er.,reateB!:e t to instantiate a le#a / ,BD omponent in an ASP. pa#e. If I "se (;.NET> I an reate and all the ,BD o!:e t :"st fine. ;"t the same ode written in ,H doesn0t ompile. The ompiler omplains that the method I0m allin# isn0t a mem!er of B!:e t. What #i)es? Aou4ve discovered an interesting feature of -..NET11namely, that it trades type safety for simplicity when late binding to "*+ obPects. "heck out the following -..NET code sample, which instantiates a "*+ obPect (&rog 7KBWintellect.+athB, and calls its Add method to add 0 and 0!

Dim Sum s Integer Dim 3in)at+ s ;-6ect 3in)at+ = Server.Create;-6ect ""3intellect.)at+"# Sum = 3in)at+. dd "RB R#

This code works Pust fine, despite that fact that Add is not a member of System.-b8e&t. The -..NET compiler rela=es its type1checking rules to simplify your code. The "3 compiler, however, does not. The following code won4t compile!

;-6ect mat+ = Server.Create;-6ect ""3intellect.)at+"# int sum = 3in)at+. dd "RB R#

The solution for "3 programmers is to late1bind to the "*+ obPect using System."ype. nvo(eMember. 'ere4s the "3 e6uivalent of the -..NET code above!

9ype t = 9ype.,et9ypeArom*rogID ""3intellect.)at+"#& ;-6ect mat+ = Server.Create;-6ect "t#& ;-6ect/0 args = $ RB R 1& int sum = "int# t.Invo:e)em-er "" dd"B 8indingAlags.Invo:e)et+odB nullB mat+B args#&

t4s not pretty, but it works, and it perfectly illustrates the e=tra effort re6uired to accomplish late binding in "3. I0m tr/in# to "se ASP.NET0s $tmlInp"tFile ontrol to "pload files to a We! ser)er> !"t the ontrol0s PostedFile propert/ is alwa/s n"llIe)en after I sele t a file and post !a k to the ser)er. What am I doin# wron#? +ost likely you forgot to include an en&typeKBmultipart)form1dataB attribute in your HformL tag. The following 'T+# form doesn4t support file uploads!

<Corm runat="server"> <input type="Cile" id=")yAile" runat="server" 2> <2Corm>

.ut the ne=t one does. 7ecorate the HformL tag as shown here and file uploads will work Pust fine!

<Corm enctype="multipart2Corm7data" runat="server">

<input type="Cile" id=")yAile" runat="server" 2> <2Corm>

ASP.NET0s 3 B"tp"t,a he dire ti)e lets me a he different )ersions of a pa#e !ased on )ar/in# inp"t parameters> $TTP headers> and !rowser t/pes. I0d also like to !e a!le to a he !ased on )ar/in# session I's. Is that possi!le? Aou bet. 'ere4s a sample page that uses a 7ary$yC!stom attribute to cache different versions of a page based on session 7s!

<%@ *age Ianguage="C#" %> <%@ ;utputCac+e Duration="DE" <ary8y*aram="None" <ary8yCustom="SessionID" %> <+tml> <-ody> <% Session/")yData"0 = "Aoo"& 22 )a:e t+e session persistent 'esponse.3rite ""Zour session ID is " K Session.SessionID#& 'esponse.3rite ""<-r>"#& 'esponse.3rite ""9+e current time is " K Date9ime.No%.9oIong9imeString "##& %> <2-ody> <2+tml>

n order for 7ary$yC!stomKBSession 7B to work, you must include in the application root a 2lobal.asa= file containing the following 6et7ary$yC!stomString method!

<script language="C#" runat="server"> pu-lic override string ,et<ary8yCustomString "5ttpConte.t conte.tB string arg# $ iC "arg.9oIo%er "# == "sessionid"# $ 5ttpCoo:ie coo:ie = conte.t.'eJuest.Coo:ies/" S*.N?9!SessionId"0& iC "coo:ie H= null# return coo:ie.<alue& 1 return -ase.,et<ary8yCustomString "conte.tB arg#& 1 <2script>

6et7ary$yC!stomString is a mechanism for e=tending %S&.NET4s page output cache. This implementation of 6et7ary$yC!stomString, which overrides the one inherited from HttpAppli&ation, responds to a 7ary$yC!stomKBSession 7B attribute in an J -!tp!tCa&he directive by returning the current session 7, if present. %S&.NET responds by caching different versions of the page if the session 7s differ. Note that 6et7ary$yC!stomString e=tracts the session 7 from the session cookie, not from the session4s Session . property. That4s because the re6uest has yet to

be associated with a session when 6et7ary$yC!stomString is called. %n unpleasant side effect is that this techni6ue doesn4t work with cookieless session state. %lso note that the page won4t be cached until a user re6uests the page for the second time, because the first re6uest lacks a valid session cookie. I0)e noti ed that 'ata9rids ro"nd-trip tons of information in )iew state> de reasin# the effe ti)e !andwidth of the onne tion. Is there an/thin# I an do to red" e the 'ata9rid0s )iew state "sa#e? Aou bet. Set the .ata6rid0s /nable7iewState property to false, as shown here!

<asp4Data,rid 'un t="server" ?na-le<ie%State="Calse" ... 2>

*nce you make this change, you4ll also have to reinitialiOe the .ata6rid in every re6uest (even during postbacks,, because the .ata6rid will no longer retain its state across postbacks. n other words, instead of doing this!

void *age!Ioad ";-6ect senderB ?vent rgs e# $ iC "HIs*ost8ac:# $ 22 9;D;4 InitialiUe t+e Data,rid 1 1

7o this!

void *age!Ioad ";-6ect senderB ?vent rgs e# $ 22 9;D;4 InitialiUe t+e Data,rid 1

The performance you lose may be more than compensated for by the effective bandwidth you gain11especially if instead of 6uerying a database on every re6uest, you 6uery once, cache the data, and initialiOe the .ata6rid from the cache. Is it possi!le to reate a 'ata9rid that "ses s rollin# rather than pa#in# to pro)ide a ess to a lon# list of items? With a little help from a HdivL tag, yes. The following %S&G file displays the B&roductsB table of SR# Server4s Northwind database in a scrolling table!

<%@ Import Namespace="System.Data.SJlClient" %> <+tml> <-ody> <Corm runat="server"> <div style="+eig+t4 RTPp.& overClo%4 auto"> <asp4Data,rid ID=")yData,rid" 3idt+="DEE%" 'un t="server" 2> <2div> <2Corm> <2-ody> <2+tml> <script language="C#" runat="server"> void *age!Ioad ";-6ect senderB ?vent rgs e# $ iC "HIs*ost8ac:# $ SJlConnection connection = ne% SJlConnection ""server=local+ost&data-ase=nort+%ind&uid=sa"#& try $ connection.;pen "#& SJlCommand command = ne% SJlCommand ""select @ Crom products"B connection#& SJlData'eader reader = command.?.ecute'eader "#& )yData,rid.DataSource = reader& )yData,rid.Data8ind "#& 1 Cinally $ connection.Close "#& 1 1 1 <2script> ;/ defa"lt> ASP.NET0s worker pro ess "ses the identit/ of a spe ial a o"nt named ASPNET that0s reated when ASP.NET is installed. ;/ in l"din# a "ser name and password in Da hine. onfi#0s element> I an onfi#"re ASP.NET to r"n "sin# an a o"nt of m/ hoosin#. $owe)er> m/ ompan/ has a stri t poli / a#ainst en odin# plainte-t passwords in onfi#"ration files. I want to spe if/ the a o"nt that ASP.NET "ses> !"t I also need to se "re the password. Is that possi!le? *ut of the bo=, %S&.NET E.9 re6uires the user name and password to be encoded in plainte=t in +achine.config. 'owever, you can obtain a patch from +icrosoft that allows the user name and password to be stored in encrypted form in a secure registry key that4s off limits to non1administrators. The hotfi= also allows you to secure the credentials used to access %S&.NET4s %S&State database when using SR# Server to store session state. Aou4ll find instructions for obtaining the hotfi= (and information about a helper utility that encrypts user names and passwords for you, at http!))support.microsoft.com)default.asp=QscidKkbUen1usUR/0;0>9. +icrosoft plans to build the hotfi= into the BEverettB release of the .NET Framework, which will ship with Windows .NET Server. .e aware, however, that Windows .NET Server comes with S ?.9, which supports an alternative means for securing process credentials. %pplications can be assigned to arbitrary application pools, and application pools can be assigned uni6ue identities using encrypted credentials stored in the S metabase. %s +icrosoft security guru Erik *lsen recently noted, this is probably the better long1term direction for companies whose policies prevent them from storing plainte=t credentials in "*NF 2 files.

I want to make 'ata9rid pa#in# more effi ient !/ "sin# "stom pa#in#. Bra le makes "stom pa#in# eas/ !/ s"pportin# @"er/-!/-row-n"m!er. SQ4 Ser)er is :"st the opposite. There0s no o!)io"s wa/ to ask SQ4 Ser)er for> sa/> rows F&F-FA& in a A&&-row res"lt set. What0s the !est wa/ to do "stom pa#in# when /o" ha)e SQ4 Ser)er on the !a k end? Aou can use a 6uery of the following form to retrieve records by row number from +icrosoft SR# Server!

S?I?C9 @ A';) "S?I?C9 9;* $E1 @ A';) "S?I?C9 9;* $D1 @ A';) $R1 ;'D?' 8Z $>1# S tD ;'D?' 8Z $>1 D?SC# S tR ;'D?' 8Z $>1

$eplace V9W with the page siOe (the number of records displayed on each page,, VEW with the page siOe S page number (E1based,, V0W with the name of the table you wish to 6uery, and V/W with a field name. The following e=ample retrieves rows :E1>9 from the B&roductsB table of the Northwind database!

S?I?C9 @ A';) "S?I?C9 9;* DE @ A';) "S?I?C9 9;* TE @ A';) *roducts ;'D?' 8Z *roductID# S tD ;'D?' 8Z *roductID D?SC# S tR ;'D?' 8Z *roductID

Aou can combine this 6uery techni6ue with custom paging to make 7ata2rid paging more efficient. With default paging, you must initialiOe the data source with all records displayed on all pages. With custom paging, you can initialiOe the data source with Pust those records that pertain to the current page. Is it possi!le to pre)ent a We! form from s rollin# to the top of the pa#e when it posts !a k to the ser)er? *ne way to do it is to add a Smart3avigation9:tr!e: attribute to the page4s @ Page directive. That re6uires nternet E=plorer >.9 or higher on the client. To prevent unwanted scrolling in a wider range of browsers, you can use a server1 side script that generates client1side script. The first step is to replace the page4s HbodyL tag with the following statements!

<%

iC "'eJuest/"!!SC';II*;S"0 H= null NN 'eJuest/"!!SC';II*;S"0 H= String.?mpty# $ int pos = Convert.9oInt>R "'eJuest/"!!SC';II*;S"0#& 'esponse.3rite ""<-ody id=L"t+e8odyL" " K "onscroll=L"6avascript4document.Corms/E0.!!SC';II*;S.value = " K "t+e8ody.scroll9op&L" " K "onload=L"6avascript4t+e8ody.scroll9op=" K pos K "&L">"#& 1 else $ 'esponse.3rite ""<-ody id=L"t+e8odyL" " K "onscroll=L"6avascript4document.Corms/E0.!!SC';II*;S.value =" K

1 %>

"t+e8ody.scroll9op&L">"#&

Step two is to add the following line somewhere between the Hform runatKBserverBL and H)formL tags!

<input type="+idden" name="!!SC';II*;S" value="" 2>

'ow does it workQ The server1side script block outputs a HbodyL tag containing an ons&roll attribute that keeps tabs on the scroll position and an onload attribute that restores the last scroll position following a postback. The scroll position is transmitted to the server in a hidden HinputL control named NNS"$*##&*S. Note that this techni6ue is compatible with nternet E=plorer but not with Netscape Navigator. If I "se the same "ser ontrol in two different pa#es and in l"de an 3 B"tp"t,a he dire ti)e in the AS,. file> will the "ser ontrol !e a hed on e or twi e? n %S&.NET version E.9, the control will be cached twice. n version E.E, you can include a Shared9:tr!e: attribute in the @ -!tp!tCa&he directive to cache the control Pust once. What0s the !est so"r e of in-depth information on ASP.NET se "rit/? 2o to http!))www.microsoft.com)downloads)release.aspQ$elease 7K::9:F and download a free book (in &7F format, from +icrosoft entitled B.uilding Secure %S&.NET %pplications.B %t ?9< pages, it4s packed with more than you4ll probably ever need to know about %S&.NET security. %n awesome resource for %S&.NET developers5 $ow do I set the fo "s to a spe ifi ontrol when a We! form loads?

With a dash of client1side script. Cpon loading, the following page sets the focus to the first of its three Te=t.o= controls!

<+tml> <-ody> <Corm runat="server"> <asp49e.t8o. ID="9e.t8o.D" 'un t="server" 2><-r> <asp49e.t8o. ID="9e.t8o.R" 'un t="server" 2><-r> <asp49e.t8o. ID="9e.t8o.>" 'un t="server" 2> <2Corm> <2-ody> <2+tml> <script language="6avascript"> document.Corms/E0.9e.t8o.D.Cocus "#& <2script> Is it possi!le to post a pa#e ontainin# a r"nat56ser)er6 form to a pa#e other than itself? Addin# an a tion attri!"te to the 1form8 ta# is f"tile !e a"se ASP.NET o)errides it with an a tion attri!"te that points !a k to the same pa#e.

%S&.NET forbids a r!nat9:server: form from posting back to another page, but you may be able to accomplish what you4re after by taking a slightly different approach. t turns out that if you remove r!nat9:server: from the HformL tag, %S&.NET won4t alter the tag4s a&tion attribute. The bad news is that a form lacking a r!nat9:server: attribute can4t host Web controls. The good news is that it &an host 'T+# controls, which means that if you can do without .ata6rids and other rich controls, you can post back to other pages Pust fine. The following page contains a login form that hosts three 'T+# controls. Note the r!nat9:server: attributes adorning the controls but the absence of r!nat9:server: in the HformL tag!

<+tml> <-ody> <Corm action="3elcome.asp."> <ta-le cellpadding="V"> <tr> <td>Fser Name4<2td> <td><input type="te.t" ID="FserName" runat="server" 2><2td> <2tr> <tr> <td>*ass%ord4<2td> <td><input type="pass%ord" ID="*ass%ord" runat="server" 2><2td> <2tr> <tr> <td><2td> <td><input type="su-mit" value="Iog In" runat="server" 2><2td> <2tr> <2ta-le> <2Corm> <2-ody> <2+tml>

"licking the #og n button submits the form to Welcome.asp=, which reads the user name that the user typed from the 'TT& re6uest and outputs it to the page. 'ere4s Welcome.asp=!

<+tml> <-ody> <+D><asp4Ia-el ID=";utput" 'un t="server" 2><2+D> <2-ody> <2+tml> <script language="C#" runat="server"> void *age!Ioad ";-6ect senderB ?vent rgs e# $ ;utput.9e.t = "5elloB " K 'eJuest/"FserName"0& 1 <2script>

7o the r!nat9:server: attributes on the HinputL tags do anything usefulQ Aou bet. They make the controls visible to server1side scripts.

When onfi#"red to store session state in a SQ4 Ser)er data!ase> ASP.NET stores sessions in the Tempd! data!ase> whi h means sessions are lost if the data!ase ser)er is re!ooted. Is it possi!le to onfi#"re ASP.NET to store session in the ASPState data!ase instead for added ro!"stness? Aou bet. $ead +icrosoft 8nowledge .ase article /EE09;, which is titled B"onfigure %S&.NET for &ersistent SR# Server Session State +anagementB and located at http!))support.microsoft.com)default.asp=QscidKkbUEN1CSU6/EE09;. The article contains a link for downloading nstall&ersistS6lState.s6l, an installation script that creates the %S&State database and configures it to store session data in %S&State tables rather than Tempdb tables. This simple configuration change enables session state to survive server restarts and is a boon for small1 and medium1siOe sites that can4t Pustify building clustered arrays of database servers on the back end. I0m "sin# an 1error8 element in We!. onfi# to redire t to a "stom error pa#e when a G&G error o "rs. Inside the error pa#e> I want to retrie)e the <=4 that a"sed the G&G error so I an write it to a lo# file. $ow do I #et that <=4? When %S&.NET redirects to a custom error page, it passes the original C$# (the one that caused the error, in a 6uery string. 'ere4s an e=ample in which &ageNotFound.asp= is the custom error page and foo.asp= is the page that produced the error! http!))localhost)&ageNotFound.asp=Qasp=errorpathK)foo.asp= &ageNotFound.asp= can therefore obtain the C$# of the page that generated the error (in your case, the none=istent page that resulted in a :9: error, like this!

string -adurl = 'eJuest/"asp.errorpat+"0&

f you4d like to retrieve the & address from which the re6uest originated for logging purposes as well, read it from ,e1!est.Server7ariablesXB$E+*TEN%77$BY or ,e1!est.UserHostAddress. $ow does S/stem.We!.<I.Pa#e0s IsPost;a k propert/ work? $ow does it determine whether a re@"est is a post!a k? sPost$a&( checks to see whether the 'TT& re6uest is accompanied by postback data containing a NN- EWST%TE or NNE-ENTT%$2ET parameter. No parameters, no postback.

También podría gustarte