Title: Hidden Gems in ASP'NET
1Hidden Gems in ASP.NET
2Agenda
- Virtual path providers
- Client callbacks
- Custom expression builders
- Custom build providers
- Encrypted configuration sections
- Session state partitioning and more
3Virtual Path Providers
- Virtualize browseable resources
- Store pages in a database
- Store pages in zipped or obfuscated format
- Magic provided by virtual path providers
- Derive from VirtualPathProvider
- Register with HostingEnvironment.-RegisterVirtualP
athProvider
http//msdn2.microsoft.com/en-us/library/Aa479502.
aspx
4Custom Virtual Path Provider
public class MyVirtualPathProvider
VirtualPathProvider public static void
AppInitialize() HostingEnvironment.R
egisterVirtualPathProvider (new
MyVirtualPathProvider()) public
override bool FileExists(string virtualPath)
... public override bool
DirectoryExists(string virtualDir) ...
public override VirtualFile GetFile(string
virtualPath) ... public override
VirtualDirectory GetDirectory(string
virtualDir) ...
5Change Detection
- VirtualPathProvider.GetFileHash
- Returns hash representing current state
- New hash triggers recompilation
- Called after every call to GetFile, unless
- VirtualPathProvider.GetCacheDependency
- Returns cache-dependency object
- e.g., SqlCacheDependency or custom
CacheDependency derivative - More efficient than GetFileHash
6File References
- Code that opens files must be fixed up if the
referenced files are virtual, too - Use VirtualPathProvider.OpenFile in lieu of
System.IO methods
// Change this... Stream stream
File.Open("Settings.xml", FileMode.Open) // To
this Stream stream VirtualPathProvider.OpenFile(
"Settings.xml")
7What Can Be Virtualized?
- Browseable resources can be virtualized
- Directories
- ASPX, ASCX, and ASMX files
- App_Themes folder and SKIN files
- CSS, JS, and image files if mapped to ASP.NET
- Non-browseable resources cannot
- Web.config and Global.asax files
- App_Code, App_Data, and Bin folders
8Virtual Path Providers
9Client Callbacks
- GetCallbackEventReference
- Returns name of JavaScript function that launches
XML-HTTP request - ICallbackEventHandler
- Implemented by pages targeted by callbacks
- RaiseCallbackEvent method called first
- GetCallbackResult method called second
- Used by GridView and other controls to implement
AJAX functionality
10Executing a Client Callback
void Page_Load (Object sender, EventArgs e)
string cb ClientScript.GetCallbackEventReference
(this, "argument", "onCallbackCompleted",
String.Empty, true) // TODO
Return JavaScript that calls cb and //
JavaScript that includes onCallbackCompleted
... // Client-side script function
onCallbackCompleted (result, context)
window.alert(result)
11Receiving a Client Callback
public void RaiseCallbackEvent(string arg)
// TODO Begin processing callback
asynchronously // (e.g., launch an
asynchronous ADO.NET query or // call a Web
service asynchronously). "arg" is the //
"argument" string passed to GetCallbackEvent-
// Reference. public string GetCallbackResult()
// TODO Return string containing callback
result // (up to you to do any serialization
required). // String returned here is the
"result" parameter // passed to
onCallbackCompleted.
12Client Callbacks
13Expression Builders
- Magic behind "" expressions
- lt AppSettings gt
- lt ConnectionStrings gt
- lt Resources gt
- Use custom expression builders to extend parsing
engine with custom expressions - Derive from ExpressionBuilder
- Override GetCodeExpression method
14Custom Expression Builder
public class MyExpressionBuilder
ExpressionBuilder public override
CodeExpression GetCodeExpression
(BoundPropertyEntry entry, object parsedData,
ExpressionBuilderContext context)
// TODO Return CodePrimitiveExpression
containing // evaluated expression
15Registering an Expression Builder
ltsystem.webgt ltcompilationgt
ltexpressionBuildersgt ltadd
expressionPrefix"Expression"
type"MyExpressionBuilder" /gt
lt/expressionBuildersgt lt/compilationgt lt/system.we
bgt
expression (e.g., "Resources")
16Custom Expression Builders
17Build Providers
- Classes that generate code from ASPXes, ASCXes,
ASMXes, and other resources - See ltbuildProvidersgt section of master web.config
file - Use custom build providers to extend ASP.NET to
support new build types - Derive from BuildProvider
- Override GenerateCode method
18Custom Build Provider
public class MyBuildProvider BuildProvider
public override void GenerateCode(AssemblyBuilder
builder) // TODO Generate code
using AssemblyBuilder
19Registering a Build Provider
ltsystem.webgt ltcompilationgt
ltbuildProvidersgt ltadd extension"Extension"
type"MyBuildProvider" /gt lt/buildProvidersgt
lt/compilationgt lt/system.webgt
File name extension (e.g., ".xdc")
20Custom Build Providers
21Session State Partitioning
- By default, all out-of-proc session state for a
given app is stored in one place - sqlConnectionString/stateConnectionString
- Custom partition resolvers enable session state
to be partitioned using custom logic - IPartitionResolver interface
- partitionResolverType config attribute
- Great for distributing load among several
session-state database servers
22Partitioning at Work
No partitioning
2-way partitioning
Load divided between two session-state databases
One session-state database bears the full load
23Custom Partition Resolver
public class DualPartitionResolver
IPartitionResolver private string
_partitions "Data Source69.21.119.191
Integrated SecuritySSPI", "Data
Source69.21.119.192Integrated SecuritySSPI"
public void Initialize() public
string ResolvePartition(object key)
int index key.GetHashCode()
_partitions.Length return
_partitionsindex
24Registering DualPartitionResolver
ltconfigurationgt ltsystem.webgt ltsessionState
mode"SQLServer" partitionResolverType"Dua
lPartitionResolver" /gt lt/system.webgt lt/confi
gurationgt
Replaces sqlConnectionString attribute
25Encrypted Configuration Sections
- ASP.NET allows most configuration sections to be
encrypted - Triple-DES using autogenerated key
- RSA using public/private keys
- Other algorithms via custom providers
- Two ways to encrypt
- Aspnet_regiis.exe
- SectionInformation.ProtectSection
- Encryption is transparent to applications
26Encrypting ltconnectionStringsgt
aspnet_regiis pef connectionStrings
c\websites\whidbeyrocks
ltconnectionStringsgt ltremove name"LocalSqlServer
" /gt ltadd name"LocalSqlServer"
connectionString"ServerlocalhostIntegrated
SecurityTrueDatabaseaspnetdb..." /gt ltadd
name"WhidbeyRocksConnectionString"
connectionString"Data Source(local)Initial
CatalogWhidbeyRocksIntegrated SecurityTrue"
providerName"System.Data.SqlClient"
/gt lt/connectionStringsgt
Before
ltconnectionStringsgt ltEncryptedData
Type"http//www.w3.org/2001/04/xmlencElement"
xmlns"http//www.w3.org/2001/04/xmlenc"gt
ltEncryptionMethod Algorithm"http//www.w3.org/200
1/04/xmlenctripledes-cbc" /gt ltKeyInfo
xmlns"http//www.w3.org/2000/09/xmldsig"gt
... lt/KeyInfogt ltCipherDatagt
ltCipherValuegtkxxLhiRQrNlloq0YLYAr2FycMt1hMbEqnguP
n1UTSbcK4BMUprnAjWq5nhZk...lt/CipherValuegt
lt/CipherDatagt lt/EncryptedDatagt lt/connectionStrin
gsgt
After
27App_offline.htm
- When present, disables ASP.NET application in
host directory - Requests for pages return content in
app_offline.html - Restarts app when removed
lthtmlgt ltbodygt lth1gtUnder constructionlt/h1gt
lt/bodygt lt/htmlgt
28ltdeploymentgt
- Configures production servers for security
- ltcompilation debug"false" /gt
- ltcustomErrors mode"RemoteOnly" /gt
- lttrace enabled"false" /gt
- Settings can't be overridden in Web.config
- Valid only in Machine.config
ltsystem.webgt ltdeployment retail"true"
/gt ltsystem.webgt
29Global Control Registration
- Custom controls and user controls must be
declared in pages that use them - In ASP.NET 2.0 and higher, controls can be
registered globally in Web.config
ltsystem.webgt ltpagesgt ltcontrolsgt ltadd
tagPrefix"user" tagName"Widget"
src"/UserControls/WidgetControl.ascx" /gt
lt/controlsgt lt/pagesgt ltsystem.webgt
30Discussion