Вы находитесь на странице: 1из 26

Latest ASP.

NET 2 Interview Questions


Q1. What is Dynamic Compilation?
A1. When an asp.net page is compiled for the first time, a copy of the compiled assembly
is saved in the Temporary ASP.NET Files folder. This compiled page is of the type
system.web.ui.page and includes all contents of the page (including html & scripts).
When it is compiled a second time, a precompiled version is accessed from this location,
thus speeding up the process. In case the source is changed, the assembly in the
Temporary ASP.NET Files folder gets deleted, and thus re-compilation occurs. This
process is called Dynamic Compilation.

Compilation may be enabled or disabled at page level by setting the CompilationMode


attribute in the Page Directive of the page.

Q2. How to set Dynamic Compilation for an entire website?


A2. In web.config, in pages element, add the attribute
CompilationMode="Auto".

Q3. Why do we sometimes need to disable compilation?


A3. In case of big sites with many pages, and we dont want to load an assembly into the
memory for every page. We set CompilationMode="Never".
The pages are interpreted at runtime.

Q4. What is the FindControl method?


A4. A method that searches for a control, with a specific ID inside a container and get a
reference to it. Its just like the
getElementById in javascript.

Q5. What is a partial class? Whats the advantage of using it?


A5. In ASP.NET 2.0, a class may be written at several places, and at the time of
compilation, all these classes (having the same name) get compiled as one single class.
Hence these classes are called Partial Classes.

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.

Q1.what are the new features in ASP.NET 2.0?

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.

* Data Controls: gridview, detailsview, and formview

* Navigation Controls: treeview, menu, and sitemappath

* Login Controls: login forms, create user forms, password retrieval, and custom UI for
logged in users or roles

* Web Part Controls

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.

5) Localization. Enabling globalization and localization in Web sites today is difficult,


requiring large amounts of custom code and resources. ASP.NET 2.0 and Visual Studio
2005 provide tools and infrastructure to easily build Localizable sites including the ability
to auto-detect incoming locale's and display the appropriate locale based UI. Visual
Studio 2005 includes built-in tools to dynamically generate resource files and localization
references. Together, building localized applications becomes a simple and integrated
part of the development experience.

6) Administration and Management -- New tools like Configuration API, ASP.NET


MMC Admin Tool, Pre-compilation Tool, Health Monitoring and Tracing have been
introduced.

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.

Q3. What are features of Visual Web Developer?

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.

HTML Source Preservation


Visual Web Developer respects your HTML. The formatting of your HTML markup --
including all white space, casing, indention, carriage returns, and word wrapping -- is
now preserved exactly as originally written, even when switching back and forth between
the design view and source view of the page. You can completely trust Visual Web
Developer to never modify your markup.

HTML Formatting Options


Visual Web Developer enables you to precisely control the format of all HTML and
ASP.NET Server Control markup generated using the WYSIWYG designer. You can
now configure the tag casing, attribute quotation, indention style and word wrap
characteristics of every html or server control tag in a page. You can set these formatting
options as defaults for all markup, as well as optionally override each formatting option
on a per tag/control basis. This provides you with the flexibility to fully control exactly
how you want your markup to be generated.

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.

Flexible Browser Targeting and Validation


Visual Web Developer enables you to easily target a specific HTML standard or browser
when writing your HTML pages. For example, you can target your HTML pages to work
with a particular browser such as Netscape Navigator 4.0 or Internet
Explorer 6.0. Alternatively, you can target a particular HTML standard such as XHTML
1.0 Strict or XHTML 1.0 Transitional.

Q4. What is Code Refactoring?

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.

Q5. What is Intellitask?

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.

Q6. How to we edit templates & tables while developing applications in


ASP.NET 2.0?

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).

Q7. Do we need FrontPage Server Extensions with ASP.NET 2.0 applications?

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.

Q8. Can we develop web pages directly on an FTP server?

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.

Q9. What is precompilation in ASP.NET 2.0? What is a pre-compiled website?

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.

There are 2 types of pre-compilation:


(i) In Place Precompilation
(ii) Precompilation for Deployment

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.

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:\MyStage

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.

Q10. If a web application is pre-compiled, How do you make changes to it?

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.

When we recompile an already pre-compiled website, what should be kept in mind?

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.

Update: use the -fixednames switch to generate repeatable assembly names.

Q11. Is Visual Web Developer XHTML compliant?

A11. Yes.

Q12. What are server controls?

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.

Q13. How do server control handle events?

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).

Sub EnterBtn_Click(Sender As Object, E As EventArgs)


Message.Text = "Hi " & Name.Text & ", wazzup there!"
End Sub

Q14. How to Navigate to another page?

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.

<asp:hyperlink id="hl_Link" runat=server text="click here"


NavigateUrl="www.somelink.com">
</asp:hyperlink>

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)

Q15. What is Simplified Code Behind Model in ASP.NET 2.0?

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

Partial Class CodeBehind_vb_aspx


Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
Label1.Text = "Hello " & TextBox1.Text
End Sub
End Class

Inline Code

<%@ page language="VB" CodeFile="CodeBehind_vb.aspx.vb"


Inherits="CodeBehind_vb_aspx" %>

<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>

Q16. Whats the advantage of Simplified Code Behind model?

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.

Q17. Whats the use of App_Code directory in ASP.NET 2.0?

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.

<@ Import Namespace="MyCustomNamespace">

Q20. How to register Assemblies in GAC (Global Assembly Cache)?

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.

Q22. What are data source controls?

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:

SqlDataSource Enables binding to a SQL database represented by an ADO.NET


provider, such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.
ObjectDataSource Enables binding to a middle-tier object such as a data access layer or
business component.
AccessDataSource Enables binding to a Microsoft™ Access (Jet) database.
SiteMapDataSource Enables binding to the hierarchy exposed by an ASP.NET 2.0 site
navigation provider.
XmlDataSource Enables binding to an XML file or document.
Q23. What are data bound controls?

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).

Q24. What is a Master Page? How do we use it?

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:

<%-- ContentPlaceHolder control --%>


<asp:contentplaceholder id="FlowerText" runat="server"/>
<%-- ContentPlaceHolder with default content --%>
<asp:contentplaceholder id="FlowerText" runat="server">
<h3>Welcome to my florist website!</h3>
</asp:contentplaceholder>

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.

<%@ Page MasterPageFile="Site.master" %>

Q25. What is a Content Page? How do we use it?

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.

<%@ Page MasterPageFile="Site.master" %>

<asp:content id="Content1" contentplaceholderid="FlowerText" runat="server">


Santa Clause will definitely meet you this Christmas! </asp:content>
<asp:content id="Content2" contentplaceholderid="FlowerPicture" runat="server">
<asp:Image id="image1" imageurl="~/images/santa.jpg" runat="server"/>
</asp:content>

Q26. How does Content page access a master page?

A26. In addition to overriding content, it is possible for a Content Page to


programmatically access its Master Page. A Content Page creates a strongly-typed
reference to the Master Page using the <%@ MasterType %> directive, specifying the
virtual path to the master page:

<%@ MasterType VirtualPath="Site.master" %>

The Content Page can then reference the Master Page using the Master property of the
Page class:

Master.FooterText = "This is my custom footer"


Dim adr As AdRotator = Master.FindControl("MyAdRotator")

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.

Q28. Can we have multiple SiteMapPath controls in an ASP.NET 2.0 web


application?

A28. Yes.

Q29. How to create a read-only Data Report using GridView?

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>

The SqlDataSource ConnectionString property specifies the connection string to the


database and the SelectCommand property specifies the query to execute to retrieve data.
The connection string can be specified literally in the page, but in this case the property is
assigned using a new expression syntax that retrieves the value from Web.config.

<configuration>
<connectionStrings>
<add name="Pubs" connectionString="Server=(local);Integrated
Security=True;Database=UrDatabaseName;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

Q30. How do we sort data in a GridView?

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?

A31. No. Sorting is only supported by SqlDataSource when in DataSet mode.

Inline Code looks like this...

<asp:GridView ID="GridView1" AllowSorting="true" runat="server"


DataSourceID="SqlDataSource1"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="ID" DataField="au_id" SortExpression="au_id" />
<asp:BoundField HeaderText="Last Name" DataField="au_lname"
SortExpression="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname"
SortExpression="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" SortExpression="phone"
/>
<asp:BoundField HeaderText="Address" DataField="address"
SortExpression="address" />
<asp:BoundField HeaderText="City" DataField="city" SortExpression="city" />
<asp:BoundField HeaderText="State" DataField="state" SortExpression="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" SortExpression="zip" />
<asp:CheckBoxField HeaderText="Contract" SortExpression="contract"
DataField="contract" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address],
[city], [state], [zip], [contract] FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />

Q32. How do we enable paging in a GridView?

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.

Inline Code looks like this...


