Added logging + array based processing.

This commit is contained in:
Patrick Fic
2020-06-01 13:39:33 -07:00
parent db86d0bc55
commit 5c3160321b
8 changed files with 215 additions and 181 deletions

View File

@@ -18,7 +18,7 @@ namespace BodyshopPartner.Utils
public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
logger.Fatal((e.ExceptionObject as Exception), "Unhandled generic exception.");
logger.Fatal((e.ExceptionObject as Exception), "Unhandled generic exception. ");
}
}
}

View File

@@ -5,14 +5,18 @@ using System.Text;
using System.Threading.Tasks;
using SimpleHttp;
using System.Xml.Linq;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace BodyshopPartner.Utils
{
public static class HTTPServer
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public static void InitHttpServer()
public delegate void HttpLogger(string s);
private static HttpLogger hlog;
public static void InitHttpServer(HttpLogger HttpLogger)
{
Route.Add("/qb/receivables", (req, res, props) =>
{
@@ -26,7 +30,8 @@ namespace BodyshopPartner.Utils
, "POST");
logger.Trace("Starting HTTP server...");
hlog = HttpLogger;
hlog("Starting HTTP server...");
//TODO As a part of the installer, add netsh http add urlacl url=http://+:1337/ user="Everyone
HttpServer.ListenAsync(1337, System.Threading.CancellationToken.None, Route.OnHttpRequestAsync).Wait();
}
@@ -34,28 +39,44 @@ namespace BodyshopPartner.Utils
private static void HandleQbReceivables(System.Net.HttpListenerRequest req, System.Net.HttpListenerResponse res)
{
logger.Debug("/qb/receivables - POST");
//Input will be an array of XMLs.
string requestXMLstring = ParseBodyToString(req);
XDocument requestXMLdoc = ParseStringToXml(requestXMLstring);
string[] requestXMLstrings = ParseBodyToArray(req);
hlog("Received QuickBooks Receivable request.");
string CustomerId = QuickBooksInterop.CreateCustomerIfNotExist(requestXMLdoc);
string InvoiceAddResponse = QuickBooksInterop.ProcessQBXmlRequest(requestXMLstring);
string[] status = new string[3];
if (InvoiceAddResponse != null) status = QuickBooksInterop.parseInvoiceAddRs(InvoiceAddResponse);
if (InvoiceAddResponse != null && status[0] == "0")
// string requestXMLstring = ParseBodyToString(req);
foreach (var requestXMLstring in requestXMLstrings)
{
logger.Debug("Invoice added successfully.");
XDocument requestXMLdoc = ParseStringToXml(requestXMLstring);
XDocument response = XDocument.Parse(QuickBooksInterop.ProcessQBXmlRequest(requestXMLstring));
Models.QbXmlResponse ResponseStatus = QuickBooksInterop.ParseResponseXml(response);
logger.Info(response.ToString());
logger.Info(ResponseStatus.ToString());
hlog(ResponseStatus.ToString());
//string[] status = new string[3];
//if (InvoiceAddResponse != null) status = QuickBooksInterop.parseInvoiceAddRs(InvoiceAddResponse);
//if (InvoiceAddResponse != null && status[0] == "0")
//{ logger.Debug("Invoice added successfully."); res.StatusCode = 200; }
//else
//{ logger.Error("Error adding Invoice.\nStatus Code: {0} \nSeverity: {1} \nMessage {2}", status[0], status[1], status[2]); res.StatusCode = 400; }
}
else
{
logger.Error("Error adding Invoice.\nStatus Code: {0} \nSeverity: {1} \nMessage {2}", status[0], status[1], status[2]);
}
res.WithCORS().AsText("Hello.");
hlog("Completed QuickBooks Receivable request.");
res.WithCORS().Close();
}
public static string[] ParseBodyToArray(System.Net.HttpListenerRequest req)
{
System.IO.Stream body = req.InputStream;
System.Text.Encoding encoding = req.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string s = reader.ReadToEnd();
body.Close();
reader.Close();
return JArray.Parse(s).Select(jv => jv.ToString()).ToArray();
}
public static string ParseBodyToString(System.Net.HttpListenerRequest req)
@@ -63,17 +84,7 @@ namespace BodyshopPartner.Utils
System.IO.Stream body = req.InputStream;
System.Text.Encoding encoding = req.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
//if (req.ContentType != null)
//{
// Console.WriteLine("Client data content type {0}", req.ContentType);
//}
//Console.WriteLine("Client data content length {0}", req.ContentLength64);
//Console.WriteLine("Start of client data:");
// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
//Console.WriteLine(s);
//Console.WriteLine("End of client data:");
body.Close();
return s;
}

View File

@@ -71,113 +71,49 @@ namespace BodyshopPartner.Utils
}
}
public static string[] parseInvoiceAddRs(string xml)
public static Models.QbXmlResponse ParseResponseXml(XDocument response)
{
string[] retVal = new string[3];
try
XElement QueryResponse = response.Root.Descendants("QBXMLMsgsRs").Descendants().FirstOrDefault();
XAttribute StatusCode = QueryResponse.Attribute("statusCode");
XAttribute StatusSeverity = QueryResponse.Attribute("statusSeverity");
XAttribute statusMessage = QueryResponse.Attribute("statusMessage");
return new Models.QbXmlResponse()
{
XmlNodeList RsNodeList = null;
XmlDocument Doc = new XmlDocument();
Doc.LoadXml(xml);
RsNodeList = Doc.GetElementsByTagName("InvoiceAddRs");
XmlAttributeCollection rsAttributes = RsNodeList.Item(0).Attributes;
XmlNode statusCode = rsAttributes.GetNamedItem("statusCode");
retVal[0] = Convert.ToString(statusCode.Value);
XmlNode statusSeverity = rsAttributes.GetNamedItem("statusSeverity");
retVal[1] = Convert.ToString(statusSeverity.Value);
XmlNode statusMessage = rsAttributes.GetNamedItem("statusMessage");
retVal[2] = Convert.ToString(statusMessage.Value);
}
catch (Exception e)
{
logger.Error("Error encountered when parsing Invoice info returned from QuickBooks: " + e.Message);
retVal = null;
}
return retVal;
StatusCode = System.Text.RegularExpressions.Regex.Unescape(StatusCode.Value),
StatusMessage = System.Text.RegularExpressions.Regex.Unescape(statusMessage.Value),
StatusSeverity = System.Text.RegularExpressions.Regex.Unescape(StatusSeverity.Value),
ResponseType = System.Text.RegularExpressions.Regex.Unescape(QueryResponse.Name.LocalName),
Response = response
};
//response.
}
public static string CreateCustomerIfNotExist(XDocument requestXML)
{
string ListID = ParseCustomerId(requestXML);
if (string.IsNullOrEmpty(ListID))
//Could be null or exist, we need to check.
{
QBSessionManager sessionManager = new QBSessionManager();
IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("CA", 13, 0);
requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
//public static string[] parseInvoiceAddRs(string xml)
//{
// string[] retVal = new string[3];
// try
// {
// XmlNodeList RsNodeList = null;
// XmlDocument Doc = new XmlDocument();
// Doc.LoadXml(xml);
// RsNodeList = Doc.GetElementsByTagName("InvoiceAddRs");
// XmlAttributeCollection rsAttributes = RsNodeList.Item(0).Attributes;
// XmlNode statusCode = rsAttributes.GetNamedItem("statusCode");
// retVal[0] = Convert.ToString(statusCode.Value);
// XmlNode statusSeverity = rsAttributes.GetNamedItem("statusSeverity");
// retVal[1] = Convert.ToString(statusSeverity.Value);
// XmlNode statusMessage = rsAttributes.GetNamedItem("statusMessage");
// retVal[2] = Convert.ToString(statusMessage.Value);
// }
// catch (Exception e)
// {
// logger.Error("Error encountered when parsing Invoice info returned from QuickBooks: " + e.Message);
// retVal = null;
// }
// return retVal;
//}
ICustomerAdd CustomerAddRq = requestMsgSet.AppendCustomerAddRq();
//Get the address & Other information from the request XML DOC.
CustomerAddRq.Name.SetValue(requestXML.Descendants("CustomerRef").First()?.Element("FullName")?.Value);
// ICustomerQuery CustomerQueryRq = requestMsgSet.AppendCustomerQueryRq();
//CustomerQueryRq.ORCustomerListQuery.ListIDList.Add(ListID);
string ret = ProcessQBXmlRequest(requestMsgSet.ToXMLString());
return ret;
}
else
{
return ListID;
}
}
public static string[] parseCustomerQueryRs(string xml)
{
string[] retVal;
try
{
XDocument responseXml = XDocument.Parse(xml);
XElement CustomerQueryRs = responseXml.Descendants("CustomerQueryRs").First();
XAttribute statusCode = CustomerQueryRs.Attribute(XName.Get("statusCode"));
if (statusCode.Value?.ToString() == "0")
{
//All good, return the ID.
}
else
{
//Need to create a new customer and return that ID.
}
//XmlNodeList RsNodeList = null;
//XmlDocument Doc = new XmlDocument();
//Doc.LoadXml(xml);
//RsNodeList = Doc.GetElementsByTagName("CustomerQueryRs");
//XmlAttributeCollection rsAttributes = RsNodeList.Item(0).Attributes;
//XmlNode statusCode = rsAttributes.GetNamedItem("statusCode");
//if (Convert.ToString(statusCode.Value) == "0")
//{
// //Found an ID for this person. Looks all good.
// retVal = new string[1];
// //xml.Desce
//}
//else
//{
// retVal = new string[3];
// retVal[0] = Convert.ToString(statusCode.Value);
// XmlNode statusSeverity = rsAttributes.GetNamedItem("statusSeverity");
// retVal[1] = Convert.ToString(statusSeverity.Value);
// XmlNode statusMessage = rsAttributes.GetNamedItem("statusMessage");
// retVal[2] = Convert.ToString(statusMessage.Value);
//}
//;
}
catch (Exception e)
{
logger.Error("Error encountered when parsing Invoice info returned from QuickBooks: " + e.Message);
retVal = null;
}
return retVal;
}
private static string ParseCustomerId(XDocument xml)
{
XElement CustomerRef = xml.Descendants("CustomerRef").First();
string ListId = CustomerRef.Element("ListID")?.Value;
return ListId;
}
}
}