Tech 'n' Tech Books


ASP.NET Frequently Asked Questions


What is the difference between ASP and ASP.NET?

Web application development in .NET with ASP.NET has evolved a great deal. The overall architecture of web applications in .Net is much more improved and robust. The enhanced features in ASP.NET make it the best available technology for web application development. The code behind the ASP.Net scripts can be in written in any .Net compliant programming language.
The script (ASP.NET scripts), logic (code behind) and presentation (view) are separated from each other so they may evolve independently. There are much more server controls now available in .Net including the standard calendar and amazingly useful data grid controls. The ASP.Net web applications can now use .NET assemblies and COM components to serve the client requests. ASP.NET pages are now compiled contrary to the ASP pages which are interpreted by the ISA server. Truly speaking, there is no comparison between ASP and ASP.NET... ASP.NET simply rules!

What is ASP.NET?

ASP.NET is a powerful programming platform for developing web-based applications and services. It comes with rich set of web controls to create dynamic, fast and interactive web pages. Web pages built using ASP.NET are called ASP.NET web pages or web forms. ASP.NET simplifies web development by using WYSIWYG (what you see is what you get) editors. ASP.NET helps to build complex web applications with the use of drag and drop control support. Visual Studion.NET helps us to build web applications (ASP.NET) using either the C# or VB programming language. The following features are making developers choose ASP.NET over other technologies:
  • ASP.NET applications can be designed and developed using RAD (Rapid Application Development) tools.
  • ASP.NET web forms support a variety of controls and also support user created and third party controls.
  • Any .NET FrameWork language can be used to develop ASP.NET applications.
  • ASP.NET uses the Common Language Runtime (CLR) resource and benefits from it's features.

What is the use of Web.config file?

ASP.NET configuration files are XML-based text files. Each "web.config" file applies configuration settings to the directory it is located in and to all virtual sub directories under it.
Settings in sub directories can optionally override or modify settings specified in main directories. The root configuration file "WinNT\Microsoft.NET\Framework\<version>\config\machine.config" provides default configuration settings for the entire machine.
ASP.NET configures IIS to prevent direct browser access to "web.config" files. This ensures that their values cannot become public (Attempts to access them will cause ASP.NET to return 403: Access Forbidden). At run time, ASP.NET uses these "web.config" configuration files to hierarchically compute a unique collection of settings for each incoming URL target request. These settings are calculated only once and then cached across subsequent requests. ASP.NET automatically watches for file changes and will invalidate the cache if any of the configuration files change.

What are Web Services and the underlying protocol used with it?

Web Services are applications that provide services on the internet. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access.
Web services are designed for use by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.
There are three main uses of Web services. Application integration Web services within an intranet are commonly used to integrate business applications running on different platforms. For example, a .NET client running on Windows 2000 can easily invoke a Java Web service running on a mainframe or Unix machine to retrieve data from a legacy application.
Business integration Web services allow trading partners to engage in e-business allowing them to leverage the existing Internet infrastructure. Organizations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e-business with Web services means a low barrier to entry because Web services can be added to existing applications running on any platform without changing legacy code.
Commercial Web services focus on selling content and business services to clients over the Internet similar to familiar Web pages. Unlike Web pages, commercial Web services target applications as their direct users.
Example, Continental Airlines exposes flight schedules and status Web services for travel Web sites and agencies to use in their applications. Like Web pages, commercial Web services are valuable only if they offer services that are needed. It makes sense to sell real-time weather information or stock quotes as a Web service. Technology can help you add value to your services and explore new markets. However ultimately customers pay for contents and/or business services, not for technology.

How to generate a WebService proxy? What are SOAP, WSDL, and UDDI?

