1

I am trying to read and write to an XML file within a .NET MVC web application. The XML reader ( GetScoresXMLReader() ) is working - it is able to output to a web page. But the XML writer ( AddScoresXMLWriter ) is not working for the form page. Can anyone tell me what i am doing wrong please? Below is the User class which defines the XML methods and the controller class ( for the AddACustomer view ) from which I am calling the XML methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;

namespace WebApplication10.Models
{
    [Serializable]
    [XmlRoot("User"), XmlType("User")]
    public class Users
    {

        // Get the current directory.
        static string path = Directory.GetCurrentDirectory();
        static String binPath = path + "\\binary\\data.bin";
        static String xmlPath = path + "\\Properties\\Users.xml";


        [Required(ErrorMessage = "Must specifiy a first name")]
        [Display(Name = "First Name")]
        [DataType(DataType.Text)]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Must specifiy a last name")]
        [DataType(DataType.Text)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required(ErrorMessage ="Must specifiy a role")]
        [Display(Name = "Role")]
        [DataType(DataType.Text)]
        public string Role { get; set; }


        //Parameter Less constructor needed for XML Serialization Only!!!
        public Users() { }


        //CONSTRUCTOR 
        public Users( String fname, String lname, String date)
        {
            FirstName = fname;
            LastName = lname;
            Role = date;
        }

        public String DisplayUser()
        {
            return ("First Name: " + FirstName + ", Last Name:" + LastName + ", Role: " + Role + "/n");
        }


        public class XMLReader
        {


            public static List<Users> AddScoresXMLWriter(Users userSet)
                {
                    List<Users> userList = GetScoresXMLReader();

                    userList.Add(userSet);
                    var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<Users>));
                    var xmlFile = new System.IO.StreamWriter(xmlPath);
                    writer.Serialize(xmlFile, userList);
                    xmlFile.Close();

                return userList;
                }

            public static List<Users> GetScoresXMLReader()
            {
                List<Users> eventList = new List<Users>();
                try
                {
                    System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(List<Users>));
                    System.IO.StreamReader file = new System.IO.StreamReader(xmlPath);
                    eventList = (List<Users>)reader.Deserialize(file);
                    file.Close();
                }
                catch (FileNotFoundException fex)
                {
                    Debug.Write(fex.Message);
                }
                catch (Exception ex)
                {
                    Debug.Write(ex.Message);
                }
                return eventList;
            }


            //FOR LIST ALL CUSTOMERS PAGE

            public List<Users> OutPutListOfAllUsers()
            {  
                DataSet ds = new DataSet();//Using dataset to read xml file  
                ds.ReadXml(xmlPath);
                var results = new List<Users>();
                results = (from rows in ds.Tables[0].AsEnumerable()
                            select new Users
                            {
                                FirstName = rows[0].ToString(), //Convert row to int  
                                LastName = rows[1].ToString(),
                                Role = rows[2].ToString(),
                            }).ToList();
                return results;
            }
        }


    }
}

And here is the controller from which the XML writer is called.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Web;
using Microsoft.Extensions.Logging;
using WebApplication10.Models;
using static WebApplication10.Models.Users;

namespace WebApplication10.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult ViewAllUsers()
        {
            XMLReader readXML = new XMLReader();
            var data = readXML.OutPutListOfAllUsers();
            return View(data.ToList());
        }

        public IActionResult AboutMe()
        {
            return View();
        }
        public IActionResult Privacy()
        {
            return View();
        }
        [HttpGet]
        public ActionResult AddACustomer()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddACustomer(Users user)
        {
            // do validation 
            if (!ModelState.IsValid)
            {
                //ADD FORM INPUT TO XML FILE
                XMLReader.AddScoresXMLWriter(user);
                return View(user);
            }
            // save user

            //redirect

            return Redirect("/");
        }


        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

If I load ViewAllCustomers page I can see the entries that I have manually added to the XML but When I fill out all required fields of form (on AddACustomer page) it submits but the XML is not modified. If I try to submit the form incompletely then I get an error that XML file is in use.

When loading page from menu or when redirected from AddACustomer page after form submission - no errors but XML is not appended with form submission

If form submit button is clicked but form is incomplete then error is generated that XML is in use and cannot be written to.

enter image description here

Vynce82
  • 119
  • 3
  • 15
  • 1
    Please could you tell us what "not working for the form page" means. Is incorrect data written, is no data written, does the computer crash, or something else? – Andrew Morton May 03 '20 at 16:25
  • The form submits but the XML is not appended with form information. I've updated the post with pictures. I hope it is clearer. The XML read method is working but the XML write function is not working. – Vynce82 May 03 '20 at 16:53
  • 1
    If this is for a multi-user application then you should use a multi-user-capable database. Apart from that, where the code has `var xmlFile = new System.IO.StreamWriter(xmlPath);` it ought to be using the [using statement](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) to make sure that unmanaged resources are cleaned up properly. – Andrew Morton May 03 '20 at 17:02
  • 1
    Andrew - you are correct! I had to add the 'using' statement to the XML reader method, which opens the XML before returning a list of user objects to be passed to the XML writer. Thank you very much! I appreciate the help! – Vynce82 May 03 '20 at 19:27
  • 1
    Does this answer your question? [IOException: The process cannot access the file 'file path' because it is being used by another process](https://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being) – Andrew Morton May 04 '20 at 12:10

0 Answers0