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.
If form submit button is clicked but form is incomplete then error is generated that XML is in use and cannot be written to.