<asp:GridView ID="GridView1" AllowSorting="true" AllowPaging="true"
PageSize="3" runat="server"
DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
<PagerSettings Mode="NextPreviousFirstLast" Position="TopAndBottom"
FirstPageImageUrl="~/Images/First.gif"
LastPageImageUrl="~/Images/Last.gif" NextPageImageUrl="~/Images/Next.gif"
PreviousPageImageUrl="~/Images/Prev.gif" />
<PagerStyle ForeColor="White" HorizontalAlign="Right" BackColor="#284775" />
<Columns>
<asp:BoundField HeaderText="ID" DataField="au_id" SortExpression="au_id" />
<asp:BoundField HeaderText="Last Name" DataField="au_lname"
SortExpression="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname"
SortExpression="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" SortExpression="phone"
/>
<asp:BoundField HeaderText="Address" DataField="address"
SortExpression="address" />
<asp:BoundField HeaderText="City" DataField="city" SortExpression="city" />
<asp:BoundField HeaderText="State" DataField="state" SortExpression="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" SortExpression="zip" />
<asp:CheckBoxField HeaderText="Contract" SortExpression="contract"
DataField="contract" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT
[au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]
FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />

Q33. How do we set the number of Records in a GridView to display?

A33. Use the PageSize property. It Gets or sets the number of records to display on a
page in a GridView control.

Q34. What is the TopPagerRow property of a GridView?

A34. Gets a GridViewRow object that represents the top pager row in a GridView
control.

Q35. Describe the Hotspot class?

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.

Q36. What is 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.

Inline code example...


<asp:ImageMap
AccessKey="string"
AlternateText="string"
BackColor="color name|#dddddd"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
CssClass="string"
DescriptionUrl="uri"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
ForeColor="color name|#dddddd"
GenerateEmptyAlternateText="True|False"
Height="size"
HotSpotMode="NotSet|Navigate|PostBack|Inactive"
ID="string"
ImageAlign="NotSet|Left|Right|Baseline|Top|Middle|Bottom|
AbsBottom|AbsMiddle|TextTop"
ImageUrl="uri"
OnClick="Click event handler"
OnDataBinding="DataBinding event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnPreRender="PreRender event handler"
OnUnload="Unload event handler"
runat="server"
SkinID="string"
Style="string"
TabIndex="integer"
Target="string"
ToolTip="string"
Visible="True|False"
Width="size"
>
<asp:CircleHotSpot
AccessKey="string"
AlternateText="string"
HotSpotMode="NotSet|Navigate|PostBack|Inactive"
NavigateUrl="uri"
PostBackValue="string"
Radius="integer"
TabIndex="integer"
Target="string|_blank|_parent|_search|_self|_top"
X="integer"
Y="integer" />
<asp:PolygonHotSpot
AccessKey="string"
AlternateText="string"
Coordinates="string"
HotSpotMode="NotSet|Navigate|PostBack|Inactive"
NavigateUrl="uri"
PostBackValue="string"
TabIndex="integer"
Target="string|_blank|_parent|_search|_self|_top"
/>
<asp:RectangleHotSpot
AccessKey="string"
AlternateText="string"
Bottom="integer"
HotSpotMode="NotSet|Navigate|PostBack|Inactive"
Left="integer"
NavigateUrl="uri"
PostBackValue="string"
Right="integer"
TabIndex="integer"
Target="string|_blank|_parent|_search|_self|_top"
Top="integer" />
</asp:ImageMap>

Q37. How do we Update & Delete data in a GridView?

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.

<asp:SqlDataSource ID="SqlDataSource1" runat="server"


ConnectionString="<%$ ConnectionStrings:Pubs %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]"
UpdateCommand="UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] =
@au_fname, [state] = @state WHERE [au_id] = @au_id"
DeleteCommand="DELETE FROM [authors] WHERE [au_id] = @au_id"/>

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.

Inline code example...


<asp:GridView ID="GridView1" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="SqlDataSource1" AutoGenerateEditButton="true" DataKeyNames="au_id"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField ReadOnly="true" HeaderText="ID" DataField="au_id" SortExpression="au_id" />
<asp:BoundField HeaderText="Last Name" DataField="au_lname" SortExpression="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname" SortExpression="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" SortExpression="phone" />
<asp:BoundField HeaderText="Address" DataField="address" SortExpression="address" />
<asp:BoundField HeaderText="City" DataField="city" SortExpression="city" />
<asp:BoundField HeaderText="State" DataField="state" SortExpression="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" SortExpression="zip" />
<asp:CheckBoxField HeaderText="Contract" SortExpression="contract" DataField="contract" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone],
[address], [city], [state], [zip], [contract] FROM [authors]"
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 %>" />

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.

