Академический Документы
Профессиональный Документы
Культура Документы
Advantage, for example, Any change in Code-Behind page gets reflected in the
Presentation Page(inline code) and vice versa, because of the partial class mechanism.
Compare this with the older ASP.NET 1.1, whenever a change was made to Code
Behind, change got reflected in Presentation page but the reverse threw an error. So for
any change in the presentation page, like addition of a new control, we need to
specifically add a reference of that control in the Code-Behind page. The concept of
partial classes in ASP.NET 2 eliminates this problem.
A1. ASP.NET is a programming framework built on the common language runtime that
can be used on a server to build powerful Web applications. The first version of
ASP.NET offered several important advantages over previous Web development models.
ASP.NET 2.0 improves upon that foundation by adding support for several new and
exciting features in the areas of developer productivity, administration and management,
extensibility, and performance.
1) New Server Controls: ASP.NET 2.0 introduces many new server controls that enable
powerful declarative support for data access, login security, wizard navigation, menus,
treeviews, portals, and more. Many of these controls take advantage of core application
services in ASP.NET for scenarios like data access, membership and roles, and
personalization.
* Login Controls: login forms, create user forms, password retrieval, and custom UI for
logged in users or roles
2) Master Pages: This feature provides the ability to define common structure and
interface elements for your site, such as a page header, footer, or navigation bar, in a
common location called a "master page", to be shared by many pages in your site.
In one simple place you can control the look, feel, and much of functionality for an entire
Web site. This improves the maintainability of your site and avoids unnecessary
duplication of code for shared site structure or behavior.
3) Themes and Skins. The themes and skins features in ASP.NET 2.0 allow for easy
customization of your site's look-and-feel. You can define style information in a common
location called a "theme", and apply that style information globally to pages or controls in
your site. Like Master Pages, this improves the maintainability of your site and avoid
unnecessary duplication of code for shared styles.
4) Personalization. Using the new personalization services in ASP.NET 2.0 you can
easily create customized experiences within Web applications. The Profile object enables
developers to easily build strongly-typed, sticky data stores for user accounts and build
highly customized, relationship based experiences. At the same time, a developer can
leverage Web Parts and the personalization service to enable Web site visitors to
completely control the layout and behavior of the site, with the knowledge that the site is
completely customized for them. Personalizaton scenarios are now easier to build than
ever before and require significantly less code and effort to implement.
Q2. What is Visual Web Developer? Is it Different from Visual Studio 2005?
A2. Visual Web Developer 2005 Express Edition is part of the Microsoft Visual Studio
2005 family, and is the best development tool for building data driven web applications
with ASP.NET 2.0. As part of the Express family, Visual Web Developer provides a
seamless upgrade path to Visual Studio Standard, Professional, and Team System.
Yes its different from Visual Studio 2005, this one is available as a free download while
Visual Studio 2005 has several versions that may be purchased from MS.
A3. Intellisense Everywhere - the popup code hints which appear while you type -- has a
dramatic impact on your productivity as a developer. While support for Intellisense in
Visual Studio .NET 2003 is excellent today, support for Intellisense in Visual Web
Developer gets even better.
In Visual Web Developer, Intellisense pops up everywhere. For example, you can take
full advantage of Intellisense within the script blocks in single file ASP.NET pages. In
addition, Visual Web Developer also supports Intellisense for ASP.NET Page Directives
and for inline CSS style attributes within a page.
Visual Web Developer also provides Intellisense for all sections within a Web.Config
configuration file, as well as any generic XML file that contains a DTD or XML Schema
reference.
Tag Navigator
The HTML source editor within Visual Web Developer ships with a new Tag Navigator
feature that enables developers to easily track their location and navigate within a
complicated HTML document. The Tag Navigator displays the current "path" within the
source of an HTML page by displaying a list of all the HTML tags which contain the tag
where your cursor is currently located. Clicking on any of the nodes enables developers
to optionally change the source level selection, and quickly move up and down a deep
HTML hierarchy.
Tag Outlining
Tag Outlining enables you to work more effectively with large HTML documents. With
Tag Outlining, you can right-click any HTML tag in the source editor and select Collapse
Tag to hide the entire contents of the tag. Collapsing different regions of the HTML
source code contained in a page makes it easier to focus on the particular region of the
page which you need to edit.
A4. Its a feature of Visual Web Express & Visual Studio 2005. Code Refactoring
Code Refactoring enables you to easily and systematically make changes to your code.
Code Refactoring is supported everywhere that you can write code including both code-
behind and single-file ASP.NET pages. For example, you can use Code Refactoring to
automatically promote a public field to a full property.
A5. Intellitask is like a super smart clipboard designed for working with code. Intellitask
improves your productivity by enabling you to easily apply standard code snippets
anywhere within the source editor. Simply by right-clicking, you can inject common code
into your pages. Visual Web Developer will ship with more than 200 web specific
Intellitask code snippets out of the box. Better yet, you can add your own code templates
to Intellitask so that you can quickly modify your code in the future.
A6. Visual Web Developer has better designer support for editing templates. You can
take advantage of the new template editing features when working with data controls
such as the DataList and GridView controls.
When adding a control to a template in the designer, you can easily specify the databound
expressions to associate with the control properties. For example, if you drag a TextBox
control onto a template, you can bind the TextBox control's Text property to a particular
field from the data control's data source. The Edit Databindings dialog box provided by
the Visual Web Developer template editing designer enables you to easily bind particular
fields by name.
Visual Web Developer has better HTML table editing features. The improved Insert
Table dialog box enables you to quickly control the look and feel of the new table when it
is added to the designer surface. In addition, Visual Web Developer provides the ability
to resize tables, table columns and table rows graphically within the designer surface (just
click and hold down the appropriate element to size it).
A7. When we create ASP.NET 2.0 applications on Visual Web Developer OR Visual
Studio 2005, We dont need Frontpage Server Extensions as we required in ASP.NET 1.1.
When you create a new IIS project, you can now view all of the Web sites and
applications configured on your machine. You can even create new IIS Web applications
or virtual directories directly from the New Web Site dialog box.
Frontpage Server Extensions (FPSE) are no longer required for locally developed IIS
web applications. You can create and fully manage your websites without having to
install or configure them.
A8. Yes. Visual Web Developer now has built-in support for editing and updating remote
web projects using the standard File Transfer Protocol (FTP). You can quickly connect to
a remote Web site using FTP within the New Web Site and Open Web Site dialog box.
A9. When the first request arrives at your web application there is a mind-numbing
amount of work to do. 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 Precompilation -> 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 arkup and instantly
have the changes reflected in the next browser request.
The price for this flexibility is the performance hit on the first request. Some people have
found their ASP.NET applications to be slow starters. These people usually work in the
sales department and perform software demos in front of customers. In place pre-
compilation makes the “first hit” to a web application and forces all pages and code in the
application to compile.
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 pplication.
C:\Windows\Microsoft.NET\Framework\v2.0.50215>aspnet_compiler -v /Website1
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.
You may find these files in the following location of your computer.
C:\windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
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.
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:
This is a marker file generated by the precompilation tool, and should not be
deleted!
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.
A10. 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.
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_murhs6vm.dll in the bin directory, the next
time you might see App_Web_gvohdjw.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.
A11. Yes.
A12. ASP.NET pages can contain server controls, which are programmable server-side
objects that typically represent a UI element in the page, such as a textbox or image.
Server controls participate in the execution of the page and produce their own markup
rendering to the client. The principle advantage of server controls is that they enable
developers to get complex rendering and behaviors from simple building-block
components, dramatically reducing the amount of code it takes to produce a dynamic
Web page. Another advantage of server controls is that it is easy to customize their
rendering or behavior. Server controls expose properties that can be set either
declaratively (on the tag) or programmatically (in code). Server controls (and the page
itself) also expose events that developers can handle to perform specific actions during
the page execution or in response to a client-side action that posts the page back to the
server (a "postback"). Server controls also simplify the problem of retaining state across
round-trips to the server, automatically retaining their values across successive postbacks.
Server controls are declared within an .aspx file using custom tags or intrinsic HTML
tags that contain a runat="server" attribute value. Intrinsic HTML tags are handled by one
of the controls in the System.Web.UI.HtmlControls namespace. Any tag that doesn't
explicitly map to one of the controls is assigned the type of
System.Web.UI.HtmlControls.HtmlGenericControl.
A13. ASP.NET server controls can optionally expose and raise server events, which can
be handled by page developers. A page developer may accomplish this by declaratively
wiring an event to a control (where the attribute name of an event wireup indicates the
event name and the attribute value indicates the name of a method to call).
A14. The following sample demonstrates how to use the <asp:hyperlink runat=server>
control to navigate to another page (passing custom query string parameters along the
way). The sample then demonstrates how to easily get access to these query string
parameters from the target page.
This navigation triggers when a click is made on the hyperlink. If we want navigation to
trigger through code, we may use response.redirect(URL) or server.transfer(URL)
A15. ASP.NET 2.0 introduces an improved runtime for code-behind pages that simplifies
the connections between the page and code. In this new code-behind model, the page is
declared as a partial class, which enables both the page and code files to be compiled into
a single class at runtime. The page code refers to the code-behind file in the CodeFile
attribute of the <%@ Page %> directive, specifying the class name in the Inherits
attribute. Note that members of the code behind class must be either public or protected
(they cannot be private).
Example
Codebehind
Inline Code
<html>
<head>
<title>ASP.NET CodeBehind Pages</title>
</head>
<body>
<form runat="server">
<h1>Welcome to ASP.NET 2.0!</h1>
<b>Enter Your Name:</b>
<asp:TextBox ID="TextBox1" Runat="server"/>
<asp:Button ID="Button1" Text="Click Me" OnClick="Button1_Click"
Runat="server"/>
<br />
<br />
<asp:Label ID="Label1" Text="Hello" Runat="server" />
</form>
</body>
</html>
A16. The advantage of the simplified code-behind model over previous versions is that
you do not need to maintain separate declarations of server control variables in the code-
behind class. Using partial classes (new in 2.0) allows the server control IDs of the ASPX
page to be accessed directly in the code-behind file. This greatly simplifies the
maintenance of code-behind pages.
A17. Just as pages can be compiled dynamically at runtime, so can arbitrary code files
(for example .cs or .vb files). ASP.NET 2.0 introduces the App_Code directory, which
can contain standalone files that contain code to be shared across several pages in your
application. Unlike ASP.NET 1.x, which required these files to be precompiled to the Bin
directory, any code files in the App_Code directory will be dynamically compiled at
runtime and made available to the application. It is possible to place files of more than
one language under the App_Code directory, provided they are partitioned in
subdirectories (registered with a particular language in Web.config).
Q18. Can we put code created in different languages in the same App_Code
directory?
A18. By default, the App_Code directory can only contain files of the same language.
However, you may partition the App_Code directory into subdirectories (each containing
files of the same language) in order to contain multiple languages under the
App_Code directory. To do this, you need to register each subdirectory in the Web.config
file for the application.
<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="Subdirectory"/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>
Q19. Whats the difference between Bin folder and App_Code folder?
A19. The Bin directory is like the Code directory, except it can contain precompiled
assemblies. This is useful when you need to use code that is possibly written by someone
other than yourself, where you don't have access to the source code (VB or C# file) but
you have a compiled DLL instead. Simply place the assembly in the Bin directory to
make it available to your site.
By default, all assemblies in the Bin directory are automatically loaded in the app and
made accessible to pages. You may need to Import specific namespaces from assemblies
in the Bin directory using the @Import directive at the top of the page.
A20. The .NET Framework 2.0 includes a number of assemblies that represent the
various parts of the Framework. These assemblies are stored in the global assembly
cache, which is a versioned repository of assemblies made available to all applications on
the machine (not just a specific application, as is the case with Bin and App_Code).
Several assemblies in the Framework are automatically made available to ASP.NET
applications. You can register additional assemblies by registration in a Web.config file
in your application.
<configuration>
<compilation>
<assemblies>
<add assembly="System.Data, Version=1.0.2411.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089"/>
</assemblies>
</compilation>
</configuration>
Note that you still need to use an @Import directive to make the namespaces in these
assemblies available to individual pages.
Q21. Can we bind data to Server Controls without writing code in ASP.NET 2.0?
A21. Yes. ASP.NET 2.0 enables a declarative solution for data binding which requires no
code at all for the most common data scenarios, such as:
Selecting and displaying data
Sorting, Paging and Caching Data
Updating, Inserting and Deleting Data
Filtering or Master-Details Using Parameters
ASP.NET 2.0 introduces two types of server controls that participate in this declarative
data binding model. These two types of data controls handle the complexity of the
stateless Web model for data scenarios, so developers don't need to understand page
request lifecycle events just to perform data binding. Another benefit of this control-
based model is that it can be easily extended to support additional data access storage
providers.
A22. Data source controls have no rendering, but instead represent a particular backend
data store, for example a database, business object, XML file, or XML Web Service.
Data source controls also enable rich capabilities over data - such as sorting, paging,
filtering, updating, deleting, and inserting - that data-bound UI controls can automatically
use. ASP.NET includes the following server controls out-of-the-box:
A23. Data-bound controls are UI controls that render data as markup to the requesting
client device or browser. A data-bound control can auto-bind to data exposed from a data
source and will fetch data at the appropriate time in the page request lifecycle. These
controls can optionally take advantage of data source capabilities such as sorting, paging,
filtering, updating, deleting, and inserting. A data-bound control connects to a data source
control through its DataSourceID property.
You may be familiar with some of the data-bound controls in ASP.NET v1.x, such as
DataGrid, DataList, Repeater, and list controls like DropDownList. ASP.NET 2.0
contains several new data-bound controls as well, such as:
GridView Renders data in a grid format. This control is an evolution of the DataGrid
control, and can automatically take advantage of data source capabilities.
DetailsView Renders a single data item in a table of label/value pairs, similar to the form
view in Microsoft™ Access. This control can also automatically take advantage of data
source capabilities.
FormView Renders a single data item at a time in a form defined by a custom template.
Renders a single data item in a table of label/value pairs, similar to the form view in
Microsoft™ Access. This control can also automatically take advantage of data source
capabilities.
TreeView Renders data in a hierarchical tree view of expandable nodes.
Menu Renders data in a hierarchical dynamic menu (including flyouts).
A24. A Master Page is a page that contains markup and controls that should be shared
across multiple pages in your site. For example, if all of your pages should have the same
header and footer banners or the same navigation menu, you could define this in a Master
Page once, and then all pages associated to this Master Page would inherit those common
elements. The advantage of defining the header, footer, and navigation in a Master Page
is that these elements need only be defined once, instead of multiple times in duplicate
code across the pages in your site.
Defining a Master Page is just like defining a normal page. Master Pages can contain
markup, controls, or code, or any combination of these elements. However, a Master
Page can contain a special type of control, called a ContentPlaceHolder control. A
ContentPlaceHolder defines a region of the master page rendering that can be substituted
with content from a page associated to the master. A ContentPlaceHolder can also
contain default content, just in case the derive page does not need to override this content.
The syntax of a ContentPlaceHolder control is given below:
To differentiate a Master Page from a normal page, a Master Page is saved under the
.master file extension. A page can derive from a Master Page by defining a
MasterPageFile attribute on its Page directive, as demonstrated below. A page that is
associated to a Master Page is called a Content Page.
A25. A Content Page can declare Content controls that specifically override content
placeholder sections in the Master Page. A Content control is associated to a particular
ContentPlaceHolder control through its ContentPlaceHolderID property. A Content Page
may only contain markup and controls inside Content controls; it cannot have any top-
level content of its own. It can, however, have directives or server-side code.
The Content Page can then reference the Master Page using the Master property of the
Page class:
In the code example above, FooterText is a public property exposed on the Master Page,
while MyAdRotator is a control on the Master Page.
Q27. Can we have multiple number of Master pages in an ASP.NET 2.0 web
application?
A27. Yes.
A28. Yes.
A29. The simplest type of data-driven page is a read-only report, which displays data but
does not allow the user to manipulate the presentation or modify the data. To create a
read-only report against a SQL database, first configure a SqlDataSource on the page and
then connect a data-bound control such as GridView to the data source by specifying its
DataSourceID property. The example below shows a GridView control associated to a
SqlDataSource control.
<form runat="server">
<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1" runat="server"/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />
</form>
<configuration>
<connectionStrings>
<add name="Pubs" connectionString="Server=(local);Integrated
Security=True;Database=UrDatabaseName;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
A30. The SqlDataSource control supports sorting when its DataSourceMode property is
set to "DataSet". To enable the sorting UI in the GridView, set the AllowSorting property
to true. This causes the GridView to render link buttons for its column headers that can
be clicked to sort a column. The GridView control passes the SortExpression associated
with the column field to the data source control, which returns the sorted data to the
GridView.
Q31. Can we sort data from a SQLDataSource when mode is set to DataReader?
A32. You can enable paging UI in the GridView by setting the AllowPaging property to
true. The GridView can automatically page over any return value from a data source that
supports the ICollection interface. The DataView returned by SqlDataSource when in
DataSet mode supports this interface, so GridView can page over the result. When in
DataReader mode, the GridView cannot page over the data returned by SqlDataSource.
A33. Use the PageSize property. It Gets or sets the number of records to display on a
page in a GridView control.
A34. Gets a GridViewRow object that represents the top pager row in a GridView
control.
A35. It implements the basic functionality common to all hot spot shapes. Its Namespace:
System.Web.UI.WebControls
You cannot directly create instances of the abstract HotSpot class. Instead, this class is
inherited by the CircleHotSpot, RectangleHotSpot, and PolygonHotSpot classes to
provide the common basic functionality for a hot spot. You must derive from the HotSpot
class to create a custom hot spot class that represents a unique shape that you define.
However, you can define most shapes using the CircleHotSpot, RectangleHotSpot, and
PolygonHotSpot classes. Its used in an ImageMap control.
A36. It is a control that displays an image on a page. When a hot spot region that is
defined within the ImageMap control is clicked, the control either generates a postback to
the server or navigates to a specified URL.
A37. GridView control can automatically render UI for modifying data through Update
and Delete operations, provided the associated data source is configured to support these
capabilities. The SqlDataSource control supports Update operations when its
UpdateCommand property is set and Delete operations when its DeleteCommand
property is set to a valid update or delete command or stored procedure. The
UpdateCommand or DeleteCommand should contain parameter placeholders for each
value that will be passed by the GridView control (more on this below). You can also
specify an UpdateParameters or DeleteParameters collection to set properties for each
parameter, such as the parameter data type, input/output direction, or default value.
To enable the UI in the GridView for Updates or Deletes, you can either set the
AutoGenerateEditButton and AutoGenerateDeleteButton properties to true, or you can
add a CommandField to the GridView control and enable its ShowEditButton and
ShowDeleteButton properties. The GridView supports editing or deleting one row at a
time. For editing, the user places the row in edit mode by clicking the Edit button, and
then confirms the Update by clicking the Update button while the row is in edit mode.
The user can also click the Cancel button to abort the edit operation and return to read-
only mode.
Notice the naming convention for parameters in the Update statement assigned to
UpdateCommand. The automatic capability of GridView and other data-bound controls
to invoke the Update operation relies on this naming convention in order to work.
Parameters are expected to be named the same as the associated field values returned by
the SelectCommand. Using this naming convention makes it possible to align the values
passed by the data-bound control to the data source with the parameters in the SQL
update statement.
A38. An important property that plays a special role in Update and Delete operations is
the DataKeyNames property. This property is typically set to the names of fields from the
data source that are part of a primary key used to match a given row in the data source.
Multiple keys are comma-separated when specifying this property declaratively, although
it is common to only have one primary key field. The values of fields specified by the
DataKeyNames property are round-tripped in viewstate for the sake of retaining original
values to pass to an Update or Delete operation, even if that field is not rendered as one
of the columns in the GridView control. When the GridView invokes the data source
Update or Delete operation, it passes the values of these fields to the data source in a
special Keys dictionary, separate from the Values dictionary that contains new values
entered by the user while the row is in edit mode (for update operations). The contents of
the Values dictionary are obtained from the input controls rendered for the row in edit
mode. To exclude a value from this dictionary, set the ReadOnly property to true on the
corresponding BoundField in the Columns collection. If you are using the GridView
designer in Visual Studio, the ReadOnly property is set to true for primary key fields by
default.
A39. A common scenario in data-driven pages is the ability to filter data in a report. For
example, suppose the user could select from a set of field values in a DropDownList to
filter the report grid to only display rows with a matching field value. In ASP.NET v1.x,
you would have needed to perform the following steps in code:
Cancel databinding in Page_Load if the request is a postback
Handle SelectedIndexChanged event
Add DropDownList SelectedValue to command's Parameters collection
Execute the command and call DataBind
In ASP.NET 2.0, this code is eliminated through the use of declarative Data Parameter
objects. A data parameter allows external values to be declaratively associated with data
source operations. These parameters are usually associated with a variable in a command
expression or property, for example a parameter in a SQL statement or stored procedure
for
SqlDataSource. Data source controls expose parameter collection properties that can
contain parameter objects for each supported data operation. For example:
<asp:DropDownList ID="DropDownList1" ... runat="server"/>
...
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Pubs %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = @state">
<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
[address], [city], [state], [zip], [contract] FROM [authors] WHERE [state] = @state"
UpdateCommand="UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id"
ConnectionString="<%$ ConnectionStrings:Pubs %>">
<SelectParameters>
<asp:QueryStringParameter Name="state" QueryStringField="state" DefaultValue="CA" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="au_lname" />
<asp:Parameter Name="au_fname" />
<asp:Parameter Name="phone" />
<asp:Parameter Name="address" />
<asp:Parameter Name="city" />
<asp:Parameter Name="state" />
<asp:Parameter Name="zip" />
<asp:Parameter Name="contract" />
<asp:Parameter Name="au_id" />
</UpdateParameters>
</asp:SqlDataSource>
Q40. How do we enabling Caching for a DataSource Control?
A40. To enable caching for the SqlDataSource control (and also ObjectDataSource), set
the EnableCaching property to true. You can specify the length of time (in seconds) to
store an entry in the cache using the CacheDuration property. You can also set the
CacheExpirationPolicy property to either Sliding or Absolute just as you can do from the
cache API. Caching is only supported on the SqlDataSource control when the
DataSourceMode property is set to "DataSet". For example, if you set CacheDuration to
5 and SlidingExpiration to Absolute, the SqlDataSource will retrieve data from the
database on the first request to the page and store this data in the cache. For subsequent
requests, the SqlDataSource will attempt to retrieve the cache entry to serve the request
without going back to the original database. After 5 seconds (or perhaps earlier, if cache
memory pressure is high), the cache entry will be purged and a subsequent request to the
page causes SqlDataSource to go back to the database again (repeating the caching
process with the new data).
If you instead set CacheDuration to 5 and SlidingExpiration to Sliding, the cached data
will have its time-to-live periodically refreshed as long as the data source requests the
cached data once every 5 seconds. If a page requests the cached data at least once every 5
seconds, and there is no cache memory pressure, the cached data effectively remains in
the cache forever. On the other hand, if no requests are made for the cached data within a
5 second time period, then the cached item is purged and the next time a request occurs
the SqlDataSource control will go back to the original database again.
The example below demonstrates caching with the SqlDataSource control. The
TimeStamp column updates each time the query is executed, so you can see how often
the data is retrieved from the database versus retrieved from the cache. Note that
approximately every five seconds, the TimeStamp updates.
@state"
UpdateCommand="UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id"
ConnectionString="<%$ ConnectionStrings:Pubs %>" CacheDuration="5" EnableCaching="True">
<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="au_lname" />
<asp:Parameter Name="au_fname" />
<asp:Parameter Name="phone" />
<asp:Parameter Name="address" />
<asp:Parameter Name="city" />
<asp:Parameter Name="state" />
<asp:Parameter Name="zip" />
<asp:Parameter Name="contract" />
<asp:Parameter Name="au_id" />
</UpdateParameters>
</asp:SqlDataSource>
A41. Declare a dropdown as usual in the master page. Instead of overriding the
InitializeCulture() place the same code in the Application_BeginRequest event handler in
the global.asax. It is very similar to InitializeCulture() in the sense that it occurs early and
no controls are ready yet. We have a little problem though, now the control is declared in
a template and its name and id attributes rendered differently.
Another collection like the form variables collection that is also not originally server
collection is the cookies collection. I use the cookie but it can be any of the ways for
cross page communication that do not depend on server controls, like profile, session,
querystring etc. We cannot use a cookie to carry the culture name value which comes
from the dropdown selected item value, because the culture would always be a step
behind. It would be set early on but later the dropdown selection change it but the
resources for the previous culture come up. So normally only the page containing the
dropdown would be a step behind, but because the dropdown is in the master page it
appears that the whole site is ALWAYS ONE STEP BEHIND.
If, however, in the cookie, we pass the control name (which is information that never
changes, so we can never be behind), instead of the culture name( which we can never
keep up with), and then use that key to get the form variable value, we have pieced
ourselves a workaround.
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="en" Text="English" />
<asp:ListItem Value="fr" Text="French" />
<asp:ListItem Value="de" Text="German" />
</asp:DropDownList>
In global.asax
void Application_BeginRequest(Object sender, EventArgs e){
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["DropDownName"];
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}
Notice, there is absolutely no code in any of the content pages. Thats it ten lines of code
and we are done for the whole site. This is not complete code, just a tip and trick of using
master page and the .net event model to globalize code.
System.Net.Mail
Public
Class MailHelper
''' <summary>
''' Sends an mail message
''' </summary>
''' <param name="from">Sender address</param>
''' <param name="recepient">Recepient address</param>
''' <param name="bcc">Bcc recepient</param>
''' <param name="cc">Cc recepient</param>
''' <param name="subject">Subject of mail message</param>
''' <param name="body">Body of mail message</param>
Public Shared Sub SendMailMessage(ByVal from As String, ByVal recepient As String, ByVal bcc As String, ByVal cc As
Web.config
<?
xml version="1.0"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="defaultEmail@yourdomain.com">
<network host="smtp.yourdomain.com" port="25" userName="yourUserName" password="yourPassword"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
Q43. Does the ASP.NET Development Server support running web pages from a
computer other than the local computer?
A43. No. It will not serve pages to another computer. Additionally, it will not serve files
that are outside of the application scope. The ASP.NET Development Server provides an
efficient way to test pages locally before you publish the pages to a production server
running IIS.
Q44. Whats the difference between running pages on ASP.NET Development Server and
IIS?
A44. An important difference between the ASP.NET Development Server and IIS is the
security context in which the respective servers run your ASP.NET pages. This difference
can affect your testing because of differences in how the pages run.
When you run a page using the ASP.NET Development Server, the page runs in the
context of your current user account. For example, if you are running as an administrator-
level user, a page running in the ASP.NET Development Server will have administrator-
level privileges. In contrast, in IIS, ASP.NET by default runs in the context of the special
user (ASPNET or NETWORK SERVICES) that typically has limited privileges. The
ASPNET or NETWORK SERVICES accounts are local to the server computer (not
domain accounts), which restricts access to resources on other computers.
If you are simply reading and running the code in ASP.NET pages, this difference is not
very important. However, the different security contexts for the two Web servers can
affect your testing of the following:
• Access to other resources that the page requires This can include reading and
writing files other than Web pages, reading and writing the Windows registry, and
so on.
• Database access When working with the ASP.NET Development Server, you
can typically rely on Windows Integrated authentication to access SQL Server.
However, when the same page runs in IIS under the ASPNET or NETWORK
SERVICES account, the page is running in the context of a local user, and you
often have to configure the page to use a connection string that includes
information about a user and password.
• Code access security If your page involves access to resources that are
protected under different zones, the page might run differently under the
ASP.NET Development Server and IIS.