Skip to content

Instantly share code, notes, and snippets.

@demndevel
Created April 3, 2022 10:12
Show Gist options
  • Save demndevel/8418c1d200e9035d1bb9656d9abc7667 to your computer and use it in GitHub Desktop.
Save demndevel/8418c1d200e9035d1bb9656d9abc7667 to your computer and use it in GitHub Desktop.
using System.Text.Json.Serialization;
using System.Xml;
using Newtonsoft.Json;
namespace chatik;
class Message
{
public string Text = "";
public string Nickname = "";
}
class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Map("/get", applicationBuilder =>
{
applicationBuilder.Run(async (context) =>
{
await context.Response.WriteAsJsonAsync(JsonConvert.SerializeObject(ParseXML()));
});
});
app.Map("/send", applicationBuilder =>
{
applicationBuilder.Run(async (context) =>
{
var form = context.Request.Form;
AddData(form["nickname"], form["text"]);
await context.Response.WriteAsync("sent!");
});
});
app.Run(async context => await context.Response.SendFileAsync("index.html"));
app.Run();
}
static List<Message> ParseXML()
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("data.xml");
XmlElement? xRoot = xDoc.DocumentElement;
List<Message> messages = new List<Message>();
if (xRoot != null)
{
foreach (XmlElement xnode in xRoot)
{
var message = new Message();
foreach (XmlNode childnode in xnode.ChildNodes)
{
if (childnode.Name == "nickname")
{
message.Nickname = childnode.InnerText;
}
if (childnode.Name == "text")
{
message.Text = childnode.InnerText;
}
}
messages.Add(message);
}
}
return messages;
}
static void AddData(string nick, string text)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("data.xml");
XmlElement? xRoot = xDoc.DocumentElement;
XmlElement messageElem = xDoc.CreateElement("message");
XmlElement nickElem = xDoc.CreateElement("nickname");
XmlElement textElem = xDoc.CreateElement("text");
XmlText nameText = xDoc.CreateTextNode(nick);
XmlText textText = xDoc.CreateTextNode(text);
nickElem.AppendChild(nameText);
textElem.AppendChild(textText);
messageElem.AppendChild(nickElem);
messageElem.AppendChild(textElem);
xRoot?.AppendChild(messageElem);
xDoc.Save("data.xml");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment