| Swaps 的个人资料Swaps Blog照片日志 | 帮助 |
|
5月30日 ASP.NET 2.0 Deployment Common ConsiderationsFolks,
Some of the common considerations which we come across while deploying ASP.NET 2.0 Applications is on which method to follow for deployment, or how to create the Single dll file like VS .NET 2003 Pattern etc. I will address some of the deployment considerations in this article
Regarding the previous ages of VS.NET 2003, web project deployment was pretty simple, but with limited options. For different types of projects, you may have different types of deployment requirements. For example, you may wish only to update the dll or contents for each component of the project separately, specially if the project is too big to take much time to upload the components each time. For smaller projects, it would be great if we can upload only one file to reflect the new changes of a project.
In the age of VS.NET 2005, I found that there several options have been offered to developers, initially which may make the developers confused. Basically there are two basic issues which should be considered at the top level of deployment design. One is content based and the another one is assembly based. When publishing a web site, there are two options are in place in this issue, which are being discussed here respectively.
1. Allow this precompiled site to be updatable
In ASP.NET deployment, we can put the aspx files in corresponding locations, just as a place holder, where the contents will be placed in the corresponding .compile file in the bin folder, which can be enabled by making this option false. In that case, the following issues should be reminded:
a. .compile file and the corresponding file should be placed for each update of a given aspx, master file. If there is only change is code-behind class (i.e. code), this file should be included too.
b. For code change in App_Code, no need to copy App_Code.compiled, just copy App_Code.dll ( so far I learned!). c. For code change in Global.asax, no need to copy App_global.asax.compiled, just copy App_global.asax.dll ( so far I learned!). d. For changes in CSS files of App_themes CSS should be copied manually. (I don't have tested image and skin files yet!). Any way, if this option is true, the deployment still requires .compiled file, but not for the pages, but for App_Code folder, App_global.asax files, which will be used as a resource locator. So any changes to these contents doesn't require to upload this files for the maximum time. I am not sure when the updated version of these files should be deployed, but to deploy the updated version of these files is a recommended practice! 2. Use fixed naming and single page assemblies
For deploying assemblies of a ASP.NET 2.0 projects there are three ways to do:
a. Single page assembly:
In Visual Studio 2005, for a ASP.NET 2.0 web application, we can deploy separate assemblies for each pages of the site! This can be done by enabling the above option.
If the ' Allow this precompiled site to be updatable' is disabled, that means a corresponding .compile file should also be deployed with the assembly of each page. In this case, if there is any change in the content (i.e. text etc) of the page, we need not to deploy the updated .compile file in the web, as all contents are placed in the dll, but as the resource locator or for the basic rule, Atlas one version of .compile file should be placed in the bin directory of the deployment site. Any way, no matter, whether the change has been done in content or code, the page dll MUST be deployed! For a change in content, if only .compiled is provided, there is no error, but change will not take effect!
b. Batch assembly:
For different type of contents and codes, different sets of assemblies will be generated, if we make the above option false. So any change in the code of a page, requires the corresponding set of assemblies to be deployed. For aspx pages, there are few assemblies will be generated, with ' App_Web' prefix. Since, we don't know, Exactly which ' App_Web..' assembly belongs the code for the updated page, we need to deploy all the assemblies prefixed ' App_Web' if there is any change of a page.
For batch assembly, each dll includes a encrypted key in it's name (for instance App_Web_pr_login.aspx.16ec59e1.dll), and for separate web publishing, there are separate keys for the same type of contents, thus separate file name for the newer version. One interesting thing about these assemblies is, newer version of assemblies can reside in the same deployment directory with the previous set of versions, without any conflict, and the newer version will automatically take place during execution of the corresponding content!
Also, if the 'Allow this precompiled site to be updatable' is disabled, and no updated version of .compile file is provided for the change on content side of the page, only deployment of the assemblies will not reflect the change in content side, unlike "Single page assembly" deployment. For change in the content side, both assembly and .compiled file MUST be deployed.
c. Merged assembly:
All of the coding contents can be embeded to a single assembly, like VS 2003 age, using a VS add-in named 'aspnet_merge.exe' provided by Microsoft. Unfortunately, this tool is not provided by default and should be downloaded and installed separately.
Swapnil (Swaps)
Pre-Compilation ToolPre-compilation Tool. ASP.NET 2.0 delivers a new application deployment utility that enables both developers and administrators to precompile a dynamic ASP.NET application prior to deployment. This precompilation automatically identifies any compilation issues anywhere within the site, as well as enables ASP.NET applications to be deployed without any source being stored on the server (one can optionally remove the content of .aspx files as part of the compile phase), further protecting your intellectual property.
ASP.NET Compilation Tool (Aspnet_compiler.exe) The ASP.NET Compilation tool (Aspnet_compiler.exe) enables you to compile an ASP.NET Web application, either in place or for deployment to a target location such as a production server. In-place compilation helps application performance because end users do not encounter a delay on the first request to the application while the application is compiled. Compilation for deployment can be performed in one of two ways: one that removes all source files, such as code-behind and markup files, or one that retains the markup files.
aspnet_compiler [-?] [-m metabasePath | -v virtualPath [-p physicalPath]] [[-u] [-f] [-d] [-fixednames] targetDir] [-c] [-errorstack] [-nologo] [[-keyfile file | -keycontainer container ] [-aptca] [-delaysign]]
The ASP.NET Compilation tool can be used in two general ways: for in-place compilation and compilation for deployment, where a target output directory is specified.
Compiling an Application in PlaceThe ASP.NET Compilation tool can compile an application in place, that is, it mimics the behavior of making multiple requests to the application, thus causing regular compilation. Users of a precompiled site will not experience a delay caused by compiling the page on first request. Note that if you are using an impersonated account, both the account and the logon user account must have write access to the target for precompilation to succeed. When you precompile a site in place, the following items apply: · The site retains its files and directory structure. · You must have compilers for all programming languages used by the site on the server. · If any file fails compilation, the entire site fails compilation. You can also recompile an application in place after adding new source files to it. The tool compiles only the new or changed files unless you include the -c option.
Compiling an Application for DeploymentYou compile an application for deployment (compilation to a target location) by specifying the targetDir parameter. The targetDir can be the final location for the Web application, or the compiled application can be further deployed. Using the -u option compiles the application in such a way that you can make changes to certain files in the compiled application without recompiling it. Aspnet_compiler.exe makes a distinction between static and dynamic file types, and handles them differently when creating the resulting application. Static file types are those that do not have an associated compiler or build provider, such as files whose names have extensions such as .css, .gif, .htm, .html, .jpg, .js and so on. These files are simply copied to the target location, with their relative places in the directory structure preserved. Dynamic file types are those that have an associated compiler or build provider, including files with ASP.NET-specific file name extensions such as .asax, .ascx, .ashx, .aspx, .browser, .master, and so on. The ASP.NET Compilation tool generates assemblies from these files. If the -u option is omitted, the tool also creates files with the file name extension .COMPILED that map the original source files to their assembly. To ensure that the directory structure of the application source is preserved, the tool generates placeholder files in the corresponding locations in the target application. You must use the -u option to indicate that the content of the compiled application can be modified. Otherwise, subsequent modifications are ignored or cause run-time errors.
Swapnil (Swaps) 5月29日 Gmail Like Loading IndicatorFolks,
Would like to share wonderfull article on Hot to make a Gmail Like Loading Indicator in you ASP.NET page with the help of Ajax. Find the below like which covers the complete article and download the source code for the same
Swapnil (Swaps)
Web Site Administration Tool ASP.NET 2.0Web Site Administration Tool One of the new features for web developers in Visual Studio 2005 is a graphical administration tool for configuring common application and security settings for your web sites. The Web site Administration tool allows you to perform the following configuration tasks:
Configure application security, including authentication and authorization settings Manage users and roles for your application Create or manage application settings Configure SMTP e-mail settings Take an application temporarily offline, to allow reliable updates of content and data Adjust debugging and tracing settings Define a default custom error page Select providers for use with site features such as membership
The Web Application Administration tool is available with all versions of Visual Studio 2005, and from Visual Studio 2005 Express Edition. To open the administration tool from a web site project, select ASP.NET Configuration from the Website menu.
Web Site Configuration
Web site configuration settings are stored in an XML file named Web.config, which is located in the root folder of the Web site. The Web Site Administration Tool lets you change your site configuration without having to manually edit the Web.config file. The first time that you use the Web Site Administration Tool to administer a specific Web site, if no Web.config file exists, the Web Site Administration Tool creates one. By default, the Web Site Administration Tool also creates a database in the App_Data folder of the Web site to store application services data, such as membership and roles information. For most settings, changes that are made in the Web Site Administration Tool take effect immediately and are reflected in the Web.config file. The Web Site Administration Tool features a tabbed interface that groups related configuration settings within each tab. The tabs and the configuration settings that the tabs manage are described in the following sections.
Security Tab Use the Security tab to manage access rules to help secure specific resources within the Web site and to manage user accounts and roles. You can specify how the Web site is used—either from the Internet (publicly) or from an intranet (on a local area network). This in turn indicates the type of authentication mode that the Web site will use. Internet Web sites use the ASP.NET membership system, where you define individual user accounts. ASP.NET uses a security system to restrict access to specific user accounts or the roles to which the user accounts belong. Intranet Web sites use Windows authentication, where users are identified by their Windows logon information.
Application Tab Use the Application tab to manage a variety of settings related to the Web site, including the following: Application settings, which are name/value pairs that you want to store centrally and access in code from anywhere in the Web site. SMTP settings, which determine how your site sends e-mail. Debug and trace settings. Offline and online settings, which take the Web site offline (shut it down) to perform maintenance or to bring a new Microsoft SQL Server Standard edition database online.
Provider Tab Use the Provider tab to test or assign providers for membership and role management for the Web site. Database providers are classes that are called to store application data for a particular feature. By default, the Web Site Administration Tool configures and uses a local Microsoft SQL Server Standard Edition database in the App_Data folder for the Web site. Instead, you can choose to use a different provider, such a remote SQL Server database, to store membership and role management. Considerations The following sections provide some considerations for working with the Web Site Administration Tool.
Restarting the Application When Saving Most changes to configuration settings that you make in the Web Site Administration Tool take effect immediately. This requires the Web site to which the change applies to be restarted. Because this will cause currently active sessions in the Web site to be lost, you should make configuration changes to a staged or development version of the Web site before publishing these changes to the production server.
Saving Your Settings Most changes to configuration settings that you make in the Web Site Administration Tool take effect immediately. For settings for which the Web Site Administration Tool interface has a dedicated Save button, leaving the Web Site Administration Tool idle or allowing the Web Site Administration Tool to time out before you click Save will cause your configuration settings changes to be lost.
Time Out As a security measure, the Web Site Administration Tool times out after a period of inactivity. Any settings that did not take effect immediately and were not saved will be lost. If the Web Site Administration Tool has timed out, close your browser, and then reopen the Web Site Administration Tool in a new window. The Web Site Administration Tool manages only some of the configuration settings that are available to the Web site. Many other settings require direct modification of configuration files either manually, by using the MMC Snap-In for ASP.NET, or programmatically, by using the ASP.NET Configuration API.
Swapnil (Swaps) http://swapsnet.spaces.live.com/
5月28日 Downloading a File with Save as Dialog in ASP.NETFolks,
This seems to be a common question that we hear frequently: How do I download a file from a Web site, but instead of displaying it in the browser see it as a file that can be saved (ie. see the Save As dialog)?
Normally when you link a file that file will always display inside of the browser because the browser loads it and automatically determines the content type based on the file extension. So when you click on a link like a jpg image the browser knows it's an image and will display that image. You can of course always use the browser short cut menu and use the Save Target As option to save the file to disk. If you want to do this automatically when a link is clicked from the server side, you have to send the file back yourself rather and add a couple of custom headers to the output. The way to do this is to use Response.Transmit() to explicitly send the file from your ASP.NET application and then add the Content Type and Content-Disposition headers. Check out this link for futher details and code snippet. Swapnil (Swaps)
MMC Administration Tool - ASP.NET 2.0One new, important feature in ASP.NET 2.0 is the ability to read/edit the configuration files in local machine or remote machine. In ASP.NET 1.x, editing of the configuration files was not supported. Only option to edit a configuration file is to treat the configuration file as an xml file and update that xml file. The major drawback in this method is that you need to treat all the sections in the configuration file as XML Node, which is not strongly typed. Hence, you can do only string manipulation to update any configuration settings in that file. However, in ASP.NET 2.0 you have strongly typed API’s to read/edit the configuration files.
This article series describes the various options available in ASP.NET 2.0 to read/edit the configuration files. The various options available to read/edit the configuration files are
1) Using ASP.NET Microsoft Management Console(MMC) 2) Using Web Site Administration Tool 3) Using Configuration API’sIn the first part of this article, I have explained about
Using ASP.NET Microsoft Management Console (MMC)
In ASP.NET 2.0, you can manage configuration file from IIS itself i.e. the configuration management API is integrated with IIS itself. This feature is available as Microsoft Management Console (MMC), which can be accessed from the properties settings of any website in. Using this console, administrator can modify both machine.config file and web.config file
A new ASP.NET tab is included in the IIS site properties window, In this tab, you can specify the version of asp.net for that web application. In previous release, if you want to change the aspnet.version for a web application, you need to use command line utility aspnet_regiis, which comes with .NET Framework. Now you can do this from IIS itself. If you want to edit machine.config, you can press Edit machine.config file button. Similarly, if you want to edit web.config file, you can press edit configuration. Both this button will invoke a separate window, which has option for editing various sections in config file as mentioned below.
1) General Tab – which contains the list of all the connection Strings with facility to Manage and add new. It also contains the App Settings section and displays both the Key and value.
2) Custom Error Tab – Custom Error Mode “Remote Only”, “On”, and “Off” option. Default redirect URL property with List of Inherited Custom errors and Local errors.
3) Authorization Tab – Contains the various Inherited and Local Authorization roles with Allow / Deny options.
4) Authentication – Contains the properties to set the Authentication Mode and Cookie information in case of Forms Authentication. Also contains the Provider section to Configure Membership Providers and Role Providers.
5) Application Tab – Contains Common compilation, page and runtime settings like default language, default theme etc. Contains Globalization settings like encoding request and response information and identity settings. 6) State Management Tab – Contains the Session state settings like session mode, cookieless mode and SQL server settings in case of SQLServer session mode.
7) Locations Tab- contains the list of Locations and allow to add and manage the locations
One of the much requested feature in.Net Framework 1.1 is to update the .config file programmatically which has been included in .NET 2.0 as Configuration class. Other then Configuration class, now you have an option to edit the configuration file using MMC snap in and a web admin page. Even you can customize this web admin page for your application. With all these options, configuration is made simpler in .Net Framework 2.0.
Swapnil (Swaps) 5月26日 Configuration API - Encryption ASP.NET 2.0Using Configuration API - Encryption
Encrypting an entire section of a configuration file is straightforward with the 2.0 configuration API. There are several configuration areas where sensitive information may appear, for instance, the <connectionStrings> section may contain database usernames and passwords, the <identity> section will contain a username and password when you need the runtime to impersonate a fixed identity. You may even keep a password for a third party web service in appSettings or a custom section. Whenever secrets like these appear, consider encrypting the section instead of leaving the secrets and passwords in plain text.
Note: there are sections that may contain passwords that you cannot encrypt, namely the <processModel> section. You can still use the Aspnet_setreg.exe tool to store a password for this section securely.
The following section of code shows how easy it is to protect (encrypt) and unprotect (decrypt) an entire configuration section. (Note: you do not need to unprotect a section in order to read configuration settings from the section. The runtime will read the encrypted data and perform the decryption necessary for your application to read the plain text values. The Unprotect method call is here to demonstrate how to return a section to unencrypted form).
protected void toggleEncryptionButton_Click(object sender, EventArgs e) { Configuration config; config = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section; section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); } else { section.SectionInformation.ProtectSection( "DataProtectionConfigurationProvider" ); }
config.Save(); WriteMessage("connections protected = " + section.SectionInformation.IsProtected); }
If we were to examine our web.config file after toggling encryption to on, we’d notice the configuration API has added some additional information: <?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<protectedData> <protectedDataSections> <add name="connectionStrings" provider="DataProtectionConfigurationProvider" inheritedByChildren="false" /> </protectedDataSections> </protectedData> <appSettings configSource="appSettings.config"/>
<connectionStrings configSource="connections.config"/>
<system.web> <compilation debug="true" /> <authentication mode="Windows"/> <identity impersonate="true"/> </system.web> </configuration>
In addition, we’d find our connectionStrings.config file would contain a cipherValue instead of plaintext connection strings. (Note: we do not need to use an external configuration source to take advantage of encryption, the configuration API would have happily encrypted the connection strings section if it lived inside of web.config).
<connectionStrings> <EncryptedData> <CipherData> <CipherValue>AQAAANCMnd8BF....</CipherValue> </CipherData> </EncryptedData> </connectionStrings>
At runtime, the configuration API will decrypt sections on the fly. We can still use WebConfigurationManager.ConnectionStrings to return connection strings usable by our application.
To understand what we are seeing in the configuration file, we first need to realize that the runtime turns to a configuration encryption provider for encryption and decryption work. The two providers shipping in .NET 2.0 are the DataProtectionConfigurationProvider and the RSAProtectedConfigurationProvider (you can also implement your own protected configuration provider if need be). We can specify the provider we want to use in the string passed to the ProtectSection method, as seen in the earlier source code snippet. In our example we are using the DataProtectionConfigurationProvider.
The DataProtectionConfigurationProvider uses the Windows Data Protection API (DPAPI) underneath the covers. This provider a machine-specific secret key for encryption and decryption work. Because the DataProtectionConfigurationProvider relies on a machine-specific key, you can only decrypt cipher text that was encrypted on the same machine. If you need to move configuration files with encrypted sections from machine to machine, you’ll need the RSAProtectedConfigurationProvider. The RSAProtectedConfigurationProvider, as the name would imply, uses RSA public key encryption.
You can work with the RSAProtectedConfigurationProvider from the command line tool aspnet_regiis, which includes options to create a keypair (-pc), export a keypair (-px), import a keypair (-pi), grant access to a keypair (-pa), remove access (-pr), and more. Command line arguments also allow you to specify which encryption provider to use.
Swapnil (Swaps) http://swapsnet.spaces.live.com/
When to Use ScriptManager or Page.ClientScript to Register Client-Side ScriptFolks,
If you want to register a script from server-side code and the script is not changed dynamically based on some logic and should not be executed directly after an async. postback, you can do it from your Page object. If you have a custom control that should register a script and you will always display the control, and the script should not be changed based on some logic between postback, you can use the Register method of the Page object (Use the ClientScript property of the Page object to get access to them.). If you have your control inside of an UpdatePanel, and need to register the script during an async. postback and the script will be changed based on some logic, then you need to use the ScriptManager's Register methods. But if the control is inside of an UpdatePanel from the start and the client-side script should always be the same, you can use the register methods of the Page object (as long as you should not register a client-side script that need to be executed after a postback). Assume you have the following Page: <body> There is a User control inside of the UpdatePanel, the User Control have a TextBox with the Id TextBox1 and a Button that will do a postback. The Page_Load of the User control have the following code: protected void Page_Load(object sender, EventArgs e) Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "myKey2", "alert('" + TextBox1.ClientID + "');", true); When the page is first loaded, two alerts will be displayed, one register by the ScriptManager and one register with the Page object. If we press the button located in the User Control, an async. postback will take place and only the script Registered by the ScriptManager will be executed, but the script for register with the Page object still exists on the page but will not be executed because it's not part of the partial update. If you set the Visible property of the User control to false, the two registered script will still be executed because they are located in teh Page_Load method of the User control. But if you move the code to the CreateChildControl of the User Control, they will not be registered until the control is visible. If you have another control inside of the UpdatePanel that should display the User control (you add the control dynamically), only the script registered with the ScriptManager will be executed and the script register by using the Page object will not be added. So if you want a script to be registered for a control located in the UpdatePanel, and the Script should always be updated, then use the ScriptManager. If you add a control dynamically during an async. postback, you also need to use the ScriptManager. If you don't add a control dynamically, you can register static scripts in the Page_Load of the control by using the Page object, but if the script code need changes during an async. postback, you should use the ScriptManager. Swapnil (Swaps) http://swapsnet.spaces.live.com/
5月23日 Configuration API - ASP.NET 2.0The configuration API in .NET 2.0 gives us the ability to read and update configuration files, including web.config and machine.config files. You can read and write configuration files for your application, for another application on the same machine, or even an application on a different server. In this article, we will take a look at some of the highlights of the configuration API from the perspective of an ASP.NET developer, including how to use encryption and alternate configuration files. Note: but be careful while updating and modifying configuration file since it leads to application restart.
AppSettings and Connection Strings Two common tasks in ASP.NET development are reading application setting strings and connection strings from the configuration file. In .NET 2.0 these settings reside in the <appSettings> and <connectionStrings> respectively. A sample web.config file for an ASP.NET site might look like the following.
<?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings> <add key="message" value="Hello World!" /> </appSettings>
<connectionStrings> <add name="AdventureWorks" connectionString="..."/> <add name="northwind" connectionString="..."/> </connectionStrings>
<system.web> <compilation debug="true" /> <authentication mode="Windows"/> <identity impersonate="true"/> </system.web>
</configuration>
The configuration API for ASP.NET developers begins with the WebConfigurationManager class in the System.Web.Configuration namespace. The WebConfigurationManager includes static (shared) properties to fetch application settings and connection string. For example, to read the “message” appSetting from the web.config we could use the following code:
string message; message = WebConfigurationManager.AppSettings["message"];
Similarly, if we want to grab the second connection string, the connection with the name of “northwing”, we could use the following code:
string connectionString = WebConfigurationManager.ConnectionStrings["northwind"].ConnectionString;
The configuration API makes easy work of reading any setting in a configuration file using the GetSection static method. GetSection takes an XPath expression to indicate the section you want to get, and you can coerce the resulting object reference into a strongly typed reference for built-in section types. For instance, there is an AuthorizationSection class to manipulate the settings inside the <authorization> section, and a PagesSection class to manipulate the settings in the <pages> section.
If we want to write out the value of the impersonate attribute in the <identity> section of web.config, we could use the following:
protected void readImpersonationButton_Click(object sender, EventArgs e) { IdentitySection section; section = WebConfigurationManager.GetSection("system.web/identity") as IdentitySection;
if (section != null) { WriteMessage("Impersonate = " + section.Impersonate); } }
Modify Configuration Files The WebConfigurationManager class also allows us to open a web configuration for update using the static method OpenWebConfiguration. We can open a configuration file inside of our application by passing just a relative path. We can also read configuration files in other applications by passing the IIS sitename and a virtual directory. It’s even possible to open application configuration files on another machine. If we want to toggle the debug attribute in the <compilation>section of the web.config for the current application from true to false and back again, we could use the following code in the event handler for a button click event:
protected void toggleDebugButton_Click(object sender, EventArgs e) { Configuration config; config = WebConfigurationManager.OpenWebConfiguration("~");
CompilationSection compilation; compilation = config.GetSection("system.web/compilation") as CompilationSection;
if (compilation != null) { compilation.Debug = !compilation.Debug; config.Save(); WriteMessage( "Debug setting is now: " + compilation.Debug ); } } Using a strongly typed CompilationSection object allows to use to read and write the attributes inside a <compilation> section. We can make changes to this section (and any others) and save all the changes at once using the Save method of the System.Configuration.Configuration object returned from OpenWebConfiguration.
Swapnil (Swaps) http://swapsnet.spaces.live.com/
Refresh Module ASP.NET 2.0Folks,
Today I am gonna share one of the most Common Problem which we all are facing while developing Web Applications. ie Pressing of F5 button in your web pages. In traditional ASP.NET 1.x you either disable the F5 key with the help of Javascript commands. But ASP.NET 2.0 provides RefreshModule to handle the above scenario.
Most of you are familiar with the feature of all web-browsers that when you press the F5 button, the content of a page is refreshed. After the F5 button is pressed, the browser repeats the previous request to the page. Nothing wrong will actually happen when the previous request is made by the GET method. However, problems appear when the last request is made by the POST method. Let's consider an example where a user is transferring money to a shop to pay for some goods. Having completed this operation, the user refreshes the page and as a result the server code is executed once again with the same data. Thus, the user may accidentally pay twice.
Check out the following Link
Swapnil (Swaps)
5月22日 ASP.NET Administration and ManagementAdministration and Management ASP.NET 2.0 is designed with administration and manageability in mind. We recognize that while simplifying the development experience is important, deployment and maintenance in a production environment is also a key component of an application's lifetime. ASP.NET 2.0 introduces several new features that further enhance the deployment, management, and operations of ASP.NET servers.
Configuration API. ASP.NET 2.0 contains new configuration management APIs, enabling users to programmatically build programs or scripts that create, read, and update Web.config and machine.config configuration files.
ASP.NET MMC Admin Tool. ASP.NET 2.0 provides a new comprehensive admin tool that plugs into the existing IIS Administration MMC, enabling an administrator to graphically read or change common settings within our XML configuration files.
Pre-compilation Tool. ASP.NET 2.0 delivers a new application deployment utility that enables both developers and administrators to precompile a dynamic ASP.NET application prior to deployment. This precompilation automatically identifies any compilation issues anywhere within the site, as well as enables ASP.NET applications to be deployed without any source being stored on the server (one can optionally remove the content of .aspx files as part of the compile phase), further protecting your intellectual property.
Health Monitoring and Tracing. ASP.NET 2.0 also provides new health-monitoring support to enable administrators to be automatically notified when an application on a server starts to experience problems. New tracing features will enable administrators to capture run-time and request data from a production server to better diagnose issues. ASP.NET 2.0 is delivering features that will enable developers and administrators to simplify the day-to-day management and maintenance of their Web applications.
Swapnil (Swaps) Master Pages ASP.NET 2.0Folks,
Would like to share today am article I come across on making up master pages for you web site.
A professional web site will have a standardized look across all pages. For example, one popular layout type places a navigation menu on the left side of the page, a copyright on the bottom, and content in the middle. It can be difficult to maintain a standard look if you must always put the common pieces in place with every web form you build. In ASP.NET 2.0, master pages will make the job easier. You’ll only need to write the common pieces once - in the master page. A master page can serve as a template for one or more web forms. Each ASPX web form only needs to define the content unique to itself, and this content will plug into specified areas of the master page layout.
Check out this link for complete Tutorial on Master Pages.
Swapnil (Swaps)
5月21日 Precompilaiton ASP.NET 2.0To reduce response time and increase safety, ASP.NET version 2.0 introduces the ability to precompile a web application. When the first request arrives at your web application, The worker process starts, the runtime initializes, ASPX pages are parsed and compiled to intermediate language, methods are just-in-time compiled to native code - and the list goes on and on. If you want to cut out some of the overhead and improve the startup time of your application, then you’ll want to look at the precompile features in ASP.NET 2.0. Although pre-compilation will give our site a performance boost, the difference in speed will only be noticeable during the first request to each folder. Perhaps a more important benefit is the new deployment option made available by the precompile - the option to deploy a site without copying any of the original source code to the server. This includes the code and markup in aspx, ascx, and master files. In Place Pre-Compilation By default, ASP.NET dynamically parses and compiles all the ASPX pages in a folder when the first request arrives for a page inside that folder. ASP.NET also needs to compile applicable files in the special folders, like App_Code, on the first request, and any code-behind files associated with ASPX and ASCX files. The runtime caches all the compilation results in order to quickly process later requests, and does not need to recompile again unless someone edits a file. This behavior gives us a great deal of flexibility, including the flexibility to change code and markup and instantly have the changes reflected in the next browser request. The tool to use for pre-compilation is the aspnet_compiler executable, which you can find in the %WINDIR%\Microsoft.NET\Framework\v2.x.xxxx directory. If we have a web application in the WebSite1 virtual directory under IIS, we could use the following command line to compile the application. The –v parameter specifies that we are passing a virtual path to our web site. On servers with multiple websites you may need to use the –m parameter and specify the full IIS metabase path to the application (-m /LM/W3SVC/1/Root/WebSite1). The pre-compiled code will end up inside of the Temporary ASP.NET File directory, just as it would when the runtime compiles files for a browser request. Inside of the bin directory for the compiled site, you’ll find the assemblies (dll files). The compiler generates special filenames to avoid naming collisions. In the shot below, the dll starting with App_Code contains the code from the App_Code directory – not too surprising. Each folder containing aspx, or ascx files will compile into a dll prefixed with App_Web. The files with a .compiled extension contain XML with information about which original source code file maps to which assembly. With the compiled files in place your web application should have a slightly better startup time, but a primary benefit to in place pre-compilation will be the ability to ensure the web application is error free. If you happen to modify a class or web form and leave an error in the file, the aspnet_compiler will fail and display the compiler error. The tool will also display any warnings, but warning will not stop compilation. Pre-Compilation for Deployment Pre-compilation for deployment creates an ‘executable’ (no source code) version of your web application. With pre-compilation for deployment you give the aspnet_compiler the path to your source code, and the path to a target directory for the compilation results, like below. aspnet_compiler -p "C:\MyDevelopment\WebSite1" -v / C:\Staging This command will compile the site and place the result in C:\Staging. You must still specify –v as a parameter, even though we are not using a virtual path as either a source or a destination. Instead, the compiler will use this parameter to resolve application root references (~). The pre-compilation for deployment step will recreate your web site’s folder structure in the destination directory. All of the static files (HTML files, image files, configuration files) are copied into the folder structure exactly as they appear in the source folder hierarchy. A bin directory will appear in the target directory with all of the assemblies and .compiled files. The target directory will contain no source code. All of the classes in the App_Code folder are now compiled into one or more assemblies in the bin directory, and no .cs or .vb files will exist in the target directory. Master page files will also compile to the bin directory and not exist. All the code and markup in ASPX, ASCX, and ASHX files, along with any associated code-behind files, will live inside of one or more assemblies in the bin directory, although these files will still exist in the target directory, they exist as nearly empty ‘marker’ files. If you open an ASPX file in a pre-compiled target directory you’ll see the following content:The IIS script map for the ASPX file extension leaves the “Verify that file exists” checkbox unchecked, and the site will work without any of the ASPX files present. There is, however, a problem getting IIS to serve a default document for a directory request unless the file is present. Once the application finishes compiling you can FTP or XCOPY the target directory to a web server (or map a virtual directory to the target directory), and the application will be ready to run. A benefit to pre-compilation for deployment is that no one can make changes to the web application by tweaking the source code – no source code exists! In fact, you can’t even place a new ASPX file into the existing application directory structure without causing an error. Making a change to your site will require you to make a change in the original source code, pre-compile the application again, and redeploy all files to the server. There is one caveat in this scenario, in that pre-compilation generates unique filenames for some assemblies in the bin folder, and these filenames will change each time the pre-compiler executes. The first time you run aspnet_compiler you might see App_Web_lufhs9vn.dll in the bin directory, the next time you might see App_Web_hviqdkt.dll with the same compiled code, even though no source file has changed. This means you might have unneeded dlls in your bin directory if you keep repeatedly copy files to the server without cleanup. Use the -fixednames switch to generate repeatable assembly names. Swapnil (Swaps) Website Navigation ASP.NET 2.0Folks
Web applications that you develop will have multiple pages interconnected with each other in some fashion. You need to have a navigation system in place which can help the end user to successfully work through your application. There is no standard mechanism which offers well-defined navigation system for the web application in ASP.NET 1.x. Only known method for building navigation within web application is to fill the pages with hyperlinks. Problem arises when you move pages around or change page names. Hyperlinks don't work phew!! As site grows and new pages are added, it will be a nightmare for the developer to manage all the links in the application.
ASP.NET 2.0 eliminates this problems with a built in site navigation feature which provides a consistent way for the user to navigate your website. The new site navigation system allows defining all the links at a central location file usually an XML file and display those links in lists or navigation menus in each required page using navigation-based server controls. Check out the following link for complete tutorial on Creating the Website Navigation http://www.beansoftware.com/ASP.NET-Tutorials/Web-Site-Navigation.aspx Swapnil (Swaps) http://swapsnet.spaces.live.com/
5月20日 ASP.NET 2.0 Compilation ModelFolks, In my previous articles on ASP.NET we have gone through the ASP.NET Coding Model, Application Directories and Provider Model. We have seen various providers and creating the custom providers etc. In this article we will compare the compilation model of ASP.Net 1.X and ASP.NET 2.0. We will also look at some of the new features in ASP.NET 2.0 compilation model.
ASP.NET 1.x Compilation Model ASP.NET supports a code behind model, meaning ASPX page can have code behind associated with it. There is a complex relationship between the aspx page and code behind page. The code behind page is derived from the System.Web.UI.Page class and aspx is inherited from code behind. The following is the page directive referring to Code behind
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
The Visual Studio Web form designer uses the code-behind attribute to refer to the code-behind page and tells the designer where to find the file. Visual Studio pre-compiles all the code-behind pages into a project assembly and places it in the bin directory. Because my Web project is named SampleWeb, the DLL is named SampleWeb.DLL. The Inherits attribute tells the compiler the class in the project assembly from which the ASPX page inherits. In the previous code snippet, it tells the compiler to look for a class called WebForm1 in the SampleWeb.DLL. If we want each page as a separate assembly (instead of the code-behind pages being precompiled into a project file), the framework supports a slightly different model for ASP.NET. In this case there is no code-behind attribute in the page directive. The link between the ASPX file and its corresponding code-behind page is managed by the Src attribute. The Src attribute points to the code-behind page as shown here. The code runs exactly the same way in both the models:
<%@ Page language="c#" Src="WebForm2.cs" AutoEventWireup="false" Inherits="WebForm2 " %>
ASP.NET compiles the ASPX page the first time the user requests it and then stores it into its cache. Next time around ASP.NET checks the cache to see if the copy of the page exists. In case it cannot find one, it creates a temporary source code file that represents the Page class. It puts it in the temporary ASP.NET files folder that exists inside the Windows\Microsoft.Net\Framework\Version\TemporaryASP.NETFiles\<Website> folder. Let's look at a simple example. Code snippet 1 shows the ASPX page WebForm1.aspx. Code snippet 2 shows the code-behind page that is associated with the ASPX file. On compilation, you will notice a class file in this temporary folder that has a class that is named WebForm1 _aspx just like the ASPX page. However, the dot has been replaced by an underscore. The auto-generated class inherits from the code-behind class as instructed, which in our example is SampleWeb. WebForm1. There are a lot of confusing things with the current way of doing things. There is a complex division of responsibility between the base class (i.e., the code-behind page) and the ASPX page. This has been simplified in ASP.NET 2.0 Compilation Model
ASP.NET 2.0 Compilation Model
<%@ Page Language="C#" CompileWith="Default.aspx.cs" ClassName="Default_aspx" %> Also, notice a new directive called ClassName, which in this case is Default_aspx. This is the name of the class that the page would be given when it is compiled. Another interesting point is that the class name of the code-behind page is the same as that of the ASPX page. So the obvious question is how is it possible to have the same class declaration in two different files? This is made possible by the new construct partial class in .NET Framework 2.0 that allows a single class to exist in multiple files. In this case, when an ASPX page with a new code-behind file is requested, the ASP.NET 2.0 runtime will actually combine the class definition that is spread in the ASPX page and the code-behind page into a single class named Default_aspx. Another change that I would like to point out is that the code-behind page no longer inherits from System.UI.web.Page and it also no longer needs to define all the controls that are defined in the ASPX page. This is because now we are dealing with one class, unlike before where we had two different classes with one inheriting from the other. ASP.NET 2.0.Visual Studio 2005 no longer pre-compiles all the code-behind pages into the project assembly. Because this intermediate step of pre-compilation is avoided, there is no need to rebuild the entire project for a single change. Another big advantage is that Visual Studio 2005 IDE now provides the same level of support Intellisense to a developer who chooses to follow the single file model for development.
New Compilation Features
http://localhost/myapp/precompile.axd
This mode of compilation is known as in-place compilation. The advantage of using in-place compilation is that it helps eliminate the time delay in batch compilation on the first request. It also helps to identify the compilation errors before the users find them. ASP.NET 2.0 supports yet another way for compiling and deploying Web applications: full deployment pre-compilation. All the code-behind, ASPX, and HTML files are compiled into one or more assemblies or executables. This type of compilation helps to protect the intellectual property in the code because the ASPX and code-behind files no longer have to be deployed as such on the production server. The compiled executable can then be copied to its destination via Xcopy or FTP. This model of compilation provides the greatest performance and security. However, it comes at a cost because we will not be able to modify the Web site once it's deployed. For full deployment pre-compilation, we use a command line tool called aspnet_compiler. The result of pre-compiling is a site with a bin directory that contains assemblies and a number of stub files with the same name as the original pages. However, when you open them you will notice that the files contain no code or HTML markup inside, although the user will not notice any difference when browsing the Web site.
Swapnil (Swaps) Creating 3 tier Applications ASP.NET 2.0Folks,
Everybody of us facing day to day challenges in creating the 3 tier applications in ASP.NET 2.0, please find the below link which shows the complete step by step tutorial on creating 3 tier Applications in ASP.NET 2.0.
Article explains
1) Data Access Layer
2) Business Logic Layer (Adding Custom Validations & Error messages)
3) Presentation Layer (Using Master Pages and Themes)
Swapnil (Swaps)
Implementing Transactions in ADO.NET Folks
A transaction is a group of operations combined into a logical unit of work that is either guaranteed to be executed as a whole or rolled back. Transactions help the database in satisfying all the ACID (Atomic, Consistent, Isolated, and Durable). Transaction processing is an indispensible part of ADO.NET. It guarantees that a block of statements will either be executed in its entirety or rolled back,( i.e., none of the statements will be executed). Transaction processing has improved a lot in ADO.NET 2.0. This article discusses how we can work with transactions in both ADO.NET 1.1 and 2.0 versions.
Implementing Transactions in ADO.NET Note that in ADO.NET, the transactions are started by calling the BeginTransaction method of the connection class. This method returns an object of type SqlTransaction. Other ADO.NET connection classes like OleDbConnection, OracleConnection also have similar methods. Once you are done executing the necessary statements within the transaction unit/block, make a call to the Commit method of the given SqlTransaction object, or you can roll back the transaction using the Rollback method, depending on your requirements (if any error occurs when the transaction unit/block was executed). To work with transactions in ADO.NET, you require an open connection instance and a transaction instance. Then you need to invoke the necessary methods as stated later in this article. Transactions are supported in ADO.NET by the SqlTransaction class that belongs to the System.Data.SqlClient namespace. The two main properties of this class are as follows:
The following are the methods of this class that are noteworthy:
The following code snippet shows how we can implement transaction processing using ADO.NET in our applications. SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(); SqlCommand sqlCommand = new SqlCommand(); try catch(Exception e) finally The next piece of code illustrates how we can use the “using” statement for the above code. According to MSDN, the "using" statement, "defines a scope, outside of which an object or objects will be disposed. A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement". using (SqlConnection sqlConnection = new SqlConnection(connectionString)) The Microsoft's ADO.NET version 2.0 added a lot of new features to its earlier counterpart to add more flexibility and ease of use. As far as transactions are concerned, a new namespace called System.Transactions has been introduced that promises a significantly improved support for distributed transactions. It contains a class called TransactionScope that can run a set of statements. It can also determine whether the objects in the scope have support for transactions. If the transaction has completed successfully, the changes are committed to the database else it is rolled back. We need to specify whether the transaction block is complete by making a call to the TransactionScope.Complete method explicitly, else, the transaction would be rolled back when the transaction instance would be discarded by the implicit Dispose method. using (TransactionScope transactionScope = new TransactionScope()) using (SqlConnection statesDatabaseConnection = new SqlConnection(statesDatabaseConnectionString)) transactionScope.Complete(); Points to be noted It should be noted that the SqlTransaction object returned by the BeginTransaction () method has to be assigned to the Transaction property of the Command object; else an InvalidOperationException will be thrown by the application when the first query is executed. Likewise, the Connection instance should be open by invoking the Open method on it prior to starting a new transaction; else an InvalidOperationException would be thrown. In order to improve the performance of applications, we should try to keep the transactions (the transaction units/blocks that contain the statements to be executed in a batch as a whole) as short as possible. This will help minimize the lock contention and hence increase throughput. Further, we should analyze whether or not we actually require a transaction for a batch of statements. Try not to unnecessarily have transactional statements in you code as it might have a performance drawback due to the reasons stated above. Conclusion Swapnil (Swaps) http://swapsnet.spaces.live.com/
5月19日 Web Events ProviderWeb Event Providers Web event providers provide the interface between Microsoft ASP.NET's health monitoring subsystem and data sources for the events ("Web events") fired by that subsystem. ASP.NET 2.0 ships with the following Web event providers: · EventLogWebEventProvider, which logs Web events in the Windows event log. · SqlWebEventProvider, which log Web events in Microsoft SQL Server and Microsoft SQL Server Express databases. · SimpleMailWebEventProvider and TemplatedMailWebEventProvider, which respond to Web events by sending e-mail. · TraceWebEventProvider, which forwards Web events to diagnostics trace. · WmiWebEventProvider, which forwards Web events to the Microsoft Windows Management Instrumentation (WMI) subsystem. The Microsoft .NET Framework's System.Web.Management namespace includes a class named WebEventProvider that defines the basic characteristics of a Web event provider. It also contains a WebEventProvider-derivative named BufferedWebEventProvider that adds buffering support. SqlWebEventProvider derives from BufferedWebEventProvider and improves performance by "batching" Web events and committing them to the database en masse. BufferedWebEventProvider is prototyped as follows:
public abstract class BufferedWebEventProvider : WebEventProvider { // Properties public bool UseBuffering { get; } public string BufferMode { get; }
// Virtual methods public override void Initialize (string name, NameValueCollection config); public override void ProcessEvent (WebBaseEvent raisedEvent); public override void Flush ();
// Abstract methods public abstract void ProcessEventFlush (WebEventBufferFlushInfo flushInfo); }
SqlWebEventProvider SqlWebEventProvider is the Microsoft Web event provider for SQL Server databases. It logs Web events in the provider database, using the schema documented in "Data Schema," and it uses the stored procedure documented in "Data Access." Knowledge of the database schema is hidden in the stored procedure, so that porting SqlWebEventProvider to other database types requires little more than modifying the stored procedure. (Depending on the targeted database type, the ADO.NET code used to call the stored procedure might have to change, too. The Microsoft Oracle .NET provider, for example, uses a different syntax for named parameters.) The ultimate reference for SqlWebEventProvider is the SqlWebEventProvider source code, which is found in SqlWebEventProvider.cs. The sections that follow highlight key aspects of SqlWebEventProvider's design and operation.
Provider Initialization Initialization occurs in SqlWebEventProvider.Initialize, which is called one time—when the provider is loaded—by ASP.NET. SqlWebEventProvider.Initialize processes the connectionStringName and maxDetailsEventLength configuration attributes. Then, it calls base.Initialize to process other supported configuration attributes such, as useBuffering, and throw an exception if unrecognized configuration attributes remain. SqlWebEventProvider.Initialize reads the connection string identified by the connectionStringName attribute from the <connectionStrings> configuration section, and caches it in a private field. It throws a ConfigurationErrorsException if the attribute is empty or nonexistent, if the attribute references a nonexistent connection string, or if the connection string doesn't use integrated security.
Data Access SqlWebEventProvider performs all database accesses through the stored procedure named aspnet_WebEvent_LogEvent (Table 7-2). That stored procedure is a simple one consisting of a single INSERT statement that initializes the fields of the new record with the input parameters generated by SqlWebEventProvider.FillParams Processing Web Events When a Web event is raised, the Web events subsystem calls the ProcessEvent method of each Web event provider mapped to that event type. If buffering is not enabled, SqlWebEventProvider.ProcessEvent records the Web event in the provider database, by calling the helper method WriteToSQL. If buffering is enabled, SqlWebEventProvider.ProcessEvent buffers the Web event by calling the base class's ProcessEvent method. The following is the source code for SqlWebEventProvider.ProcessEvent, with diagnostic code removed for clarity:
public override void ProcessEvent(WebBaseEvent eventRaised) { if (UseBuffering) { base.ProcessEvent(eventRaised); } else { WriteToSQL(new WebBaseEventCollection(eventRaised), 0, new DateTime(0)); } }
If buffering is enabled, the Web events subsystem calls the provider's ProcessEventFlush method to flush buffered Web events. ProcessEventFlush's job is to read buffered Web events from the event buffer, and commit them to the database. SqlWebEventProvider.ProcessEventFlush calls WriteToSQL to log the buffered events. as follows:
public override void ProcessEventFlush (WebEventBufferFlushInfo flushInfo) { WriteToSQL(flushInfo.Events, flushInfo.EventsDiscardedSinceLastNotification, flushInfo.LastNotificationUtc);
}
SqlWebEventProvider.WriteToSQL contains the logic for recording Web events in the provider database. WriteToSQL calls FillParams to generate the parameters written to the database, and then calls the stored procedure aspnet_WebEvent_LogEvent to write the parameters to the provider database. WriteToSql is capable of writing one Web event or multiple Web events, and it contains built-in logic for delaying retries for at least 30 seconds (or the number of seconds specified by the commandTimeout configuration attribute) after a failed attempt to write to the database.
Differences Between the Published Source Code and the .NET Framework's SqlWebEventProvider The published source code for SqlWebEventProvider differs from the .NET Framework version in the following respects: · Declarative and imperative CAS checks were commented out. Because the source code can be compiled standalone, and thus will run as user code rather than trusted code in the global assembly cache, the CAS checks are not necessary. · The published version includes a derived event type called MyWebBaseEvent that is used for manipulating events in the provider. The .NET Framework provider uses the base WebBaseEvent class directly, because the .NET Framework provider is able to call internal WebBaseEvent methods.
Swapnil (Swaps) http://swapsnet.spaces.live.com/
Hidding Columns in GridViewFolks,
I have got most of the queries on how do we hide the columns in GridView control in ASP.NET 2.0.
When displaying data in a grid, there are instances when you would want the data column not to be visible to the client and still require it for further processing. This can be achieved by simply setting the column’s visibility property to False. This can be done in versions prior to ASP.NET 2.0, but how do you achieve this in ASP.NET 2.0? The GridView of ASP.NET 2.0 has replaced the DataGrid and the scenario mentioned above just does not work in ASP.NET 2.0. When the column’s visibility property is set to False, the GridView does not bind the data to the column. When you try to retrieve data from the hidden column, you get an empty string. Result? You start debugging your application and end up being lost in the web. I hope the solution mentioned below saves some of your precious development time. Add the GridView’s RowCreated event and set the cell’s visibility property to False. Public Sub myGridView_OnRowCreated(ByVal sender As Object, ByVal e As _
Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowCreated
'Hide the cell of the column you do not want to display as each row gets
'created, eventually leading to the entire column being hidden.
e.Row.Cells(0).Visible = False
End SubThe GridView’s RowCreated event gets called after the data is bound to the grid. So the first column is hidden only after it is databound. It is possible to hide the other columns by changing the cell index. Hope this is usefull to you. Swapnil (Swaps) http://swapsnet.spaces.live.com/
5月16日 Ploymorphism & EncapsulationFolks,
Polymorphism and encapsulation are two big words in OO development, and are also a fundamental concept of software development. This article will demystify these concepts by showing you some real world examples.
Swapnil (Swaps)
|
|
|