Reading and writing to an XML file.


Question:
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.

5 comments:

  1. with this code i am able to read the file, but writing is not updates,either in the xml file or the listbox.

    ReplyDelete
  2. This is the first time i am using this blog ..wonderful... keep posting xml realated topics...

    ReplyDelete
  3. Very good, a lot of source material.
    Keep it up.

    ReplyDelete
  4. this is awsome website.lots of things to study.
    weldone venkat..

    ReplyDelete
  5. its my first time to write xml file by .cs page

    ReplyDelete

If you are aware of any other asp.net questions asked in an interview, please post them below. If you find anything missing or wrong, please feel free to correct by submitting the form below.

 
Disclaimer - Terms of use - Contact Us