SOAP is an XML-based messaging protocol designed for exchanging formatted data (messages) over the Internet. Using SOAP you can send request and reply messages. SOAP is simple, easy to use, light weight and completely neutral with respect to operating systems, programming languages, and distributed computing platforms. After SOAP came into existence as a mechanism for exchanging XML messages among enterprises, a function was needed to describe the messages and how they are exchanged.
The Web Services Description Language (WSDL) is a particular form of an XML Schema. Developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL specification describes how to map messages and operations to SOAP 1.1, HTTP GET/POST and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols using "ports".
The "Universal Description, Discovery, and Integration" (UDDI) defines a data model (in XML). Also SOAP API's for registration and searching business information, web services that a business exposes to the Internet are also covered. UDDI is an independent consortium of vendors founded by Microsoft, IBM and Ariba. This project purpose of developing an Internet standard for web service description registration and discovery.
Microsoft, IBM and Ariba also are hosting the initial deployment of the UDDI service. This is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses).
UDDI uses a private agreement profile of SOAP (UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use SOAP APIs to register themselves with UDDI. Other businesses search the UDDI when they want to discover a trading partner.
The information in UDDI is categorized according to industry type and geographical location, allowing UDDI subscribers to search through lists of potentially matching businesses. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes.

What is the trace utility used for?

Using the SOAP Trace Utility
The Microsoft Simple Object Access Protocol (SOAP) Toolkit 2.0 includes a TCP/IP trace utility, MSSOAPT.EXE. You use this trace utility to view the SOAP messages sent by HTTP between a SOAP client and a service on a server. In order to use the Trace Utility, perform the following steps on the server. Open the Web Services Description Language (WSDL) file.
1) In the WSDL file, locate the <soap:address> element that corresponds to the service and change the location attribute for this element to port 8080.
For example, change
<http://MyServer/VDir/Service.wsdl>
to
<http://MyServer:8080/VDir/Service.wsdl>
.
2) Run MSSOAPT.exe.
3) File menu, New, Click "Formatted Trace" (if you don't want to see HTTP headers) or click Unformatted Trace (if you want to see HTTP headers). 4) In the Trace Setup dialog box, click OK to accept the default values.
Using the Trace Utility on Client
To see all send/receive messages from a service, do the following steps on the client.
1) Copy the WSDL file from the server to the client.
2) Modify location attribute of the <soap:address> element in the local copy of the WSDL document to direct the client to
localhost:8080
Make a note of the current host and port.
For example, Change
<http://MyServer/VDir/Service.wsdl>
to
<http://localhost:8080/VDir/Service.wsdl>
and make note of "MyServer". 3) On the client, run MSSOPT.exe.
4) File menu, New, and either click Formatted Trace (if you don't want to see HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
5) In the Destination host box, enter the host specified in Step 2.
6) In the Destination port box, enter the port specified in Step 2.
7) Click OK.

How do I upload a file from my ASP.NET page?

To upload a file with your ASP.NET page, you need the use of two classes: System.Web.UI.HtmlControls.HtmlInputFile class and the System.Web.HttpPostedFile.
The HtmlInputFile class represents an HTML input control that the user will use on the client to select a file to upload.
The HttpPostedFile class represents the uploaded file. This is obtained from the .PostedFile property of the HtmlInputFile control.
In order to use the HtmlInputFile control, you need to add the enctype attribute to your form tag as follows:
<form id="upload" method="post" runat="server" enctype="multipart/form-data">
Below is a simple example of how to upload a file via an ASP.NET page using C#.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI.HtmlControls" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<head>
<title>upload_cs</title>
</head>
<script language="C#" runat="server">
public void UploadFile(object sender, EventArgs e)
{
if (loFile.PostedFile != null)
{
try
{
String strFileName, strFileNamePath, strFileFolder;
strFileFolder = Context.Server.MapPath(@"data\");
strFileName = loFile.PostedFile.FileName;
strFileName = Path.GetFileName(strFileName);
strFileNamePath = strFileFolder + strFileName;
loFile.PostedFile.SaveAs(strFileNamePath);
lblFileName.Text = strFileName;
lblFileLength.Text = loFile.PostedFile.ContentLength.ToString();
lblFileType.Text = loFile.PostedFile.ContentType;
pnStatus.Visible = true;
}
catch (Exception x)
{
Label lblError = new Label();
lblError.ForeColor = Color.Red;
lblError.Text = "Exception occurred: " + x.Message;
lblError.Visible = true;
this.Controls.Add(lblError);
}
}
} 
</script>
<body>
<form id="upload_cs" method="post" runat="server" enctype="multipart/form-data">
<P>
<INPUT type="file" id="loFile" runat="server">
</P>
<P>
<asp:Button id="btnUpload" runat="server" Text=" Upload " OnClick="UploadFile"></asp:Button></P>
<P>
<asp:Panel id="pnStatus" runat="server" Visible="False">
<asp:Label id="lblFileName" Font-Bold="True" Runat="server"></asp:Label> uploaded<BR>
<asp:Label id="lblFileLength" Runat="server"></asp:Label> bytes<BR>
<asp:Label id="lblFileType" Runat="server"></asp:Label>
</asp:Panel></P>
</form>
</body>
</html
Tip
The /data directory is the only directory with write permissions enabled for an anonymous user. Therefore, you will need to make sure that your code uploads the file to the /data directory or one of its subdirectories.

How do I send an email from my ASP.NET page?

Include the System.Web.Mail.MailMessage and the System.Web.Mail.SmtpMail classes to send email from ASPX pages.
Below is a sample of sending email using said classes in C#.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Mail" %>
<html>
<head>
<title>Mail Test</title>
</head>
<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs e)
{
try
{
MailMessage mailObj = new MailMessage();
mailObj.From = "xyz@programmersheaven.com";
'mail from address
mailObj.To = "abc@hotmail.com";
'mail to address
mailObj.Subject = "New Article Suggestion";
'mail subject
mailObj.Body = "I am sending a link to this article which is really very interesting";
'mail body
mailObj.BodyFormat = MailFormat.Text;
SmtpMail.SmtpServer = "mail.programmersheaven.com";
'specify mail server name depending on your mail server 
SmtpMail.Send(mailObj);
Response.Write("Mail sent successfully");
}
catch (Exception x)
{
Response.Write("Your message was not sent: " + x.Message);
}
} 
</script>
<body>
<form id="mail_test" method="post" runat="server">
</form>
</body>
</HTML>
Tip
In order to send email through your mail server, you should set the static SmtpServer property of the SmtpMail class to mail-fwd.

