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.
Subscribe to:
Comments (Atom)