diff --git a/BodyshopUploader/App.xaml b/BodyshopUploader/App.xaml index 2ae91cc..b9ae366 100644 --- a/BodyshopUploader/App.xaml +++ b/BodyshopUploader/App.xaml @@ -3,6 +3,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BodyshopPartner" ShutdownMode="OnExplicitShutdown" + Exit="Application_Exit" StartupUri="Views\Login.xaml"> diff --git a/BodyshopUploader/App.xaml.cs b/BodyshopUploader/App.xaml.cs index c02d01c..d72d1cd 100644 --- a/BodyshopUploader/App.xaml.cs +++ b/BodyshopUploader/App.xaml.cs @@ -18,5 +18,10 @@ namespace BodyshopPartner //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("es-MX"); //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-CA"); } + + private void Application_Exit(object sender, ExitEventArgs e) + { + Utils.QuickBooksInterop.DisconnectFromQuickBooks(); + } } } diff --git a/BodyshopUploader/Utils/HTTPServer.cs b/BodyshopUploader/Utils/HTTPServer.cs index a7b9730..a736e19 100644 --- a/BodyshopUploader/Utils/HTTPServer.cs +++ b/BodyshopUploader/Utils/HTTPServer.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using SimpleHttp; +using System.Xml.Linq; namespace BodyshopPartner.Utils { @@ -20,21 +21,9 @@ namespace BodyshopPartner.Utils res.Close(); }, "OPTIONS"); - Route.Add("/qb/receivables", (req, res, props) => - { - logger.Debug("/qb/receivables - POST"); - string AuthToken = req.Headers.Get("Authorization"); - string requestXML = ParseBody(req); - logger.Trace("Incoming Request XML", requestXML); - - //res.WithCORS(); - Utils.QuickBooksInterop.ConnectToQuickBooks(); - string result = Utils.QuickBooksInterop.processRequestFromQB(requestXML); - Utils.QuickBooksInterop.DisconnectFromQuickBooks(); - - - res.WithCORS().AsText("Hello."); - }, "POST"); + Route.Add("/qb/receivables", + (req, res, props) => { HandleQbReceivables(req, res); } + , "POST"); logger.Trace("Starting HTTP server..."); @@ -42,24 +31,58 @@ namespace BodyshopPartner.Utils HttpServer.ListenAsync(1337, System.Threading.CancellationToken.None, Route.OnHttpRequestAsync).Wait(); } - public static string ParseBody(System.Net.HttpListenerRequest req) + private static void HandleQbReceivables(System.Net.HttpListenerRequest req, System.Net.HttpListenerResponse res) + { + logger.Debug("/qb/receivables - POST"); + + string requestXMLstring = ParseBodyToString(req); + XDocument requestXMLdoc = ParseStringToXml(requestXMLstring); + + 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") + { + logger.Debug("Invoice added successfully."); + } + else + { + logger.Error("Error adding Invoice.\nStatus Code: {0} \nSeverity: {1} \nMessage {2}", status[0], status[1], status[2]); + } + res.WithCORS().AsText("Hello."); + } + + public static string ParseBodyToString(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); - if (req.ContentType != null) - { - Console.WriteLine("Client data content type {0}", req.ContentType); - } - Console.WriteLine("Client data content length {0}", req.ContentLength64); + //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:"); + //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:"); + //Console.WriteLine(s); + //Console.WriteLine("End of client data:"); body.Close(); return s; } + + public static XDocument ParseStringToXml(string input) + { + return XDocument.Parse(input); + } + + } } diff --git a/BodyshopUploader/Utils/QuickBooksInterop.cs b/BodyshopUploader/Utils/QuickBooksInterop.cs index d7b1df5..b41c560 100644 --- a/BodyshopUploader/Utils/QuickBooksInterop.cs +++ b/BodyshopUploader/Utils/QuickBooksInterop.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Xml; +using System.Xml.Linq; using Interop.QBFC13; using Interop.QBXMLRP2; @@ -21,7 +23,6 @@ namespace BodyshopPartner.Utils public static void ConnectToQuickBooks() { - try { rp = new RequestProcessor2Class(); @@ -53,18 +54,72 @@ namespace BodyshopPartner.Utils } } } - public static string processRequestFromQB(string request) + public static string ProcessQBXmlRequest(string request) { try { - return rp.ProcessRequest(ticket, request); + ConnectToQuickBooks(); + var ret = rp.ProcessRequest(ticket, request); + DisconnectFromQuickBooks(); + return ret; } catch (Exception e) { logger.Error(e.Message); + DisconnectFromQuickBooks(); return null; } } + 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; + } + + public static string CreateCustomerIfNotExist(XDocument requestXML) + { + string ListID = ParseCustomerId(requestXML); + + //Could be null or exist, we need to check. + QBSessionManager sessionManager = new QBSessionManager(); + + //Create the message set request object to hold our request + IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("CA", 13, 0); + requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; + ICustomerQuery CustomerQueryRq = requestMsgSet.AppendCustomerQueryRq(); + CustomerQueryRq.ORCustomerListQuery.ListIDList.Add(ListID); + + string ret = ProcessQBXmlRequest(requestMsgSet.ToXMLString()); + + return requestMsgSet.ToXMLString(); + } + + private static string ParseCustomerId(XDocument xml) + { + XElement CustomerRef = xml.Descendants("CustomerRef").First(); + string ListId = CustomerRef.Element("ListID")?.Value; + return ListId; + } + } }