IIS with Windows Server 2003 benefits?

Below are the benefits of using IIS 6.0 with Windows Server 2003.
  1. Faster sites without the need for high spec hardware for Web sites, intranets, and Web-based applications.
  2. You can check your site's potential speed improvement with real-time Compression Check tool provided by Port80 Software.
  3. Reduces total response time per page request. Using HTTP compression helps end users experience a 50% reduction in download time.
  4. HTTP compression reduces the size of files sent from your Web server to the Web browser by an average of 30 to 50 percent which is a dramatic decrease in bandwidth.
  5. Using IIS 6.0 compression feature you can have savings in monthly bandwidth charges.
  6. You can reduce bandwidth by enabling compression, and serve more users with the same hardware.
  7. You can delay or eliminate the need to add more Web servers by enabling IIS 6.0 compression, even when your site gets more traffic.
  8. Management code for compression is now part of core IIS 6.0 Web server for speed and stability.
  9. Server-side compatibility issues are resolved.
  10. Granular compression allows turning compression on/off at the global, site, folder, and file levels.

What is State Management and what are the different ways to maintain a state in .Net?

Web pages are recreated each time a page is posted to a server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls within the page would be lost with each round trip.
To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes when Managing the State. The page framework includes a facility called view state that automatically preserves property values of the page and all controls on it between round trips.
However, you will probably also have application-specific values that you want to preserve. This can be done using state management options.
Client-Based State Management Options: View State Hidden Form Fields Cookies Query Strings
Server-Based State Management Options

ASP.NET Controls

What server controls come with ASP.NET?

Server controls are supplied with ASP.NET. Server controls in ASP.NET are different to the normal windows controls as they work within the .NET FrameWork. The different types of server controls in ASP.NET are:
  • HTML Server Controls: These controls refer to the HTML elements that can be used in server code. The HTML elements can be converted into HTML server controls.
  • ASP.NET Server controls: ASP.NET server controls are the general controls like textbox, buttons, tables etc.
  • Validation Controls: these controls are used to validate user input. Normally these controls are attached with textboxes, checkboxes and radio buttons to check the values entered or selected.
  • USER Controls: These controls are those controls that are created by the user and are used just like all other controls.

What is the AdRotator control and it's uses?

AdRotator is a special control in ASP.NET used to display flashing banner advertisments. The control can display advertisments randomly or sequentially as set by the developer.
Using the AdRotator control
To use the control, drag it from the toolbox. In the properties window you will there are three key properties:
.AdvertisementsFile .KeywordFilter .Target
The advertisement file is an XML file which contains information about the image to be displayed and the page to which the user should be redirected on click.
The following example assumes there are two images named one.gif and two.gif. Below is the XML to correspond with our
example:
<Advertisement>
<Ad>
<ImageUrl>
one.gif
</ImageUrl>
<NavigateUrl>
http://www.onlinetechbooks.com
</NavigateUrl>
<AlternateText>
The Web's fastest growing technical encyclopdia
</AlternateText>
<Impressions>
1
</Impressions>
<Keyword>
Visual Basic
</Keyword>
</Ad>
<Ad>
<ImageUrl>
two.gif
</ImageUrl>
<NavigateUrl>
http://www.onlinetechbooks.com
</NavigateUrl>
<AlternateText>
Where the pro's are 
</AlternateText>
<Impressions>
1
</Impressions>
<Keyword>
Programming
</Keyword>
</Ad>
</Advertisements>
The above tags are explained below:
<ImageUrl>: The image URL that presents the advertisement image.
<NavigateUrl>: The on click redirect URL.
<AlternateText>: Image description/name thats show when the mouse is over the image ( Optional use ).
<Keyword>: Optional parameter that specifies the keyword (category) like books, programming etc.
<Impressions>: A number input that indicates the weight of the advertisment. This can be use to control the order of rotation with respect to other advertisments in the file. Again, this is optional.

What is a Calendar control and how do I use it?

