Hidden Gems in ASP'NET - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Hidden Gems in ASP'NET

Description:

... zipped or obfuscated format. Magic provided by virtual path providers ... Custom partition resolvers enable session state to be partitioned using custom logic ... – PowerPoint PPT presentation

Number of Views:76
Avg rating:3.0/5.0
Slides: 31
Provided by: downloadM
Category:
Tags: asp | net | gems | hidden | magic | partition

less

Transcript and Presenter's Notes

Title: Hidden Gems in ASP'NET


1
Hidden Gems in ASP.NET
2
Agenda
  • Virtual path providers
  • Client callbacks
  • Custom expression builders
  • Custom build providers
  • Encrypted configuration sections
  • Session state partitioning and more

3
Virtual 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
4
Custom 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) ...
5
Change 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

6
File 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")
7
What 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

8
Virtual Path Providers
9
Client 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

10
Executing 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)
11
Receiving 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.
12
Client Callbacks
13
Expression 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

14
Custom Expression Builder
public class MyExpressionBuilder
ExpressionBuilder public override
CodeExpression GetCodeExpression
(BoundPropertyEntry entry, object parsedData,
ExpressionBuilderContext context)
// TODO Return CodePrimitiveExpression
containing // evaluated expression
15
Registering 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")
16
Custom Expression Builders
17
Build 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

18
Custom Build Provider
public class MyBuildProvider BuildProvider
public override void GenerateCode(AssemblyBuilder
builder) // TODO Generate code
using AssemblyBuilder
19
Registering 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")
20
Custom Build Providers
21
Session 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

22
Partitioning at Work
No partitioning
2-way partitioning
Load divided between two session-state databases
One session-state database bears the full load
23
Custom 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
24
Registering DualPartitionResolver
ltconfigurationgt ltsystem.webgt ltsessionState
mode"SQLServer" partitionResolverType"Dua
lPartitionResolver" /gt lt/system.webgt lt/confi
gurationgt
Replaces sqlConnectionString attribute
25
Encrypted 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

26
Encrypting 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
27
App_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
28
ltdeploymentgt
  • 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
29
Global 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
30
Discussion
Write a Comment
User Comments (0)
About PowerShow.com