Q38. What is the DataKeyNames property?

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.

Q39. How do we filter GridView data in ASP.NET 2.0 as compared to Datagrid in


ASP.NET 1.1?

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>

Inline code example...


<asp:GridView ID="GridView1" AllowSorting="True" AllowPaging="True" Runat="server"
DataSourceID="SqlDataSource1" AutoGenerateEditButton="True" DataKeyNames="au_id"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField ReadOnly="true" HeaderText="ID" DataField="au_id" SortExpression="au_id" />
<asp:BoundField HeaderText="Last Name" DataField="au_lname" SortExpression="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname" SortExpression="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" SortExpression="phone" />
<asp:BoundField HeaderText="Address" DataField="address" SortExpression="address" />
<asp:BoundField HeaderText="City" DataField="city" SortExpression="city" />
<asp:BoundField HeaderText="State" DataField="state" SortExpression="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" SortExpression="zip" />
<asp:CheckBoxField HeaderText="Contract" SortExpression="contract" DataField="contract" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone],

[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.

Inline Code Example of Caching...


<asp:DropDownList ID="DropDownList1" DataSourceID="SqlDataSource2" AutoPostBack="true"
DataTextField="state" Runat="server" />
<asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [state] FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />
<br />
<br />
<asp:GridView ID="GridView1" AllowSorting="True" AllowPaging="True" Runat="server"
DataSourceID="SqlDataSource1" AutoGenerateEditButton="True" DataKeyNames="au_id"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="TimeStamp" HeaderText="TimeStamp" ReadOnly="True">
<ItemStyle Font-Bold="True" />
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="ID" DataField="au_id" SortExpression="au_id" />
<asp:BoundField HeaderText="Last Name" DataField="au_lname" SortExpression="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname" SortExpression="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" SortExpression="phone" />
<asp:BoundField HeaderText="Address" DataField="address" SortExpression="address" />
<asp:BoundField HeaderText="City" DataField="city" SortExpression="city" />
<asp:BoundField HeaderText="State" DataField="state" SortExpression="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" SortExpression="zip" />
<asp:CheckBoxField HeaderText="Contract" SortExpression="contract" DataField="contract" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT DatePart(second, GetDate()) As TimeStamp,
[au_id], [au_lname], [au_fname], [phone], [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 %>" 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>

Q41. How to do a language switch in the Masterpage?

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.

in the master page:


<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="true"

OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="en" Text="English" />
<asp:ListItem Value="fr" Text="French" />
<asp:ListItem Value="de" Text="German" />
</asp:DropDownList>

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){


HttpCookie cookie = new HttpCookie("DropDownName");
cookie.Value=DropDownList1.UniqueID;
Response.SetCookie(cookie);
}

In global.asax
void Application_BeginRequest(Object sender, EventArgs e){
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["DropDownName"];

if (cookie != null && cookie.Value != null)


lang = Request.Form[cookie.Value];

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.

Q42. How to send a mail using System.Net.Mail?


(This question is answered by Ryan Olshan) Ryan Olshan's Blog

A42. Here is the code...


Imports

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

String, ByVal subject As String, ByVal body As String)


' Instantiate a new instance of MailMessage
Dim mMailMessage As New MailMessage()
' Set the sender address of the mail message
mMailMessage.From = New MailAddress(from)
' Set the recepient address of the mail message
mMailMessage.To.Add(New MailAddress(recepient))

' Check if the bcc value is nothing or an empty string


If Not bcc Is Nothing And bcc <> String.Empty Then
' Set the Bcc address of the mail message
mMailMessage.Bcc.Add(New MailAddress(bcc))
End If

' Check if the cc value is nothing or an empty value


If Not cc Is Nothing And cc <> String.Empty Then
' Set the CC address of the mail message
mMailMessage.CC.Add(New MailAddress(cc))
End If

' Set the subject of the mail message


mMailMessage.Subject = subject
' Set the body of the mail message
mMailMessage.Body = body

' Set the format of the mail message body as HTML


mMailMessage.IsBodyHtml = True
' Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal

' Instantiate a new instance of SmtpClient


Dim mSmtpClient As New SmtpClient()
' Send the mail message
mSmtpClient.Send(mMailMessage)
End Sub
End Class

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.

Вам также может понравиться