The Calendar control is used to display the calendar year on a web page. You can view dates or select a specific day, week or month. The default event of the Calendar control is Selection Changed event that is called when a selection is made on the control.
Drag a calendar control and a textbox from the toolbox. We will display the date selected from the calendar control in the textbox.
The sample code for that is:
Private Sub Calendar1_SelectionChanged 
(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles Calendar1.SelectionChanged
TextBox1.Text = Calendar1.SelectedDat
End Sub
In Runtime Mode - Select a date from the calendar control. That date will now be the .Text Value of the textbox.

What is a RequiredFieldValidator control?

The RequiredFieldValidator is a control that checks whether the value of an assigned input control is different from its initial value.
To work with this control drag a RequiredFieldValidator control, Command Button and two TextBoxes from the Toolbox. The intention is to display the text entered in TextBox1 in TextBox2 when the Command Button is clicked. If there is no value in TextBox1, an error message ("Saying Textbox1 needs a value") will be spawned.
All you have to make the RequiredFieldValidator work is to open the properties of the control. Looking at two properties; ErrorMessage and ControltoValidate specifically. The ErrorMessage property should be completed with a warning that the field needs to be completed. Secondly, the ControltoValidate property is used to tag which control is to be validated.
The sample code for that is:
Private Sub Button1_Click(ByVal sender As System.Object, 
ByVal e As System.EventArgs) Handles Button1.Click
TextBox2.Text = TextBox1.Text

End Sub

What is a CompareValidatorControl?

CompareValidator is used to make sure that a value matches a specified value. This control is often used when validating passwords. Important properties of this control are .ControlToValidate and .ControlToCompare.
.ControlTovalidate property is used to set the control to be validated and the .ControlToCompare property is used to identify the control to be compared.
To work with this control drag a CompareValidatorControl, a Command Button and two TextBoxes from the ToolBox. The intention is to enter two values the textboxes. If the two values do not match, an error is generated denoting that the values are not alike.
Set the following control properties in CompareValidatorControl; .ControlToCompare property as TextBox1 and .ControltoValidate property as TextBox2.
Run the code and enter some text in both the textboxes and click the button. If both the TextBox values are the same then no error message will arise else an error.

What is a RangeValidator control?

A RangeValidator control is used to determine whether a control value falls within a specified range. The RangeValidator checks whether the value passed to the control is within the range specified. This type of watch dog is generally used when buying products online like tickets etc.
To work with the RangeValidator control, drag a TextBox and a RangeValidator Control from the toolbox. Open the RangeValidator control properties and enter a value of 8 in the MaximumValue field, 3 in the MinimumValue field and set TextBox1 as the control to be validated.
Run the code and try entering some values in the TextBox. If the value entered is within the specified range ( 8 High, 3 Low ) then nothing happens else an error message is displayed.

What is a RegularExpressionValidator?

RegularExpressionValidator control is used to check a value against a regular expression. It checks whether the value of the associated input control matches the pattern of the regular expression. This Control generally used to check whether the entered phone number or email address matches a set format. A notable property of this control is the ValidationExpression property, which is used to set the validation criteria and which comes with some predefined formats.
To work with a RegularExpressionValidator control; Drag a TextBox and a Command Button from the ToolBox. Our intention is to check for the format of an email address and display an error message if the input format is not correct. An example of a correctly formated inpput would be "xyz@programmersheaven.com". To implement format definition. In the properties window of the Regularexpression click on the ellipse button for ValidationExpression and select Internet E-mail Address from the pop-up window. When you run the program and enter a value not in the format of abc@xyz.com the error message is displayed.

What is the difference between a Web User Control and a Web Custom Control?

Web custom controls are compiled components that run on the server and encapsulate the user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox. There are several ways to create Web custom controls:
You can compile a control that combines the functionality of two or more existing controls. For example, if you need a control that encapsulates a button and a text box. You can create it by compiling the existing controls together.
If an existing server control almost meets your requirements but lacks some required features, you can customize the control by deriving from it and overriding its properties, methods, and events. If none of the existing Web server controls (or their combinations) meet your requirements, you can create a custom control by deriving from one of the base control classes. These classes provide all the functionality like other Web server controls. You only need to write the logic for the programming features you require.
If none of the existing ASP.NET server controls meet the specific requirements of your applications, you can create either a Web user control or a Web custom control that encapsulates the functionality you need.
The main difference between the two controls lies in ease of creation vs. ease of use at design time. Web user controls are easy to make, but they can be less convenient to use in advanced scenarios. Web user controls can be developed almost exactly the same way that you develop Web Form pages.
Like Web Forms, user controls can be created in the visual designer or they can be written with code separate from the HTML. They can also support execution events. However, since Web user controls are compiled dynamically at run time they cannot be added to the Toolbox and they are represented by a simple placeholder when added to a page.
This makes Web user controls harder to use if you are accustomed to full Visual Studio .NET design-time support, including the Properties window and Design view previews. Also the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control.
Web custom controls are compiled code, which makes them easier to use but more difficult to create. Web custom controls must be authored in code. Once you have created the control you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which make maintenance easier.