Wednesday, 26 November 2008
List all the files in a directory on a web form in asp.net
List all the files in a directory on a web form. The files must be displayed in a gridview control. The name of the file and create date must be displayed.
Answer:
1. Create a new web form. Drag and drop a gridview control from the toolbox onto the webform.
2. Create 2 bound fields for the gridview. One bound field will display the file name and the other will display the create date.
3. The HTML for your web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListFiles.aspx.cs" Inherits="ListFiles" %>
<html>
<head runat="server">
<title>List all the files in a directory</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="File Name"></asp:BoundField>
<asp:BoundField DataField="DateCreated" HeaderText="Date" DataFormatString="{0:d}"></asp:BoundField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
4. In the code behind file write a function which can get the list of files from the directory and bind to the gridview. The function is as shown below.
private void LoadFiles()
{
/* Create an instance of DirectoryInfo class for enumarating through the directory. */
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Server.MapPath("FilesDirectory"));
/* Call the GetFiles() instance method of the DirectoryInfo class object, which will return a files list from the current directory */
System.IO.FileInfo[] fiFiles = dirInfo.GetFiles();
/* Create a DataTable which can be used as the datasource for the gridview */
DataTable dtFileList = new DataTable("Files");
/* Create a DataColumn for file name */
DataColumn dcFileName = new DataColumn("FileName");
/* Create a DataColumn for file create date */
DataColumn dcDateCreated = new DataColumn("DateCreated", typeof(DateTime));
/* Add the 2 data columns to the data table */
dtFileList.Columns.Add(dcFileName);
dtFileList.Columns.Add(dcDateCreated);
/* Now loop through each FileInfo object and get the file name and file create date */
foreach (System.IO.FileInfo f in fiFiles)
{
DataRow dtNewRow = dtFileList.NewRow();
/* Get the file name using FileInfo object "Name" property */
dtNewRow["FileName"] = f.Name.ToString();
/* Get the file create date and time using FileInfo object "CreationTime" property */
dtNewRow["DateCreated"] = f.CreationTime.ToShortDateString();
/* Add the row to the DataTable */
dtFileList.Rows.Add(dtNewRow);
}
/* Set the datatable as the DataSource for the gridview and call the DataBind() method */
GridView1.DataSource = dtFileList;
GridView1.DataBind();
}
5. Finally call the LoadFiles() method on the page load event handler as shown below.
protected void Page_Load(object sender, EventArgs e)
{
LoadFiles();
}
Testing the application:
1. Right click on the project name in solution explorer, and left click on "NewFolder"
2. Rename the "NewFolder" to "FilesDirectory"
3. Drag and Drop some files into the directoy.
4. Then run the application. All the files in the "FilesDirectory" folder will be shown in the gridview.
ASP.NET Interview Questions on Write and Read a cookie
Question:Give an example to show how to write and read a cookie from a client's computer.
Answer:
1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores
FirstName
LastName
LastVisit
2. Create the user interface to enter FirstName and LastName. The HTML for the webform is as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesExample.aspx.cs" Inherits="CookiesExample" %>
<html>
<head runat="server">
<title>Write a cookie to the client computer</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td style="width: 100px">
First Name</td>
<td style="width: 100px">
<asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
Last Name
</td>
<td style="width: 100px">
<asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="WriteCookieButton" runat="server" Text="Write Cookie" OnClick="WriteCookieButton_Click" />
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="ReadCookieButton" runat="server" Text="Read Cookie" OnClick="ReadCookieButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}
4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}
5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.
Answer:
1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores
FirstName
LastName
LastVisit
2. Create the user interface to enter FirstName and LastName. The HTML for the webform is as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesExample.aspx.cs" Inherits="CookiesExample" %>
<html>
<head runat="server">
<title>Write a cookie to the client computer</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td style="width: 100px">
First Name</td>
<td style="width: 100px">
<asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
Last Name
</td>
<td style="width: 100px">
<asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="WriteCookieButton" runat="server" Text="Write Cookie" OnClick="WriteCookieButton_Click" />
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="ReadCookieButton" runat="server" Text="Read Cookie" OnClick="ReadCookieButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}
4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}
5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.
Tuesday, 25 November 2008
The IHttpHandler and IHttpHandlerFactory interfaces ?
The IHttpHandler interface is implemented by all the handlers. The interface consists of one property called IsReusable. The IsReusable property gets a value indicating whether another request can use the IHttpHandler instance. The method ProcessRequest() allows you to process the current request. This is the core place where all your code goes. This method receives a parameter of type HttpContext using which you can access the intrinsic objects such as Request and Response. The IHttpHandlerFactory interface consists of two methods - GetHandler and ReleaseHandler. The GetHandler() method instantiates the required HTTP handler based on some condition and returns it back to ASP.NET. The ReleaseHandler() method allows the factory to reuse an existing handler.
Does .NET CLR and SQL SERVER run in different process?
Dot Net CLR and all .net realtes application and Sql Server run in same process or we can say that that on the same address because there is no issue of speed because if these two process are run in different process then there may be a speed issue created one process goes fast and other slow may create the problem.
What do you mean by three-tier architecture?
The three-tier architecture was comes into existence to improve management of code and contents and to improve the performance of the web based applications. There are mainly three layers in three-tier architecture. the are define as follows
(1)Presentation
(2)Business Logic
(3)Database
(1)First layer Presentation contains mainly the interface code, and this is shown to user. This code could contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.
(2)Second layer is Business Logic which contains all the code of the server-side .This layer have code to interact with database and to query, manipulate, pass data to user interface and handle any input from the UI as well.
Monday, 24 November 2008
ASP.NET Interview Questions on HTTP modules and HTTP Handlers
What is an HTTP Handler?
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
What is HTTP module?An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
What is the interface that you have to implement if you have to create a Custom HTTP Handler?
Implement IHttpHandler interface to create a synchronous handler.
Implement IHttpAsyncHandler to create an asynchronous handler.
What is the difference between asynchronous and synchronous HTTP Handlers?A synchronous handler does not return until it finishes processing the HTTP request for which it is called.
An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.
Which class is responsible for receiving and forwarding a request to the appropriate HTTP handler?
IHttpHandlerFactory Class
Can you create your own custom HTTP handler factory class?Yes, we can create a custom HTTP handler factory class by creating a class that implements the IHttpHandlerFactory interface.
What is the use of HTTP modules?
HTTP modules are used to implement various application features, such as forms authentication, caching, session state, and client script services.
What is the difference between HTTP modules and HTTP handlers?An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.
What is the common way to register an HTTP module?The common way to register an HTTP module is to have an entry in the application's Web.config file.
Much of the functionality of a module can be implemented in a global.asax file. When do you create an HTTP module over using Global.asax File?
You create an HTTP module over using Global.asax file if the following conditions are true
1. You want to re-use the module in other applications.
2. You want to avoid putting complex code in the Global.asax file.
3. The module applies to all requests in the pipeline.
Saturday, 22 November 2008
ASP.NET Interview Questions on Themes and Skins
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What is a "theme" in ASP.NET?A "theme" is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.
What is the extension for a skin file?
.skinWhat are the 2 types of control skins in ASP.NET?
1. Default skins
2. Named skinsWhat is the difference between Named skins and Default skins?A default skin automatically applies to all controls of the same type when a theme is applied to a page. A control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)
A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application.What are the 3 levels at which a theme can be applied for a web application?
1. At the page level - Use the Theme or StyleSheetTheme attribute of the @ Page directive.
2. At the application level - Can be applied to all pages in an application by setting the <pages> element in the application configuration file.
3. At the web server level - Define the <pages> element in machine.config file. This will apply the theme to all the web applications on that web server.What is the name of the folder that contains the application themes?App_Themes
What is a global theme?
A global theme is a theme that you can apply to all the Web sites on a server. Global themes allow you to define an overall look for your domain when you maintain multiple Web sites on the same server.
What is the difference between themes and CSS?
1. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.
2. Themes can include graphics.
3. Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property.
4. Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.What are the security concerns to keep in mind when using themes?Themes can cause security issues when they are used on your Web site. Malicious themes can be used to:
1. Alter a control's behavior so that it does not behave as expected.
2. Inject client-side script, therefore posing a cross-site scripting risk.
3. Expose sensitive information.
4. The mitigations for these common threats are:
5. Protect the global and application theme directories with proper access control settings. Only trusted users should be allowed to write files to the theme directories.
6. Do not use themes from an untrusted source. Always examine any themes from outside your organization for malicious code before using them on you Web site.
7. Do not expose the theme name in query data. Malicious users could use this information to use themes that are unknown to the developer and thereby expose sensitive information.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Reading and writing to an XML file.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Create a simple web page, that can read and write to an XML file. The XML file has a list of email ids. The sample web form should have the following functionality. You have 30 minutes to code and test.
1. A TextBox to accept a valid email id.
2. A submit button. When you click the submit button, the email id entered in the TextBox must be saved to the XML file.
3. If I donot enter anything in the TextBox and click the submit button, the application should show a validation message stating "Email is required".
4. If I enter an invalid email, the application should show a message "Invalid Email".
5. If javascript is enabled the validation should happen on the client browser without postback. If javascript is disabled the validation should happen on the web server.
6. Finally we should have a list box, which will show all the existing email ids in the XML file. When you submit a new email, the listbox should be reloaded showing the newly added email along with already existing email ids.
Answer:
1. Create a webform and add a TextBox, RequiredFieldValidator, RegularExpressionValidator, Button and a ListBox.
2. Set the RequiredFieldValidator "ErrorMessage" property to "Email Required" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
3. Set the RegularExpressionValidator "ErrorMessage" property to "Invalid Email" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
4. Set the ListBox, "DataTextField" property to "Email" and DataValueField property to "Email"
5. The complete HTML of the web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
<title>Email List</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
Please enter a valid email:
</td>
<td>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /></td>
</tr>
</table>
<br />
Existing Email Ids
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="292px" Width="192px" DataTextField="Email" DataValueField="Email"></asp:ListBox>
</form>
</body>
</html>
6. Place the XML file that contains the list of email ids in the root folder of the web application. The sample XML file is shown below.
<?xml version="1.0" standalone="yes"?>
<EmailsList>
<Emails>
<Email>dhex@yahoo.com</Email>
</Emails>
<Emails>
<Email>dmexy@aol.com</Email>
</Emails>
<Emails>
<Email>dpitt@gmail.com</Email>
</Emails>
<Emails>
<Email>mston@microsoft.com</Email>
</Emails>
</EmailsList>
7. In the code behind file, write a function the can read the email ids from the XML file into a DataSet. Set this DataSet as the DataSource for the ListBox and call the DataBind() method. The function should be as shown below.
private void LoadExistingEmails()
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
ListBox1.DataSource = DS;
ListBox1.DataBind();
}
8. Call the above LoadExistingEmails() function in the Page_Load event handler as shown in the sample code below.
protected void Page_Load(object sender, EventArgs e)
{
LoadExistingEmails();
}
9. Finally, when you click the submit button write to the XML file as shown below.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
DataRow DR = DS.Tables[0].NewRow();
DR["Email"] = EmailTextBox.Text;
DS.Tables[0].Rows.Add(DR);
DS.WriteXml(Server.MapPath("Emails.xml"));
LoadExistingEmails();
}
}
Points to remember:
1. Validation controls work both on the client and on the server.
2. If javascript is enabled validations happen on the client browser without posting the page back to the server.
3. If javascript is disabled, validations happen on the server. To check if all the validation controls haved passed validation, use Page.IsValid property.
4. Page.IsValid returns "true" if the page has succeeded validation and "false" even if a single validation control has filed validation.
5. In our example, we write to the XML file only if Page.IsValid property returns true.
Testing the sample application:To test if the validation controls are working on the server, disable javascript on the client browser. To disable javascript on the client browser follow the below steps.
1. Open internet explorer.
2. Click on Tools.
3. Click on Internet Options. You will see Internet Options dialog page.
4. Click on the Security tab.
5. On the Security tab, select Local intranet under Select a zone to view or change security settings.
6. Click "Custom Level" button under "Security Level for this zone"
7. On the "Security Setting - Local Intranet Zone" dialog page, scroll down to "Scripting" section.
8. Select "Disable" radio button under "Active scription" and click "OK" button.
Click here for all ASP.NET Interview Questions
Create a simple web page, that can read and write to an XML file. The XML file has a list of email ids. The sample web form should have the following functionality. You have 30 minutes to code and test.
1. A TextBox to accept a valid email id.
2. A submit button. When you click the submit button, the email id entered in the TextBox must be saved to the XML file.
3. If I donot enter anything in the TextBox and click the submit button, the application should show a validation message stating "Email is required".
4. If I enter an invalid email, the application should show a message "Invalid Email".
5. If javascript is enabled the validation should happen on the client browser without postback. If javascript is disabled the validation should happen on the web server.
6. Finally we should have a list box, which will show all the existing email ids in the XML file. When you submit a new email, the listbox should be reloaded showing the newly added email along with already existing email ids.
Answer:
1. Create a webform and add a TextBox, RequiredFieldValidator, RegularExpressionValidator, Button and a ListBox.
2. Set the RequiredFieldValidator "ErrorMessage" property to "Email Required" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
3. Set the RegularExpressionValidator "ErrorMessage" property to "Invalid Email" and "ControlToValidate" property to "EmailTextBox" and "Display" property to "Dynamic" as shown below.
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
4. Set the ListBox, "DataTextField" property to "Email" and DataValueField property to "Email"
5. The complete HTML of the web form should be as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
<title>Email List</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
Please enter a valid email:
</td>
<td>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ErrorMessage="Email Required" ControlToValidate="EmailTextBox" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server" ErrorMessage="Invalid Email" ControlToValidate="EmailTextBox" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /></td>
</tr>
</table>
<br />
Existing Email Ids
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="292px" Width="192px" DataTextField="Email" DataValueField="Email"></asp:ListBox>
</form>
</body>
</html>
6. Place the XML file that contains the list of email ids in the root folder of the web application. The sample XML file is shown below.
<?xml version="1.0" standalone="yes"?>
<EmailsList>
<Emails>
<Email>dhex@yahoo.com</Email>
</Emails>
<Emails>
<Email>dmexy@aol.com</Email>
</Emails>
<Emails>
<Email>dpitt@gmail.com</Email>
</Emails>
<Emails>
<Email>mston@microsoft.com</Email>
</Emails>
</EmailsList>
7. In the code behind file, write a function the can read the email ids from the XML file into a DataSet. Set this DataSet as the DataSource for the ListBox and call the DataBind() method. The function should be as shown below.
private void LoadExistingEmails()
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
ListBox1.DataSource = DS;
ListBox1.DataBind();
}
8. Call the above LoadExistingEmails() function in the Page_Load event handler as shown in the sample code below.
protected void Page_Load(object sender, EventArgs e)
{
LoadExistingEmails();
}
9. Finally, when you click the submit button write to the XML file as shown below.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Emails.xml"));
DataRow DR = DS.Tables[0].NewRow();
DR["Email"] = EmailTextBox.Text;
DS.Tables[0].Rows.Add(DR);
DS.WriteXml(Server.MapPath("Emails.xml"));
LoadExistingEmails();
}
}
Points to remember:
1. Validation controls work both on the client and on the server.
2. If javascript is enabled validations happen on the client browser without posting the page back to the server.
3. If javascript is disabled, validations happen on the server. To check if all the validation controls haved passed validation, use Page.IsValid property.
4. Page.IsValid returns "true" if the page has succeeded validation and "false" even if a single validation control has filed validation.
5. In our example, we write to the XML file only if Page.IsValid property returns true.
Testing the sample application:To test if the validation controls are working on the server, disable javascript on the client browser. To disable javascript on the client browser follow the below steps.
1. Open internet explorer.
2. Click on Tools.
3. Click on Internet Options. You will see Internet Options dialog page.
4. Click on the Security tab.
5. On the Security tab, select Local intranet under Select a zone to view or change security settings.
6. Click "Custom Level" button under "Security Level for this zone"
7. On the "Security Setting - Local Intranet Zone" dialog page, scroll down to "Scripting" section.
8. Select "Disable" radio button under "Active scription" and click "OK" button.
Thursday, 20 November 2008
write a custom reusable function to populate a dropdownlist
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Write a custom function in c-sharp. The custom function parameters should be an instance of a dropdownlist, an xml file and a string.
1. The function should be capabale of populating the passed in dropdownlist.
2. The first item in the dropdownlist should be the passed in string parameter.
3. The data for the dropdownlist comes from the passed in XML file.
The idea is to create a custom function which can be reused through out the project for populating any dropdownlist on any web page. You have 20 minutes to code, test and demonstrate.
The sample code for custom function is shown below. For this example to work drop the XML file in the root folder of the web application.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
public void PopulateDropdownlist(System.Web.UI.WebControls.DropDownList DropDownListObjectToBePopulated,string XMLFilePath, string InitialString)
{
try
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(XMLFilePath));
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
}
catch(Exception Ex)
{
}
}
The XML file that has the data for the dropdownlist is as shown below.<?xml version="1.0" encoding="utf-8" ?>
<StatesList>
<State>
<StateName>Virginia</StateName>
<StateCode>VA</StateCode>
</State>
<State>
<StateName>Iowa</StateName>
<StateCode>IA</StateCode>
</State>
<State>
<StateName>North Carolina</StateName>
<StateCode>NC</StateCode>
</State>
<State>
<StateName>Pennsylvania</StateName>
<StateCode>PA</StateCode>
</State>
<State>
<StateName>Texas</StateName>
<StateCode>TX</StateCode>
</State>
</StatesList>
Explanation of the code:
1. PopulateDropdownlist function has 3 parameters. DropDownList to be populated, the path of the XML file which has the data for the dropdownlist and the initial string.
2. Create an instance of DataSet. In our example the instance is DS.
DataSet DS = new DataSet();
3. Read the XML data into the dataset instance using ReadXml() method. Pass the path of the XML file to ReadXml() method. We used Server.MapPath() method to return the physical file path that corresponds to the specified virtual path on the web server.
DS.ReadXml(Server.MapPath(XMLFilePath));
4. We now have the data from the XML file in the dataset as a DataTable.
5. Check if the InitialString is empty. If not empty create a new ListItem object and populate the Text and Value properties. Then add the listitem object to the dropdownlist.
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
6. Finally loop thru the rows in the DataTable and create an instance of ListItem class. Populate the Text and Value properties to StateName and StateCode respectively. Finally add the ListItem object to the dropdownlist.
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
7. Drag and drop the dropdownlist on a webform. Call the PopulateDropdownlist() custom function in the Page_Load event handler. When you call the custom function pass the dropdownlist to be populated, XML file path and the initial string.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
Write a custom function in c-sharp. The custom function parameters should be an instance of a dropdownlist, an xml file and a string.
1. The function should be capabale of populating the passed in dropdownlist.
2. The first item in the dropdownlist should be the passed in string parameter.
3. The data for the dropdownlist comes from the passed in XML file.
The idea is to create a custom function which can be reused through out the project for populating any dropdownlist on any web page. You have 20 minutes to code, test and demonstrate.
The sample code for custom function is shown below. For this example to work drop the XML file in the root folder of the web application.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
public void PopulateDropdownlist(System.Web.UI.WebControls.DropDownList DropDownListObjectToBePopulated,string XMLFilePath, string InitialString)
{
try
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(XMLFilePath));
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
}
catch(Exception Ex)
{
}
}
The XML file that has the data for the dropdownlist is as shown below.<?xml version="1.0" encoding="utf-8" ?>
<StatesList>
<State>
<StateName>Virginia</StateName>
<StateCode>VA</StateCode>
</State>
<State>
<StateName>Iowa</StateName>
<StateCode>IA</StateCode>
</State>
<State>
<StateName>North Carolina</StateName>
<StateCode>NC</StateCode>
</State>
<State>
<StateName>Pennsylvania</StateName>
<StateCode>PA</StateCode>
</State>
<State>
<StateName>Texas</StateName>
<StateCode>TX</StateCode>
</State>
</StatesList>
Explanation of the code:
1. PopulateDropdownlist function has 3 parameters. DropDownList to be populated, the path of the XML file which has the data for the dropdownlist and the initial string.
2. Create an instance of DataSet. In our example the instance is DS.
DataSet DS = new DataSet();
3. Read the XML data into the dataset instance using ReadXml() method. Pass the path of the XML file to ReadXml() method. We used Server.MapPath() method to return the physical file path that corresponds to the specified virtual path on the web server.
DS.ReadXml(Server.MapPath(XMLFilePath));
4. We now have the data from the XML file in the dataset as a DataTable.
5. Check if the InitialString is empty. If not empty create a new ListItem object and populate the Text and Value properties. Then add the listitem object to the dropdownlist.
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
6. Finally loop thru the rows in the DataTable and create an instance of ListItem class. Populate the Text and Value properties to StateName and StateCode respectively. Finally add the ListItem object to the dropdownlist.
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
7. Drag and drop the dropdownlist on a webform. Call the PopulateDropdownlist() custom function in the Page_Load event handler. When you call the custom function pass the dropdownlist to be populated, XML file path and the initial string.
protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Wednesday, 19 November 2008
DataSet
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What is a DataSet?DataSet is an in-memory cache of data.
In which namespace is the DataSet class present?
System.Data
Can you add more than one table to a dataset?Yes
Can you enforce constarints and relations on tables inside a DataSet?Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.
What happens when you invoke AcceptChanges() method on a DataSet?
Invoking AcceptChanges() method on the DataSet causes AcceptChanges() method to be called on each table within the DataSet.
Both the DataRow and DataTable classes also have AcceptChanges() methods. Calling AcceptChanges() at the DataTable level causes the AcceptChanges method for each DataRow to be called.
When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes. Added and Modified rows become Unchanged, and Deleted rows are removed.
If the DataSet contains ForeignKeyConstraint objects, invoking the AcceptChanges method also causes the AcceptRejectRule to be enforced.
Is there a way to clear all the rows from all the tables in a DataSet at once?Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.
What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
DataSet.Copy() copies both the structure and data.
How do you get a copy of the DataSet containing all changes made to it since it was last loaded?
Use DataSet.GetChanges() method
What is the use of DataSet.HasChanges() Method?
DataSet.HasChanges method returns a boolean true if there are any changes made to the DataSet, including new, deleted, or modified rows. This method can be used to update a DataSource only if there are any changes.
How do you roll back all the changes made to a DataSet since it was created? Invoke the DataSet.RejectChanges() method to undo or roll back all the changes made to a DataSet since it was created.
What happnes when you invoke RejectChanges method, on a DataSet that contains 3 tables in it?
RejectChanges() method will be automatically invoked on all the 3 tables in the dataset and any changes that were done will be rolled back for all the 3 tables.
When the DataTable.RejectChanges method is called, any rows that are still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state. The DataRowState for all the modified and deleted rows will be flipped back to unchanged.
What is the DataSet.CaseSensitive property used for?
When you set the CaseSensitive property of a DataSet to true, string comparisons for all the DataTables within dataset will be case sensitive. By default the CaseSensitive property is false.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
What is a DataSet?DataSet is an in-memory cache of data.
In which namespace is the DataSet class present?
System.Data
Can you add more than one table to a dataset?Yes
Can you enforce constarints and relations on tables inside a DataSet?Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.
What happens when you invoke AcceptChanges() method on a DataSet?
Invoking AcceptChanges() method on the DataSet causes AcceptChanges() method to be called on each table within the DataSet.
Both the DataRow and DataTable classes also have AcceptChanges() methods. Calling AcceptChanges() at the DataTable level causes the AcceptChanges method for each DataRow to be called.
When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes. Added and Modified rows become Unchanged, and Deleted rows are removed.
If the DataSet contains ForeignKeyConstraint objects, invoking the AcceptChanges method also causes the AcceptRejectRule to be enforced.
Is there a way to clear all the rows from all the tables in a DataSet at once?Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.
What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
DataSet.Copy() copies both the structure and data.
How do you get a copy of the DataSet containing all changes made to it since it was last loaded?
Use DataSet.GetChanges() method
What is the use of DataSet.HasChanges() Method?
DataSet.HasChanges method returns a boolean true if there are any changes made to the DataSet, including new, deleted, or modified rows. This method can be used to update a DataSource only if there are any changes.
How do you roll back all the changes made to a DataSet since it was created? Invoke the DataSet.RejectChanges() method to undo or roll back all the changes made to a DataSet since it was created.
What happnes when you invoke RejectChanges method, on a DataSet that contains 3 tables in it?
RejectChanges() method will be automatically invoked on all the 3 tables in the dataset and any changes that were done will be rolled back for all the 3 tables.
When the DataTable.RejectChanges method is called, any rows that are still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state. The DataRowState for all the modified and deleted rows will be flipped back to unchanged.
What is the DataSet.CaseSensitive property used for?
When you set the CaseSensitive property of a DataSet to true, string comparisons for all the DataTables within dataset will be case sensitive. By default the CaseSensitive property is false.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Monday, 17 November 2008
ASP.NET Interview Questions on Globalization
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application into multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.
The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application�s current culture, and much of the work is done automatically!
What are the 3 different ways to globalize web applications?
Detect and redirect approach : In this approach we create a separate Web application for each supported culture, and then detect the user�s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.
Run-time adjustment approach : In this approach we create a single Web application that detects the user�s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.
Satellite assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user�s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.
In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object�s UserLanguages property to return a list of the user�s language preferences. The first element of the array returned by UserLanguages is the user�s current language on his/her computer.
What are the steps to follow to get user's culture at run time?To get the user�s culture at run time, follow these steps:
1. Get the Request object�s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user�s current culture.
For example, the following code gets the user�s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}
What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.
What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific Web site.
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.
What is the use of culture attribute of the globalization element in web.config?The Web.config file�s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.
Web.config globalization settings in subordinate folders override the globalization settings in the application�s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user�s CurrentCulture.
The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.
<body dir="rtl">
You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.
What do you mean by neutral cultures?Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.
What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn�t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don�t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.
For what type of web applications setting the culture dynamically is best suited?Setting the culture dynamically is best suited for simple Web applications that don�t contain large amounts of text that must be translated into different languages.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application into multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.
The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application�s current culture, and much of the work is done automatically!
What are the 3 different ways to globalize web applications?
Detect and redirect approach : In this approach we create a separate Web application for each supported culture, and then detect the user�s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.
Run-time adjustment approach : In this approach we create a single Web application that detects the user�s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.
Satellite assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user�s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.
In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object�s UserLanguages property to return a list of the user�s language preferences. The first element of the array returned by UserLanguages is the user�s current language on his/her computer.
What are the steps to follow to get user's culture at run time?To get the user�s culture at run time, follow these steps:
1. Get the Request object�s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user�s current culture.
For example, the following code gets the user�s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}
What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.
What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific Web site.
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.
What is the use of culture attribute of the globalization element in web.config?The Web.config file�s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.
Web.config globalization settings in subordinate folders override the globalization settings in the application�s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user�s CurrentCulture.
The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.
<body dir="rtl">
You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.
What do you mean by neutral cultures?Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.
What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn�t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don�t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.
For what type of web applications setting the culture dynamically is best suited?Setting the culture dynamically is best suited for simple Web applications that don�t contain large amounts of text that must be translated into different languages.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Thursday, 13 November 2008
Arrays
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below
1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
int[] IntegerArray; // not int IntegerArray[];
2. Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.
int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array
What are the 3 different types of arrays that we have in C#?1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays
Are arrays in C# value types or reference types?Reference types.
What is the base class for all arrays in C#?System.Array
How do you sort an array in C#?The Sort static method of the Array class can be used to sort array items.
Give an example to print the numbers in the array in descending order?using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}
What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}
Give an example to show how to copy one array into another array?We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below
1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
int[] IntegerArray; // not int IntegerArray[];
2. Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.
int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array
What are the 3 different types of arrays that we have in C#?1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays
Are arrays in C# value types or reference types?Reference types.
What is the base class for all arrays in C#?System.Array
How do you sort an array in C#?The Sort static method of the Array class can be used to sort array items.
Give an example to print the numbers in the array in descending order?using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}
What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}
Give an example to show how to copy one array into another array?We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Value types VS Reference types C#
What is difference between Value types and Reference types in VB.NET or C# (Value types VS Reference types)C# provides two types�class and struct, class is a reference type while the other is a value type. Here is difference between Value types and Reference types.Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure. Reference types
Wednesday, 12 November 2008
XML Interview Questions
What determines the validity of an XML document?
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.
What is a valid XML document?XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.
What are the 2 types of XML parsers?
Nonvalidating Parsers - Parsers that don�t support validation
Validating Parsers - Parsers that support validation
Can you combine both Schema and DTD references in a single XML document?Yes
Are DTD's well-formed XML documents?
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.
Are XML schema's well-formed XML documents?Yes.
What is the difference between an XML schema and a DTD?
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.
How do you define references to schemas in an XML document?References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.
<rootelement xmlns:xsi=�http://www.w3.org/2001/XMLSchemainstance� xsi:noNamespaceSchemaLocation=�schemafile.xsd�>
The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.
You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.
What is a valid XML document?XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.
What are the 2 types of XML parsers?
Nonvalidating Parsers - Parsers that don�t support validation
Validating Parsers - Parsers that support validation
Can you combine both Schema and DTD references in a single XML document?Yes
Are DTD's well-formed XML documents?
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.
Are XML schema's well-formed XML documents?Yes.
What is the difference between an XML schema and a DTD?
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.
How do you define references to schemas in an XML document?References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.
<rootelement xmlns:xsi=�http://www.w3.org/2001/XMLSchemainstance� xsi:noNamespaceSchemaLocation=�schemafile.xsd�>
The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.
You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.
Tuesday, 11 November 2008
XML related Interview Questions
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What Is XML?
XML stands for Extensible Markup Language, and it is used to describe documents and data in a standardized, text-based format that can be easily transported via standard Internet protocols. XML, like HTML, is based on, Standard Generalized Markup Language (SGML).
What are Well-formed XML documents?
XML, is very strict about a small core of format requirements that make the difference between a text document containing a bunch of tags and an actual XML document. XML documents that meet W3C XML document formatting recommendations are described as being well-formed XML documents. Well-formed XML documents can contain elements, attributes, and text.
What is an empty XML element?
Elements with no attributes or text are called as empty XML element. Empty XML elements can be represented in an XML document as shown below:
<element/>
What is meant by XML document declaration?Most XML documents start with an <?xml?> element at the top of the page. This is called an XML document declaration. An XML document declaration is an optional element that is useful to determine the version of XML and the encoding type of the source data. It is not a required element for an XML document to be well formed. Most common XML document declaration is shown below:
<?xml version=�1.0� encoding=�UTF-8�?>
What does UTF stands for?
UTF stands for Universal Character Set Transformation Format.
Should every XML document have a root element?Yes.
Can an XML document contain multiple root level elements?
No, an XML document can contain only one root level element.
What is the use of XML attributes?XML attributes are used for adding more information and descriptions to the values of elements,and the text associated with elements.
Is XML case sensitive?
Yes
How do you comment lines in XML?You can comment lines in XML as shown below.
<! -- This is commented line in an XML document -->
What are XML namespaces?
Namespaces are a method for separating and identifying duplicate XML element names in an XML document. Namespaces can also be used as identifiers to describe data types and other information. Namespace declarations can be compared to defining a short variable name for a long variable (such as pi=3.14159....) in programming languages. In XML, the variable assignment is defined by an attribute declaration. The variable name is the attribute name, and the variable value is the attribute value. In order to identify namespace declarations versus other types of attribute declarations, a reserved xmlns: prefix is used when declaring a namespace name and value. The attribute name after the xmlns: prefix identifies the name for the defined namespace. The value of the attribute provides the unique identifier for the namespace. Once the namespace is declared, the namespace name can be used as a prefix in element names.
Why is it a good idea to use a URL as the XML namespace value?
Although the namespace declaration value does not need to be a URL or resolve to an actual URL destination, it is a good idea to use a URL anyway, and to choose a URL that could resolve to an actual destination, just in case developers want to add documentation for the namespace to the URL in the future.
When to use namespaces?Namespaces are optional components of basic XML documents. However, namespace declarations are recommended if your XML documents have any current or future potential of being shared with other XML documents that may share the same element names. Also, newer XML-based technologies such as XML Schemas,SOAP, and WSDL make heavy use of XML namespaces to identify data encoding types and important elements of their structure.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
What Is XML?
XML stands for Extensible Markup Language, and it is used to describe documents and data in a standardized, text-based format that can be easily transported via standard Internet protocols. XML, like HTML, is based on, Standard Generalized Markup Language (SGML).
What are Well-formed XML documents?
XML, is very strict about a small core of format requirements that make the difference between a text document containing a bunch of tags and an actual XML document. XML documents that meet W3C XML document formatting recommendations are described as being well-formed XML documents. Well-formed XML documents can contain elements, attributes, and text.
What is an empty XML element?
Elements with no attributes or text are called as empty XML element. Empty XML elements can be represented in an XML document as shown below:
<element/>
What is meant by XML document declaration?Most XML documents start with an <?xml?> element at the top of the page. This is called an XML document declaration. An XML document declaration is an optional element that is useful to determine the version of XML and the encoding type of the source data. It is not a required element for an XML document to be well formed. Most common XML document declaration is shown below:
<?xml version=�1.0� encoding=�UTF-8�?>
What does UTF stands for?
UTF stands for Universal Character Set Transformation Format.
Should every XML document have a root element?Yes.
Can an XML document contain multiple root level elements?
No, an XML document can contain only one root level element.
What is the use of XML attributes?XML attributes are used for adding more information and descriptions to the values of elements,and the text associated with elements.
Is XML case sensitive?
Yes
How do you comment lines in XML?You can comment lines in XML as shown below.
<! -- This is commented line in an XML document -->
What are XML namespaces?
Namespaces are a method for separating and identifying duplicate XML element names in an XML document. Namespaces can also be used as identifiers to describe data types and other information. Namespace declarations can be compared to defining a short variable name for a long variable (such as pi=3.14159....) in programming languages. In XML, the variable assignment is defined by an attribute declaration. The variable name is the attribute name, and the variable value is the attribute value. In order to identify namespace declarations versus other types of attribute declarations, a reserved xmlns: prefix is used when declaring a namespace name and value. The attribute name after the xmlns: prefix identifies the name for the defined namespace. The value of the attribute provides the unique identifier for the namespace. Once the namespace is declared, the namespace name can be used as a prefix in element names.
Why is it a good idea to use a URL as the XML namespace value?
Although the namespace declaration value does not need to be a URL or resolve to an actual URL destination, it is a good idea to use a URL anyway, and to choose a URL that could resolve to an actual destination, just in case developers want to add documentation for the namespace to the URL in the future.
When to use namespaces?Namespaces are optional components of basic XML documents. However, namespace declarations are recommended if your XML documents have any current or future potential of being shared with other XML documents that may share the same element names. Also, newer XML-based technologies such as XML Schemas,SOAP, and WSDL make heavy use of XML namespaces to identify data encoding types and important elements of their structure.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Monday, 10 November 2008
When not to use Design Patterns
Do not use design patterns in any of the following situations.
� When the software being designed would not change with time.
� When the requirements of the source code of the application are unique.
If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design.
� When the software being designed would not change with time.
� When the requirements of the source code of the application are unique.
If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design.
When to use Design Patterns
Design Patterns are particularly useful in one of the following scenarios.
� When the software application would change in due course of time.
� When the application contains source code that involves object creation and event notification.
� When the software application would change in due course of time.
� When the application contains source code that involves object creation and event notification.
Benefits of Design Patterns
The following are some of the major advantages of using Design Patterns in software development.
� Flexibility
� Adaptability to change
� Reusability
� Flexibility
� Adaptability to change
� Reusability
What are Design Patterns?
A Design Pattern essentially consists of a problem in a software design and a solution to the same. In Design Patterns each pattern is described with its name, the motivation behind the pattern and its applicability.
According to MSDN, "A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development.
According to MSDN, "A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development.
Friday, 31 October 2008
What is IIS Metabase? How to edit IIS metabase? How to backup IIS metabase file?
IIS metabase is the repository of the configuration values that are set in the Internet Information Server (IIS). The IIS metabase in an XML file. It may be controlled through program or manually too.
In order to edit IIS metabase entries, the user needs to have administrative rights on the system. To do this, in run window, type "inetmgr". Browse to "Local Computer" and right click it. Click on "Properties". Select the "Enable Direct Metabase Edit" check box.
Many times, due to the existence of multiple versions of .NET framework, some settings in the IIS metabase may get affected and cause your program not to run. For such scenarios, you may take a backup of the IIS metabase XML file and recover it. To create a portable backup, open run window and type "inetmgr". Next browse to "Local Computer" and go to "All Tasks". Next, click on Backup/Restore Configuration. Next, click on "Create Backup". In the textbox box for Configuration Backup name, type a name for your backup file. Also select the encrypt backup option and type a password. To finish the process, click "OK".
In order to edit IIS metabase entries, the user needs to have administrative rights on the system. To do this, in run window, type "inetmgr". Browse to "Local Computer" and right click it. Click on "Properties". Select the "Enable Direct Metabase Edit" check box.
Many times, due to the existence of multiple versions of .NET framework, some settings in the IIS metabase may get affected and cause your program not to run. For such scenarios, you may take a backup of the IIS metabase XML file and recover it. To create a portable backup, open run window and type "inetmgr". Next browse to "Local Computer" and go to "All Tasks". Next, click on Backup/Restore Configuration. Next, click on "Create Backup". In the textbox box for Configuration Backup name, type a name for your backup file. Also select the encrypt backup option and type a password. To finish the process, click "OK".
Describe the Provider Model in ASP.NET 2.0?
The Provider model in ASP.NET 2.0 is based on the Provider Design Pattern that was created in the year 2002 and later implemented in the .NET Framework 2.0.
The Provider Model supports automatic creation of users and their respective roles by creating entries of them directly in the SQL Server (May even use MS Access and other custom data sources). So actually, this model also supports automatically creating the user table's schema.
The Provider model has 2 security providers in it: Membership provider and Role Provider. The membership provider saves inside it the user name (id) and corresponding passwords, whereas the Role provider stores the Roles of the users.
For SQL Server, the SqlMembershipProvider is used, while for MS Access, the AccessMembershipProvider is used. The Security settings may be set using the website adminstration tool. Automatically, the AccessMembershipProvider creates a Microsoft Access database file named aspnetdb.mdb inside the application's App_Data folder. This contains 10 tables.
The Provider Model supports automatic creation of users and their respective roles by creating entries of them directly in the SQL Server (May even use MS Access and other custom data sources). So actually, this model also supports automatically creating the user table's schema.
The Provider model has 2 security providers in it: Membership provider and Role Provider. The membership provider saves inside it the user name (id) and corresponding passwords, whereas the Role provider stores the Roles of the users.
For SQL Server, the SqlMembershipProvider is used, while for MS Access, the AccessMembershipProvider is used. The Security settings may be set using the website adminstration tool. Automatically, the AccessMembershipProvider creates a Microsoft Access database file named aspnetdb.mdb inside the application's App_Data folder. This contains 10 tables.
Explain about Generics?
Generics are not a completely new construct; similar concepts exist with other languages. For example, C++ templates can be compared to generics. However, there's a big difference between C++ templates and .NET generics. With C++ templates the source code of the template is required when a template is instantiated with a specific type. Contrary to C++ templates, generics are not only a construct of the C# language; generics are defined with the CLR. This makes it possible to instantiate generics with a specific type in Visual Basic even though the generic class was defined with C#.
Tuesday, 28 October 2008
Interview Questions on Cascading Style Sheets
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What are the 2 ways provided by ASP.NET to format output in a Web application?
1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and behavior of the HTML elements on a Web page.
2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those elements.
What are Cascading style sheets?
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.
What are the 3 levels at which formatting can be applied with in a web application?
1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet.
2. You can also define styles in the page�s head element. These styles can be applied to all elements on the current page.
3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are defined.
Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading.
What are the advantages of storing style definitions in a style sheet file (.css) rather than locally in each Web form or inline with each HTML element?
1. Formatting can be maintained in one location so that you make changes only once for an entire application.
2. Several sets of parallel formatting rules can be maintained in separate style sheets for formatting output on different devices or for different user needs. For example, an application might provide standard, enlarged-type, and printer-friendly style sheets that the user can select at run time.
3. In general, you should use page and inline styles only when you have a really good reason to override the global styles. Relying heavily on page and inline styles can make it difficult to maintain the formatting in a Web application.
What HTML element is used to reference a style sheet on webform?To reference a style sheet on webform you must add a link element to the page�s head element, as shown below.
<link href="Styles.css" type="text/css" rel="stylesheet">What is the use of Style Builder?
Style Builder is used to change the appearance of any of the styles in a style sheet. Changes to the style sheet change the appearance of all Web forms that reference that style sheet.
How do you modify a style sheet using style builder?To modify a style sheet using style builder, follow these steps:
1. Open the style sheet in Visual Studio. Visual Studio .NET displays the style definitions in the Document window and an outline of the style sheet in the Tool window
2. Select the style to modify from the Tool window. Visual Studio .NET displays the definition for that style in the Document window.
3. Right-click in the style definition or right-click the style in the Tool window, and select Build Style from the shortcut menu. Visual Studio .NET displays the Style Builder Wizard.
4. Use the Style Builder to compose the formatting that you want to add or modify in the selected style, and then click OK.
5. When you have finished, you�ll see that the Style Builder adds the new or modified style attributes to the style definition.
Can you apply styles using class names or element IDs?Yes, Using class names allows you to apply a single style to a number of different elements or to style the same element differently, depending on how the element is used. Using element IDs allows you to apply a style to a unique element on one or more Web forms.
When you create a style rule for a class, Visual Studio .NET adds a style definition to the style sheet using a .classname identifier.
You apply the style class to HTML elements by using the class attribute. You apply the style to server controls by using the CssClass attribute.
Can you change style sheets at run time?Yes.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
What are the 2 ways provided by ASP.NET to format output in a Web application?
1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and behavior of the HTML elements on a Web page.
2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those elements.
What are Cascading style sheets?
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.
What are the 3 levels at which formatting can be applied with in a web application?
1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet.
2. You can also define styles in the page�s head element. These styles can be applied to all elements on the current page.
3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are defined.
Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading.
What are the advantages of storing style definitions in a style sheet file (.css) rather than locally in each Web form or inline with each HTML element?
1. Formatting can be maintained in one location so that you make changes only once for an entire application.
2. Several sets of parallel formatting rules can be maintained in separate style sheets for formatting output on different devices or for different user needs. For example, an application might provide standard, enlarged-type, and printer-friendly style sheets that the user can select at run time.
3. In general, you should use page and inline styles only when you have a really good reason to override the global styles. Relying heavily on page and inline styles can make it difficult to maintain the formatting in a Web application.
What HTML element is used to reference a style sheet on webform?To reference a style sheet on webform you must add a link element to the page�s head element, as shown below.
<link href="Styles.css" type="text/css" rel="stylesheet">What is the use of Style Builder?
Style Builder is used to change the appearance of any of the styles in a style sheet. Changes to the style sheet change the appearance of all Web forms that reference that style sheet.
How do you modify a style sheet using style builder?To modify a style sheet using style builder, follow these steps:
1. Open the style sheet in Visual Studio. Visual Studio .NET displays the style definitions in the Document window and an outline of the style sheet in the Tool window
2. Select the style to modify from the Tool window. Visual Studio .NET displays the definition for that style in the Document window.
3. Right-click in the style definition or right-click the style in the Tool window, and select Build Style from the shortcut menu. Visual Studio .NET displays the Style Builder Wizard.
4. Use the Style Builder to compose the formatting that you want to add or modify in the selected style, and then click OK.
5. When you have finished, you�ll see that the Style Builder adds the new or modified style attributes to the style definition.
Can you apply styles using class names or element IDs?Yes, Using class names allows you to apply a single style to a number of different elements or to style the same element differently, depending on how the element is used. Using element IDs allows you to apply a style to a unique element on one or more Web forms.
When you create a style rule for a class, Visual Studio .NET adds a style definition to the style sheet using a .classname identifier.
You apply the style class to HTML elements by using the class attribute. You apply the style to server controls by using the CssClass attribute.
Can you change style sheets at run time?Yes.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Sunday, 26 October 2008
String manipulation
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Questions:
Please write a sample program that parses the string into a series of substrings where the delimiter between the substrings is "^*!%~" and then reassembles the strings and delimiters into a single new string where each of the substrings is in the reverse order from the original string. The method must return the final string.Original String:Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E
Output String:
Token E^*!%~Token D^*!%~Token C^*!%~Token B^*!%~Token AThe code sample below shows how to solve the above question:using System;
using System.Text;
namespace GenericsSample
{
class Program
{
static void Main()
{
string strOriginalString = "Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E";
string[] strSeperator = new string[1];
strSeperator[0] = "^*!%~";
string[] strArrayIndividualStrings = strOriginalString.Split(strSeperator, StringSplitOptions.RemoveEmptyEntries);
int intLengthOfStringArray = strArrayIndividualStrings.Length;
StringBuilder sbOutputString = new StringBuilder();
for (int i = (intLengthOfStringArray - 1); i >= 0; i--)
{
sbOutputString.Append(strArrayIndividualStrings[i] + strSeperator[0]);
}
Console.WriteLine("Original String : " + strOriginalString);
Console.WriteLine("Output String : " + sbOutputString.ToString());
Console.ReadLine();
}
}
}
Explanation of the above sample program:
1. We take the original string into a string variable strOriginalString. I named this variable as strOriginalString. str indicates that the variable is of string datatype. This will give a good impression to the person who reviews your code bcos you are following the coding standards.
2. I then store the string delimiter "^*!%~" in strSeperator variable. strSeperator is of string array data type. This is bcos the split function expects string array or character array as seprator.
3. I then split the strOriginalString into a string array using the split function.
4. I created a variable sbOutputString to store the Output string. sbOutputString data type is StringBuilder.
5. I then loop thru the array from the highest index to 0 and retrieve the individual strings and append to the sbOutputString. As the output string is changing as we loop thru the array it is good to use StringBuilder rather than System.String. Strings of type System.Text.StringBuilder are mutable where as strings of type System.String are immutable. If a string is manipulated many times always use StringBuilder over System.String.
6. Two good things to remember from this example are, follow the coding standards in naming the variables and always use StringBuilder class over Strings where we manipulate a particular string many times.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
Questions:
Please write a sample program that parses the string into a series of substrings where the delimiter between the substrings is "^*!%~" and then reassembles the strings and delimiters into a single new string where each of the substrings is in the reverse order from the original string. The method must return the final string.Original String:Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E
Output String:
Token E^*!%~Token D^*!%~Token C^*!%~Token B^*!%~Token AThe code sample below shows how to solve the above question:using System;
using System.Text;
namespace GenericsSample
{
class Program
{
static void Main()
{
string strOriginalString = "Token A^*!%~Token B^*!%~Token C^*!%~Token D^*!%~Token E";
string[] strSeperator = new string[1];
strSeperator[0] = "^*!%~";
string[] strArrayIndividualStrings = strOriginalString.Split(strSeperator, StringSplitOptions.RemoveEmptyEntries);
int intLengthOfStringArray = strArrayIndividualStrings.Length;
StringBuilder sbOutputString = new StringBuilder();
for (int i = (intLengthOfStringArray - 1); i >= 0; i--)
{
sbOutputString.Append(strArrayIndividualStrings[i] + strSeperator[0]);
}
Console.WriteLine("Original String : " + strOriginalString);
Console.WriteLine("Output String : " + sbOutputString.ToString());
Console.ReadLine();
}
}
}
Explanation of the above sample program:
1. We take the original string into a string variable strOriginalString. I named this variable as strOriginalString. str indicates that the variable is of string datatype. This will give a good impression to the person who reviews your code bcos you are following the coding standards.
2. I then store the string delimiter "^*!%~" in strSeperator variable. strSeperator is of string array data type. This is bcos the split function expects string array or character array as seprator.
3. I then split the strOriginalString into a string array using the split function.
4. I created a variable sbOutputString to store the Output string. sbOutputString data type is StringBuilder.
5. I then loop thru the array from the highest index to 0 and retrieve the individual strings and append to the sbOutputString. As the output string is changing as we loop thru the array it is good to use StringBuilder rather than System.String. Strings of type System.Text.StringBuilder are mutable where as strings of type System.String are immutable. If a string is manipulated many times always use StringBuilder over System.String.
6. Two good things to remember from this example are, follow the coding standards in naming the variables and always use StringBuilder class over Strings where we manipulate a particular string many times.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Friday, 24 October 2008
ASP.NET Interview Questions on caching application data
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Which object can used to store frequently used items in the server�s memory for quick retrieval?
Cache object can be used to store frequently used items in the server�s memory for quick retrieval.
Is the cache object available for all web forms with in a web application?
Yes, the Cache object is global, that is, data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.
What are the 3 different ways to store data in the Cache object?
Use assignment.
Assigning a value to an unused key in the Cache object automatically creates that key and assigns the value to that key. Assigning a value to a key that already exists replaces the cached value with the assigned value.Use the Insert method.The Insert method uses parameters rather than assignment to create or change cached data. Insert optionally accepts parameters to establish dependencies and set expiration policy.Use the Add method.The Add method is similar to Insert; however, it requires all parameters and returns an object reference to the cached data.
For example, the following Cache statements all add the same item to the cache:
using System.Web.Caching;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Cache["NewItem"] = "Some string data";
Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null);
Cache.Insert("NewItem", "Some string data");
}
}
What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?
absoluteExpirationA DateTime object that identifies when the data should be removed from the cache. If you�re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.slidingExpirationA TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you�re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.
Which delegate can be used to notify the application when items are removed from the cache?
onRemoveCallback is used to notify the application when items are removed from the cache.
How do you retrieve the value of a cache item stored in the servers memory?
You can retrieve the value of a cache item stored in the servers memory through the item�s key, just as you do with the Application and Session objects. Because cached items might be removed from memory, you should always check for their existence before attempting to retrieve their value, as shown in the following code:
private void Button1_Click(object sender, EventArgs e)
{
if (Cache["ChachedItem"] == null)
{
Lable1.Text = "Cached Item not found.";
}
else
{
Lable1.Text = Cache["ChachedItem"].ToString();
}
}
Which method can be used to remove data from the cache?
Cache object�s Remove method can be used to remove data from the cache as shown in the following code example / sample.
private void RemoveButton_Click(object sender, System.EventArgs e)
{
Cache.Remove("CachedItem");
}
How do you control how long data is cached?
The Cache object�s Add and Insert method parameters allow you to control how long an item is stored in the server�s memory. In practice, these parameter settings provide only indirect control of how long data remains in memory. If your server runs low on available memory, ASP.NET recovers as much memory as possible from expired cache items. If that�s not enough, ASP.NET will unload unexpired items from the cache based on their priority and when they were last accessed.
What is CacheItemPriority enumeration used for?
CacheItemPriority enumeration is used to set the relative importance of cached items. CacheItemPriority.NotRemoveable has the highest priority and CacheItemPriority.Low has the lowest priority.
Which is the only "event� provided by Cache object?
CacheItemRemoved "event� is the only "event� provided by Cache object.
How do you update the Cache object when data changes?
Items stored in the cache are often copies of data that is stored and maintained elsewhere, such as records in a database. Use the Add and Insert methods� dependency parameter to establish a relationship between a cached data item and an external source, such as a file, a folder, or a group of files.
The dependency parameter accepts a CacheDependency object, which in turn identifies the file, folder, or set of files to watch for changes. ASP.NET checks the time stamp of the items in the CacheDependency object, if one of those time stamps is later than the DateTime entered for the cached item, ASP.NET unloads that item from the cache.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Thursday, 23 October 2008
ASP.NET Interview Questions on fragment caching
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What is fragment caching?
Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.
What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.
What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control�s class declaration to enable fragment caching.
What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.
VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).
If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can�t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.
When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect.
If the Web form�s cache duration is longer than the user control�s, both the Web form response and the user control response will expire using the Web form setting.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Click here for all ASP.NET Interview Questions
What is fragment caching?
Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.
What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.
What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control�s class declaration to enable fragment caching.
What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.
VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).
If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can�t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.
When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect.
If the Web form�s cache duration is longer than the user control�s, both the Web form response and the user control response will expire using the Web form setting.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Wednesday, 22 October 2008
What is caching?
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
How do you cache multiple responses from a single Web form?The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.
You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.
The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application�s Global.asax file.Is it possible to cache a web form without using @OutputCache directive?Yes, you can cache a web form using the Response object�s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive�s attributes.Give a simple example to show how to cache a web form without using @OutputCache directive?For example, the following code caches the Web form�s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}
The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"
What is @OutputCache directive�s Location attribute and the HttpCachePolicy object�s SetCacheability property used for?
The @OutputCache directive�s Location attribute and the HttpCachePolicy object�s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheability setting as more of a request than a command.What is HttpCachePolicy object�s SetAllowResponseInBrowserHistory method used for?You can override the cache location settings using the HttpCachePolicy object�s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client�s history folder even if the location setting is None or Server.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview QuestionsHigh-performance Web applications should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form�s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.
Caching an item incurs considerable overhead, so it�s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form�s server-side content so that changes to that content do not appear until the cache is refreshed.What directive is used to cache a web form?The @OutputCache page directive is used to cache a Web form in the server�s memory.What is the use of duration attribute of @OutputCache page directive?The @OutputCache directive�s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.
The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.
After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.What are the 2 required attributes of the @OutputCache directive?The @OutputCache directive has two required attributes:
1. Duration
2. VaryByParam.
Click here for all ASP.NET Interview Questions
How do you cache multiple responses from a single Web form?The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.
You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.
The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application�s Global.asax file.Is it possible to cache a web form without using @OutputCache directive?Yes, you can cache a web form using the Response object�s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive�s attributes.Give a simple example to show how to cache a web form without using @OutputCache directive?For example, the following code caches the Web form�s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}
The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"
What is @OutputCache directive�s Location attribute and the HttpCachePolicy object�s SetCacheability property used for?
The @OutputCache directive�s Location attribute and the HttpCachePolicy object�s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheability setting as more of a request than a command.What is HttpCachePolicy object�s SetAllowResponseInBrowserHistory method used for?You can override the cache location settings using the HttpCachePolicy object�s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client�s history folder even if the location setting is None or Server.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview QuestionsHigh-performance Web applications should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form�s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.
Caching an item incurs considerable overhead, so it�s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form�s server-side content so that changes to that content do not appear until the cache is refreshed.What directive is used to cache a web form?The @OutputCache page directive is used to cache a Web form in the server�s memory.What is the use of duration attribute of @OutputCache page directive?The @OutputCache directive�s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.
The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.
After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.What are the 2 required attributes of the @OutputCache directive?The @OutputCache directive has two required attributes:
1. Duration
2. VaryByParam.
Tuesday, 21 October 2008
Interview Questions on ASP.NET Custom Controls
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
What are composite custom controls?
2. User Controls cannot be compiled into an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user control in every project where you want to use it, where as this is not the case with custom controls. You can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.
5. User controls are used for reusing existing user interface elements and code, but are not useful for developing reusable components for multiple web applications.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Composite custom controls combine one or more server or HTML controls within a single control class, which can be compiled along with other control classes to create an assembly (.dll) that contains a custom control library. Once created, the custom control library can be loaded into Visual Studio .NET and used in the same way as the standard server and HTML controls.
Composite custom controls are functionally similar to user controls, but they reside in their own assemblies, so you can share the same control among multiple projects without having to copy the control to each project, as you must do with user controls. However, composite controls are somewhat more difficult to create because you can�t draw them visually using the Visual Studio .NET Designer.
What are the steps to follow create and use a custom control in a Web application?
1. Create a solution containing a custom control project.
2. Add a Web application project to the solution, and set it as the startup project. You will use the Web application project to test the custom control during development.
3. Add a project reference from the Web application to the custom control project, and add an HTML @Register directive and control element to use the custom control on a Web form.
4. Create the custom control�s visual interface by adding existing controls to it through the custom control�s CreateChildControls method.
5. Add the properties, methods, and events that the custom control provides.
6. Build and test the custom control.
In general what is the base class for every composite custom control?
System.Web.UI.WebControls.WebControl
Which directive is used to add a custom control to a Web form?
Register directive.
What are the 3 Register directive's attributes?
TagPrefix
This name identifies the group that the user control belongs to. For example, the tag prefix for ASP.NET server controls is �asp�. You use this prefix to create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that contains the controls to register. Microsoft Visual Basic .NET uses the project name as an implicit namespace, so for controls written in Visual Basic .NET, use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The control assembly must be referenced by the Web application. Referencing the assembly maintains a copy of it in the Web application�s /bin directory.
What are the differences between User Controls and Custom Controls?
1. User Controls are easy to create where as Custom Controls are difficult to create.
Click here for all ASP.NET Interview Questions
What are composite custom controls?
2. User Controls cannot be compiled into an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user control in every project where you want to use it, where as this is not the case with custom controls. You can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.
5. User controls are used for reusing existing user interface elements and code, but are not useful for developing reusable components for multiple web applications.
Click here for all C# Interview Questions
Click here for all ASP.NET Interview Questions
Composite custom controls combine one or more server or HTML controls within a single control class, which can be compiled along with other control classes to create an assembly (.dll) that contains a custom control library. Once created, the custom control library can be loaded into Visual Studio .NET and used in the same way as the standard server and HTML controls.
Composite custom controls are functionally similar to user controls, but they reside in their own assemblies, so you can share the same control among multiple projects without having to copy the control to each project, as you must do with user controls. However, composite controls are somewhat more difficult to create because you can�t draw them visually using the Visual Studio .NET Designer.
What are the steps to follow create and use a custom control in a Web application?
1. Create a solution containing a custom control project.
2. Add a Web application project to the solution, and set it as the startup project. You will use the Web application project to test the custom control during development.
3. Add a project reference from the Web application to the custom control project, and add an HTML @Register directive and control element to use the custom control on a Web form.
4. Create the custom control�s visual interface by adding existing controls to it through the custom control�s CreateChildControls method.
5. Add the properties, methods, and events that the custom control provides.
6. Build and test the custom control.
In general what is the base class for every composite custom control?
System.Web.UI.WebControls.WebControl
Which directive is used to add a custom control to a Web form?
Register directive.
What are the 3 Register directive's attributes?
TagPrefix
This name identifies the group that the user control belongs to. For example, the tag prefix for ASP.NET server controls is �asp�. You use this prefix to create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that contains the controls to register. Microsoft Visual Basic .NET uses the project name as an implicit namespace, so for controls written in Visual Basic .NET, use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The control assembly must be referenced by the Web application. Referencing the assembly maintains a copy of it in the Web application�s /bin directory.
What are the differences between User Controls and Custom Controls?
1. User Controls are easy to create where as Custom Controls are difficult to create.
Subscribe to:
Comments (Atom)