Locating an XML Element

Introduction

In some cases, you may want to perform an operation on an existing and particular node. For example, you may want to change the value of a node, you may want to add a new child node to an existing node, etc. Before taking any of these actions, you must be able to locate or identify the desired element.

Locating an element consists of looking for a particular node among the nodes. To do this, you must start somewhere. Obviously, the first node you can identify is the root. Once you get the root, you can then get a collection of its children. After getting a collection of the children of the root, you can locate a node in the collection. If the node you are looking for is a child of that first collection, you can then get a collection of the child nodes of that node and proceed.

The System.Xml namespace provides various means of looking for a node in an XML file.

Practical LearningPractical Learning: Introducing XML Node Maintenance

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle frame of the New Project dialog box, click ASP.NET Web Application (.NET Framework). Change the project Name to TireDirect1
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  6. In the Solution Explorer, right-click TireDirect1 -> Add -> New Folder
  7. Type Images
  8. Save the following graphic to the Images folder:

    Tire Direct - Tires

  9. In the Solution Explorer, right-click Content -> Add New -> Item...
  10. In the left frame of the Add New Item dialog box, click Web. In the middle frame, click Style Sheet
  11. Change the file Name to TireDirect
  12. Click Add
  13. Create some styles as follows:
    body {
        background-color: #F2EDDA;
    }
    
    .bold             { font-weight:      600;               }
    .xsmall-size      { width:            75px;              }
    .small-size       { width:            125px;             }
    .medium-size      { width:            150px;             }
    .large-size       { width:            200px;             }
    .lead             { color:            #d4d393;           }
    .col-md-4 h2      { color:            #800000;           }
    .navbar           { background-color: #b46a03;           }
    .navbar-fixed-top { border-bottom:    6px solid #000;    }
    .form-control     { border:           1px solid #b46a03; }
    .topbar           { top:              0;
                        width:            100%;
                        height:           16em;
                        position:         fixed;
                        background-color: #5b3807;
                        border-bottom:    4px solid #000000; }
    .tires-container  { margin:           auto;
                        height:           220px;
                        width:            715px;
                        border:           4px solid #000;
                        background-image: url("../Images/td1.png"); }
    .jumbotron        { padding-top:      30px;
                        padding-bottom:   10px;
                        background-color: #5b3807; }
    .jumbotron h1     { text-align:       center;
                        color:            #F2EDDA; }
    .grouping         { border-radius:    5px;
                        padding-left:     20px;
                        padding-right:    20px;
                        background-color: #E0DCCC;
                        border:           2px solid #800000; }
    .group-small      { width:            315px; }
    .group-large      { width:            400px; }
    .grouping legend  { border-radius:    5px;
                        margin-left:      10px;
                        font-size:        16px;
                        width:            235px;
                        color:            #E5DDAF;
                        background-color: #6B2C3D;
                        padding:          5px 15px;
                        box-shadow:       0 0 0 5px #E5DDAF; }
    .grouping table   { margin-bottom:    15px;
                        margin-left:      15px;    }
    .small-container  { margin:           auto;
                        width:            400px;   }
    .large-container  { margin:           auto;
                        width:            1240px;  }
    .copyright        { text-align:       center;
                        color:            wheat;   }
    .navbar-inverse .navbar-brand              { color:         #FFF;    }
    .navbar-inverse .navbar-brand:hover,
    .navbar-inverse .navbar-brand:focus        { color:         #d8d553; }
    .navbar-inverse .navbar-nav > li > a       { color:         #FFF;    }
    .navbar-inverse .navbar-nav > li > a:hover,
    .navbar-inverse .navbar-nav > li > a:focus { color:         #d8d553; }
    .container .jumbotron                      { border-radius: 1px;
                                                 border-bottom-left-radius: 16px;
                                                 border-bottom-right-radius: 16px; }
  14. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  15. Change the document as follows:
    using System.Web.Optimization;
    
    namespace TireDirect1
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/TireDirect.css"));
            }
        }
    }
  16. In the Solution Explorer, right-click TireDirect -> Add -> New Folder
  17. Type TireDirect
  18. In the Solution Explorer, expand Views and expand Shared
  19. Double-click _Layout.cshtml to open it
  20. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Tire Direct</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Tire Direct", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Locations", "About", "Home")</li>
                        <li>@Html.ActionLink("Vehicles", "Index", "Home")</li>
                        <li>@Html.ActionLink("Accessories", "Index", "Home")</li>
                        <li>@Html.ActionLink("Tires & Seasons", "About", "Home")</li>
                        <li>@Html.ActionLink("Tire Selection", "Contact", "Home")</li>
                        <li>@Html.ActionLink("Scenario", "About", "Home")</li>
                        <li>@Html.ActionLink("FAQs", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
        </div>
        <div class="navbar navbar-inverse navbar-fixed-bottom">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Tools & Equipment", "About", "Home")</li>
                        <li>@Html.ActionLink("Tire Parts", "Index", "Home")</li>
                        <li>@Html.ActionLink("Cars", "Index", "Home")</li>
                        <li>@Html.ActionLink("Motorcycles", "About", "Home")</li>
                        <li>@Html.ActionLink("RVs", "About", "Home")</li>
                        <li>@Html.ActionLink("Current Deals", "About", "Home")</li>
                        <li>@Html.ActionLink("Tire Care", "Contact", "Home")</li>
                        <li>@Html.ActionLink("About Us", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
            <hr />
            <footer>
                <p class="copyright">&copy; @DateTime.Now.Year - Tire Direct</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  21. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  22. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller - Empty
  23. Click Add
  24. Type Employees to get EmployeesController
  25. Click Add
  26. Create an action method named Create as follows:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace TireDirect11.Controllers
    {
        public class EmployeesController : Controller
        {
            // GET: Employees
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: Employees/Create
            public ActionResult Create(string EmployeeNumber, string FirstName, string LastName)
            {
                if (!string.IsNullOrEmpty(EmployeeNumber))
                {
                    XmlDocument xdEmployees = new XmlDocument();
                    string fileName = Server.MapPath("/TireDirect/Employees.xml");
    
                    if (System.IO.File.Exists(fileName))
                    {
                        using (FileStream fsEmployees = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdEmployees.Load(fsEmployees);
                        }
                    }
                    else
                    {
                        xdEmployees.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                            "<employees></employees>");
                    }
    
                    XmlElement xeEmployee = xdEmployees.CreateElement("employee");
    
                    xeEmployee.InnerXml = "<employee-number>" + EmployeeNumber + "</employee-number>" +
                                          "<first-name>" + FirstName + "</first-name>" +
                                          "<last-name>" + LastName + "</last-name>";
    
                    xdEmployees.DocumentElement.PrependChild(xeEmployee);
    
                    using (FileStream fsStudies = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                    {
                        xdEmployees.Save(fsStudies);
                    }
    
                    return RedirectToAction("CreateEmployeeRecord");
                }
    
                return View();
            }
        }
    }
  27. In the document, right-click incide the Create() method and click Add View
  28. In the Add View dialog box, make sure the text box displays Create.
    Click Add
  29. Create a form as follows:
    @{
        ViewBag.Title = "New Employee Record";
    }
    
    <div class="text-center">
        <h2>New Employee Record</h2>
    </div>
    
    <hr />
    
    <div align="center">
        @using (Html.BeginForm())
        {
            <table>
                <tr>
                    <td><b>Employee #:</b></td>
                    <td>@Html.TextBox("EmployeeNumber", "", htmlAttributes: new { @class = "form-control" })</td>
                </tr>
                <tr>
                    <td><b>First Name:</b></td>
                    <td>@Html.TextBox("FirstName", "", htmlAttributes: new { @class = "form-control" })</td>
                </tr>
                <tr>
                    <td><b>Last Name:</b></td>
                    <td>@Html.TextBox("LastName", "", htmlAttributes: new { @class = "form-control" })</td>
                </tr>
            </table>
    
            <hr />
    
            <p class="text-center"><input type="submit" name="btnCreateEmployeeRecord" value="Create Employee Record" class="btn btn-warning" /></p>
        }
    </div>

Locating an Element Using its Index

Consider the following XML file named videos.xml:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
	<title>The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<length>112 Minutes</length>
	<format>DVD</format>
	<rating>R</rating>
  </video>
  <video>
	<title>Her Alibi</title>
	<director>Bruce Beresford</director>
	<length>94 Minutes</length>
	<format>DVD</format>
	<rating>PG-13</rating>
  </video>
  <video>
	<title>The Day After Tomorrow</title>
	<director>Roland Emmerich</director>
	<length>124 Minutes</length>
	<format>DVD</format>
	<rating>PG-13</rating>
  </video>
  <video>
	<title>Other People&#039;s Money</title>
	<director>Alan Brunstein</director>
	<length>114 Minutes</length>
	<format>VHS</format>
	<rating>PG-13</rating>
  </video>
</videos>

We know that the XmlNodeList class is equipped with both a method and an indexed propery named Item. Their syntaxes are:

public abstract XmlNode Item(int index);
public virtual XmlNode this[int i] { get; }

These two members allow you to access an element based on its index. Here are examples:

@{
    string strVideosFile = Server.MapPath("~/App_Data/Videos.xml");
    System.Xml.XmlDocument xdVideos = new System.Xml.XmlDocument();

    if (File.Exists(strVideosFile))
    {
        xdVideos.Load(strVideosFile);

        System.Xml.XmlElement xeRoot = xdVideos.DocumentElement;
        System.Xml.XmlNodeList xnlVideos = xeRoot.ChildNodes;

        <p>@xnlVideos[1].InnerText</p>
        <p>@xnlVideos.Item(3).InnerXml</p>
    }
}

This would produce:

Locating an Element Using its Index

You can use this characteristic to locate a node. Because XML is very flexible with the names (you can have two child nodes that have the same name) and values (you can have two child nodes that have the same value) of nodes, when creating an XML file, it is your responsibility to create a scheme that would eventually allow you to uniquely identify each element.

Locating an Element Using its Name

To assist you with locating the first child node of a node, the XmlNode class is equipped with an indexed property (named Item) overloaded with two versions. One of the versions is declared as follows:

public virtual XmlElement this[string name] { get; }

This indexed property takes the name of a node as argument. After the property has been called, the parser checks the child nodes of the element on which the property was applied. If the parser finds a node with that name, it returns it as an XmlElement object. Here is an example:

@{
    string strVideosFile = Server.MapPath("~/App_Data/Videos.xml");
    System.Xml.XmlDocument xdVideos = new System.Xml.XmlDocument();

    if (File.Exists(strVideosFile))
    {
        xdVideos.Load(strVideosFile);

        System.Xml.XmlElement xeRoot = xdVideos.DocumentElement;
        System.Xml.XmlNodeList xnlVideos = xeRoot.ChildNodes;

        <p>@xnlVideos[1]["director"].InnerText</p>
        <p>@xnlVideos.Item(3)["format"].InnerXml</p>
    }
}

Based on the videos.xml file we had earlier, this would produce:

Locating an Element Using its Name

If the node has more than one child with the same name, then it would return the first child with that name. You can use this characteristic to look for, or locate, an element.

Locating an Element Using a Tag Name

To assist you with finding a node, the XmlDocument class is equipped with a method name GetElementByTagName which is overloaded with two versions. One of the syntaxes used is:

public virtual XmlNodeList GetElementsByTagName(string name);

This method takes as argument a string. The string must be the name of a node. If at least one node that holds that name exists in the file, this method returns a collection of the nodes with that name. If there is no node with that name, the collection is returned empty and there is no exception thrown.

Here is an example of calling the method:

@{
    string strVideosFile = Server.MapPath("~/App_Data/Videos.xml");
    System.Xml.XmlDocument xdVideos = new System.Xml.XmlDocument();

    if (File.Exists(strVideosFile))
    {
        xdVideos.Load(strVideosFile);

        // Get a reference to the root node
        System.Xml.XmlElement xeRoot = xdVideos.DocumentElement;

        // Create a list of nodes whose name is Title
        System.Xml.XmlNodeList xnlTitles = xdVideos.GetElementsByTagName("title");

        <ul>
            @foreach (System.Xml.XmlNode node in xnlTitles)
            {
                <li>@node.InnerText</li>
            }
        </ul>
    }
}

Once you have a list of the nodes of a particular criterion, you can then act as you see fit. For example, you can look for a particular node that holds text of your choice.

Practical Learning: Locating an Element Using its Tag Name

  1. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  2. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller - Empty is selected.
    Click Add
  3. Type TireInstallations to get TireInstallationsController
  4. Click Add
  5. In the TireInstallationsController class, create three action methods as follows:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace TireDirect11.Controllers
    {
        public class TireInstallationsController : Controller
        {
            // GET: TireInstallations
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: TireInstallations/PayrollStartUp
            public ActionResult PayrollStartUp()
            {
                return View();
            }
    
            // GET: TireInstallations/PayrollPreparation
            public ActionResult PayrollPreparation(string EmployeeNumber, string BaseHourlyRate, string BaseTireRate,
                                                   string MondayInstallations, string TuesdayInstallations,
                                                   string WednesdayInstallations, string ThursdayInstallations, string FridayInstallations)
            {
                int payrollNumber = 100000;
                XmlDocument xdPayroll = new XmlDocument();
                XmlDocument xdEmployees = new XmlDocument();
                string payrollFile = Server.MapPath("/TireDirect/Payroll.xml");
                string employeesFile = Server.MapPath("/TireDirect/Employees.xml");
    
                if (!string.IsNullOrEmpty(EmployeeNumber))
                {
                    if (System.IO.File.Exists(employeesFile))
                    {
                        using (FileStream fsEmployees = new FileStream(employeesFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdEmployees.Load(fsEmployees);
    
                            XmlNodeList xnlEmployees = xdEmployees.GetElementsByTagName("employee-number");
    
                            foreach (XmlNode xnEmployee in xnlEmployees)
                            {
                                if (xnEmployee.InnerText == EmployeeNumber)
                                {
                                    TempData["FirstName"] = xnEmployee.NextSibling.InnerText;
                                    TempData["LastName"] = xnEmployee.NextSibling.NextSibling.InnerText;
                                }
                            }
                        }
    
                        if (System.IO.File.Exists(payrollFile))
                        {
                            using (FileStream fsPayroll = new FileStream(payrollFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                xdPayroll.Load(fsPayroll);
    
                                XmlNodeList xnlPayroll = xdPayroll.GetElementsByTagName("payrol-number");
    
                                foreach (XmlNode xnPayroll in xnlPayroll)
                                {
                                    payrollNumber = int.Parse(xnPayroll.InnerText);
                                }
                            }
                        }
    
                        payrollNumber++;
    
                        double payRate = 0.00;
                        double tireRate = 0.00;
    
                        double dMondayNetPay = 0.00;
                        double dTuesdayNetPay = 0.00;
                        double dWednesdayNetPay = 0.00;
                        double dThursdayNetPay = 0.00;
                        double dFridayNetPay = 0.00;
                        double dailySalary = 0.00;
    
                        double dInstallationMondayPay = 0.00;
                        double dInstallationTuesdayPay = 0.00;
                        double dInstallationWednesdayPay = 0.00;
                        double dInstallationThursdayPay = 0.00;
                        double dInstallationFridayPay = 0.00;
    
                        if (!string.IsNullOrEmpty(Request["BaseHourlyRate"]))
                        {
                            payRate = double.Parse(Request["BaseHourlyRate"]);
    
                            dailySalary = payRate * 8.00;
                        }
    
                        if (!string.IsNullOrEmpty(Request["BaseTireRate"]))
                        {
                            tireRate = double.Parse(Request["BaseTireRate"]);
                        }
    
                        if (!string.IsNullOrEmpty(Request["MondayInstallations"]))
                        {
                            dInstallationMondayPay = int.Parse(Request["MondayInstallations"]) * tireRate;
                        }
    
                        if (!string.IsNullOrEmpty(Request["TuesdayInstallations"]))
                        {
                            dInstallationTuesdayPay = int.Parse(Request["TuesdayInstallations"]) * tireRate;
                        }
    
                        if (!string.IsNullOrEmpty(Request["WednesdayInstallations"]))
                        {
                            dInstallationWednesdayPay = int.Parse(Request["WednesdayInstallations"]) * tireRate;
                        }
    
                        if (!string.IsNullOrEmpty(Request["ThursdayInstallations"]))
                        {
                            dInstallationThursdayPay = int.Parse(Request["ThursdayInstallations"]) * tireRate;
                        }
    
                        if (!string.IsNullOrEmpty(Request["FridayInstallations"]))
                        {
                            dInstallationFridayPay = int.Parse(Request["FridayInstallations"]) * tireRate;
                        }
    
                        dMondayNetPay = dInstallationMondayPay;
                        dTuesdayNetPay = dInstallationTuesdayPay;
                        dWednesdayNetPay = dInstallationWednesdayPay;
                        dThursdayNetPay = dInstallationThursdayPay;
                        dFridayNetPay = dInstallationFridayPay;
    
                        if (dInstallationMondayPay < dailySalary) { dMondayNetPay = dailySalary; }
                        if (dInstallationTuesdayPay < dailySalary) { dTuesdayNetPay = dailySalary; }
                        if (dInstallationWednesdayPay < dailySalary) { dWednesdayNetPay = dailySalary; }
                        if (dInstallationThursdayPay < dailySalary) { dThursdayNetPay = dailySalary; }
                        if (dInstallationFridayPay < dailySalary) { dFridayNetPay = dailySalary; }
    
                        TempData["PayrollNumber"] = payrollNumber;
                        TempData["EmployeeNumber"] = EmployeeNumber;
                        TempData["BaseHourlyRate"] = BaseHourlyRate;
                        TempData["BaseTireRate"] = BaseTireRate;
                        TempData["MondayInstallations"] = MondayInstallations;
                        TempData["TuesdayInstallations"] = TuesdayInstallations;
                        TempData["WednesdayInstallations"] = WednesdayInstallations;
                        TempData["ThursdayInstallations"] = ThursdayInstallations;
                        TempData["FridayInstallations"] = FridayInstallations;
                        TempData["MondayNetPay"] = dMondayNetPay.ToString("F");
                        TempData["TuesdayNetPay"] = dTuesdayNetPay.ToString("F");
                        TempData["WednesdayNetPay"] = dWednesdayNetPay.ToString("F");
                        TempData["ThursdayNetPay"] = dThursdayNetPay.ToString("F");
                        TempData["FridayNetPay"] = dFridayNetPay.ToString("F");
    
                        TempData["NetPay"] = (dMondayNetPay + dTuesdayNetPay + dWednesdayNetPay + dThursdayNetPay + dFridayNetPay).ToString("F");
                    }
    
                    return RedirectToAction("PayrollPreparation");
                }
    
                return View();
            }
    
            // GET: TireInstallations/SavePayroll
            public ActionResult SavePayroll(string PayrollNumber, string EmployeeNumber, string BaseHourlyRate, string BaseTireRate,
                                            string MondayInstallations, string MondayPay, string TuesdayInstallations, string TuesdayPay,
                                            string WednesdayInstallations, string WednesdayPay, string ThursdayInstallations,
                                            string ThursdayPay, string FridayInstallations, string FridayPay, string NetPay, string RecordValidation)
            {
                XmlDocument xdPayroll = new XmlDocument();
                string payrollFile = Server.MapPath("/TireDirect/Payroll.xml");
    
                if (System.IO.File.Exists(payrollFile))
                {
                    using (FileStream fsPayroll = new FileStream(payrollFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayroll.Load(fsPayroll);
                    }
                }
                else
                {
                    xdPayroll.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                      "<payrolls></payrolls>");
                }
    
                XmlElement xePayroll = xdPayroll.CreateElement("payroll");
    
                xePayroll.InnerXml = "<payrol-number>" + PayrollNumber + "</payrol-number>" +
                                     "<employee-number>" + EmployeeNumber + "</employee-number>" +
                                     "<base-hourly-rate>" + BaseHourlyRate + "</base-hourly-rate>" +
                                     "<base-tire-rate>" + BaseTireRate + "</base-tire-rate>" +
                                     "<monday-installations>" + MondayInstallations + "</monday-installations>" +
                                     "<monday-pay>" + MondayPay + "</monday-pay>" +
                                     "<tuesday-installations>" + TuesdayInstallations + "</tuesday-installations>" +
                                     "<tuesday-pay>" + TuesdayPay + "</tuesday-pay>" +
                                     "<wednesday-installations>" + WednesdayInstallations + "</wednesday-installations>" +
                                     "<wednesday-pay>" + WednesdayPay + "</wednesday-pay>" +
                                     "<thursday-installations>" + ThursdayInstallations + "</thursday-installations>" +
                                     "<thursday-pay>" + ThursdayPay + "</thursday-pay>" +
                                     "<friday-installations>" + FridayInstallations + "</friday-installations>" +
                                     "<friday-pay>" + FridayPay + "</friday-pay>" +
                                     "<net-pay>" + NetPay + "</net-pay>";
    
                xdPayroll.DocumentElement.AppendChild(xePayroll);
    
                if (RecordValidation != "Invalid")
                {
                    using (FileStream fsPayroll = new FileStream(payrollFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                    {
                        xdPayroll.Save(fsPayroll);
                    }
                }
    
                return RedirectToAction("PayrollStartUp");
            }
        }
    }
  6. In the document, right-click inside the PayrollPreparation() method and click Add View
  7. In the Add View dialog box, make sure the View Name text box displays PayrollPreparation and click Add
  8. Change the document as follows:
    @{
        ViewBag.Title = "Payroll Preparation";
    }
    
    <h2 class="text-center">Payroll Preparation</h2>
    
    @{
        string strErrorCode = "";
        string strLastName = string.Empty;
        string strFirstName = string.Empty;
        string dMondayNetPay = string.Empty;
        string dTuesdayNetPay = string.Empty;
        string strErrorMessage = string.Empty;
        string dWednesdayNetPay = string.Empty;
        string dThursdayNetPay = string.Empty;
        string dFridayNetPay = string.Empty;
        string dNetPay = string.Empty;
    
        try
        {
            strLastName = TempData["LastName"].ToString();
            strFirstName = TempData["FirstName"].ToString();
            dMondayNetPay = TempData["MondayNetPay"].ToString();
            dTuesdayNetPay = TempData["TuesdayNetPay"].ToString();
            dWednesdayNetPay = TempData["WednesdayNetPay"].ToString();
            dThursdayNetPay = TempData["ThursdayNetPay"].ToString();
            dFridayNetPay = TempData["FridayNetPay"].ToString();
            dNetPay = TempData["NetPay"].ToString();
    
            strErrorCode = "Valid";
        }
        catch (System.NullReferenceException)
        {
            strErrorCode = "Invalid";
            strErrorMessage = "The employee number is not valid. The payroll cannot be processed.";
        }
    }
    
    @using (Html.BeginForm("SavePayroll", "TireInstallations", FormMethod.Post))
    {
        <div class="row large-container">
            <div class="col-md-4">
                <fieldset class="grouping group-large">
                    <legend>Employee Details</legend>
                    <table>
                        <tr>
                            <td class="large-size bold">Employee #:</td>
                            <td>@Html.TextBox("EmployeeNumber", TempData["EmployeeNumber"], htmlAttributes: new { @class = "form-control small-size" })</td>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td class="bold">Employee Name:</td>
                            <td>@Html.TextBox("FirstName", @strFirstName, htmlAttributes: new { @class = "form-control small-size" })</td>
                            <td>@Html.TextBox("LastName", @strLastName, htmlAttributes: new { @class = "form-control small-size" })</td>
                        </tr>
                    </table>
                    <table>
                        <tr>
                            <td class="bold">Base Hourly Rate:</td>
                            <td>@Html.TextBox("BaseHourlyRate", TempData["BaseHourlyRate"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td><b>/Hr</b></td>
                        </tr>
                        <tr>
                            <td class="bold">Base Tire Rate:</td>
                            <td>@Html.TextBox("BaseTireRate", TempData["BaseTireRate"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td><b>/Tire</b></td>
                        </tr>
                    </table>
                </fieldset>
                <hr />
                <table>
                    <tr>
                        <td class="bold">Net Pay:</td>
                        <td>@Html.TextBox("NetPay", @dNetPay, htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                        <td>&nbsp;</td>
                        <td class="bold">Payroll #:</td>
                        <td>@Html.TextBox("PayrollNumber", @TempData["PayrollNumber"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                    </tr>
                </table>
    
                <hr />
                <p class="text-center"><input type="submit" name="btnSavePayroll" value="Save Payroll" class="btn btn-warning medium-size" /></p>
            </div>
            <div class="col-md-4">
                <fieldset class="grouping group-small">
                    <legend>Tires Installations</legend>
                    <table>
                        <tr>
                            <td class="left-col">&nbsp;</td>
                            <td class="bold">Day</td>
                            <td class="bold">Pay</td>
                        </tr>
                        <tr>
                            <td class="bold">Monday:</td>
                            <td>@Html.TextBox("MondayInstallations", TempData["MondayInstallations"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td>@Html.TextBox("MondayPay", @dMondayNetPay, htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                        </tr>
                        <tr>
                            <td class="bold">Tuesday:</td>
                            <td>@Html.TextBox("TuesdayInstallations", TempData["TuesdayInstallations"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td>@Html.TextBox("TuesdayPay", @dTuesdayNetPay, htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                        </tr>
                        <tr>
                            <td class="bold">Wednesday:</td>
                            <td>@Html.TextBox("WednesdayInstallations", TempData["WednesdayInstallations"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td>@Html.TextBox("WednesdayPay", @dWednesdayNetPay, htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                        </tr>
                        <tr>
                            <td class="bold">Thursday:</td>
                            <td>@Html.TextBox("ThursdayInstallations", TempData["ThursdayInstallations"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td>@Html.TextBox("ThursdayPay", @dThursdayNetPay, htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                        </tr>
                        <tr>
                            <td class="bold">Friday:</td>
                            <td>@Html.TextBox("FridayInstallations", TempData["FridayInstallations"], htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                            <td>@Html.TextBox("FridayPay", @dFridayNetPay, htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                        </tr>
                    </table>
                </fieldset>
            </div>
        </div>
    
        <p>@Html.Hidden("RecordValidation", @strErrorCode)</p>
    
        <p style="text-align: center; color: red;">@strErrorMessage</p>
    }
  9. Click the TireInstallationsController.cs tab to access the class
  10. In the document, right-click inside the PayrollStartUp() method and click Add View...
  11. In the Add View dialog box, make sure the View Name text box displays PayrollStartUp.
    Click Add
  12. Create a form as follows:
    @{
        ViewBag.Title = "Payroll Start-Up";
    }
    
    <h2 class="text-center">Payroll Start-Up</h2>
    
    <hr />
    
    @using (Html.BeginForm("PayrollPreparation", "TireInstallations", FormMethod.Post))
    {
        <div class="small-container">
            <table>
                <tr>
                    <td class="small-size bold">Employee #:</td>
                    <td>@Html.TextBox("EmployeeNumber", "", htmlAttributes: new { @class = "form-control" })</td>
                </tr>
            </table>
            <table>
                <tr>
                    <td class="small-size bold">Base Hourly Rate:</td>
                    <td>@Html.TextBox("BaseHourlyRate", "12.50", htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                    <td>/Hr</td>
                </tr>
                <tr>
                    <td class="bold">Base Tire Rate:</td>
                    <td>@Html.TextBox("BaseTireRate", "1.15", htmlAttributes: new { @class = "form-control xsmall-size" })</td>
                    <td>/Tire</td>
                </tr>
            </table>
            <hr />
            <fieldset class="grouping group-small">
                <legend>Number of Tires Installed on</legend>
                <table>
                    <tr>
                        <td class="bold">Monday:</td>
                        <td>@Html.TextBox("MondayInstallations", "0", htmlAttributes: new { @class = "form-control medium-size" })</td>
                    </tr>
                    <tr>
                        <td class="bold">Tuesday:</td>
                        <td>@Html.TextBox("TuesdayInstallations", "0", htmlAttributes: new { @class = "form-control medium-size" })</td>
                    </tr>
                    <tr>
                        <td class="bold">Wednesday:</td>
                        <td>@Html.TextBox("WednesdayInstallations", "0", htmlAttributes: new { @class = "form-control medium-size" })</td>
                    </tr>
                    <tr>
                        <td class="bold">Thursday:</td>
                        <td>@Html.TextBox("ThursdayInstallations", "0", htmlAttributes: new { @class = "form-control medium-size" })</td>
                    </tr>
                    <tr>
                        <td class="bold">Friday:</td>
                        <td>@Html.TextBox("FridayInstallations", "0", htmlAttributes: new { @class = "form-control medium-size" })</td>
                    </tr>
                </table>
            </fieldset>
            <hr />
            <p class="text-center"><input type="submit" name="btnPreparePayroll" value="Prepare Payroll" class="btn btn-warning medium-size" /></p>
        </div>
    }
  13. In the Solution Explorer, under Views, expand Home and double-click Index.cshtml to open it
  14. Change the document as follows:
    @{
        ViewBag.Title = "Welcome to Tire Direct";
    }
    
    <div class="jumbotron">
        <div class="tires-container">
        </div>
        <h1>Tire Direct</h1>
        <p class="lead">
            At Tire Direct, we install tires on all types of vehicles,
            for all seasons, under every circumference. Visit one or our many locations.
            Check our equipment. Meet our staff. Our service is money-back guaranteed.
        </p>
        <p class="text-center"><a href="https://asp.net" class="btn btn-warning btn-lg">Visit One of Our Locations &raquo;</a></p>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            <h2>Tire Installation</h2>
            <p>Our service is fast. Our staff is friendly and professional. Our rates
                are competitive.</p>
            <p><a class="btn btn-warning" href="https://go.microsoft.com/fwlink/?LinkId=301865">Schedule an Appointment &raquo;</a></p>
        </div>
        <div class="col-md-4">
            <h2>Tire Installation/Rates</h2>
            <p>Our tire installation rates are very competitive compared to other shops.</p>
            <p>@Html.ActionLink("Start Tire Installation " + Server.HtmlDecode("&raquo;"), "PayrollStartUp", "TireInstallation", null, new { @class = "btn btn-warning" })</p>
        </div>
        <div class="col-md-4">
            <h2>Employees Portal</h2>
            <p>This is the place for employees to check email, payroll,
                benefits, requests for time off, etc.</p>
            <p>@Html.ActionLink("Hire Employee " + Server.HtmlDecode("&raquo;"), "Create", "Employees", null, new { @class="btn btn-warning" })</p>
        </div>
    </div>
  15. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Maintenance of XML Elements

  16. Click the Hire Employee link:

    Maintenance of XML Elements

  17. Enter the values for each row of the following table. Click Create Employee Record after the values from each row:


    Employee # First Name Last Name
    928547 Robert Tanner
    294708 Frank Rodd
    529485 Paula Robinson
    135170 James Vertue
    948069 Harry Atkinson
  18. Click the Tire Direct link in the top-left corner
  19. Click the Start Tire Installation link
  20. To execute, on the main menu, click Debug -> Start Without Debugging:

    Locating an Element Using its Name

  21. Fill the text boxes with the following values:

    Employee #: 948069
    Base Hourly Rate: 11.25
    Base Tire Rate: 1.25
    Monday: 92
    Tuesday: 116
    Wednesday: 78
    Thursday: 123
    Friday: 105

    Locating an Element Using its Name

  22. Click the Prepare Payroll button:

    Locating an Element Using its Name

  23. Click the Save Payroll button
  24. Fill the text boxes with the following values:

    Employee #: 529485
    Base Hourly Rate: 10.65
    Base Tire Rate: 1.08
    Monday: 106
    Tuesday: 112
    Wednesday: 83
    Thursday: 87
    Friday: 126
  25. Click the Prepare Payroll button
  26. Click the Save Payroll button
  27. Close the browser and return to your programming environment
  28. On the main menu of Microsoft Visual Studio, click File -> New -> Project ...
  29. In the middle frame of the New Project dialog box, click ASP.NET Web Application (.NET Framework) and change the project Name to WaterDistributionCompany1
  30. Click OK
  31. In the New ASP.NET Application dialog box, click the MVC icon
  32. Click OK
  33. In the Solution Explorer, right-click WaterDistribution2 -> Add -> New Folder
  34. Type Images
  35. Save the following picture to the Images folder:

    Water for a Shining Life

  36. Right-click the picture where you saved it and click Copy
  37. In the Solution Explorer, right-click Images and click Paste
  38. In the Solution Explorer, right-click Content -> Add -> New Item...
  39. In the middle frame of the Add New Item dialog box, click Style Sheet
  40. Change the file Name to WaterDistribution
  41. Click Add
  42. Change the document as follows:
    body {
        background-color: #2b5b8f;
    }
    
    .bold              { font-weight:      600;               }
    .top-bar           { top:              0;
                         width:            100%;
                         z-index:          1000;
                         position:         fixed;
                         height:           6.85em;
                         background-color: #203864;           }
    .containment       { margin:           auto;
                         width:            460px;             }
    .navbar-inverse    { background-color: #001132;
                         border-top:       3px solid #cfdde0;
                         border-bottom:    3px solid #cfdde0; }
    .navbar-fixed-top  { top:              6.75em;            }
    .jumbotron         { padding-bottom:   4px;
                         background-color: #153a62;           }
    .col-md-3 h2       { color:            #abcbd9;
                         border-bottom:    1px solid #cfdde0; }
    .lead              { color:            #cfdde0;           }
    .col-md-3 p        { color:            #d5d4c2;           }
    .caption           { color:            lightblue;         }
    .control-label     { font-weight:      400;
                         font-family:      Garamond, Georgia, 'Times New Roman', serif; }
    .copyright         { color:            #beeeab;           }
    .push-down         { margin-top:       8em;               }
    .push-down h2      { font-weight:      600;
                         font-size:        26px;
                         text-align:       center;
                         color:            #d5d4c2;
                         font-family:      Garamond, Georgia, 'Times New Roman', serif; }
    .push-down h3      { color:            #abcbd9;           }
    .push-down p       { color:            #cfdde0;           }
    .water-nav         { text-decoration:  none;
                         color:            yellow;            }
    .water-nav:link    { color:            lightcyan;         }
    .water-nav:visited { color:            aliceblue;         }
    .water-nav:active  { color:            #a8c3ce;           }
    .water-nav:hover   { color:            yellow;            }
    .common-font       { font-family:      Garamond, Georgia, 'Times New Roman', serif; }
    .col-md-125        { min-height:       1px;
                         padding-right:    15px;
                         padding-left:     15px;
                         width:            12.50%;
                         position:         relative;          }
    
    @media (min-width: 992px) {
        .col-md-125 {
            float: left;
            width: 12.50%;
        }
    }
    
    .table-striped > tbody > tr:nth-of-type(even) {
        color: navy;
        background-color: azure;
    }
    
    .table-striped > tbody > tr:nth-of-type(odd) {
        color: aliceblue;
        background-color: cornflowerblue;
    }
  43. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  44. Change the document as follows:
    using System.Web.Optimization;
    
    namespace WaterDistribution2
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/WaterDistribution.css"));
            }
        }
    }
  45. In the Solution Explorer, right-click WaterDistribution2 -> Add -> New Folder
  46. Type WaterDistribution
  47. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  48. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller With Read/Write Actions
  49. Click Add
  50. Type WaterMeters to get WaterMetersController
  51. Click Add
  52. Implement the Index(), the Details(), and the second Create() methods as follows:
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class WaterMetersController : Controller
        {
            // GET: WaterMeters
            public ActionResult Index()
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
                    }
    
                    if (xdWaterMeters.DocumentElement.ChildNodes.Count > 0)
                    {
                        ViewBag.WaterMeters = xdWaterMeters.DocumentElement.ChildNodes;
                    }
                    else
                    {
                        ViewBag.WaterMeters = null;
                    }
                }
    
                return View();
            }
    
            // GET: WaterMeters/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                        {
                            if (xnWaterMeter.InnerText == id.ToString())
                            {
                                ViewBag.WaterMeterID = xnWaterMeter.InnerText;
                                ViewBag.MeterNumber = xnWaterMeter.NextSibling.InnerText;
                                ViewBag.Make = xnWaterMeter.NextSibling.NextSibling.InnerText;
                                ViewBag.Model = xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterSize = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.DateLastUpdate = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterValue = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: WaterMeters/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: WaterMeters/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int meter_id = -1;
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    // Make sure a meter number was provided. If not, don't do nothing
                    if (!string.IsNullOrEmpty(collection["MeterNumber"]))
                    {
                        // If an XML file for water meters was created already, ...
                        if (System.IO.File.Exists(strFileWaterMeters))
                        {
                            // ... open it ...
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                // ... and put the records in the DOM
                                xdWaterMeters.Load(fsWaterMeters);
    
                                // We need the meters numbers. Therefore, use XPath to specify their path
                                XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                                // Check the whole list of meters numbers
                                foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                                {
                                    // Every time, assign the current meter number to our meterNumber variable
                                    meter_id = int.Parse(xnWaterMeter.InnerText);
                                }
                            }
                        }
                        else
                        {
                            // If there is no XML file yet, create skeleton code for an XML document, ...
                            xdWaterMeters.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                  "<water-meters></water-meters>");
                            // and set our meterNumber variable to 0
                            meter_id = 0;
                        }
                    }
    
                    // Get ready to create an XML element named water-meter
                    XmlElement xeWaterMeter = xdWaterMeters.CreateElement("water-meter");
    
                    // Increase the meterNumber variable by 1
                    meter_id += 1;
    
                    // Create the markup of the XML water meter
                    string strWaterMeter = "<meter-id>"         + meter_id            + "</meter-id>" +
                                           "<meter-number>"     + collection["MeterNumber"] + "</meter-number>" +
                                           "<make>"             + collection["Make"] + "</make>" +
                                           "<model>"            + collection["Model"] + "</model>" +
                                           "<meter-size>"       + collection["MeterSize"] + "</meter-size>" +
                                           "<date-last-update>" + collection["DateLastUpdate"] + "</date-last-update>" +
                                           "<counter-value>"    + collection["CounterValue"] + "</counter-value>";
    
                    // Specify the markup of the new element
                    xeWaterMeter.InnerXml = strWaterMeter;
                    // Add the new node to the root
                    xdWaterMeters.DocumentElement.AppendChild(xeWaterMeter);
    
                    // Save the (new version of the) XML file
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Create, FileAccess.Write, FileShare.Write))
                    {
                        xdWaterMeters.Save(fsWaterMeters);
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }    
    
            . . . No Change
        }
    }
  53. In the class, right-click Under Index() and click Add View...
  54. In the Add View dialog box, make sure the View Name text box is displaying Index.
    Click Add
  55. Chreate a form as follows:
    @{
        ViewBag.Title = "Water Meters";
    }
    
    <div class="push-down">
        <h2 class="common-font bold text-center">Water Meters</h2>
    </div>
    
    <hr />
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold">Meter ID</th>
            <th class="bold">Meter #</th>
            <th class="bold">Make</th>
            <th class="bold">Model</th>
            <th class="bold">Meter Size</th>
            <th class="bold">Date Last Update</th>
            <th class="bold">Counter Value</th>
            <th>@Html.ActionLink("New Water Meter", "Create", null, htmlAttributes: new { @class = "water-nav" })</th>
        </tr>
    
        @if (ViewBag.waterMeters != null)
        {
            foreach (System.Xml.XmlNode meter in ViewBag.WaterMeters as System.Xml.XmlNodeList)
            {
                <tr>
                    <td class="text-center">@meter.FirstChild.InnerText</td>
                    <td>@meter.FirstChild.NextSibling.InnerText</td>
                    <td>@meter.FirstChild.NextSibling.NextSibling.InnerText</td>
                    <td>@meter.FirstChild.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@meter.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@meter.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@meter.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>
                        @Html.ActionLink("Update", "Edit", new { id = @meter.FirstChild.InnerText }) |
                        @Html.ActionLink("Review", "Details", new { id = @meter.FirstChild.InnerText }) |
                        @Html.ActionLink("Remove", "Delete", new { id = @meter.FirstChild.InnerText })
                    </td>
                </tr>
            }
        }
    </table>
  56. Click the WaterMetersController.cs tab to access the controller
  57. In the document, right-click Details() and click Add View...
  58. In the Add View dialog box, make sure the View Name text box is displaying Details.
    Click Add
  59. Change the code as follows:
    @{
        ViewBag.Title = "Water Meter Details";
    }
    
    <div class="push-down">
        <h2>Water Meter Details</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt class="bold">Meter ID:</dt>
            <dd>@ViewBag.WaterMeterID</dd>
            <dt>Water Meter #:</dt>
            <dd>@ViewBag.MeterNumber</dd>
            <dt>Make:</dt>
            <dd>@ViewBag.Make</dd>
            <dt>Model:</dt>
            <dd>@ViewBag.Model</dd>
            <dt>Meter Size:</dt>
            <dd>@ViewBag.MeterSize</dd>
            <dt>Date Last Update:</dt>
            <dd>@ViewBag.DateLastUpdate</dd>
            <dt>Counter Value:</dt>
            <dd>@ViewBag.CounterValue</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit/Update Water Meter Information", "Edit",
                         null, htmlAttributes: new { id = @ViewBag.WaterMeterID, @class = "water-nav" }) |
        @Html.ActionLink("Water Meters", "Index",
                         null, new { @class = "water-nav" })
    </p>
  60. Click the WaterMetersController.cs tab to access the class
  61. In the class, right-click Create() and click Add View...
  62. Make sure the View Name text box displays Create.
    Press Enter
  63. Create a form as follows:
    @{
        ViewBag.Title = "New Water Meter";
    }
    
    <div class="push-down">
        <h2>New Water Meter</h2>
    </div>
    <hr />
    @using (Html.BeginForm())
    {
        <div class="form-horizontal">
            <div class="form-group">
                <label for="mtrNbr" class="control-label col-md-4 caption">Meter #:</label>
                <div class="col-md-8">
                    @Html.TextBox("MeterNumber", null, htmlAttributes: new { @class = "form-control", id = "mtrNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="make" class="control-label col-md-4 caption">Make:</label>
                <div class="col-md-8">
                    @Html.TextBox("Make", null, htmlAttributes: new { @class = "form-control", id = "make" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="model" class="control-label col-md-4 caption">Model:</label>
                <div class="col-md-8">
                    @Html.TextBox("Model", null, htmlAttributes: new { @class = "form-control", id = "model" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="mtrSize" class="control-label col-md-4 caption">Meter Size:</label>
                <div class="col-md-8">
                    @Html.TextBox("MeterSize", null, htmlAttributes: new { @class = "form-control", id = "mtrSize" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="dlu" class="control-label col-md-4 caption">Date Last Update:</label>
                <div class="col-md-8">
                    @Html.TextBox("DateLastUpdate",
                        null, htmlAttributes: new { @class = "form-control", type = "date", id = "dlu" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="cntVal" class="control-label col-md-4 caption">Counter Value:</label>
                <div class="col-md-8">
                    @Html.TextBox("CounterValue", null, htmlAttributes: new { @class = "form-control", id = "cntVal" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-5">
                    @Html.ActionLink("Water Meters", "Index", null, htmlAttributes: new { @class = "water-nav" })
                </label>
                <div class="col-md-7">
                    <input type="submit" value="Create Water Meter" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
  64. In the Solution Explorer, right-click Controllers -> Add -> New Scaffold Item...
  65. In the left list of the Add Scaffold dialog box, click MVC and, in the middle list, click MVC 5 Controller With Read/Write Actions
  66. Click Add
  67. Type Customers to get CustomersController
  68. Click Add
  69. In the class, change the Index(), the Details(), and the second Create() methods as follows:
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class CustomersController : Controller
        {
            // GET: Customers
            public ActionResult Index()
            {
                // Get a reference to the XML DOM
                XmlDocument xdCustomers = new XmlDocument();
                // This is the name and path of the XML file that contains the customers records
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                // If a file that contains the customers records was previously created, ...
                if (System.IO.File.Exists(strFileCustomers))
                {
                    // ... open it
                    using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // and store the records in the DOM
                        xdCustomers.Load(fsCustomers);
                    }
    
                    /* If the Customers records exist, send them to the view.
                     * If there is no file for the customers, indicate that the DOM is null. */
                    ViewBag.Customers = xdCustomers.DocumentElement.ChildNodes.Count > 0 ? xdCustomers.DocumentElement.ChildNodes : null;
                }
    
                return View();
            }
    
            // GET: Customers/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdCustomers = new XmlDocument();
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strFileCustomers))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdCustomers.Load(fsWaterMeters);
    
                        XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-id");
    
                        foreach (XmlNode xnCustomer in xnlCustomers)
                        {
                            if (xnCustomer.InnerText == id.ToString())
                            {
                                ViewBag.AccountID = xnCustomer.InnerText;
                                ViewBag.AccountNumber = xnCustomer.NextSibling.InnerText;
                                ViewBag.MeterNumber = xnCustomer.NextSibling.NextSibling.InnerText;
                                ViewBag.FirstName = xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LastName = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Address = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.City = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.County = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.State = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.ZIPCode = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: Customers/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Customers/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int account_id = -1;
                    bool meterNumberIsValid = false;
                    XmlDocument xdWaterMeters = new XmlDocument();
                    XmlDocument xdCustomersAccounts = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    // Make sure the user provides an account number, ...
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        // If the user provided an account number, to start, find out if a file for water meters was created already.
                        if (System.IO.File.Exists(strFileWaterMeters))
                        {
                            // If a file for water meters exists, open it
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open,
                                                                                                 FileAccess.Read,
                                                                                                 FileShare.Read))
                            {
                                // Store the list of water meters in an XML document
                                xdWaterMeters.Load(fsWaterMeters);
    
                                // Create a list of child nodes of the root node
                                XmlNodeList xnlWaterMeters = xdWaterMeters.DocumentElement.ChildNodes;
    
                                // Visit each node of the list of elements
                                foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                                {
                                    // When you get to a list of (child) nodes of a water-meter node, visit each child node
                                    foreach (XmlNode xnMeterNumber in xnWaterMeter.ChildNodes)
                                    {
                                        // If you find a meter number that is the same as the meter number from the form, ...
                                        if (xnMeterNumber.InnerText == collection["MeterNumber"])
                                        {
                                            // ... make a note
                                            meterNumberIsValid = true;
                                        }
                                    }
                                }
                            }
                        }
    
                        // If either the user didn't provide a meter number or provided a meter number that doesn't exist, ...
                        if (meterNumberIsValid == false)
                        {
                            // ... create a message that will display to the user
                            ViewBag.ErrorMessage = "You must provide a valid meter number";
                        }
                        else
                        {
                            // It appears that the user provided both an account number and a valid meter number.
    
                            // If an XML file for customers accounts was previously created, ...
                            if (System.IO.File.Exists(strFileCustomers))
                            {
                                // ... open it ...
                                using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.OpenOrCreate,
                                                                                                 FileAccess.ReadWrite,
                                                                                                 FileShare.ReadWrite))
                                {
                                    // ... and put the records in the DOM
                                    xdCustomersAccounts.Load(fsCustomers);
    
                                    XmlNodeList xnlCustomers = xdCustomersAccounts.GetElementsByTagName("account-id");
    
                                    foreach (XmlNode xnCustomer in xnlCustomers)
                                    {
                                        account_id = int.Parse(xnCustomer.InnerText);
                                    }
                                }
                            }
                            else
                            {
                                // If there is no XML file yet for the customers, create skeleton code for an XML document
                                xdCustomersAccounts.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                            "<customers></customers>");
                                account_id = 0;
                            }
    
                            // Get ready to create an XML element named customer
                            XmlElement xeCustomer = xdCustomersAccounts.CreateElement("customer");
    
                            account_id++;
    
                            // Create the markup of the XML customer
                            string strCustomer = "<account-id>" + account_id + "</account-id>" +
                                                 "<account-number>" + collection["AccountNumber"] + "</account-number>" +
                                                 "<meter-number>" + collection["MeterNumber"] + "</meter-number>" +
                                                 "<first-name>" + collection["FirstName"] + "</first-name>" +
                                                 "<last-name>" + collection["LastName"] + "</last-name>" +
                                                 "<address>" + collection["Address"] + "</address>" +
                                                 "<city>" + collection["City"] + "</city>" +
                                                 "<county>" + collection["County"] + "</county>" +
                                                 "<state>" + collection["State"] + "</state>" +
                                                 "<zip-code>" + collection["ZIPCode"] + "</zip-code>";
    
                            // Specify the markup of the new element
                            xeCustomer.InnerXml = strCustomer;
    
                            // Add the new node to the root
                            xdCustomersAccounts.DocumentElement.AppendChild(xeCustomer);
    
                            // Save the (new version of the) XML file
                            using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Create, FileAccess.Write, FileShare.Write))
                            {
                                xdCustomersAccounts.Save(fsCustomers);
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
                
        }
    }
  70. In the class, right-click Index() and click Add View...
  71. In the Add View dialog box, make sure the View Name text box is displaying Index.
    Click Add
  72. Change the webpage as follows:
    @{
        ViewBag.Title = "Customers Accounts";
    }
    
    <div class="push-down">
        <h2 class="common-font bold text-center">Customers Accounts</h2>
    </div>
    
    <hr />
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold">Account ID</th>
            <th class="bold">Account #</th>
            <th class="bold">Meter #</th>
            <th class="bold">First Name</th>
            <th class="bold">Last Name</th>
            <th class="bold">Address</th>
            <th class="bold">City</th>
            <th class="bold">County</th>
            <th class="bold">State</th>
            <th class="bold">ZIP Code</th>
            <th>@Html.ActionLink("New Customer Account", "Create", null, htmlAttributes: new { @class = "water-nav" })</th>
        </tr>
    
        @if (ViewBag.customers != null)
        {
            foreach (System.Xml.XmlNode client in ViewBag.Customers as System.Xml.XmlNodeList)
            {
                <tr>
                    <td class="text-center">@client.FirstChild.InnerText</td>
                    <td>@client.FirstChild.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@client.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
    
                    <td>
                        @Html.ActionLink("Update", "Edit", new { id = @client.FirstChild.InnerText }) |
                        @Html.ActionLink("Review", "Details", new { id = @client.FirstChild.InnerText }) |
                        @Html.ActionLink("Remove", "Delete", new { id = @client.FirstChild.InnerText })
                    </td>
                </tr>
            }
        }
    </table>
  73. In the Solution Explorer, under Views, right-click Customers -> Add -> View...
  74. Type Details as the name of the view
  75. Press Enter
  76. Change the document as follows:
    @{
        ViewBag.Title = "Customer Account Details";
    }
    
    <div class="push-down">
        <h2>Customer Account Details</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt class="bold">Account ID:</dt>
            <dd>@ViewBag.AccountID</dd>
            <dt>Account #:</dt>
            <dd>@ViewBag.AccountNumber</dd>
            <dt>Water Meter #</dt>
            <dd>@ViewBag.MeterNumber</dd>
            <dt>First Name:</dt>
            <dd>@ViewBag.FirstName</dd>
            <dt>Last Name:</dt>
            <dd>@ViewBag.LastName</dd>
            <dt>Address:</dt>
            <dd>@ViewBag.Address</dd>
            <dt>City:</dt>
            <dd>@ViewBag.City</dd>
            <dt>County:</dt>
            <dd>@ViewBag.County</dd>
            <dt>State:</dt>
            <dd>@ViewBag.State</dd>
            <dt>ZIP Code:</dt>
            <dd>@ViewBag.ZIPCode</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit/Update Customer Account Details", "Edit",
                         new { id = @ViewBag.AccountID }, htmlAttributes: new { @class = "water-nav" }) ||
        @Html.ActionLink("Customers Accounts", "Index",
                         null, new { @class = "water-nav" })
    </p>
  77. In the Solution Explorer, under Views, right-click Customers -> Add -> View...
  78. Type Create as the name of the view
  79. Click Add
  80. Change the document as follows
    @{
        ViewBag.Title = "New Customer Account";
    }
    
    <div class="push-down">
        <h2>New Customer Account</h2>
    </div>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div class="form-horizontal">
            <div class="form-group">
                <label for="acntNbr" class="control-label col-md-4 caption">Account #:</label>
                <div class="col-md-8">
                    @Html.TextBox("AccountNumber", null, htmlAttributes: new { @class = "form-control", id = "acntNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="mtrNbr" class="control-label col-md-4 caption">Water Meter:</label>
    
                <div class="col-md-8">
                    @Html.TextBox("MeterNumber", null, htmlAttributes: new { @class = "form-control", id = "mtrNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-4 caption">&nbsp;</label>
                <div class="col-md-8"><input type="text" id="meterDetails" class="form-control" disabled /></div>
            </div>
    
            <div class="form-group">
                <label for="fName" class="control-label col-md-4 caption">First Name:</label>
                <div class="col-md-8">
                    @Html.TextBox("FirstName", null, htmlAttributes: new { @class = "form-control", id = "fName" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="lName" class="control-label col-md-4 caption">Last Name:</label>
                <div class="col-md-8">
                    @Html.TextBox("LastName", null, htmlAttributes: new { @class = "form-control", id = "lName" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="adrs" class="control-label col-md-4 caption">Address:</label>
                <div class="col-md-8">
                    @Html.TextBox("Address", null, htmlAttributes: new { @class = "form-control", id = "adrs" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="ct" class="control-label col-md-4 caption">City:</label>
                <div class="col-md-8">
                    @Html.TextBox("City", null, htmlAttributes: new { @class = "form-control", id = "ct" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="county" class="control-label col-md-4 caption">County:</label>
                <div class="col-md-8">
                    @Html.TextBox("County", null, htmlAttributes: new { @class = "form-control", id = "county" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="state" class="control-label col-md-4 caption">State:</label>
                <div class="col-md-8">
                    @Html.TextBox("State", null, htmlAttributes: new { @class = "form-control", id = "state" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="zip" class="control-label col-md-4 caption">ZIP Code:</label>
                <div class="col-md-8">
                    @Html.TextBox("ZIPCode", null, htmlAttributes: new { @class = "form-control", id = "zip" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-5">
                    @Html.ActionLink("Customers", "Index", null, htmlAttributes: new { @class = "water-nav" })
                </label>
                <div class="col-md-7">
                    <input type="submit" value="Create Customer Account" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#mtrNbr").blur(function (event) {
                var connection = {
                    url: "/WaterDistribution/WaterMeters.xml",
                    method: "GET",
                    dataType: "xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var waterMeters = $(data).find("water-meter");
                        waterMeters.each(function () {
                            if ($(this).find("meter-number").text() == $("#mtrNbr").val())
                                $("#meterDetails").val($(this).find("make").text() + " " + $(this).find("model").text() + " (" + $(this).find("meter-size").text() + ")");
                        });
                    });
            }); // Lost Focus Event
        }); // Document.Ready
    </script>
  81. In the Solution Explorer, expand Views and expand Shared
  82. Double-click _Layout.cshtml and change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Water for a Shining Life</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="top-bar">
            <div class="containment"><img src="~/Images/wsl1.png" alt="Water for a Shining Life" width="490" height="92" /></div>
        </div>
    
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Emergency Services", "Index", "Home")</li>
                        <li>@Html.ActionLink("Cummunity", "Index", "Home")</li>
                        <li>@Html.ActionLink("Environment", "Index", "Home")</li>
                        <li>@Html.ActionLink("Resources", "Index", "Home")</li>
                        <li>@Html.ActionLink("Projects", "Index", "Home")</li>
                        <li>@Html.ActionLink("Customer Service", "Index", "Home")</li>
                        <li>@Html.ActionLink("Employment", "Index", "Home")</li>
                        <li>@Html.ActionLink("Questions?", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p class="copyright text-center common-font">&copy; @DateTime.Now.Year - Water for a Shining Life</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  83. In the Solution Explorer, under Views, expand Home, and double-click Index.cshtml
  84. Change the document as follows:
    <div class="jumbotron">
        <h2>.</h2>
        <p class="lead">
            Our water utility company provides energy, greatness, and warmth
            for a everyday life, a shining life. We provide solutions to families, businesses,
            and the community.
        </p>
    
        <p class="lead">
            This is the employees portal section of the company. From here,
            employees can register a new water meter, manage a customer account, or
            create a water bill.
        </p>
    </div>
    
    <div class="row">
        <div class="col-md-3">
            <h2>Water Meters</h2>
            <p>
                Our company uses the most accurate, sophisticated, and environment-friendly
                water meters on the market.
            </p>
            <p>@Html.ActionLink("Water Meters", "Index", "WaterMeters", null, new { @class = "btn btn-primary" })</p>
        </div>
        <div class="col-md-3">
            <h2>Customers</h2>
            <p>
                We supply water to individuals, families, small
                businesses, as well as enterprises or government agencies.
            </p>
            <p>@Html.ActionLink("Customers", "Index", "Customers", null, new { @class = "btn btn-primary" })</p>
        </div>
        <div class="col-md-3">
            <h2>Water Bills</h2>
            <p>
                Our water rates are very competitive nationwide. We use precise,
                effective, and strict algorithms when calculating our bills.
            </p>
            <p>@Html.ActionLink("Bills/Invoices", "Index", "WaterBills", null, new { @class = "btn btn-primary" })</p>
        </div>
        <div class="col-md-3">
            <h2>Payments</h2>
            <p>
                Our payment system is the simplest, the fairest, and the fastest. Our custiomer's service
                is highly rated.
            </p>
            <p>@Html.ActionLink("Bills Payments", "Index", "Payments", null, new { @class = "btn btn-primary" })</p>
        </div>
    </div>
  85. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Switching a String

  86. Click the Water Meters button

    Switching a String

  87. Click the New Water Meter link and create the following records:
     
    Meter # Make Model Meter Size Date Last Update Counter Value
    392-44-572 Constance Technologies TG-4822 5/8 Inches 03/31/2018 109992
    938-75-869 Standard Trend 266G 1 1/2 Inches 10/22/2017 137926
    799-28-461 Constance Technologies BD-7000 3/4 Inches 05/05/2018 6268
    207-94-835 Constance Technologies TG-6220 5/8 Inches 02/17/2018 96
    592-84-957 Standard Trend 428T 3/4 Inches 12/07/2018 49
    28358958 Igawa International TR6224 3/4 Inches 04/22/2012 1138

    XML Records Maintenance

    <?xml version="1.0" encoding="utf-8" ?>
    <water-meters>
      <water-meter>
        <meter-id>1</meter-id>
        <meter-number>392-44-572</meter-number>
        <make>Constance Technologies</make>
        <model>TG-4822</model>
        <meter-size>5/8 Inches</meter-size>
        <date-last-update>2018-03-31</date-last-update>
        <counter-value>109992</counter-value>
      </water-meter>
      <water-meter>
        <meter-id>2</meter-id>
        <meter-number>938-75-869</meter-number>
        <make>Standard Trend</make>
        <model>266G</model>
        <meter-size>2 1/2 Inches</meter-size>
        <date-last-update>2017-10-22</date-last-update>
        <counter-value>137926</counter-value>
      </water-meter>
      <water-meter>
        <meter-id>3</meter-id>
        <meter-number>799-28-461</meter-number>
        <make>Constance Technologies</make>
        <model>BD-7000</model>
        <meter-size>3/4 Inches</meter-size>
        <date-last-update>2018-05-05</date-last-update>
        <counter-value>6268</counter-value>
      </water-meter>
      <water-meter>
        <meter-id>4</meter-id>
        <meter-number>207-94-835</meter-number>
        <make>Constance Technologies</make>
        <model>TG-6220</model>
        <meter-size>5/8 Inches</meter-size>
        <date-last-update>2018-02-17</date-last-update>
        <counter-value>96</counter-value>
      </water-meter>
      <water-meter>
        <meter-id>5</meter-id>
        <meter-number>592-84-957</meter-number>
        <make>Standard Trend</make>
        <model>428T</model>
        <meter-size>3/4 Inches</meter-size>
        <date-last-update>2017-12-07</date-last-update>
        <counter-value>49</counter-value>
      </water-meter>
      <water-meter>
        <meter-id>6</meter-id>
        <meter-number>28358958</meter-number>
        <make>Const Tech</make>
        <model>BD-7000</model>
        <meter-size>3/4 Inches</meter-size>
        <date-last-update>04/22/2012</date-last-update>
        <counter-value>1138</counter-value>
      </water-meter>
    </water-meters>
  88. Click the Review link that corresponds to the fourth record

    Editing - Updating a Record

  89. Click the Home link
  90. In the webpage, click the Customers link
  91. Click the New Customer link
  92. Create the following records:
     
    Account # Meter # First Name Last Name Address City County State ZIP Code
    9279-570-8394 799-28-461 Thomas Stones 10252 Broward Ave #D4 Frederick Frederick MD 21703
    4820-375-2842 392-44-572 Akhil Koumari 748 Red Hills Rd Roanoke   VA 24012
    7518-302-6895 207-94-835 Grace Brenner 4299 Peachtree Court Rockville Montgomery MD 20853
    2038-413-9680 938-75-869 Amidou Gomah 2075 Rose Hills Ave Washington   DC 20004
    5938-074-5293 592-84-957 Marie Rath 582G Dunhill Ave Lanham Prince George MD 20706
    28864153060 392-44-572 Janice Edson 10304 Rolando Drv Anderson PA 17262
    <?xml version="1.0" encoding="utf-8" ?>
    <customers>
      <customer>
        <account-id>1</account-id>
        <account-number>9279-570-8394</account-number>
        <meter-number>799-28-461</meter-number>
        <first-name>Thomas</first-name>
        <last-name>Stones</last-name>
        <address>10252 Broward Ave #D4</address>
        <city>Frederick</city>
        <county>Frederick</county>
        <state>Frederick</state>
        <zip-code>21703</zip-code>
      </customer>
      <customer>
        <account-id>2</account-id>
        <account-number>4820-375-2842</account-number>
        <meter-number>392-44-572</meter-number>
        <first-name>Akhil</first-name>
        <last-name>Koumari</last-name>
        <address>748 Red Hills Rd</address>
        <city>Roanoke</city>
        <county>
        </county>
        <state>VA</state>
        <zip-code>24012</zip-code>
      </customer>
      <customer>
        <account-id>3</account-id>
        <account-number>7518-302-6895</account-number>
        <meter-number>207-94-835</meter-number>
        <first-name>Grace</first-name>
        <last-name>Brenner</last-name>
        <address>4299 Peachtree Court</address>
        <city>Rockville</city>
        <county>Montgomery</county>
        <state>MD</state>
        <zip-code>20853</zip-code>
      </customer>
      <customer>
        <account-id>4</account-id>
        <account-number>2038-413-9680</account-number>
        <meter-number>938-75-869</meter-number>
        <first-name>Amidou</first-name>
        <last-name>Gomah</last-name>
        <address>2075 Rose Hills Ave</address>
        <city>Washington</city>
        <county>
        </county>
        <state>DC</state>
        <zip-code>20004</zip-code>
      </customer>
      <customer>
        <account-id>5</account-id>
        <account-number>5938-074-5293</account-number>
        <meter-number>592-84-957</meter-number>
        <first-name>Marie</first-name>
        <last-name>Rath</last-name>
        <address>582G Dunhill Ave</address>
        <city>Lanham</city>
        <county>Prince George</county>
        <state>MD</state>
        <zip-code>20706</zip-code>
      </customer>
      <customer>
        <account-id>6</account-id>
        <account-number>28864153060</account-number>
        <meter-number>392-44-572</meter-number>
        <first-name>Janice</first-name>
        <last-name>Edson</last-name>
        <address>10304 Rolando Drv</address>
        <city>Anderson</city>
        <county>
        </county>
        <state>PA</state>
        <zip-code>17262</zip-code>
      </customer>
    </customers>
  93. Close the browser and return to your programming environment
  94. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  95. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions is selected.
    Click Add
  96. Type WaterBills to get WaterBillsControllers
  97. Press Enter
  98. Change the Index(), the Details(), and the first Create() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class WaterBillsController : Controller
        {
            // GET: WaterBills
            public ActionResult Index()
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
                    }
    
                    if (xdWaterBills.DocumentElement.ChildNodes.Count > 0)
                    {
                        ViewBag.Invoices = xdWaterBills.DocumentElement.ChildNodes;
                    }
                    else
                    {
                        ViewBag.Invoices = null;
                    }
                }
    
                return View(xdWaterBills);
            }
    
            // GET: WaterBills/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            if (xnWaterBill.InnerText == id.ToString())
                            {
                                ViewBag.WaterBillID           = xnWaterBill.InnerText;
                                ViewBag.InvoiceNumber         = xnWaterBill.NextSibling.InnerText;
                                ViewBag.AccountNumber         = xnWaterBill.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingStartDate = xnWaterBill.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingEndDate   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.BillingDays           = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingStart   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingEnd     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalHCF              = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalGallons          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.First15HCF            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Next10HCF             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.RemainingHCF          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.SewerCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StormCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.WaterUsageCharges     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LocalTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StateTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDueDate        = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.AmountDue             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LatePaymentDueDate    = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LateAmountDue         = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: WaterBills/Create
            public ActionResult Create()
            {
                int water_bill_id = 0;
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            water_bill_id = int.Parse(xnWaterBill.InnerText);
                        }
                    }
                }
    
                ViewBag.WaterBillID = (water_bill_id + 1);
    
                Random rndNumber = new Random();
                ViewBag.InvoiceNumber = rndNumber.Next(100001, 999999).ToString();
    
                return View();
            }
    
            // POST: WaterBills/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  99. In the class, right-click Index() and click Add View...
  100. In the Add View dialog box, make sure the View Name text box is displaying Index. Click Add
  101. Change the document as follows:
    @{
        ViewBag.Title = "Customers Water Bills";
    }
    
    <div class="push-down">
        <h2 class="common-font bold text-center">Customers Water Bills</h2>
    </div>
    
    <hr />
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center" colspan="2">Identification</th>
            <th class="bold text-center" colspan="4">Meter Reading</th>
            <th class="bold text-center" colspan="2">Counter Reading</th>
            <th class="bold text-center" colspan="5">HCF Summary</th>
            <th class="bold text-center" colspan="4">Charges</th>
            <th class="bold text-center" colspan="2">Taxes</th>
            <th class="bold text-center" colspan="4">Payment</th>
            <th>&nbsp;</th>
        </tr>
        <tr>
            <th class="bold">Bill ID</th>
            <th class="bold">Invoice #</th>
            <th class="bold">Account #</th>
            <th class="bold">Start Date</th>
            <th class="bold">End Date</th>
            <th class="bold">Days</th>
            <th class="bold">Start</th>
            <th class="bold">End</th>
            <th class="bold">Total</th>
            <th class="bold">Gallons</th>
            <th class="bold">First 15</th>
            <th class="bold">Next 10</th>
            <th class="bold">Remaining</th>
            <th class="bold">Sewer</th>
            <th class="bold">Storm</th>
            <th class="bold">Water Usage</th>
            <th class="bold">Total</th>
            <th class="bold">Local</th>
            <th class="bold">State</th>
            <th class="bold">Due Date</th>
            <th class="bold">Amount</th>
            <th class="bold">Late Pmt</th>
            <th class="bold">Late Amt</th>
            <th>&nbsp;</th>
        </tr>
    
        @if (ViewBag.Invoices != null)
        {
            foreach (System.Xml.XmlNode bill in ViewBag.Invoices as System.Xml.XmlNodeList)
            {
                <tr>
                    <td class="text-center">@bill.FirstChild.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>@bill.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText</td>
                    <td>
                        @Html.ActionLink("Update", "Edit", new { id = @bill.FirstChild.InnerText }) <span style="color: aquamarine">::</span>
                        @Html.ActionLink("Review", "Details", new { id = @bill.FirstChild.InnerText }) <span style="color: aquamarine">::</span>
                        @Html.ActionLink("Remove", "Delete", new { id = @bill.FirstChild.InnerText })
                    </td>
                </tr>
            }
        }
    </table>
    
    <p class="text-center">@Html.ActionLink("New Water Bill", "Create", null, htmlAttributes: new { @class = "water-nav" })</p>
  102. Click the WaterBillsController.cs tab to access its class
  103. In the class, right-click Details() and click Add View...
  104. Makre sure the View Name text box is displaying Details. Click Add
  105. Change the document as follows:
    @{
        ViewBag.Title = "Water Bill Details";
    }
    
    <div class="push-down">
        <h2>Water Bill Details</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt class="bold">Water Bill ID:</dt>
            <dd>@ViewBag.WaterBillID</dd>
            <dt class="bold">Invoice #:</dt>
            <dd>@ViewBag.InvoiceNumber</dd>
            <dt class="bold">Account #:</dt>
            <dd>@ViewBag.AccountNumber</dd>
            <dt class="bold">Meter Reading Start Date:</dt>
            <dd>@ViewBag.MeterReadingStartDate</dd>
            <dt class="bold">Meter Reading End Date:</dt>
            <dd>@ViewBag.MeterReadingEndDate</dd>
            <dt class="bold">Billing Days:</dt>
            <dd>@ViewBag.BillingDays</dd>
            <dt class="bold">Counter Reading Start:</dt>
            <dd>@ViewBag.CounterReadingStart</dd>
            <dt class="bold">Counter Reading End:</dt>
            <dd>@ViewBag.CounterReadingEnd</dd>
            <dt class="bold">Total HCF:</dt>
            <dd>@ViewBag.TotalHCF</dd>
            <dt class="bold">Total Gallons:</dt>
            <dd>@ViewBag.TotalGallons</dd>
            <dt class="bold">First 15 HCF:</dt>
            <dd>@ViewBag.First15HCF</dd>
            <dt class="bold">Next 10 HCF:</dt>
            <dd>@ViewBag.Next10HCF</dd>
            <dt class="bold">Remaining HCF:</dt>
            <dd>@ViewBag.RemainingHCF</dd>
            <dt class="bold">Sewer Charges:</dt>
            <dd>@ViewBag.SewerCharges</dd>
            <dt class="bold">Storm Charges:</dt>
            <dd>@ViewBag.StormCharges</dd>
            <dt class="bold">Water Usage Charges:</dt>
            <dd>@ViewBag.WaterUsageCharges</dd>
            <dt class="bold">Total Charges:</dt>
            <dd>@ViewBag.TotalCharges</dd>
            <dt class="bold">Local Taxes:</dt>
            <dd>@ViewBag.LocalTaxes</dd>
            <dt class="bold">State Taxes:</dt>
            <dd>@ViewBag.State Taxes</dd>
            <dt class="bold">Payment Due Date:</dt>
            <dd>@ViewBag.PaymentDueDate</dd>
            <dt class="bold">Amount Due:</dt>
            <dd>@ViewBag.AmountDue</dd>
            <dt class="bold">Late Payment Due Date:</dt>
            <dd>@ViewBag.LatePaymentDueDate</dd>
            <dt class="bold">Late Amount Due:</dt>
            <dd>@ViewBag.LateAmountDue</dd>
        </dl>
    </div>
    
    <p class="text-center">
        @Html.ActionLink("Edit/Update Customer Water Bill", "Edit",
                         new { id = @ViewBag.WaterBillID }, htmlAttributes: new { @class = "water-nav" }) ||
        @Html.ActionLink("Customers Water Bills", "Index",
                         null, new { @class = "water-nav" })
    </p>
  106. Click the WaterBillsController.cs tab
  107. In the class, right-click one of the Create() methods and click Add View...
  108. In the Add View dialog box, make sure the View Name text box is displaying Create. Click Add
  109. Create the form as follows:
    @{
        ViewBag.Title = "Prepare Customer Water Bill";
    }
    
    <div class="push-down">
        <h2>Prepare Customer Water Bill</h2>
    </div>
    
    <hr />
    
    @using (Html.BeginForm())
    {
    <div class="form-horizontal">
        <div class="form-group">
            <label for="billNbr" class="control-label col-md-4 caption">Water Bill ID:</label>
            <div class="col-md-8">
                @Html.TextBox("WaterBillID", null,
                              htmlAttributes: new { @class = "form-control", id = "billNbr", disabled = "disabled" })
            </div>
        </div>
        <div class="form-group">
            <label for="invoiceNbr" class="control-label col-md-4 caption">Invoice #:</label>
            <div class="col-md-8">
                @Html.TextBox("InvoiceNumber", null,
                              htmlAttributes: new { @class = "form-control", id = "invoiceNbr" })
            </div>
        </div>
        <div class="form-group">
            <label for="acntNbr" class="control-label col-md-4 caption">Customer Account #:</label>
            <div class="col-md-8">
                @Html.TextBox("AccountNumber", null,
                              htmlAttributes: new { @class = "form-control", id = "acntNbr" })
            </div>
        </div>
    
        <div class="form-group">
            <label class="control-label col-md-4 caption">Customer Name:</label>
            <div class="col-md-8">
                @Html.TextBox("CustomerName", null,
                              new { @class = "form-control", id = "custName", disabled = "disabled" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4 caption">Customer Address:</label>
            <div class="col-md-8">
                @Html.TextBox("CustomerAddress", null,
                              new { @class = "form-control", id = "adrs", disabled = "disabled" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-125">
                @Html.TextBox("CustomerCity", null,
                              new { @class = "form-control", id = "city", disabled = "disabled" })
            </div>
            <div class="col-md-125">
                @Html.TextBox("CustomerCounty", null,
                              new { @class = "form-control", id = "county", disabled = "disabled" })
            </div>
            <div class="col-md-125">
                @Html.TextBox("CustomerState", null,
                              new { @class = "form-control", id = "state", disabled = "disabled" })
            </div>
            <div class="col-md-125">
                @Html.TextBox("CustomerZIPCode", null,
                              new { @class = "form-control", id = "zip", disabled = "disabled" })
            </div>
        </div>
    
        <div class="form-group">
            <label class="control-label col-md-4 caption">Meter Details:</label>
            <div class="col-md-125">
                @Html.TextBox("MeterNumber", null,
                              new { @class = "form-control", id = "mtrNbr", disabled = "disabled" })
            </div>
            <div class="col-md-6">
                @Html.TextBox("MeterDetails", null,
                              htmlAttributes: new { @class = "form-control", id = "meterDetails", disabled = "disabled" })
            </div>
        </div>
        <hr />
        <div class="form-group">
            <label for="mrsd" class="control-label col-md-4 caption">Meter Reading Start Date:</label>
            <div class="col-md-2">
                @Html.TextBox("MeterReadingStartDate", null,
                              htmlAttributes: new { @class = "form-control", id = "mrsd" })
            </div>
            <label for="mred" class="control-label col-md-125 caption">Meter Reading End Date:</label>
            <div class="col-md-125">
                @Html.TextBox("MeterReadingEndDate", null,
                              htmlAttributes: new { @class = "form-control", type = "date", id = "mred" })
            </div>
            <label for="days" class="control-label col-md-2 caption">Billing Days:</label>
            <div class="col-md-1">
                @Html.TextBox("BillingDays", null, htmlAttributes: new { @class = "form-control", id = "days" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="crs" class="control-label col-md-4 caption">Counter Reading Start:</label>
            <div class="col-md-2">
                @Html.TextBox("CounterReadingStart", null, htmlAttributes: new { @class = "form-control", id = "crs" })
            </div>
            <label for="cre" class="control-label col-md-125 caption">Current Meter Reading:</label>
            <div class="col-md-125">
                @Html.TextBox("CounterReadingEnd", null, htmlAttributes: new { @class = "form-control", id = "cre" })
            </div>
            <label for="thcf" class="control-label col-md-2 caption">Total HCF:</label>
            <div class="col-md-1">
                @Html.TextBox("TotalHCF", null, htmlAttributes: new { @class = "form-control", id = "thcf" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-2">&nbsp;</div>
            <label class="control-label col-md-125">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="gallons" class="control-label col-md-2 caption">Total Gallons:</label>
            <div class="col-md-1">
                @Html.TextBox("TotalGallons", null, htmlAttributes: new { @class = "form-control", id = "gallons" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="f15HCF" class="control-label col-md-4 caption">1st 15 HCF at $3.6121:</label>
            <div class="col-md-2">
                @Html.TextBox("First15HCF", null,
                              htmlAttributes: new { @class = "form-control", id = "f15HCF" })
            </div>
            <label for="next10HCF" class="control-label col-md-125 caption">Next 10 HCF at $3.9180:</label>
            <div class="col-md-125">
                @Html.TextBox("Next10HCF", null,
                              htmlAttributes: new { @class = "form-control", id = "next10HCF" })
            </div>
            <label for="remHCF" class="control-label col-md-2 caption">Remaining HCF at $4.2763:</label>
            <div class="col-md-1">
                @Html.TextBox("RemainingHCF", null, htmlAttributes: new { @class = "form-control", id = "remHCF" })
            </div>
        </div>
        <div class="form-group">
            <label for="sewerCharges" class="control-label col-md-4 caption">Sewer Charges:</label>
            <div class="col-md-2">
                @Html.TextBox("SewerCharges", null,
                              htmlAttributes: new { @class = "form-control", id = "sewerCharges" })
            </div>
            <label for="stormCharges" class="control-label col-md-125 caption">Storm Charges:</label>
            <div class="col-md-125">
                @Html.TextBox("StormCharges", null,
                              htmlAttributes: new { @class = "form-control", id = "stormCharges" })
            </div>
            <label for="wuc" class="control-label col-md-2 caption">Water Usage Charges:</label>
            <div class="col-md-1">
                @Html.TextBox("WaterUsageCharges", null, htmlAttributes: new { @class = "form-control", id = "wuc" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-2">&nbsp;</div>
            <label class="control-label col-md-125">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="totalCharges" class="control-label col-md-2 caption">Total Charges:</label>
            <div class="col-md-1">
                @Html.TextBox("TotalCharges", null, htmlAttributes: new { @class = "form-control", id = "totalCharges" })
            </div>
        </div>
        <hr />
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="localTaxes" class="control-label col-md-125 caption">Local Taxes:</label>
            <div class="col-md-125">
                @Html.TextBox("LocalTaxes", null,
                              htmlAttributes: new { @class = "form-control", id = "localTaxes" })
            </div>
            <label for="stateTaxes" class="control-label col-md-125 caption">State Taxes:</label>
            <div class="col-md-125">
                @Html.TextBox("StateTaxes", null, htmlAttributes: new { @class = "form-control", id = "stateTaxes" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="pdd" class="control-label col-md-125 caption">Payment Due Date:</label>
            <div class="col-md-125">
                @Html.TextBox("PaymentDueDate", null,
                              htmlAttributes: new { @class = "form-control", type = "date", id = "pdd" })
            </div>
            <label for="amtDue" class="control-label col-md-125 caption">Amount Due:</label>
            <div class="col-md-125">
                @Html.TextBox("AmountDue", null,
                              htmlAttributes: new { @class = "form-control", id = "amtDue" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4 caption">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="lpdd" class="control-label col-md-125 caption">Late Payment Due Date:</label>
            <div class="col-md-125">
                @Html.TextBox("LatePaymentDueDate", null,
                              htmlAttributes: new { @class = "form-control", id = "lpdd" })
            </div>
            <label for="lateAmtDue" class="control-label col-md-125 caption">Late Amount Due:</label>
            <div class="col-md-125">
                @Html.TextBox("LateAmountDue", null, htmlAttributes: new { @class = "form-control", id = "lateAmtDue" })
            </div>
        </div>
    
        <div class="form-group text-center">
            <label class="control-label col-md-5">
                @Html.ActionLink("Water Bills", "Index", null, htmlAttributes: new { @class = "water-nav" })
            </label>
            <div class="col-md-7">
                <input type="submit" value="Save Water Bill" class="btn btn-primary" />
            </div>
        </div>
    </div>
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#acntNbr").blur(function (event) {
                var connection = {
                    method:   "GET",
                    dataType: "xml",
                    url:      "/WaterDistribution/Customers.xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var clients = $(data).find("customer");
                        clients.each(function () {
                            if ($(this).find("account-number").text() === $("#acntNbr").val()) {
                                $("#mtrNbr").val($(this).find("meter-number").text());
                                $("#custName").val($(this).find("first-name").text() + " " + $(this).find("last-name").text());
                                $("#adrs").val($(this).find("address").text());
                                $("#city").val($(this).find("city").text());
                                $("#county").val($(this).find("county").text());
                                $("#state").val($(this).find("state").text());
                                $("#zip").val($(this).find("zip-code").text());
                            }
                        });
                    });
    
                connection = {
                    method:   "GET",
                    dataType: "xml",
                    url:      "/WaterDistribution/WaterMeters.xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var waterMeters = $(data).find("water-meter");
                        waterMeters.each(function () {
                            if ($(this).find("meter-number").text() === $("#mtrNbr").val()) {
                                $("#meterDetails").val($(this).find("make").text() + " " + $(this).find("model").text() + " (" + $(this).find("meter-size").text() + ")");
                                $("#mrsd").val($(this).find("date-last-update").text());
                                $("#crs").val($(this).find("counter-value").text());
                            }
                        });
                    });
    
                connection = {
                    method:   "GET",
                    dataType: "xml",
                    url:      "/WaterDistribution/WaterBills.xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var invoices = $(data).find("invoice");
                        invoices.each(function () {
                            if ($(this).find("account-number").text() === $("#acntNbr").val()) {
                                $("#mrsd").val($(this).find("meter-reading-end-date").text());
                                $("#crs").val($(this).find("counter-reading-end").text());
                            }
                        });
                    });
            }); // Account # Lost Focus
    
            $("#mred").change(function (event) {
                var meterReadingStartDate = Date.parse($("#mrsd").val());
                var meterReadingEndDate   = Date.parse($("#mred").val());
    
                var days = (meterReadingEndDate - meterReadingStartDate) / 86400000;
    
                $("#days").val(days.toFixed());
            }); // Meter Reading End Date Lost Focus
    
            $("#cre").focusout(function (event) {
                var counterReadingStart = parseInt($("#crs").val());
                var counterReadingEnd   = parseInt($("#cre").val());
                var totalHCF = counterReadingEnd - counterReadingStart;
                var gallons = totalHCF * 748; // 748.05
    
                var first15HCF = totalHCF * 3.612;
                var next10HCF = 0, remainingHCF = 0;
    
                if (totalHCF <= 15) {
                    first15HCF = totalHCF * 3.612;
                    next10HCF = 0;
                    remainingHCF = 0;
                }
                else if (totalHCF <= 25) {
                    first15HCF = 15 * 3.612;
                    next10HCF = (totalHCF - 15) * 3.918;
                    remainingHCF = 0;
                }
                else {
                    first15HCF = 15 * 3.612;
                    next10HCF = 10 * 3.918;
                    remainingHCF = (totalHCF - 25) * 2.2763;
                }
    
                var waterUsageCharges = first15HCF + next10HCF + remainingHCF;
                var sewerCharges      = waterUsageCharges * 0.252;
                var stormCharges      = waterUsageCharges * 0.0025;
                var totalCharges      = waterUsageCharges + sewerCharges + stormCharges;
                var localTaxes        = totalCharges * 0.0152;
                var stateTaxes        = totalCharges * 0.005;
                var amountDue         = totalCharges + localTaxes + stateTaxes;
    
                $("#thcf").val(totalHCF.toFixed());
                $("#gallons").val(gallons.toFixed());
                $("#amtDue").val(amountDue.toFixed(2));
                $("#f15HCF").val(first15HCF.toFixed(2));
                $("#next10HCF").val(next10HCF.toFixed(2));
                $("#remHCF").val(remainingHCF.toFixed(2));
                $("#wuc").val(waterUsageCharges.toFixed(2));
                $("#stateTaxes").val(stateTaxes.toFixed(2));
                $("#localTaxes").val(localTaxes.toFixed(2));
                $("#sewerCharges").val(sewerCharges.toFixed(2));
                $("#stormCharges").val(stormCharges.toFixed(2));
                $("#totalCharges").val(totalCharges.toFixed(2));
                $("#lateAmtDue").val((amountDue + 8.95).toFixed(2));
            }); // Counter Reading End Lost Focus
        }); // Document.Ready
    </script>
  110. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  111. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions is selected.
    Click Add
  112. Type Payments to get PaymentsControllers
  113. Press Enter
  114. Change the Index(), the Details(), and the Create() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class PaymentsController : Controller
        {
            // GET: Payments
            public ActionResult Index()
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
                    }
    
                    if (xdPayments.DocumentElement.ChildNodes.Count > 0)
                    {
                        ViewBag.Payments = xdPayments.DocumentElement.ChildNodes;
                    }
                    else
                    {
                        ViewBag.Payments = null;
                    }
                }
    
                return View();
            }
    
            // GET: Payments/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            if (xnPayment.InnerText == id.ToString())
                            {
                                ViewBag.PaymentID     = xnPayment.InnerText;
                                ViewBag.ReceiptNumber = xnPayment.NextSibling.InnerText;
                                ViewBag.WaterBillID   = xnPayment.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDate   = xnPayment.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentAmount = xnPayment.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: Payments/Create
            public ActionResult Create()
            {
                int payment_id = 0;
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            payment_id = int.Parse(xnPayment.InnerText);
                        }
                    }
                }
    
                ViewBag.PaymentID = (payment_id + 1);
    
                Random rndNumber = new Random();
                ViewBag.ReceiptNumber = rndNumber.Next(100001, 999999).ToString();
    
                return View();
            }
    
            // POST: Payments/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    XmlDocument xdPayments = new XmlDocument();
                    string strFilePayments= Server.MapPath("/WaterDistribution/Payments.xml");
                    
                    if (System.IO.File.Exists(strFilePayments))
                    {
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdPayments.Load(fsPayments);
                        }
                    }
                    else
                    {
                        xdPayments.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                           "<payments></payments>");
                    }
                    
                    XmlElement xePayment = xdPayments.CreateElement("bill-payment");
    
                    xePayment.InnerXml = "<payment-id>"     + collection["PaymentID"]     + "</payment-id>"    +
                                         "<receipt-number>" + collection["ReceiptNumber"] + "</receipt-number>" +
                                         "<water-bill-id>"  + collection["WaterBillID"]   + "</water-bill-id>"  +
                                         "<payment-date>"   + collection["PaymentDate"]   + "</payment-date>"   +
                                         "<payment-amount>" + collection["PaymentAmount"] + "</payment-amount>";
    
                    xdPayments.DocumentElement.AppendChild(xePayment);
                    
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        xdPayments.Save(fsPayments);
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
            
    
            . . . No Change
        }
    }

Updating an XML Element

Introduction

Consider the following version of our Videos.xml file:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video>
    <title>The Day After Tomorrow</title>
    <director>Roland Emmerich</director>
    <length>124 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
</videos>

The .NET Framework implementation of XML provides various options to change the aspect, structure, or value(s), of an element. For example, you can use the same logic used in collection classes. This consists of locating a node and simply changing its value(s). Here is an example:

@{
    string strVideosFile = Server.MapPath("~/App_Data/Videos.xml");
    System.Xml.XmlDocument xdVideos = new System.Xml.XmlDocument();

    // Open the XML file
    xdVideos.Load(strVideosFile);
    System.Xml.XmlNodeList xnlVideos = xdVideos.DocumentElement.GetElementsByTagName("title");

    foreach (System.Xml.XmlNode xnVideo in xnlVideos)
    {
        if (xnVideo.InnerText.Contains("The Day After Tomorrow"))
        {
            xnVideo.ParentNode.InnerXml = "<title>Day After Tomorrow (The)</title>" +
                                          "<director>Roland Emmerich</director>" +
                                          "<year>2004</year>" +
                                          "<length>124 Minutes</length>" +
                                          "<format>DVD</format>" +
                                          "<rating>PG-13</rating>";
            xdVideos.Save(strVideosFile);
            break;
        }
    }
}

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video>
    <title>Day After Tomorrow(The)</title>
    <director>Roland Emmerich</director>
    <year>2004</year>
    <length>124</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
</videos>

Practical LearningPractical Learning: Updating an Element

  1. In the Solution Explorer, under Controllers, double-click WaterMetersController.cs to access the file
  2. Change both Edit() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class WaterMetersController : Controller
        {
            . . . No Change
    
            
            // GET: WaterMeters/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                        {
                            if (xnWaterMeter.InnerText == id.ToString())
                            {
                                ViewBag.WaterMeterID = xnWaterMeter.InnerText;
                                ViewBag.MeterNumber = xnWaterMeter.NextSibling.InnerText;
                                ViewBag.Make = xnWaterMeter.NextSibling.NextSibling.InnerText;
                                ViewBag.Model = xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterSize = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.DateLastUpdate = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterValue = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: WaterMeters/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    if (System.IO.File.Exists(strFileWaterMeters))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdWaterMeters.Load(fsWaterMeters);
                        }
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                            {
                                if (xnWaterMeter.InnerText == id.ToString())
                                {
                                    xnWaterMeter.ParentNode.InnerXml = "<meter-id>" + id + "</meter-id>" +
                                                                       "<meter-number>" + collection["MeterNumber"] + "</meter-number>" +
                                                                       "<make>" + collection["Make"] + "</make>" +
                                                                       "<model>" + collection["Model"] + "</model>" +
                                                                       "<meter-size>" + collection["MeterSize"] + "</meter-size>" +
                                                                       "<date-last-update>" + collection["DateLastUpdate"] + "</date-last-update>" +
                                                                       "<counter-value>" + collection["CounterValue"] + "</counter-value>";
                                    xdWaterMeters.Save(fsWaterMeters);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
           . . . No Change
        }
    }
  3. In the document, right-click one of the Edit() methods and click Add View...
  4. Make sure the View Name text box is displaying Edit.
    Click Add
  5. Change the document as follows:
    @{
        ViewBag.Title = "Edit/Update Water Meter";
    }
    
    <div class="push-down">
        <h2>Edit/Update Water Meter</h2>
    </div>
    <hr />
    @using (Html.BeginForm())
    {
        <div class="form-horizontal">
            <div class="form-group">
                <label class="control-label col-md-4 caption">Meter #:</label>
                <div class="col-md-8">
                    @Html.TextBox("WaterMeterID", ViewBag.WaterMeterID as string, htmlAttributes: new { @class = "form-control", disabled = "disabled" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="mtrNbr" class="control-label col-md-4 caption">Meter #:</label>
                <div class="col-md-8">
                    @Html.TextBox("MeterNumber", ViewBag.MeterNumber as string, htmlAttributes: new { @class = "form-control", id = "mtrNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="make" class="control-label col-md-4 caption">Make:</label>
                <div class="col-md-8">
                    @Html.TextBox("Make", ViewBag.Make as string, htmlAttributes: new { @class = "form-control", id = "make" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="model" class="control-label col-md-4 caption">Model:</label>
                <div class="col-md-8">
                    @Html.TextBox("Model", ViewBag.Model as string, htmlAttributes: new { @class = "form-control", id = "model" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="mtrSize" class="control-label col-md-4 caption">Meter Size:</label>
                <div class="col-md-8">
                    @Html.TextBox("MeterSize", ViewBag.MeterSize as string, htmlAttributes: new { @class = "form-control", id = "mtrSize" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="dlu" class="control-label col-md-4 caption">Date Last Update:</label>
                <div class="col-md-8">
                    @Html.TextBox("DateLastUpdate",
                        ViewBag.DateLastUpdate as string, htmlAttributes: new { @class = "form-control", type = "date", id = "dlu" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="cntVal" class="control-label col-md-4 caption">Counter Value:</label>
                <div class="col-md-8">
                    @Html.TextBox("CounterValue", ViewBag.CounterValue as string, htmlAttributes: new { @class = "form-control", id = "cntVal" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-5">
                    @Html.ActionLink("Water Meters", "Index", null, htmlAttributes: new { @class = "water-nav" })
                </label>
                <div class="col-md-7">
                    <input type="submit" value="Update Water Meter Details" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
  6. In the Solution Explorer, under Views and under WaterMeters, double-click Index.cshtml
  7. To execute, on the main menu, click Debug and click Start Without Debugging
  8. Click the Review link of the last record

    Editing - Updating a Record

  9. Click the Edit/Update Water Meter Information link:

    Introducing Interfaces

  10. Change the following values:
    Meter #:         283-58-958
    Make:            Constance Technologies
    Model:           TR-6224
    Date Last Udate: 04/22/2018
  11. Click Update Water Meter Details

    Editing - Updating a Record

  12. Close the browser and return to your programming environment
  13. In the Solution Explorer, under Controllers, double-click WaterBills.cs to access its controller
  14. Implement the second Create() and both Edit() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class WaterBillsController : Controller
        {
            
            . . . No Change
    
            // GET: WaterBills/Create
            public ActionResult Create()
            {
                int water_bill_id = 0;
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            water_bill_id = int.Parse(xnWaterBill.InnerText);
                        }
                    }
                }
    
                ViewBag.WaterBillID = (water_bill_id + 1);
    
                Random rndNumber = new Random();
                ViewBag.InvoiceNumber = rndNumber.Next(100001, 999999).ToString();
    
                return View();
            }
    
            // POST: WaterBills/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int bill_id              = -1;
                    bool customerIsValid     = false;
                    string meterNumber       = string.Empty;
                    XmlDocument xdCustomers  = new XmlDocument();
                    XmlDocument xdWaterBills = new XmlDocument();
                    string strFileCustomers  = Server.MapPath("/WaterDistribution/Customers.xml");
                    string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                    // Make sure the user provided an account number for the customer, ...
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        // If the user provided an account number, find out if an XML file for customers was already created.
                        if (System.IO.File.Exists(strFileCustomers))
                        {
                            // If a file for customers exists, open it
                            using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Open,
                                                                                             FileAccess.Read,
                                                                                             FileShare.Read))
                            {
                                // Store the list of customers in an XML document
                                xdCustomers.Load(fsCustomers);
    
                                // Create a list of customers nodes that use the account number provided by the user
                                XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-number");
    
                                // Visit each node of the list of elements
                                foreach (XmlNode xnCustomer in xnlCustomers)
                                {
                                    // If you find a customer that is the same as the account number from the form, ...
                                    if (xnCustomer.InnerText == collection["AccountNumber"])
                                    {
                                        // ... make a note
                                        customerIsValid = true;
                                        // and get the meter number used by that customer
                                        meterNumber = xnCustomer.NextSibling.InnerText;
                                    }
                                }
                            }
                        }
                    }
    
                    if (customerIsValid == true)
                    {
                        // It appears that the user provided a valid customer account number.
                        // If an XML file for water bills was previously created, ...
                        if (System.IO.File.Exists(strFileWaterBills))
                        {
                            // ... open it ...
                            using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.OpenOrCreate,
                                                                                               FileAccess.ReadWrite,
                                                                                               FileShare.ReadWrite))
                            {
                                // ... and put the records in the DOM
                                xdWaterBills.Load(fsWaterBills);
    
                                XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                                foreach (XmlNode xnWaterBill in xnlWaterBills)
                                {
                                    bill_id = int.Parse(xnWaterBill.InnerText);
                                }
                            }
                        }
                        else
                        {
                            // If there is no XML file yet for the customers, create skeleton code for an XML document
                            xdWaterBills.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                 "<water-bills></water-bills>");
                            bill_id = 0;
                        }
    
                        // Get ready to create an XML element named water-bill
                        XmlElement xeWaterBill = xdWaterBills.CreateElement("invoice");
    
                        bill_id++;
    
                        // Create the markup of the XML water bill
                        xeWaterBill.InnerXml = "<water-bill-id>"            + bill_id                             + "</water-bill-id>"            +
                                               "<invoice-number>"           + collection["InvoiceNumber"]         + "</invoice-number>"           +
                                               "<account-number>"           + collection["AccountNumber"]         + "</account-number>"           +
                                               "<meter-reading-start-date>" + collection["MeterReadingStartDate"] + "</meter-reading-start-date>" +
                                               "<meter-reading-end-date>"   + collection["MeterReadingEndDate"]   + "</meter-reading-end-date>"   +
                                               "<billing-days>"             + collection["BillingDays"]           + "</billing-days>"             +
                                               "<counter-reading-start>"    + collection["CounterReadingStart"]   + "</counter-reading-start>"    +
                                               "<counter-reading-end>"      + collection["CounterReadingEnd"]     + "</counter-reading-end>"      +
                                               "<total-hcf>"                + collection["TotalHCF"]              + "</total-hcf>"                +
                                               "<total-gallons>"            + collection["TotalGallons"]          + "</total-gallons>"            +
                                               "<first-15-hcf>"             + collection["First15HCF"]            + "</first-15-hcf>"             +
                                               "<next-10-hcf>"              + collection["Next10HCF"]             + "</next-10-hcf>"              +
                                               "<remaining-hcf>"            + collection["RemainingHCF"]          + "</remaining-hcf>"            +
                                               "<sewer-charges>"            + collection["SewerCharges"]          + "</sewer-charges>"            +
                                               "<storm-charges>"            + collection["StormCharges"]          + "</storm-charges>"            +
                                               "<water-usage-charges>"      + collection["WaterUsageCharges"]     + "</water-usage-charges>"      +
                                               "<total-charges>"            + collection["TotalCharges"]          + "</total-charges>"            +
                                               "<local-taxes>"              + collection["LocalTaxes"]            + "</local-taxes>"              +
                                               "<state-taxes>"              + collection["StateTaxes"]            + "</state-taxes>"              +
                                               "<payment-due-date>"         + collection["PaymentDueDate"]        + "</payment-due-date>"         +
                                               "<amount-due>"               + collection["AmountDue"]             + "</amount-due>"               +
                                               "<late-payment-due-date>"    + collection["LatePaymentDueDate"]    + "</late-payment-due-date>"    +
                                               "<late-amount-due>"          + collection["LateAmountDue"]         + "</late-amount-due>";
    
                        // Add the new node to the root
                        xdWaterBills.DocumentElement.AppendChild(xeWaterBill);
    
                        // Save the (new version of the) XML file
                        using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            xdWaterBills.Save(fsWaterBills);
                        }
    
                        // We also want to update the counter value on the water meter with the new Counter Reading End value
                        XmlDocument xdWaterMeters = new XmlDocument();
                        string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                        if (System.IO.File.Exists(strFileWaterMeters))
                        {
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                xdWaterMeters.Load(fsWaterMeters);
                            }
    
                            XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                                {
                                    if (xnWaterMeter.NextSibling.InnerText == meterNumber)
                                    {
                                        xnWaterMeter.ParentNode.InnerXml = "<meter-id>"         + xnWaterMeter.InnerText + "</meter-id>" +
                                                                           "<meter-number>"     + meterNumber + "</meter-number>" +
                                                                           "<make>"             + xnWaterMeter.NextSibling.NextSibling.InnerText + "</make>" +
                                                                           "<model>"            + xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText + "</model>" +
                                                                           "<meter-size>"       + xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "</meter-size>" +
                                                                           "<date-last-update>" + xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "</date-last-update>" +
                                                                           "<counter-value>"    + collection["CounterReadingEnd"] + "</counter-value>";
                                        xdWaterMeters.Save(fsWaterMeters);
                                        break;
                                    }
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: WaterBills/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strAccountNumber = string.Empty, strMeterNumber = string.Empty;
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            if (xnWaterBill.InnerText == id.ToString())
                            {
                                ViewBag.WaterBillID           = xnWaterBill.InnerText;
                                ViewBag.InvoiceNumber         = xnWaterBill.NextSibling.InnerText;
                                ViewBag.AccountNumber         = xnWaterBill.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingStartDate = xnWaterBill.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingEndDate   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.BillingDays           = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingStart   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingEnd     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalHCF              = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalGallons          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.First15HCF            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Next10HCF             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.RemainingHCF          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.SewerCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StormCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.WaterUsageCharges     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LocalTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StateTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDueDate        = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.AmountDue             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LatePaymentDueDate    = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LateAmountDue         = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
    
                                strAccountNumber = xnWaterBill.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
    
                    XmlDocument xdCustomers = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                    if (System.IO.File.Exists(strFileCustomers))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdCustomers.Load(fsWaterMeters);
    
                            XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-number");
    
                            foreach (XmlNode xnCustomer in xnlCustomers)
                            {
                                if (xnCustomer.InnerText == strAccountNumber)
                                {
                                    ViewBag.AccountNumber   = xnCustomer.InnerText;
                                    ViewBag.MeterNumber     = xnCustomer.NextSibling.InnerText;
                                    ViewBag.CustomerName    = xnCustomer.NextSibling.NextSibling.InnerText + " " + 
                                                              xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerAddress = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerCity    = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerCounty  = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerState   = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerZIPCode = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
    
                                    strMeterNumber = xnCustomer.NextSibling.InnerText;
                                }
                            }
                        }
                    }
    
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    if (System.IO.File.Exists(strFileWaterMeters))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdWaterMeters.Load(fsWaterMeters);
    
                            XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-number");
    
                            foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                            {
                                if (xnWaterMeter.InnerText == strMeterNumber)
                                {
                                    ViewBag.MeterDetails = xnWaterMeter.InnerText + " " + 
                                                           xnWaterMeter.NextSibling.InnerText + " (" + 
                                                           xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText + ")";
                                }
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: WaterBills/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdWaterBills = new XmlDocument();
                    string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                    if (System.IO.File.Exists(strFileWaterBills))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdWaterBills.Load(fsWaterMeters);
                        }
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (XmlNode xnWaterBill in xnlWaterBills)
                            {
                                if (xnWaterBill.InnerText == id.ToString())
                                {
                                    xnWaterBill.ParentNode.InnerXml = "<water-bill-id>"            + id                                  + "</water-bill-id>"            +
                                                                      "<invoice-number>"           + collection["InvoiceNumber"]         + "</invoice-number>"           +
                                                                      "<account-number>"           + collection["AccountNumber"]         + "</account-number>"           +
                                                                      "<meter-reading-start-date>" + collection["MeterReadingStartDate"] + "</meter-reading-start-date>" +
                                                                      "<meter-reading-end-date>"   + collection["MeterReadingEndDate"]   + "</meter-reading-end-date>"   +
                                                                      "<billing-days>"             + collection["BillingDays"]           + "</billing-days>"             +
                                                                      "<counter-reading-start>"    + collection["CounterReadingStart"]   + "</counter-reading-start>"    +
                                                                      "<counter-reading-end>"      + collection["CounterReadingEnd"]     + "</counter-reading-end>"      +
                                                                      "<total-hcf>"                + collection["TotalHCF"]              + "</total-hcf>"                +
                                                                      "<total-gallons>"            + collection["TotalGallons"]          + "</total-gallons>"            +
                                                                      "<first-15-hcf>"             + collection["First15HCF"]            + "</first-15-hcf>"             +
                                                                      "<next-10-hcf>"              + collection["Next10HCF"]             + "</next-10-hcf>"              +
                                                                      "<remaining-hcf>"            + collection["RemainingHCF"]          + "</remaining-hcf>"            +
                                                                      "<sewer-charges>"            + collection["SewerCharges"]          + "</sewer-charges>"            +
                                                                      "<storm-charges>"            + collection["StormCharges"]          + "</storm-charges>"            +
                                                                      "<water-usage-charges>"      + collection["WaterUsageCharges"]     + "</water-usage-charges>"      +
                                                                      "<total-charges>"            + collection["TotalCharges"]          + "</total-charges>"            +
                                                                      "<local-taxes>"              + collection["LocalTaxes"]            + "</local-taxes>"              +
                                                                      "<state-taxes>"              + collection["StateTaxes"]            + "</state-taxes>"              +
                                                                      "<payment-due-date>"         + collection["PaymentDueDate"]        + "</payment-due-date>"         +
                                                                      "<amount-due>"               + collection["AmountDue"]             + "</amount-due>"               +
                                                                     "<late-payment-due-date>"     + collection["LatePaymentDueDate"]    + "</late-payment-due-date>"    +
                                                                     "<late-amount-due>"           + collection["LateAmountDue"]         + "</late-amount-due>";
    
                                    xdWaterBills.Save(fsWaterBills);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . .  No Change
          
        }
    }
  15. In the class, right-click one of the Create() methods and click Add View...
  16. In the Add View dialog box, make sure the View Name text box is displaying Create. Click Add
  17. Create a form as follows:
    @{
        ViewBag.Title = "Prepare Customer Water Bill";
    }
    
    <div class="push-down">
        <h2>Prepare Customer Water Bill</h2>
    </div>
    
    <hr />
    
    @using (Html.BeginForm())
    {
    <div class="form-horizontal">
        <div class="form-group">
            <label for="billNbr" class="control-label col-md-4 caption">Water Bill ID:</label>
            <div class="col-md-8">
                @Html.TextBox("WaterBillID", null,
                              htmlAttributes: new { @class = "form-control", id = "billNbr", disabled = "disabled" })
            </div>
        </div>
        <div class="form-group">
            <label for="invoiceNbr" class="control-label col-md-4 caption">Invoice #:</label>
            <div class="col-md-8">
                @Html.TextBox("InvoiceNumber", null,
                              htmlAttributes: new { @class = "form-control", id = "invoiceNbr" })
            </div>
        </div>
        <div class="form-group">
            <label for="acntNbr" class="control-label col-md-4 caption">Customer Account #:</label>
            <div class="col-md-8">
                @Html.TextBox("AccountNumber", null,
                              htmlAttributes: new { @class = "form-control", id = "acntNbr" })
            </div>
        </div>
    
        <div class="form-group">
            <label class="control-label col-md-4 caption">Customer Name:</label>
            <div class="col-md-8">
                @Html.TextBox("CustomerName", null,
                              new { @class = "form-control", id = "custName", disabled = "disabled" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4 caption">Customer Address:</label>
            <div class="col-md-8">
                @Html.TextBox("CustomerAddress", null,
                              new { @class = "form-control", id = "adrs", disabled = "disabled" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-125">
                @Html.TextBox("CustomerCity", null,
                              new { @class = "form-control", id = "city", disabled = "disabled" })
            </div>
            <div class="col-md-125">
                @Html.TextBox("CustomerCounty", null,
                              new { @class = "form-control", id = "county", disabled = "disabled" })
            </div>
            <div class="col-md-125">
                @Html.TextBox("CustomerState", null,
                              new { @class = "form-control", id = "state", disabled = "disabled" })
            </div>
            <div class="col-md-125">
                @Html.TextBox("CustomerZIPCode", null,
                              new { @class = "form-control", id = "zip", disabled = "disabled" })
            </div>
        </div>
    
        <div class="form-group">
            <label class="control-label col-md-4 caption">Meter Details:</label>
            <div class="col-md-125">
                @Html.TextBox("MeterNumber", null,
                              new { @class = "form-control", id = "mtrNbr", disabled = "disabled" })
            </div>
            <div class="col-md-6">
                @Html.TextBox("MeterDetails", null,
                              htmlAttributes: new { @class = "form-control", id = "meterDetails", disabled = "disabled" })
            </div>
        </div>
        <hr />
        <div class="form-group">
            <label for="mrsd" class="control-label col-md-4 caption">Meter Reading Start Date:</label>
            <div class="col-md-2">
                @Html.TextBox("MeterReadingStartDate", null,
                              htmlAttributes: new { @class = "form-control", id = "mrsd" })
            </div>
            <label for="mred" class="control-label col-md-125 caption">Meter Reading End Date:</label>
            <div class="col-md-125">
                @Html.TextBox("MeterReadingEndDate", null,
                              htmlAttributes: new { @class = "form-control", type = "date", id = "mred" })
            </div>
            <label for="days" class="control-label col-md-2 caption">Billing Days:</label>
            <div class="col-md-1">
                @Html.TextBox("BillingDays", null, htmlAttributes: new { @class = "form-control", id = "days" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="crs" class="control-label col-md-4 caption">Counter Reading Start:</label>
            <div class="col-md-2">
                @Html.TextBox("CounterReadingStart", null, htmlAttributes: new { @class = "form-control", id = "crs" })
            </div>
            <label for="cre" class="control-label col-md-125 caption">Current Meter Reading:</label>
            <div class="col-md-125">
                @Html.TextBox("CounterReadingEnd", null, htmlAttributes: new { @class = "form-control", id = "cre" })
            </div>
            <label for="thcf" class="control-label col-md-2 caption">Total HCF:</label>
            <div class="col-md-1">
                @Html.TextBox("TotalHCF", null, htmlAttributes: new { @class = "form-control", id = "thcf" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-2">&nbsp;</div>
            <label class="control-label col-md-125">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="gallons" class="control-label col-md-2 caption">Total Gallons:</label>
            <div class="col-md-1">
                @Html.TextBox("TotalGallons", null, htmlAttributes: new { @class = "form-control", id = "gallons" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="f15HCF" class="control-label col-md-4 caption">1st 15 HCF at $3.6121:</label>
            <div class="col-md-2">
                @Html.TextBox("First15HCF", null,
                              htmlAttributes: new { @class = "form-control", id = "f15HCF" })
            </div>
            <label for="next10HCF" class="control-label col-md-125 caption">Next 10 HCF at $3.9180:</label>
            <div class="col-md-125">
                @Html.TextBox("Next10HCF", null,
                              htmlAttributes: new { @class = "form-control", id = "next10HCF" })
            </div>
            <label for="remHCF" class="control-label col-md-2 caption">Remaining HCF at $4.2763:</label>
            <div class="col-md-1">
                @Html.TextBox("RemainingHCF", null, htmlAttributes: new { @class = "form-control", id = "remHCF" })
            </div>
        </div>
        <div class="form-group">
            <label for="sewerCharges" class="control-label col-md-4 caption">Sewer Charges:</label>
            <div class="col-md-2">
                @Html.TextBox("SewerCharges", null,
                              htmlAttributes: new { @class = "form-control", id = "sewerCharges" })
            </div>
            <label for="stormCharges" class="control-label col-md-125 caption">Storm Charges:</label>
            <div class="col-md-125">
                @Html.TextBox("StormCharges", null,
                              htmlAttributes: new { @class = "form-control", id = "stormCharges" })
            </div>
            <label for="wuc" class="control-label col-md-2 caption">Water Usage Charges:</label>
            <div class="col-md-1">
                @Html.TextBox("WaterUsageCharges", null, htmlAttributes: new { @class = "form-control", id = "wuc" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-2">&nbsp;</div>
            <label class="control-label col-md-125">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="totalCharges" class="control-label col-md-2 caption">Total Charges:</label>
            <div class="col-md-1">
                @Html.TextBox("TotalCharges", null, htmlAttributes: new { @class = "form-control", id = "totalCharges" })
            </div>
        </div>
        <hr />
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="localTaxes" class="control-label col-md-125 caption">Local Taxes:</label>
            <div class="col-md-125">
                @Html.TextBox("LocalTaxes", null,
                              htmlAttributes: new { @class = "form-control", id = "localTaxes" })
            </div>
            <label for="stateTaxes" class="control-label col-md-125 caption">State Taxes:</label>
            <div class="col-md-125">
                @Html.TextBox("StateTaxes", null, htmlAttributes: new { @class = "form-control", id = "stateTaxes" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="pdd" class="control-label col-md-125 caption">Payment Due Date:</label>
            <div class="col-md-125">
                @Html.TextBox("PaymentDueDate", null,
                              htmlAttributes: new { @class = "form-control", type = "date", id = "pdd" })
            </div>
            <label for="amtDue" class="control-label col-md-125 caption">Amount Due:</label>
            <div class="col-md-125">
                @Html.TextBox("AmountDue", null,
                              htmlAttributes: new { @class = "form-control", id = "amtDue" })
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4 caption">&nbsp;</label>
            <div class="col-md-125">&nbsp;</div>
            <label for="lpdd" class="control-label col-md-125 caption">Late Payment Due Date:</label>
            <div class="col-md-125">
                @Html.TextBox("LatePaymentDueDate", null,
                              htmlAttributes: new { @class = "form-control", id = "lpdd" })
            </div>
            <label for="lateAmtDue" class="control-label col-md-125 caption">Late Amount Due:</label>
            <div class="col-md-125">
                @Html.TextBox("LateAmountDue", null, htmlAttributes: new { @class = "form-control", id = "lateAmtDue" })
            </div>
        </div>
    
        <div class="form-group text-center">
            <label class="control-label col-md-5">
                @Html.ActionLink("Water Bills", "Index", null, htmlAttributes: new { @class = "water-nav" })
            </label>
            <div class="col-md-7">
                <input type="submit" value="Save Water Bill" class="btn btn-primary" />
            </div>
        </div>
    </div>
    }
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#acntNbr").blur(function (event) {
                var connection = {
                    method:   "GET",
                    dataType: "xml",
                    url:      "/WaterDistribution/Customers.xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var clients = $(data).find("customer");
                        clients.each(function () {
                            if ($(this).find("account-number").text() === $("#acntNbr").val()) {
                                $("#mtrNbr").val($(this).find("meter-number").text());
                                $("#custName").val($(this).find("first-name").text() + " " + $(this).find("last-name").text());
                                $("#adrs").val($(this).find("address").text());
                                $("#city").val($(this).find("city").text());
                                $("#county").val($(this).find("county").text());
                                $("#state").val($(this).find("state").text());
                                $("#zip").val($(this).find("zip-code").text());
                            }
                        });
                    });
    
                connection = {
                    method:   "GET",
                    dataType: "xml",
                    url:      "/WaterDistribution/WaterMeters.xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var waterMeters = $(data).find("water-meter");
                        waterMeters.each(function () {
                            if ($(this).find("meter-number").text() === $("#mtrNbr").val()) {
                                $("#meterDetails").val($(this).find("make").text() + " " + $(this).find("model").text() + " (" + $(this).find("meter-size").text() + ")");
                                $("#mrsd").val($(this).find("date-last-update").text());
                                $("#crs").val($(this).find("counter-value").text());
                            }
                        });
                    });
    
                connection = {
                    method:   "GET",
                    dataType: "xml",
                    url:      "/WaterDistribution/WaterBills.xml"
                };
                $.ajax(connection).
                    done(function (data) {
                        var invoices = $(data).find("invoice");
                        invoices.each(function () {
                            if ($(this).find("account-number").text() === $("#acntNbr").val()) {
                                $("#mrsd").val($(this).find("meter-reading-end-date").text());
                                $("#crs").val($(this).find("counter-reading-end").text());
                            }
                        });
                    });
            }); // Account # Lost Focus
    
            $("#mred").change(function (event) {
                var meterReadingStartDate = Date.parse($("#mrsd").val());
                var meterReadingEndDate   = Date.parse($("#mred").val());
    
                var days = (meterReadingEndDate - meterReadingStartDate) / 86400000;
    
                $("#days").val(days.toFixed());
            }); // Meter Reading End Date Lost Focus
    
            $("#cre").focusout(function (event) {
                var counterReadingStart = parseInt($("#crs").val());
                var counterReadingEnd   = parseInt($("#cre").val());
                var totalHCF = counterReadingEnd - counterReadingStart;
                var gallons = totalHCF * 748; // 748.05
    
                var first15HCF = totalHCF * 3.612;
                var next10HCF = 0, remainingHCF = 0;
    
                if (totalHCF <= 15) {
                    first15HCF = totalHCF * 3.612;
                    next10HCF = 0;
                    remainingHCF = 0;
                }
                else if (totalHCF <= 25) {
                    first15HCF = 15 * 3.612;
                    next10HCF = (totalHCF - 15) * 3.918;
                    remainingHCF = 0;
                }
                else {
                    first15HCF = 15 * 3.612;
                    next10HCF = 10 * 3.918;
                    remainingHCF = (totalHCF - 25) * 2.2763;
                }
    
                var waterUsageCharges = first15HCF + next10HCF + remainingHCF;
                var sewerCharges      = waterUsageCharges * 0.252;
                var stormCharges      = waterUsageCharges * 0.0025;
                var totalCharges      = waterUsageCharges + sewerCharges + stormCharges;
                var localTaxes        = totalCharges * 0.0152;
                var stateTaxes        = totalCharges * 0.005;
                var amountDue         = totalCharges + localTaxes + stateTaxes;
    
                $("#thcf").val(totalHCF.toFixed());
                $("#gallons").val(gallons.toFixed());
                $("#amtDue").val(amountDue.toFixed(2));
                $("#f15HCF").val(first15HCF.toFixed(2));
                $("#next10HCF").val(next10HCF.toFixed(2));
                $("#remHCF").val(remainingHCF.toFixed(2));
                $("#wuc").val(waterUsageCharges.toFixed(2));
                $("#stateTaxes").val(stateTaxes.toFixed(2));
                $("#localTaxes").val(localTaxes.toFixed(2));
                $("#sewerCharges").val(sewerCharges.toFixed(2));
                $("#stormCharges").val(stormCharges.toFixed(2));
                $("#totalCharges").val(totalCharges.toFixed(2));
                $("#lateAmtDue").val((amountDue + 8.95).toFixed(2));
            }); // Counter Reading End Lost Focus
        }); // Document.Ready
    </script>
  18. Click the WaterBillsController.cs tab to return to the controller
  19. In the class, right-click one of the Edit() methods and click Add View...
  20. In the Add View dialog box, make sure the View Name text box is displaying Edit. Click Add
  21. Create a form as follows:
    @{
        ViewBag.Title = "Edit/Update Water Bill";
    }
    
    <div class="push-down">
        <h2>Edit/Update Water Bill</h2>
    </div>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <div class="form-horizontal">
            <div class="form-group">
                <label for="billNbr" class="control-label col-md-4 caption">Water Bill ID:</label>
                <div class="col-md-8">
                    @Html.TextBox("WaterBillID", null,
                                  htmlAttributes: new { @class = "form-control", id = "billNbr", disabled = "disabled" })
                </div>
            </div>
            <div class="form-group">
                <label for="invoiceNbr" class="control-label col-md-4 caption">Invoice #:</label>
                <div class="col-md-8">
                    @Html.TextBox("InvoiceNumber", null,
                                  htmlAttributes: new { @class = "form-control", id = "invoiceNbr" })
                </div>
            </div>
            <div class="form-group">
                <label for="acntNbr" class="control-label col-md-4 caption">Customer Account #:</label>
                <div class="col-md-8">
                    @Html.TextBox("AccountNumber", null,
                                  htmlAttributes: new { @class = "form-control", id = "acntNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-4 caption">Customer Name:</label>
                <div class="col-md-8">
                    @Html.TextBox("CustomerName", null,
                                  new { @class = "form-control", id = "custName", disabled = "disabled" })
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-4 caption">Customer Address:</label>
                <div class="col-md-8">
                    @Html.TextBox("CustomerAddress", null,
                                  new { @class = "form-control", id = "adrs", disabled = "disabled" })
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-4">&nbsp;</label>
                <div class="col-md-125">
                    @Html.TextBox("CustomerCity", null,
                                  new { @class = "form-control", id = "city", disabled = "disabled" })
                </div>
                <div class="col-md-125">
                    @Html.TextBox("CustomerCounty", null,
                                  new { @class = "form-control", id = "county", disabled = "disabled" })
                </div>
                <div class="col-md-125">
                    @Html.TextBox("CustomerState", null,
                                  new { @class = "form-control", id = "state", disabled = "disabled" })
                </div>
                <div class="col-md-125">
                    @Html.TextBox("CustomerZIPCode", null,
                                  new { @class = "form-control", id = "zip", disabled = "disabled" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-4 caption">Meter Details:</label>
                <div class="col-md-125">
                    @Html.TextBox("MeterNumber", null,
                                  new { @class = "form-control", id = "mtrNbr", disabled = "disabled" })
                </div>
                <div class="col-md-6">
                    @Html.TextBox("MeterDetails", null,
                                  new { @class = "form-control", id = "meterDetails", disabled = "disabled" })
                </div>
            </div>
            <hr />
            <div class="form-group">
                <label for="mrsd" class="control-label col-md-4 caption">Meter Reading Start Date:</label>
                <div class="col-md-2">
                    @Html.TextBox("MeterReadingStartDate", null,
                                  htmlAttributes: new { @class = "form-control", id = "mrsd" })
                </div>
                <label for="mred" class="control-label col-md-125 caption">Meter Reading End Date:</label>
                <div class="col-md-125">
                    @Html.TextBox("MeterReadingEndDate", null,
                                  htmlAttributes: new { @class = "form-control", type = "date", id = "mred" })
                </div>
                <label for="days" class="control-label col-md-2 caption">Billing Days:</label>
                <div class="col-md-1">
                    @Html.TextBox("BillingDays", null, htmlAttributes: new { @class = "form-control", id = "days" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="crs" class="control-label col-md-4 caption">Counter Reading Start:</label>
                <div class="col-md-2">
                    @Html.TextBox("CounterReadingStart", null, htmlAttributes: new { @class = "form-control", id = "crs" })
                </div>
                <label for="cre" class="control-label col-md-125 caption">Current Meter Reading:</label>
                <div class="col-md-125">
                    @Html.TextBox("CounterReadingEnd", null, htmlAttributes: new { @class = "form-control", id = "cre" })
                </div>
                <label for="thcf" class="control-label col-md-2 caption">Total HCF:</label>
                <div class="col-md-1">
                    @Html.TextBox("TotalHCF", null, htmlAttributes: new { @class = "form-control", id = "thcf" })
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-4">&nbsp;</label>
                <div class="col-md-2">&nbsp;</div>
                <label class="control-label col-md-125">&nbsp;</label>
                <div class="col-md-125">&nbsp;</div>
                <label for="gallons" class="control-label col-md-2 caption">Total Gallons:</label>
                <div class="col-md-1">
                    @Html.TextBox("TotalGallons", null, htmlAttributes: new { @class = "form-control", id = "gallons" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="f15HCF" class="control-label col-md-4 caption">1st 15 HCF at $3.6121:</label>
                <div class="col-md-2">
                    @Html.TextBox("First15HCF", null,
                                  htmlAttributes: new { @class = "form-control", id = "f15HCF" })
                </div>
                <label for="next10HCF" class="control-label col-md-125 caption">Next 10 HCF at $3.9180:</label>
                <div class="col-md-125">
                    @Html.TextBox("Next10HCF", null,
                                  htmlAttributes: new { @class = "form-control", id = "next10HCF" })
                </div>
                <label for="remHCF" class="control-label col-md-2 caption">Remaining HCF at $4.2763:</label>
                <div class="col-md-1">
                    @Html.TextBox("RemainingHCF", null, htmlAttributes: new { @class = "form-control", id = "remHCF" })
                </div>
            </div>
            <div class="form-group">
                <label for="sewerCharges" class="control-label col-md-4 caption">Sewer Charges:</label>
                <div class="col-md-2">
                    @Html.TextBox("SewerCharges", null,
                                  htmlAttributes: new { @class = "form-control", id = "sewerCharges" })
                </div>
                <label for="stormCharges" class="control-label col-md-125 caption">Storm Charges:</label>
                <div class="col-md-125">
                    @Html.TextBox("StormCharges", null,
                                  htmlAttributes: new { @class = "form-control", id = "stormCharges" })
                </div>
                <label for="wuc" class="control-label col-md-2 caption">Water Usage Charges:</label>
                <div class="col-md-1">
                    @Html.TextBox("WaterUsageCharges", null, htmlAttributes: new { @class = "form-control", id = "wuc" })
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-4">&nbsp;</label>
                <div class="col-md-2">&nbsp;</div>
                <label class="control-label col-md-125">&nbsp;</label>
                <div class="col-md-125">&nbsp;</div>
                <label for="totalCharges" class="control-label col-md-2 caption">Total Charges:</label>
                <div class="col-md-1">
                    @Html.TextBox("TotalCharges", null, htmlAttributes: new { @class = "form-control", id = "totalCharges" })
                </div>
            </div>
            <hr />
            <div class="form-group">
                <label class="control-label col-md-4">&nbsp;</label>
                <div class="col-md-125">&nbsp;</div>
                <label for="localTaxes" class="control-label col-md-125 caption">Local Taxes:</label>
                <div class="col-md-125">
                    @Html.TextBox("LocalTaxes", null,
                                  htmlAttributes: new { @class = "form-control", id = "localTaxes" })
                </div>
                <label for="stateTaxes" class="control-label col-md-125 caption">State Taxes:</label>
                <div class="col-md-125">
                    @Html.TextBox("StateTaxes", null, htmlAttributes: new { @class = "form-control", id = "stateTaxes" })
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-4">&nbsp;</label>
                <div class="col-md-125">&nbsp;</div>
                <label for="pdd" class="control-label col-md-125 caption">Payment Due Date:</label>
                <div class="col-md-125">
                    @Html.TextBox("PaymentDueDate", null,
                                  htmlAttributes: new { @class = "form-control", type = "date", id = "pdd" })
                </div>
                <label for="amtDue" class="control-label col-md-125 caption">Amount Due:</label>
                <div class="col-md-125">
                    @Html.TextBox("AmountDue", null,
                                  htmlAttributes: new { @class = "form-control", id = "amtDue" })
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-4 caption">&nbsp;</label>
                <div class="col-md-125">&nbsp;</div>
                <label for="lpdd" class="control-label col-md-125 caption">Late Payment Due Date:</label>
                <div class="col-md-125">
                    @Html.TextBox("LatePaymentDueDate", null,
                                  htmlAttributes: new { @class = "form-control", id = "lpdd" })
                </div>
                <label for="lateAmtDue" class="control-label col-md-125 caption">Late Amount Due:</label>
                <div class="col-md-125">
                    @Html.TextBox("LateAmountDue", null, htmlAttributes: new { @class = "form-control", id = "lateAmtDue" })
                </div>
            </div>
    
            <div class="form-group text-center">
                <label class="control-label col-md-5">
                    @Html.ActionLink("Water Bills", "Index", null, htmlAttributes: new { @class = "water-nav" })
                </label>
                <div class="col-md-7">
                    <input type="submit" value="Update Water Bill" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
  22. In the Solution Explorer, under Controllers, double-clickick PaymentsController.cs
  23. Implement the Edit() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class PaymentsController : Controller
        { 
    
            . . . No Change
    
            // GET: Payments/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments= xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            if (xnPayment.InnerText == id.ToString())
                            {
                                ViewBag.PaymentID = xnPayment.InnerText;
                                ViewBag.ReceiptNumber = xnPayment.NextSibling.InnerText;
                                ViewBag.WaterBillID = xnPayment.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDate = xnPayment.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentAmount = xnPayment.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Payments/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdPayments = new XmlDocument();
                    string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                    if (System.IO.File.Exists(strFilePayments))
                    {
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdPayments.Load(fsPayments);
                        }
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (XmlNode xnPayment in xnlPayments)
                            {
                                if (xnPayment.InnerText == id.ToString())
                                {
                                    xnPayment.ParentNode.InnerXml = "<payment-id>" + id + "</payment-id>" +
                                                                    "<receipt-number>" + collection["ReceiptNumber"] + "</receipt-number>" +
                                                                    "<water-bill-id>" + collection["WaterBillID"] + "</water-bill-id>" +
                                                                    "<payment-date>" + collection["PaymentDate"] + "</payment-date>" +
                                                                    "<payment-amount>" + collection["PaymentAmount"] + "</payment-amount>";
                                    xdPayments.Save(fsPayments);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  24. In the PaymentsController class, right-click one of the Edit() methods and click Add View...
  25. Make sure the View Name text box is displaying Edit. Click Add
  26. Change the webpage as follows:
    @{
        ViewBag.Title = "Edit/Update Bill Payment";
    }
    
    <div class="push-down">
        <h2>Edit/Update Bill Payment</h2>
    </div>
    
    <hr />
    
    @using (Html.BeginForm())
    {
    <div class="form-horizontal">
        <div class="form-group">
            <label class="control-label col-md-4 caption">Payment ID:</label>
            <div class="col-md-8">
                @Html.TextBox("PaymentID", null,
                              htmlAttributes: new { @class = "form-control", disabled = "disabled" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="recNbr" class="control-label col-md-4 caption">Receipt #:</label>
            <div class="col-md-8">
                @Html.TextBox("ReceiptNumber", null, htmlAttributes: new { @class = "form-control", id = "recNbr" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="billNbr" class="control-label col-md-4 caption">Account #:</label>
            <div class="col-md-8">
                @Html.TextBox("WaterBillID", null, htmlAttributes: new { @class = "form-control", id = "billNbr" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="pmtDate" class="control-label col-md-4 caption">Payment Date:</label>
            <div class="col-md-8">
                @Html.TextBox("PaymentDate", null,
                              htmlAttributes: new { @class = "form-control", type = "date", id = "pmtDate" })
            </div>
        </div>
    
        <div class="form-group">
            <label for="pmtAmt" class="control-label col-md-4 caption">Payment Amount:</label>
            <div class="col-md-8">
                @Html.TextBox("PaymentAmount", null, htmlAttributes: new { @class = "form-control", id = "pmtAmt" })
            </div>
        </div>
    
        <div class="form-group">
            <label class="control-label col-md-5">
                @Html.ActionLink("Bills Payments", "Index", null, htmlAttributes: new { @class = "water-nav" })
            </label>
            <div class="col-md-7">
                <input type="submit" value="Update this Payment" class="btn btn-primary" />
            </div>
        </div>
    </div>
    }
  27. In the Solution Explorer, under Views and under Home, double-click Index.cshtml
  28. To execute, on the main menu, click Debug -> Start Without Debugging
  29. Click the Bills/Invoices button
  30. Click the New Water Bill link
  31. To start a record, in the Customer Account # text box, type 7518-302-6895 and press Tab

    Edit - Update XML Elements

  32. In the Meter Reading End Date text box, type 7/30/2018 and press Tab

    Edit - Update XML Elements

  33. In the Current Meter Reading text box, type 114 and press Tab

    Edit - Update XML Elements

  34. Enter the following two values:
    Payment Due Date:      08/27/2018
    Late Payment Due Date: 09/13/2018

    Edit - Update XML Elements

  35. Click the Save Water Bill button
  36. Click the New Water Bill link
  37. Create a few records with the following values:

    Account # Meter Reading End Date Current Meter Reading Payment Due Date Late Payment Due Date
    4820-375-2842 07/31/2018 109998 08/28/2018 09/14/2018
    2038-413-9680 7/30/2018 137975 8/27/2018 9/13/2018
    9279-570-8394 08/07/2018 6275 08/04/2018 08/20/2018
    7518-302-6895 11/07/2018 118 12/01/2018 12/15/2018
    2038-413-9680 10/27/2018 138012 11/24/2018 12/10/2018
  38. Click the Home link and click the Bills Payments button
  39. Click the New Bill Payment link
  40. Create a few records with the following values:

    Receipt # Bill ID Payment Date Payment Amount
    625288 2 08/24/2018 27.74
    836168 3 09/12/2018 198.36
    886415 1 08/27/2018 84.39
    724705 4 09/01/2018 32.36
    141806 6 12/05/2018 163.40
    706953 5 12/10/2018 27.44
  41. Close the browser and return to your programming environment

Replacing an Element

The XmlNode class is equipped with a method named ReplaceChild. Its syntax is:

public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild);

To use this method, first locate an element and get its reference. Then change the values or child nodes you want, and finally replace the original value with the new version. In reality, and as its name implies, it is not the primary purpose of this method to edit or update an element. The role of this method is to use one node in place of another.

Practical LearningPractical Learning: Replacing an Element

  1. In the Solution Explorer, under Controllers, double-click CustomersController.cs to access the class
  2. Implement both Edit() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class CustomersController : Controller
        {
    
            . . . No Change
    
            // GET: Customers/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdCustomers = new XmlDocument();
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strFileCustomers))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdCustomers.Load(fsWaterMeters);
    
                        XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-id");
    
                        foreach (XmlNode xnCustomer in xnlCustomers)
                        {
                            if (xnCustomer.InnerText == id.ToString())
                            {
                                ViewBag.AccountID = xnCustomer.InnerText;
                                ViewBag.AccountNumber = xnCustomer.NextSibling.InnerText;
                                ViewBag.MeterNumber = xnCustomer.NextSibling.NextSibling.InnerText;
                                ViewBag.FirstName = xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LastName = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Address = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.City = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.County = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.State = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.ZIPCode = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Customers/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdCustomers = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                    XmlElement xeCustomer = xdCustomers.CreateElement("customer");
    
                    // Create the markup of a customer
                    string strCustomer = "<account-id>" + id + "</account-id>" +
                                         "<account-number>" + collection["AccountNumber"] + "</account-number>" +
                                         "<meter-number>" + collection["MeterNumber"] + "</meter-number>" +
                                         "<first-name>" + collection["FirstName"] + "</first-name>" +
                                         "<last-name>" + collection["LastName"] + "</last-name>" +
                                         "<address>" + collection["Address"] + "</address>" +
                                         "<city>" + collection["City"] + "</city>" +
                                         "<county>" + collection["County"] + "</county>" +
                                         "<state>" + collection["State"] + "</state>" +
                                         "<zip-code>" + collection["ZIPCode"] + "</zip-code>";
                    
                    xeCustomer.InnerXml = strCustomer;
    
                    if (System.IO.File.Exists(strFileCustomers))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdCustomers.Load(fsWaterMeters);
                        }
    
                        using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("customer");
    
                            foreach (XmlNode xnCustomer in xnlCustomers)
                            {
                                if (xnCustomer.FirstChild.InnerText == id.ToString())
                                {
                                    xnCustomer.ParentNode.ReplaceChild(xeCustomer, xnCustomer);
                                    xdCustomers.Save(fsCustomers);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            . . . No Change
        }
    }
  3. In the class, right-click one of the Edit() methods and click Add View...
  4. Make sure the View Name text box is displaying Edit.
    Click Add
  5. Create a form as follows:
    @{
        ViewBag.Title = "Edit/Update Customer Details";
    }
    
    <div class="push-down">
        <h2>Edit/Update Customer Details</h2>
    </div>
    <hr />
    @using (Html.BeginForm())
    {
        <div class="form-horizontal">
            <div class="form-group">
                <label class="control-label col-md-4 caption">Acount ID:</label>
                <div class="col-md-8">
                    @Html.TextBox("AccountID", ViewBag.AccountID as string, htmlAttributes: new { @class = "form-control", disabled = "disabled" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="acntNbr" class="control-label col-md-4 caption">Account #:</label>
                <div class="col-md-8">
                    @Html.TextBox("AccountNumber", ViewBag.AccountNumber as string, htmlAttributes: new { @class = "form-control", id = "acntNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="mtrNbr" class="control-label col-md-4 caption">Meter #:</label>
                <div class="col-md-8">
                    @Html.TextBox("MeterNumber", ViewBag.MeterNumber as string, htmlAttributes: new { @class = "form-control", id = "mtrNbr" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="fname" class="control-label col-md-4 caption">First Name:</label>
                <div class="col-md-8">
                    @Html.TextBox("FirstName", ViewBag.FirstName as string, htmlAttributes: new { @class = "form-control", id = "fname" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="lname" class="control-label col-md-4 caption">Last Name:</label>
                <div class="col-md-8">
                    @Html.TextBox("LastName", ViewBag.LastName as string, htmlAttributes: new { @class = "form-control", id = "lname" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="adrs" class="control-label col-md-4 caption">Address:</label>
                <div class="col-md-8">
                    @Html.TextBox("Address", ViewBag.Address as string, htmlAttributes: new { @class = "form-control", id = "adrs" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="ct" class="control-label col-md-4 caption">City:</label>
                <div class="col-md-8">
                    @Html.TextBox("City",
                        ViewBag.DateLastUpdate as string, htmlAttributes: new { @class = "form-control", id = "ct" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="county" class="control-label col-md-4 caption">County:</label>
                <div class="col-md-8">
                    @Html.TextBox("County", ViewBag.CounterValue as string, htmlAttributes: new { @class = "form-control", id = "county" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="state" class="control-label col-md-4 caption">State:</label>
                <div class="col-md-8">
                    @Html.TextBox("State", ViewBag.CounterValue as string, htmlAttributes: new { @class = "form-control", id = "state" })
                </div>
            </div>
    
            <div class="form-group">
                <label for="zip" class="control-label col-md-4 caption">ZIP-Code:</label>
                <div class="col-md-8">
                    @Html.TextBox("ZIPCode", ViewBag.CounterValue as string, htmlAttributes: new { @class = "form-control", id = "zip" })
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-5">
                    @Html.ActionLink("Customers Accounts", "Index", null, htmlAttributes: new { @class = "water-nav" })
                </label>
                <div class="col-md-7">
                    <input type="submit" value="Update Customer Details" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
  6. In the Solution Explorer, under Views and under Customers, double-click Index.cshtml
  7. To execute the project, press Ctrl + F5

    Replacing an XML Element

  8. Click the Update link for the last record
  9. Change the following values:
    Account: 2886-415-3060
    City:    Amberson
    County:  Franklin
  10. Click Update Customer Details
  11. Close the browser and return to your programming environment

Deleting Elements

Deleting an Element

If you have a node you don't want or don't need anymore in the file, you can delete it. To delete a node, the XmlNode class provides the RemoveChild() method. Its syntax is:

public virtual XmlNode RemoveChild(XmlNode oldChild);

This method takes as argument the node to delete. If the node exists, it would be deleted and the method would return the node that was deleted. If the node does not exist, nothing would happen. To effectively use this method, you should first locate the particular node you want to delete. You can look for it using any of the techniques we have applied so far. Once you find the node, you can then delete it. Imagine you want to delete a node whose name is Director and whose value is Bruce Beresford. Here is an example of calling this method to perform the operation:

@{
    string strVideosFile = Server.MapPath("~/App_Data/Videos.xml");
    System.Xml.XmlDocument xdVideos = new System.Xml.XmlDocument();

    if (File.Exists(strVideosFile))
    {
        xdVideos.Load(strVideosFile);

        // Get a reference to the root node
        System.Xml.XmlElement xeRoot = xdVideos.DocumentElement;

        // Create a list of the videos
        System.Xml.XmlNodeList xnlVideos = xdVideos.GetElementsByTagName("video");

        // visit each video
        foreach (System.Xml.XmlNode node in xnlVideos)
        {
            // Within a video, get a list of its children
            System.Xml.XmlNodeList xnlChildren = node.ChildNodes;

            // Visit each child node
            foreach (System.Xml.XmlNode dir in xnlChildren)
            {
                // If the child node is Bruce Beresford
                if (dir.InnerText == "Bruce Beresford")
                {
                    node.RemoveChild(dir);

                    // Save the file
                    xdVideos.Save(strVideosFile);

                    // Stop
                    break;
                }
            }
        }
    }
}

Practical LearningPractical Learning: Deleting an Element

  1. In the Solution Explorer, under Controllers, double-click WaterMetersController.cs
  2. Implement the Delete() methods as follows:
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class WaterMetersController : Controller
        {
            // GET: WaterMeters
            public ActionResult Index()
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
                    }
    
                    if (xdWaterMeters.DocumentElement.ChildNodes.Count > 0)
                    {
                        ViewBag.WaterMeters = xdWaterMeters.DocumentElement.ChildNodes;
                    }
                    else
                    {
                        ViewBag.WaterMeters = null;
                    }
                }
    
                return View();
            }
    
            // GET: WaterMeters/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                        {
                            if (xnWaterMeter.InnerText == id.ToString())
                            {
                                ViewBag.WaterMeterID = xnWaterMeter.InnerText;
                                ViewBag.MeterNumber = xnWaterMeter.NextSibling.InnerText;
                                ViewBag.Make = xnWaterMeter.NextSibling.NextSibling.InnerText;
                                ViewBag.Model = xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterSize = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.DateLastUpdate = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterValue = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: WaterMeters/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: WaterMeters/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int meter_id = -1;
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    // Make sure a meter number was provided. If not, don't do nothing
                    if (!string.IsNullOrEmpty(collection["MeterNumber"]))
                    {
                        // If an XML file for water meters was created already, ...
                        if (System.IO.File.Exists(strFileWaterMeters))
                        {
                            // ... open it ...
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                // ... and put the records in the DOM
                                xdWaterMeters.Load(fsWaterMeters);
    
                                // We need the meters numbers. Therefore, use XPath to specify their path
                                XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                                // Check the whole list of meters numbers
                                foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                                {
                                    // Every time, assign the current meter number to our meterNumber variable
                                    meter_id = int.Parse(xnWaterMeter.InnerText);
                                }
                            }
                        }
                        else
                        {
                            // If there is no XML file yet, create skeleton code for an XML document, ...
                            xdWaterMeters.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                  "<water-meters></water-meters>");
                            // and set our meterNumber variable to 0
                            meter_id = 0;
                        }
                    }
    
                    // Get ready to create an XML element named water-meter
                    XmlElement xeWaterMeter = xdWaterMeters.CreateElement("water-meter");
    
                    // Increase the meterNumber variable by 1
                    meter_id += 1;
    
                    // Create the markup of the XML water meter
                    string strWaterMeter = "<meter-id>"         + meter_id            + "</meter-id>" +
                                           "<meter-number>"     + collection["MeterNumber"] + "</meter-number>" +
                                           "<make>"             + collection["Make"] + "</make>" +
                                           "<model>"            + collection["Model"] + "</model>" +
                                           "<meter-size>"       + collection["MeterSize"] + "</meter-size>" +
                                           "<date-last-update>" + collection["DateLastUpdate"] + "</date-last-update>" +
                                           "<counter-value>"    + collection["CounterValue"] + "</counter-value>";
    
                    // Specify the markup of the new element
                    xeWaterMeter.InnerXml = strWaterMeter;
                    // Add the new node to the root
                    xdWaterMeters.DocumentElement.AppendChild(xeWaterMeter);
    
                    // Save the (new version of the) XML file
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Create, FileAccess.Write, FileShare.Write))
                    {
                        xdWaterMeters.Save(fsWaterMeters);
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: WaterMeters/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                        {
                            if (xnWaterMeter.InnerText == id.ToString())
                            {
                                ViewBag.WaterMeterID = xnWaterMeter.InnerText;
                                ViewBag.MeterNumber = xnWaterMeter.NextSibling.InnerText;
                                ViewBag.Make = xnWaterMeter.NextSibling.NextSibling.InnerText;
                                ViewBag.Model = xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterSize = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.DateLastUpdate = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterValue = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: WaterMeters/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    if (System.IO.File.Exists(strFileWaterMeters))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdWaterMeters.Load(fsWaterMeters);
                        }
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                            {
                                if (xnWaterMeter.InnerText == id.ToString())
                                {
                                    xnWaterMeter.ParentNode.InnerXml = "<meter-id>" + id + "</meter-id>" +
                                                                       "<meter-number>" + collection["MeterNumber"] + "</meter-number>" +
                                                                       "<make>" + collection["Make"] + "</make>" +
                                                                       "<model>" + collection["Model"] + "</model>" +
                                                                       "<meter-size>" + collection["MeterSize"] + "</meter-size>" +
                                                                       "<date-last-update>" + collection["DateLastUpdate"] + "</date-last-update>" +
                                                                       "<counter-value>" + collection["CounterValue"] + "</counter-value>";
                                    xdWaterMeters.Save(fsWaterMeters);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: WaterMeters/Delete/5
            public ActionResult Delete(int id)
            {
                XmlDocument xdWaterMeters = new XmlDocument();
                string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                if (System.IO.File.Exists(strFileWaterMeters))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterMeters.Load(fsWaterMeters);
    
                        XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                        foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                        {
                            if (xnWaterMeter.InnerText == id.ToString())
                            {
                                ViewBag.WaterMeterID = xnWaterMeter.InnerText;
                                ViewBag.MeterNumber = xnWaterMeter.NextSibling.InnerText;
                                ViewBag.Make = xnWaterMeter.NextSibling.NextSibling.InnerText;
                                ViewBag.Model = xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterSize = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.DateLastUpdate = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterValue = xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: WaterMeters/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    /* Make sure an XML file for the water meters was previously created 
                     * (normally, this is not necessary; if there is no such file, this code 
                     * will never run because it is completely based on routing) */
                    if (System.IO.File.Exists(strFileWaterMeters))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdWaterMeters.Load(fsWaterMeters);
                        }
    
                        // Get ready to change something on the file
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Truncate, FileAccess.Write, FileShare.Write))
                        {
                            // Get a collection of water meter nodes
                            XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("water-meter");
    
                            // Check each node
                            foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                            {
                                /* If you find a water-meter record whose meter-id is 
                                 * the same as the id of the record the user clicked, ... */
                                if (xnWaterMeter.FirstChild.InnerText == id.ToString())
                                {
                                    // ... ask its parent to delete that record
                                    xnWaterMeter.ParentNode.RemoveChild(xnWaterMeter);
                                    // Now that the record has been deleted, save the XML file
                                    xdWaterMeters.Save(fsWaterMeters);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  3. In the class, right-click one of the Delete() methods and click Add View...
  4. Make sure the View Name is displaying Delete. Click Add
  5. Change the document as follows:
    @{
        ViewBag.Title = "Delete Water Meter";
    }
    
    <div class="push-down">
        <h2>Deleting a Water Meter</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt>Water Meter ID:</dt>
            <dd>@ViewBag.WaterMeterID</dd>
    
            <dt>Meter #:</dt>
            <dd>@ViewBag.MeterNumber</dd>
    
            <dt>Make:</dt>
            <dd>@ViewBag.Make</dd>
    
            <dt>Model:</dt>
            <dd>@ViewBag.Model</dd>
    
            <dt>Meter Size:</dt>
            <dd>@ViewBag.MeterSize</dd>
    
            <dt>Date Last Update:</dt>
            <dd>@ViewBag.DateLastUpdate</dd>
    
            <dt>Counter Value:</dt>
            <dd>@ViewBag.CounterValue</dd>
        </dl>
    
        <h3 class="common-font caption">Are you sure you want to remove this water meter from the system?</h3>
    
        @using (Html.BeginForm())
        {
            <div class="form-actions no-color">
                <input type="submit" value="Delete this Water Meter" class="btn btn-primary" /> |
                @Html.ActionLink("Water Meters", "Index", null, new { @class = "water-nav" })
            </div>
        }
    </div>
  6. In the Solution Explorer, under Controllers, double-click CustomersControllers.cs
  7. Implement the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class CustomersController : Controller
        {
            // GET: Customers
            public ActionResult Index()
            {
                // Get a reference to the XML DOM
                XmlDocument xdCustomers = new XmlDocument();
                // This is the name and path of the XML file that contains the customers records
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                // If a file that contains the customers records was previously created, ...
                if (System.IO.File.Exists(strFileCustomers))
                {
                    // ... open it
                    using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // and store the records in the DOM
                        xdCustomers.Load(fsCustomers);
                    }
    
                    /* If the Customers records exist, send them to the view.
                     * If there is no file for the customers, indicate that the DOM is null. */
                    ViewBag.Customers = xdCustomers.DocumentElement.ChildNodes.Count > 0 ? xdCustomers.DocumentElement.ChildNodes : null;
                }
    
                return View();
            }
    
            // GET: Customers/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdCustomers = new XmlDocument();
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strFileCustomers))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdCustomers.Load(fsWaterMeters);
    
                        XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-id");
    
                        foreach (XmlNode xnCustomer in xnlCustomers)
                        {
                            if (xnCustomer.InnerText == id.ToString())
                            {
                                ViewBag.AccountID = xnCustomer.InnerText;
                                ViewBag.AccountNumber = xnCustomer.NextSibling.InnerText;
                                ViewBag.MeterNumber = xnCustomer.NextSibling.NextSibling.InnerText;
                                ViewBag.FirstName = xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LastName = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Address = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.City = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.County = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.State = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.ZIPCode = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: Customers/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Customers/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int account_id = -1;
                    bool meterNumberIsValid = false;
                    XmlDocument xdWaterMeters = new XmlDocument();
                    XmlDocument xdCustomersAccounts = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    // Make sure the user provides an account number, ...
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        // If the user provided an account number, to start, find out if a file for water meters was created already.
                        if (System.IO.File.Exists(strFileWaterMeters))
                        {
                            // If a file for water meters exists, open it
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open,
                                                                                                 FileAccess.Read,
                                                                                                 FileShare.Read))
                            {
                                // Store the list of water meters in an XML document
                                xdWaterMeters.Load(fsWaterMeters);
    
                                // Create a list of child nodes of the root node
                                XmlNodeList xnlWaterMeters = xdWaterMeters.DocumentElement.ChildNodes;
    
                                // Visit each node of the list of elements
                                foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                                {
                                    // When you get to a list of (child) nodes of a water-meter node, visit each child node
                                    foreach (XmlNode xnMeterNumber in xnWaterMeter.ChildNodes)
                                    {
                                        // If you find a meter number that is the same as the meter number from the form, ...
                                        if (xnMeterNumber.InnerText == collection["MeterNumber"])
                                        {
                                            // ... make a note
                                            meterNumberIsValid = true;
                                        }
                                    }
                                }
                            }
                        }
    
                        // If either the user didn't provide a meter number or provided a meter number that doesn't exist, ...
                        if (meterNumberIsValid == false)
                        {
                            // ... create a message that will display to the user
                            ViewBag.ErrorMessage = "You must provide a valid meter number";
                        }
                        else
                        {
                            // It appears that the user provided both an account number and a valid meter number.
    
                            // If an XML file for customers accounts was previously created, ...
                            if (System.IO.File.Exists(strFileCustomers))
                            {
                                // ... open it ...
                                using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.OpenOrCreate,
                                                                                                 FileAccess.ReadWrite,
                                                                                                 FileShare.ReadWrite))
                                {
                                    // ... and put the records in the DOM
                                    xdCustomersAccounts.Load(fsCustomers);
    
                                    XmlNodeList xnlCustomers = xdCustomersAccounts.GetElementsByTagName("account-id");
    
                                    foreach (XmlNode xnCustomer in xnlCustomers)
                                    {
                                        account_id = int.Parse(xnCustomer.InnerText);
                                    }
                                }
                            }
                            else
                            {
                                // If there is no XML file yet for the customers, create skeleton code for an XML document
                                xdCustomersAccounts.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                            "<customers></customers>");
                                account_id = 0;
                            }
    
                            // Get ready to create an XML element named customer
                            XmlElement xeCustomer = xdCustomersAccounts.CreateElement("customer");
    
                            account_id++;
    
                            // Create the markup of the XML customer
                            string strCustomer = "<account-id>" + account_id + "</account-id>" +
                                                 "<account-number>" + collection["AccountNumber"] + "</account-number>" +
                                                 "<meter-number>" + collection["MeterNumber"] + "</meter-number>" +
                                                 "<first-name>" + collection["FirstName"] + "</first-name>" +
                                                 "<last-name>" + collection["LastName"] + "</last-name>" +
                                                 "<address>" + collection["Address"] + "</address>" +
                                                 "<city>" + collection["City"] + "</city>" +
                                                 "<county>" + collection["County"] + "</county>" +
                                                 "<state>" + collection["State"] + "</state>" +
                                                 "<zip-code>" + collection["ZIPCode"] + "</zip-code>";
    
                            // Specify the markup of the new element
                            xeCustomer.InnerXml = strCustomer;
    
                            // Add the new node to the root
                            xdCustomersAccounts.DocumentElement.AppendChild(xeCustomer);
    
                            // Save the (new version of the) XML file
                            using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Create, FileAccess.Write, FileShare.Write))
                            {
                                xdCustomersAccounts.Save(fsCustomers);
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Customers/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdCustomers = new XmlDocument();
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strFileCustomers))
                {
                    using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdCustomers.Load(fsWaterMeters);
    
                        XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-id");
    
                        foreach (XmlNode xnCustomer in xnlCustomers)
                        {
                            if (xnCustomer.InnerText == id.ToString())
                            {
                                ViewBag.AccountID     = xnCustomer.InnerText;
                                ViewBag.AccountNumber = xnCustomer.NextSibling.InnerText;
                                ViewBag.MeterNumber   = xnCustomer.NextSibling.NextSibling.InnerText;
                                ViewBag.FirstName     = xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LastName      = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Address       = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.City          = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.County        = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.State         = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.ZIPCode       = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Customers/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdCustomers = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                    XmlElement xeCustomer = xdCustomers.CreateElement("customer");
    
                    // Create the markup of a customer
                    string strCustomer = "<account-id>"     + id                          + "</account-id>"     +
                                         "<account-number>" + collection["AccountNumber"] + "</account-number>" +
                                         "<meter-number>"   + collection["MeterNumber"]   + "</meter-number>"   +
                                         "<first-name>"     + collection["FirstName"]     + "</first-name>"     +
                                         "<last-name>"      + collection["LastName"]      + "</last-name>"      +
                                         "<address>"        + collection["Address"]       + "</address>"        +
                                         "<city>"           + collection["City"]          + "</city>"           +
                                         "<county>"         + collection["County"]        + "</county>"         +
                                         "<state>"          + collection["State"]         + "</state>"          +
                                         "<zip-code>"       + collection["ZIPCode"]       + "</zip-code>";
    
                    xeCustomer.InnerXml = strCustomer;
    
                    if (System.IO.File.Exists(strFileCustomers))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdCustomers.Load(fsWaterMeters);
                        }
    
                        using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("customer");
    
                            foreach (XmlNode xnCustomer in xnlCustomers)
                            {
                                if (xnCustomer.FirstChild.InnerText == id.ToString())
                                {
                                    xnCustomer.ParentNode.ReplaceChild(xeCustomer, xnCustomer);
                                    xdCustomers.Save(fsCustomers);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Customers/Delete/5
            public ActionResult Delete(int id)
            {
                XmlDocument xdCustomers = new XmlDocument();
                string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                if (System.IO.File.Exists(strFileCustomers))
                {
                    using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdCustomers.Load(fsCustomers);
    
                        XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-id");
    
                        foreach (XmlNode xnCustomer in xnlCustomers)
                        {
                            if (xnCustomer.InnerText == id.ToString())
                            {
                                ViewBag.AccountID = xnCustomer.InnerText;
                                ViewBag.AccountNumber = xnCustomer.NextSibling.InnerText;
                                ViewBag.MeterNumber = xnCustomer.NextSibling.NextSibling.InnerText;
                                ViewBag.FirstName = xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LastName = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Address = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.City = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.County = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.State = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.ZIPCode = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Customers/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    XmlDocument xdCustomers = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                    /* Open the XML file that contains customers accounts so you can fill the DOM with records */
                    using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdCustomers.Load(fsWaterMeters);
                    }
    
                    // Get ready to change something on the file
                    using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Truncate, FileAccess.Write, FileShare.Write))
                    {
                        // Get a collection of customer nodes
                        XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("customer");
    
                        // Check each node
                        foreach (XmlNode xnCustomer in xnlCustomers)
                        {
                            /* If you find a customer record whose customer-id is
                             * the same as the id of the record the user clicked, ... */
                            if (xnCustomer.FirstChild.InnerText == id.ToString())
                            {
                                // ... ask its parent to delete that record
                                xnCustomer.ParentNode.RemoveChild(xnCustomer);
                                // Now that the record has been deleted, save the XML file
                                xdCustomers.Save(fsCustomers);
                                break;
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  8. In the class, right-click one of the Delete() methods and click Add View...
  9. Make sure the View Name text box is displaying Delete. Click Add
  10. Change the document as follows:
    @{
        ViewBag.Title = "Delete Customer Account";
    }
    
    <div class="push-down">
        <h2>Closing Customer Account</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt>Account ID:</dt>
            <dd>@ViewBag.AccountID</dd>
            <dt>Account #:</dt>
            <dd>@ViewBag.AccountNumber</dd>
            <dt>Meter #:</dt>
            <dd>@ViewBag.MeterNumber</dd>
            <dt>First Name:</dt>
            <dd>@ViewBag.FirstName</dd>
            <dt>Last Name:</dt>
            <dd>@ViewBag.LastName</dd>
            <dt>Address:</dt>
            <dd>@ViewBag.Address</dd>
            <dt>City:</dt>
            <dd>@ViewBag.City</dd>
            <dt>County:</dt>
            <dd>@ViewBag.County</dd>
            <dt>State:</dt>
            <dd>@ViewBag.State</dd>
            <dt>ZIP-Code:</dt>
            <dd>@ViewBag.ZIPCode</dd>
        </dl>
    
        <h3 class="common-font caption">Are you sure you want to close the account of this customer (if you do, the account will disappear from our system)?</h3>
    
        @using (Html.BeginForm())
        {
            <div class="form-actions no-color">
                <input type="submit" value="Close this Customer's Account" class="btn btn-primary" /> |
                @Html.ActionLink("Customers Accounts", "Index", null, new { @class = "water-nav" })
            </div>
        }
    </div>
  11. In the Solution Explorer, under Controllers, double-click WaterBillsControllers.cs
  12. Implement the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class WaterBillsController : Controller
        {
            // GET: WaterBills
            public ActionResult Index()
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
                    }
    
                    if (xdWaterBills.DocumentElement.ChildNodes.Count > 0)
                    {
                        ViewBag.Invoices = xdWaterBills.DocumentElement.ChildNodes;
                    }
                    else
                    {
                        ViewBag.Invoices = null;
                    }
                }
    
                return View(xdWaterBills);
            }
    
            // GET: WaterBills/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            if (xnWaterBill.InnerText == id.ToString())
                            {
                                ViewBag.WaterBillID           = xnWaterBill.InnerText;
                                ViewBag.InvoiceNumber         = xnWaterBill.NextSibling.InnerText;
                                ViewBag.AccountNumber         = xnWaterBill.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingStartDate = xnWaterBill.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingEndDate   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.BillingDays           = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingStart   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingEnd     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalHCF              = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalGallons          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.First15HCF            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Next10HCF             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.RemainingHCF          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.SewerCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StormCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.WaterUsageCharges     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LocalTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StateTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDueDate        = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.AmountDue             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LatePaymentDueDate    = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LateAmountDue         = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: WaterBills/Create
            public ActionResult Create()
            {
                int water_bill_id = 0;
                XmlDocument xdWaterBills = new XmlDocument();
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            water_bill_id = int.Parse(xnWaterBill.InnerText);
                        }
                    }
                }
    
                ViewBag.WaterBillID = (water_bill_id + 1);
    
                Random rndNumber = new Random();
                ViewBag.InvoiceNumber = rndNumber.Next(100001, 999999).ToString();
    
                return View();
            }
    
            // POST: WaterBills/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    int bill_id              = -1;
                    bool customerIsValid     = false;
                    string meterNumber       = string.Empty;
                    XmlDocument xdCustomers  = new XmlDocument();
                    XmlDocument xdWaterBills = new XmlDocument();
                    string strFileCustomers  = Server.MapPath("/WaterDistribution/Customers.xml");
                    string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                    // Make sure the user provided an account number for the customer, ...
                    if (!string.IsNullOrEmpty(collection["AccountNumber"]))
                    {
                        // If the user provided an account number, find out if an XML file for customers was already created.
                        if (System.IO.File.Exists(strFileCustomers))
                        {
                            // If a file for customers exists, open it
                            using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Open,
                                                                                             FileAccess.Read,
                                                                                             FileShare.Read))
                            {
                                // Store the list of customers in an XML document
                                xdCustomers.Load(fsCustomers);
    
                                // Create a list of customers nodes that use the account number provided by the user
                                XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-number");
    
                                // Visit each node of the list of elements
                                foreach (XmlNode xnCustomer in xnlCustomers)
                                {
                                    // If you find a customer that is the same as the account number from the form, ...
                                    if (xnCustomer.InnerText == collection["AccountNumber"])
                                    {
                                        // ... make a note
                                        customerIsValid = true;
                                        // and get the meter number used by that customer
                                        meterNumber = xnCustomer.NextSibling.InnerText;
                                    }
                                }
                            }
                        }
                    }
    
                    if (customerIsValid == true)
                    {
                        // It appears that the user provided a valid customer account number.
                        // If an XML file for water bills was previously created, ...
                        if (System.IO.File.Exists(strFileWaterBills))
                        {
                            // ... open it ...
                            using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.OpenOrCreate,
                                                                                               FileAccess.ReadWrite,
                                                                                               FileShare.ReadWrite))
                            {
                                // ... and put the records in the DOM
                                xdWaterBills.Load(fsWaterBills);
    
                                XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                                foreach (XmlNode xnWaterBill in xnlWaterBills)
                                {
                                    bill_id = int.Parse(xnWaterBill.InnerText);
                                }
                            }
                        }
                        else
                        {
                            // If there is no XML file yet for the customers, create skeleton code for an XML document
                            xdWaterBills.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                 "<water-bills></water-bills>");
                            bill_id = 0;
                        }
    
                        // Get ready to create an XML element named water-bill
                        XmlElement xeWaterBill = xdWaterBills.CreateElement("invoice");
    
                        bill_id++;
    
                        // Create the markup of the XML water bill
                        xeWaterBill.InnerXml = "<water-bill-id>"            + bill_id                             + "</water-bill-id>"            +
                                               "<invoice-number>"           + collection["InvoiceNumber"]         + "</invoice-number>"           +
                                               "<account-number>"           + collection["AccountNumber"]         + "</account-number>"           +
                                               "<meter-reading-start-date>" + collection["MeterReadingStartDate"] + "</meter-reading-start-date>" +
                                               "<meter-reading-end-date>"   + collection["MeterReadingEndDate"]   + "</meter-reading-end-date>"   +
                                               "<billing-days>"             + collection["BillingDays"]           + "</billing-days>"             +
                                               "<counter-reading-start>"    + collection["CounterReadingStart"]   + "</counter-reading-start>"    +
                                               "<counter-reading-end>"      + collection["CounterReadingEnd"]     + "</counter-reading-end>"      +
                                               "<total-hcf>"                + collection["TotalHCF"]              + "</total-hcf>"                +
                                               "<total-gallons>"            + collection["TotalGallons"]          + "</total-gallons>"            +
                                               "<first-15-hcf>"             + collection["First15HCF"]            + "</first-15-hcf>"             +
                                               "<next-10-hcf>"              + collection["Next10HCF"]             + "</next-10-hcf>"              +
                                               "<remaining-hcf>"            + collection["RemainingHCF"]          + "</remaining-hcf>"            +
                                               "<sewer-charges>"            + collection["SewerCharges"]          + "</sewer-charges>"            +
                                               "<storm-charges>"            + collection["StormCharges"]          + "</storm-charges>"            +
                                               "<water-usage-charges>"      + collection["WaterUsageCharges"]     + "</water-usage-charges>"      +
                                               "<total-charges>"            + collection["TotalCharges"]          + "</total-charges>"            +
                                               "<local-taxes>"              + collection["LocalTaxes"]            + "</local-taxes>"              +
                                               "<state-taxes>"              + collection["StateTaxes"]            + "</state-taxes>"              +
                                               "<payment-due-date>"         + collection["PaymentDueDate"]        + "</payment-due-date>"         +
                                               "<amount-due>"               + collection["AmountDue"]             + "</amount-due>"               +
                                               "<late-payment-due-date>"    + collection["LatePaymentDueDate"]    + "</late-payment-due-date>"    +
                                               "<late-amount-due>"          + collection["LateAmountDue"]         + "</late-amount-due>";
    
                        // Add the new node to the root
                        xdWaterBills.DocumentElement.AppendChild(xeWaterBill);
    
                        // Save the (new version of the) XML file
                        using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Create, FileAccess.Write, FileShare.Write))
                        {
                            xdWaterBills.Save(fsWaterBills);
                        }
    
                        // We also want to update the counter value on the water meter with the new Counter Reading End value
                        XmlDocument xdWaterMeters = new XmlDocument();
                        string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                        if (System.IO.File.Exists(strFileWaterMeters))
                        {
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                xdWaterMeters.Load(fsWaterMeters);
                            }
    
                            XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-id");
    
                            using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                                {
                                    if (xnWaterMeter.NextSibling.InnerText == meterNumber)
                                    {
                                        xnWaterMeter.ParentNode.InnerXml = "<meter-id>"         + xnWaterMeter.InnerText + "</meter-id>" +
                                                                           "<meter-number>"     + meterNumber + "</meter-number>" +
                                                                           "<make>"             + xnWaterMeter.NextSibling.NextSibling.InnerText + "</make>" +
                                                                           "<model>"            + xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText + "</model>" +
                                                                           "<meter-size>"       + xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "</meter-size>" +
                                                                           "<date-last-update>" + xnWaterMeter.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "</date-last-update>" +
                                                                           "<counter-value>"    + collection["CounterReadingEnd"] + "</counter-value>";
                                        xdWaterMeters.Save(fsWaterMeters);
                                        break;
                                    }
                                }
                            }
                        }
                        
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: WaterBills/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strAccountNumber = string.Empty, strMeterNumber = string.Empty;
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            if (xnWaterBill.InnerText == id.ToString())
                            {
                                ViewBag.WaterBillID           = xnWaterBill.InnerText;
                                ViewBag.InvoiceNumber         = xnWaterBill.NextSibling.InnerText;
                                ViewBag.AccountNumber         = xnWaterBill.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingStartDate = xnWaterBill.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingEndDate   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.BillingDays           = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingStart   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingEnd     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalHCF              = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalGallons          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.First15HCF            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Next10HCF             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.RemainingHCF          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.SewerCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StormCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.WaterUsageCharges     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LocalTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StateTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDueDate        = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.AmountDue             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LatePaymentDueDate    = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LateAmountDue         = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
    
                                strAccountNumber = xnWaterBill.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
    
                    XmlDocument xdCustomers = new XmlDocument();
                    string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");
    
                    if (System.IO.File.Exists(strFileCustomers))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdCustomers.Load(fsWaterMeters);
    
                            XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-number");
    
                            foreach (XmlNode xnCustomer in xnlCustomers)
                            {
                                if (xnCustomer.InnerText == strAccountNumber)
                                {
                                    ViewBag.AccountNumber   = xnCustomer.InnerText;
                                    ViewBag.MeterNumber     = xnCustomer.NextSibling.InnerText;
                                    ViewBag.CustomerName    = xnCustomer.NextSibling.NextSibling.InnerText + " " + 
                                                              xnCustomer.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerAddress = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerCity    = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerCounty  = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerState   = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                    ViewBag.CustomerZIPCode = xnCustomer.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
    
                                    strMeterNumber = xnCustomer.NextSibling.InnerText;
                                }
                            }
                        }
                    }
    
                    XmlDocument xdWaterMeters = new XmlDocument();
                    string strFileWaterMeters = Server.MapPath("/WaterDistribution/WaterMeters.xml");
    
                    if (System.IO.File.Exists(strFileWaterMeters))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterMeters, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdWaterMeters.Load(fsWaterMeters);
    
                            XmlNodeList xnlWaterMeters = xdWaterMeters.GetElementsByTagName("meter-number");
    
                            foreach (XmlNode xnWaterMeter in xnlWaterMeters)
                            {
                                if (xnWaterMeter.InnerText == strMeterNumber)
                                {
                                    ViewBag.MeterDetails = xnWaterMeter.InnerText + " " + 
                                                           xnWaterMeter.NextSibling.InnerText + " (" + 
                                                           xnWaterMeter.NextSibling.NextSibling.NextSibling.InnerText + ")";
                                }
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: WaterBills/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdWaterBills = new XmlDocument();
                    string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                    if (System.IO.File.Exists(strFileWaterBills))
                    {
                        using (FileStream fsWaterMeters = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdWaterBills.Load(fsWaterMeters);
                        }
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (XmlNode xnWaterBill in xnlWaterBills)
                            {
                                if (xnWaterBill.InnerText == id.ToString())
                                {
                                    xnWaterBill.ParentNode.InnerXml = "<water-bill-id>"            + id                                  + "</water-bill-id>"            +
                                                                      "<invoice-number>"           + collection["InvoiceNumber"]         + "</invoice-number>"           +
                                                                      "<account-number>"           + collection["AccountNumber"]         + "</account-number>"           +
                                                                      "<meter-reading-start-date>" + collection["MeterReadingStartDate"] + "</meter-reading-start-date>" +
                                                                      "<meter-reading-end-date>"   + collection["MeterReadingEndDate"]   + "</meter-reading-end-date>"   +
                                                                      "<billing-days>"             + collection["BillingDays"]           + "</billing-days>"             +
                                                                      "<counter-reading-start>"    + collection["CounterReadingStart"]   + "</counter-reading-start>"    +
                                                                      "<counter-reading-end>"      + collection["CounterReadingEnd"]     + "</counter-reading-end>"      +
                                                                      "<total-hcf>"                + collection["TotalHCF"]              + "</total-hcf>"                +
                                                                      "<total-gallons>"            + collection["TotalGallons"]          + "</total-gallons>"            +
                                                                      "<first-15-hcf>"             + collection["First15HCF"]            + "</first-15-hcf>"             +
                                                                      "<next-10-hcf>"              + collection["Next10HCF"]             + "</next-10-hcf>"              +
                                                                      "<remaining-hcf>"            + collection["RemainingHCF"]          + "</remaining-hcf>"            +
                                                                      "<sewer-charges>"            + collection["SewerCharges"]          + "</sewer-charges>"            +
                                                                      "<storm-charges>"            + collection["StormCharges"]          + "</storm-charges>"            +
                                                                      "<water-usage-charges>"      + collection["WaterUsageCharges"]     + "</water-usage-charges>"      +
                                                                      "<total-charges>"            + collection["TotalCharges"]          + "</total-charges>"            +
                                                                      "<local-taxes>"              + collection["LocalTaxes"]            + "</local-taxes>"              +
                                                                      "<state-taxes>"              + collection["StateTaxes"]            + "</state-taxes>"              +
                                                                      "<payment-due-date>"         + collection["PaymentDueDate"]        + "</payment-due-date>"         +
                                                                      "<amount-due>"               + collection["AmountDue"]             + "</amount-due>"               +
                                                                     "<late-payment-due-date>"     + collection["LatePaymentDueDate"]    + "</late-payment-due-date>"    +
                                                                     "<late-amount-due>"           + collection["LateAmountDue"]         + "</late-amount-due>";
    
                                    xdWaterBills.Save(fsWaterBills);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: WaterBills/Delete/5
            public ActionResult Delete(int id)
            {
                XmlDocument xdWaterBills = new XmlDocument();
                string strAccountNumber = string.Empty, strMeterNumber = string.Empty;
                string strFileWaterBills = Server.MapPath("/WaterDistribution/WaterBills.xml");
    
                if (System.IO.File.Exists(strFileWaterBills))
                {
                    using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdWaterBills.Load(fsWaterBills);
    
                        XmlNodeList xnlWaterBills = xdWaterBills.GetElementsByTagName("water-bill-id");
    
                        foreach (XmlNode xnWaterBill in xnlWaterBills)
                        {
                            if (xnWaterBill.InnerText == id.ToString())
                            {
                                ViewBag.WaterBillID           = xnWaterBill.InnerText;
                                ViewBag.InvoiceNumber         = xnWaterBill.NextSibling.InnerText;
                                ViewBag.AccountNumber         = xnWaterBill.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingStartDate = xnWaterBill.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.MeterReadingEndDate   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.BillingDays           = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingStart   = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.CounterReadingEnd     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalHCF              = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalGallons          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.First15HCF            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.Next10HCF             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.RemainingHCF          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.SewerCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StormCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.WaterUsageCharges     = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.TotalCharges          = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LocalTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.StateTaxes            = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDueDate        = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.AmountDue             = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LatePaymentDueDate    = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.LateAmountDue         = xnWaterBill.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
    
                                strAccountNumber = xnWaterBill.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: WaterBills/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    XmlDocument xdWaterBills = new XmlDocument();
                    string strFileWaterBills= Server.MapPath("/WaterDistribution/WaterBills.xml");
                    
                    if (System.IO.File.Exists(strFileWaterBills))
                    {
                        using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdWaterBills.Load(fsWaterBills);
                        }
                        
                        using (FileStream fsWaterBills = new FileStream(strFileWaterBills, FileMode.Truncate, FileAccess.Write, FileShare.Write))
                        {
                            XmlNodeList xnlWaterBills= xdWaterBills.GetElementsByTagName("invoice");
                            
                            foreach (XmlNode xnWaterBill in xnlWaterBills)
                            {
                                if (xnWaterBill.FirstChild.InnerText == id.ToString())
                                {
                                    xnWaterBill.ParentNode.RemoveChild(xnWaterBill);
                                    xdWaterBills.Save(fsWaterBills);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  13. In the document, right-click one of the Delete() methods and click Add View...
  14. In the Add View dialog box, make sure the View Name text box is displayinig Delete. Click Add
  15. Create the webpage as follows:
    @{
        ViewBag.Title = "Deleting Water Bill";
    }
    
    <div class="push-down">
        <h2>Cancel Water Bill</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt class="bold">Water Bill ID:</dt>
            <dd>@ViewBag.WaterBillID</dd>
            <dt class="bold">Invoice #:</dt>
            <dd>@ViewBag.InvoiceNumber</dd>
            <dt class="bold">Account #:</dt>
            <dd>@ViewBag.AccountNumber</dd>
            <dt class="bold">Meter Reading Start Date:</dt>
            <dd>@ViewBag.MeterReadingStartDate</dd>
            <dt class="bold">Meter Reading End Date:</dt>
            <dd>@ViewBag.MeterReadingEndDate</dd>
            <dt class="bold">Billing Days:</dt>
            <dd>@ViewBag.BillingDays</dd>
            <dt class="bold">Counter Reading Start:</dt>
            <dd>@ViewBag.CounterReadingStart</dd>
            <dt class="bold">Counter Reading End:</dt>
            <dd>@ViewBag.CounterReadingEnd</dd>
            <dt class="bold">Total HCF:</dt>
            <dd>@ViewBag.TotalHCF</dd>
            <dt class="bold">Total Gallons:</dt>
            <dd>@ViewBag.TotalGallons</dd>
            <dt class="bold">First 15 HCF:</dt>
            <dd>@ViewBag.First15HCF</dd>
            <dt class="bold">Next 10 HCF:</dt>
            <dd>@ViewBag.Next10HCF</dd>
            <dt class="bold">Remaining HCF:</dt>
            <dd>@ViewBag.RemainingHCF</dd>
            <dt class="bold">Sewer Charges:</dt>
            <dd>@ViewBag.SewerCharges</dd>
            <dt class="bold">Storm Charges:</dt>
            <dd>@ViewBag.StormCharges</dd>
            <dt class="bold">Water Usage Charges:</dt>
            <dd>@ViewBag.WaterUsageCharges</dd>
            <dt class="bold">Total Charges:</dt>
            <dd>@ViewBag.TotalCharges</dd>
            <dt class="bold">Local Taxes:</dt>
            <dd>@ViewBag.LocalTaxes</dd>
            <dt class="bold">State Taxes:</dt>
            <dd>@ViewBag.State Taxes</dd>
            <dt class="bold">Payment Due Date:</dt>
            <dd>@ViewBag.PaymentDueDate</dd>
            <dt class="bold">Amount Due:</dt>
            <dd>@ViewBag.AmountDue</dd>
            <dt class="bold">Late Payment Due Date:</dt>
            <dd>@ViewBag.LatePaymentDueDate</dd>
            <dt class="bold">Late Amount Due:</dt>
            <dd>@ViewBag.LateAmountDue</dd>
        </dl>
    
        <h3 class="common-font caption">Are you sure you want to cancel this water bill (if you do, the bill will disappear from the system)?</h3>
    
        @using (Html.BeginForm())
        {
            <div class="form-actions no-color">
                <input type="submit" value="Cancel this Water Bill" class="btn btn-primary" /> |
                @Html.ActionLink("Customers Water Bills", "Index", null, new { @class = "water-nav" })
            </div>
        }
    </div>
  16. In the Solution Explorer, under Controllers, double-click PaymentsControllers.cs
  17. Implement the Delete() methods as follows:
    using System;
    using System.IO;
    using System.Xml;
    using System.Web.Mvc;
    
    namespace WaterDistributionCompany1.Controllers
    {
        public class PaymentsController : Controller
        {
            // GET: Payments
            public ActionResult Index()
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
                    }
    
                    if (xdPayments.DocumentElement.ChildNodes.Count > 0)
                    {
                        ViewBag.Payments = xdPayments.DocumentElement.ChildNodes;
                    }
                    else
                    {
                        ViewBag.Payments = null;
                    }
                }
    
                return View();
            }
    
            // GET: Payments/Details/5
            public ActionResult Details(int id)
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            if (xnPayment.InnerText == id.ToString())
                            {
                                ViewBag.PaymentID     = xnPayment.InnerText;
                                ViewBag.ReceiptNumber = xnPayment.NextSibling.InnerText;
                                ViewBag.WaterBillID   = xnPayment.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDate   = xnPayment.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentAmount = xnPayment.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // GET: Payments/Create
            public ActionResult Create()
            {
                int payment_id = 0;
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            payment_id = int.Parse(xnPayment.InnerText);
                        }
                    }
                }
    
                ViewBag.PaymentID = (payment_id + 1);
    
                Random rndNumber = new Random();
                ViewBag.ReceiptNumber = rndNumber.Next(100001, 999999).ToString();
    
                return View();
            }
    
            // POST: Payments/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
                    XmlDocument xdPayments = new XmlDocument();
                    string strFilePayments= Server.MapPath("/WaterDistribution/Payments.xml");
                    
                    if (System.IO.File.Exists(strFilePayments))
                    {
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdPayments.Load(fsPayments);
                        }
                    }
                    else
                    {
                        xdPayments.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                           "<payments></payments>");
                    }
                    
                    XmlElement xePayment = xdPayments.CreateElement("bill-payment");
    
                    xePayment.InnerXml = "<payment-id>"     + collection["PaymentID"]     + "</payment-id>"    +
                                         "<receipt-number>" + collection["ReceiptNumber"] + "</receipt-number>" +
                                         "<water-bill-id>"  + collection["WaterBillID"]   + "</water-bill-id>"  +
                                         "<payment-date>"   + collection["PaymentDate"]   + "</payment-date>"   +
                                         "<payment-amount>" + collection["PaymentAmount"] + "</payment-amount>";
    
                    xdPayments.DocumentElement.AppendChild(xePayment);
                    
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        xdPayments.Save(fsPayments);
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Payments/Edit/5
            public ActionResult Edit(int id)
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments= xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            if (xnPayment.InnerText == id.ToString())
                            {
                                ViewBag.PaymentID = xnPayment.InnerText;
                                ViewBag.ReceiptNumber = xnPayment.NextSibling.InnerText;
                                ViewBag.WaterBillID = xnPayment.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDate = xnPayment.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentAmount = xnPayment.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Payments/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
                    XmlDocument xdPayments = new XmlDocument();
                    string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                    if (System.IO.File.Exists(strFilePayments))
                    {
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            xdPayments.Load(fsPayments);
                        }
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            foreach (XmlNode xnPayment in xnlPayments)
                            {
                                if (xnPayment.InnerText == id.ToString())
                                {
                                    xnPayment.ParentNode.InnerXml = "<payment-id>" + id + "</payment-id>" +
                                                                    "<receipt-number>" + collection["ReceiptNumber"] + "</receipt-number>" +
                                                                    "<water-bill-id>" + collection["WaterBillID"] + "</water-bill-id>" +
                                                                    "<payment-date>" + collection["PaymentDate"] + "</payment-date>" +
                                                                    "<payment-amount>" + collection["PaymentAmount"] + "</payment-amount>";
                                    xdPayments.Save(fsPayments);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Payments/Delete/5
            public ActionResult Delete(int id)
            {
                XmlDocument xdPayments = new XmlDocument();
                string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
    
                if (System.IO.File.Exists(strFilePayments))
                {
                    using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        xdPayments.Load(fsPayments);
    
                        XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment-id");
    
                        foreach (XmlNode xnPayment in xnlPayments)
                        {
                            if (xnPayment.InnerText == id.ToString())
                            {
                                ViewBag.PaymentID     = xnPayment.InnerText;
                                ViewBag.ReceiptNumber = xnPayment.NextSibling.InnerText;
                                ViewBag.WaterBillID   = xnPayment.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentDate   = xnPayment.NextSibling.NextSibling.NextSibling.InnerText;
                                ViewBag.PaymentAmount = xnPayment.NextSibling.NextSibling.NextSibling.NextSibling.InnerText;
                            }
                        }
                    }
                }
    
                return View();
            }
    
            // POST: Payments/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
                    XmlDocument xdPayments = new XmlDocument();
                    string strFilePayments = Server.MapPath("/WaterDistribution/Payments.xml");
                    
                    if (System.IO.File.Exists(strFilePayments))
                    {
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            xdPayments.Load(fsPayments);
                        }
                        
                        using (FileStream fsPayments = new FileStream(strFilePayments, FileMode.Truncate, FileAccess.Write, FileShare.Write))
                        {
                            XmlNodeList xnlPayments = xdPayments.GetElementsByTagName("payment");
                            
                            foreach (XmlNode xnPayment in xnlPayments)
                            {
    
                                if (xnPayment.FirstChild.InnerText == id.ToString())
                                {
                                    xnPayment.ParentNode.RemoveChild(xnPayment);
                                    xdPayments.Save(fsPayments);
                                    break;
                                }
                            }
                        }
                    }
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  18. In the document, right-click one of the Delete() methods and click Add View...
  19. Make sure the View Name text box is displaying Delete. Click Add
  20. Create the wepbpage as follows:
    @{
        ViewBag.Title = "Delete Bill Payment";
    }
    
    <div class="push-down">
        <h2>Cancel Bill Payment</h2>
    </div>
    
    <hr />
    
    <div class="containment">
        <dl class="dl-horizontal common-font caption">
            <dt>Payment ID:</dt>
            <dd>@ViewBag.PaymentID</dd>
            <dt>Receipt #:</dt>
            <dd>@ViewBag.ReceiptNumber</dd>
            <dt>Water Bill ID:</dt>
            <dd>@ViewBag.WaterBillID</dd>
            <dt>Payment Date:</dt>
            <dd>@ViewBag.PaymentDate</dd>
            <dt>Payment Amount:</dt>
            <dd>@ViewBag.PaymentAmount</dd>
        </dl>
    
        <h3 class="common-font caption">Are you sure you want to cancel this payment?</h3>
    
        @using (Html.BeginForm())
        {
            <div class="form-actions no-color">
                <input type="submit" value="Cancel this bill payment" class="btn btn-primary" /> |
                @Html.ActionLink("Water Bills Payments", "Index", null, new { @class = "water-nav" })
            </div>
        }
    </div>
  21. In the Solution Explorer, under Views and under Shared, double-click _Layout.cshtml
  22. On the webpage, click the Customers link
  23. In the Customers webpage, click the Remove link of the last record

    Creating and Using Virtual Members

  24. In the webpage, click the Delete this Customer's Account button
  25. Close the browser and return to your programming environment

Clearing an Element of its Children

Consider this XML document named Customers.xml from our WaterDistributionCompany exercise:

<?xml version="1.0" encoding="utf-8"?>
<customers>
  <customer>
    <account-id>1</account-id>
    <account-number>9279-570-8394</account-number>
    <meter-number>799-28-461</meter-number>
    <first-name>Thomas</first-name>
    <last-name>Stones</last-name>
    <address>10252 Broward Ave #D4</address>
    <city>Frederick</city>
    <county>Frederick</county>
    <state>Frederick</state>
    <zip-code>21703</zip-code>
  </customer>
  <customer>
    <account-id>2</account-id>
    <account-number>4820-375-2842</account-number>
    <meter-number>392-44-572</meter-number>
    <first-name>Akhil</first-name>
    <last-name>Koumari</last-name>
    <address>748 Red Hills Rd</address>
    <city>Roanoke</city>
    <county>
    </county>
    <state>VA</state>
    <zip-code>24012</zip-code>
  </customer>
  <customer>
    <account-id>3</account-id>
    <account-number>7518-302-6895</account-number>
    <meter-number>207-94-835</meter-number>
    <first-name>Grace</first-name>
    <last-name>Brenner</last-name>
    <address>4299 Peachtree Court</address>
    <city>Rockville</city>
    <county>Montgomery</county>
    <state>MD</state>
    <zip-code>20853</zip-code>
  </customer>
</customers>

To let you delete all child nodes of a node, the XmlNode class provides a method named RemoveAll. Its syntax is:

public virtual void RemoveAll();

When this method is called by a node, if the element doesn't have children, only its own value will be deleted but its start tag (including the end tag) will remain. Here is an example:

// POST: Customers/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
    try
    {
        XmlDocument xdCustomers = new XmlDocument();
        string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");

        using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            xdCustomers.Load(fsWaterMeters);
        }

        using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Truncate, FileAccess.Write, FileShare.Write))
        {
            XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("account-id");

            foreach (XmlNode xnCustomer in xnlCustomers)
            {
                if (xnCustomer.InnerText == id.ToString())
                {
                    xnCustomer.RemoveAll();
                    xdCustomers.Save(fsCustomers);
                    break;
                }
            }
        }

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

If the user had clicked the second record and the button to delete it, we would get:

<?xml version="1.0" encoding="utf-8"?>
<customers>
  <customer>
    <account-id>1</account-id>
    <account-number>9279-570-8394</account-number>
    <meter-number>799-28-461</meter-number>
    <first-name>Thomas</first-name>
    <last-name>Stones</last-name>
    <address>10252 Broward Ave #D4</address>
    <city>Frederick</city>
    <county>Frederick</county>
    <state>Frederick</state>
    <zip-code>21703</zip-code>
  </customer>
  <customer>
    <account-id>
    </account-id>
    <account-number>4820-375-2842</account-number>
    <meter-number>392-44-572</meter-number>
    <first-name>Akhil</first-name>
    <last-name>Koumari</last-name>
    <address>748 Red Hills Rd</address>
    <city>Roanoke</city>
    <county>
    </county>
    <state>VA</state>
    <zip-code>24012</zip-code>
  </customer>
  <customer>
    <account-id>3</account-id>
    <account-number>7518-302-6895</account-number>
    <meter-number>207-94-835</meter-number>
    <first-name>Grace</first-name>
    <last-name>Brenner</last-name>
    <address>4299 Peachtree Court</address>
    <city>Rockville</city>
    <county>Montgomery</county>
    <state>MD</state>
    <zip-code>20853</zip-code>
  </customer>
</customers>

Once again, consider the following XML document named Customers.xml:

<?xml version="1.0" encoding="utf-8"?>
<customers>
  <customer>
    <account-id>1</account-id>
    <account-number>9279-570-8394</account-number>
    <meter-number>799-28-461</meter-number>
    <first-name>Thomas</first-name>
    <last-name>Stones</last-name>
    <address>10252 Broward Ave #D4</address>
    <city>Frederick</city>
    <county>Frederick</county>
    <state>Frederick</state>
    <zip-code>21703</zip-code>
  </customer>
  <customer>
    <account-id>2</account-id>
    <account-number>4820-375-2842</account-number>
    <meter-number>392-44-572</meter-number>
    <first-name>Akhil</first-name>
    <last-name>Koumari</last-name>
    <address>748 Red Hills Rd</address>
    <city>Roanoke</city>
    <county>
    </county>
    <state>VA</state>
    <zip-code>24012</zip-code>
  </customer>
  <customer>
    <account-id>3</account-id>
    <account-number>7518-302-6895</account-number>
    <meter-number>207-94-835</meter-number>
    <first-name>Grace</first-name>
    <last-name>Brenner</last-name>
    <address>4299 Peachtree Court</address>
    <city>Rockville</city>
    <county>Montgomery</county>
    <state>MD</state>
    <zip-code>20853</zip-code>
  </customer>
</customers>

If the XmlNode.RemoveAll() method is called by a node that has children, the node's children would be removed. Only the start tag (and end tag) of that node woule remain. Here is an example:

// POST: Customers/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
    try
    {
        XmlDocument xdCustomers = new XmlDocument();
        string strFileCustomers = Server.MapPath("/WaterDistribution/Customers.xml");

        using (FileStream fsWaterMeters = new FileStream(strFileCustomers, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            xdCustomers.Load(fsWaterMeters);
        }

        using (FileStream fsCustomers = new FileStream(strFileCustomers, FileMode.Truncate, FileAccess.Write, FileShare.Write))
        {
            XmlNodeList xnlCustomers = xdCustomers.GetElementsByTagName("customer");

            // Check each node
            foreach (XmlNode xnCustomer in xnlCustomers)
            {
                if (xnCustomer.FirstChild.InnerText == id.ToString())
	            {
                    // ... ask its parent to delete that record
                    xnCustomer.RemoveAll();
                    // Now that the record has been deleted, save the XML file
                    xdCustomers.Save(fsCustomers);
                    break;
                }
            }
        }

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

From our example, if the user had clicked the Remove link for the second record and clicked the button to delete the record, we would get the following result:

<?xml version="1.0" encoding="utf-8"?>
<customers>
  <customer>
    <account-id>1</account-id>
    <account-number>9279-570-8394</account-number>
    <meter-number>799-28-461</meter-number>
    <first-name>Thomas</first-name>
    <last-name>Stones</last-name>
    <address>10252 Broward Ave #D4</address>
    <city>Frederick</city>
    <county>Frederick</county>
    <state>Frederick</state>
    <zip-code>21703</zip-code>
  </customer>
  <customer></customer>
  <customer>
    <account-id>3</account-id>
    <account-number>7518-302-6895</account-number>
    <meter-number>207-94-835</meter-number>
    <first-name>Grace</first-name>
    <last-name>Brenner</last-name>
    <address>4299 Peachtree Court</address>
    <city>Rockville</city>
    <county>Montgomery</county>
    <state>MD</state>
    <zip-code>20853</zip-code>
  </customer>
</customers>

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2005-2019, FunctionX Next