Esempio n. 1
0
        static string QBConnect(string data)
        {
            RequestProcessor2 rp       = null;
            string            ticket   = null;
            string            response = null;

            try {
                rp = new RequestProcessor2();
                rp.OpenConnection("", "Ghost QuickBooks XML Bridge");
                ticket   = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                response = rp.ProcessRequest(ticket, data);
            } catch (System.Runtime.InteropServices.COMException ex) {
                return("COM Error Description = " + ex.Message + "\n");
            } finally {
                if (ticket != null)
                {
                    rp.EndSession(ticket);
                }
                if (rp != null)
                {
                    rp.CloseConnection();
                }
            };
            return(response);
        }
Esempio n. 2
0
        private List <QBDUnitOfMeasureSet> SyncUnitOfMeasureSets(QuickBooksService service, string ticket, RequestProcessor2 req)
        {
            // Requests to the QuickBooks API are made in QBXML format.
            var doc = new XmlDocument();

            // Add the prolog processing instructions.
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, null));
            doc.AppendChild(doc.CreateProcessingInstruction("qbxml", "version=\"14.0\""));

            XmlElement outer = doc.CreateElement("QBXML");

            doc.AppendChild(outer);

            XmlElement inner = doc.CreateElement("QBXMLMsgsRq");

            outer.AppendChild(inner);
            inner.SetAttribute("onError", "stopOnError");

            // Build the request to get unit of measure sets.
            service.BuildUnitOfMeasureSetQueryRq(doc, inner);

            try
            {
                Logger.Debug(doc.OuterXml);

                var response = req.ProcessRequest(ticket, doc.OuterXml);

                Logger.Debug(response);

                if (string.IsNullOrEmpty(response))
                {
                    return(new List <QBDUnitOfMeasureSet>());
                }

                // Then walk the response.
                var walkReponse = service.WalkUnitOfMeasureSetQueryRs(response);

                if (SaveErrorCount > 0)
                {
                    StatusText += string.Format("{0} - Sync failed. Please correct the {1} errors first.\r\n", DateTime.Now.ToString(), SaveErrorCount);
                    OnPropertyChanged("StatusText");

                    return(new List <QBDUnitOfMeasureSet>());
                }
                else
                {
                    return(walkReponse.Item3);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                return(new List <QBDUnitOfMeasureSet>());
            }
        }
        public string ProcessRequest(string xml)
        {
            // The variable “xmlRequestSet” in the following line represents a fully formed qbXML request set;
            //This snippet omitted the code that assembled the request set in order to keep the
            //example focused on the session and the connection.
            string sendXMLtoQB = MyQbXMLRP2.ProcessRequest(ticket, xml);



            return(sendXMLtoQB);
        }
Esempio n. 4
0
        private static void ExecuteStatement(string outputFile, string XMLInput, ref string ticket, ref RequestProcessor2 rp)
        {
            string response = rp.ProcessRequest(ticket, XMLInput);

            //Console.WriteLine(response);
            StreamWriter wrt = new StreamWriter(outputFile);

            wrt.WriteLine(response);
            wrt.Flush();
            wrt.Close();
        }
Esempio n. 5
0
            internal QBResponse ProcessRequest(QBRequest request)
            {
                string     resp     = rp.ProcessRequest(ticket, request.XML);
                QBResponse response = new QBResponse
                {
                    Data      = resp,
                    Timestamp = DateTime.Now
                };

                return(response);
            }
Esempio n. 6
0
        /// <summary>
        /// Connect with quickbooks and read/write data.
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="qbFilePath"></param>
        /// <returns></returns>
        public static ResponseModel ProcessQuickBookRequest(string xml, string qbFilePath)
        {
            bool sessionBegun          = false;
            bool connectionOpen        = false;
            RequestProcessor2 rp       = null;
            string            ticket   = string.Empty;
            ResponseModel     response = null;

            try
            {
                //Create the Request Processor object
                rp = new RequestProcessor2();

                //Connect to QuickBooks and begin a session
                rp.OpenConnection("12345", "Testing");//id of your .net project and name of your .net project.
                connectionOpen = true;
                //ticket = rp.BeginSession(ConfigurationManager.AppSettings["QuickBookFile"], QBFileMode.qbFileOpenDoNotCare);
                ticket       = rp.BeginSession(qbFilePath, QBFileMode.qbFileOpenDoNotCare);
                sessionBegun = true;

                //Send the request and get the response from QuickBooks
                response = new ResponseModel
                {
                    ResponseString = rp.ProcessRequest(ticket, xml),
                    Succeeded      = true
                };
                //End the session and close the connection to QuickBooks
                rp.EndSession(ticket);
                sessionBegun = false;
                rp.CloseConnection();
                connectionOpen = false;

                //WalkCustomerAddRs(responseStr);
            }
            catch (Exception e)
            {
                if (sessionBegun)
                {
                    rp.EndSession(ticket);
                }
                if (connectionOpen)
                {
                    rp.CloseConnection();
                }
                response = new ResponseModel
                {
                    Message   = e.Message,
                    Succeeded = false
                };
            }

            return(response);
        }
Esempio n. 7
0
        public static string DoRequest(XmlDocument doc)
        {
            RequestProcessor2 rp = null;
            string ticket = null;
            string response = null;
            bool errorOccurred = false;
            int maxTries = 1;
            int tries = 0;

            do
            {
                try
                {
                    tries++;
                    rp = new RequestProcessor2();
                    rp.OpenConnection("QBMT1", "QBMigrationTool");
                    ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                    CheckIfBuildTypeAndQuickBooksFileMatch(rp.GetCurrentCompanyFileName(ticket));
                    response = rp.ProcessRequest(ticket, doc.OuterXml);

                    if (errorOccurred)
                    {
                        Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "DoRequest Retry succeeded.");
                        errorOccurred = false;
                    }
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "Error in DoRequest.  Retrying.  Details: " + e.ToString());
                    //MessageBox.Show("Outer: " + doc.OuterXml);
                    errorOccurred = true;
                }
                catch (Exception e)
                {
                    Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "Error in DoRequest.  Retrying.  Details: " + e.ToString());
                    break;
                }
                finally
                {
                    if (ticket != null)
                    {
                        rp.EndSession(ticket);
                    }
                    if (rp != null)
                    {
                        rp.CloseConnection();
                    }
                }

            } while (errorOccurred && tries <= maxTries);

            return response;
        }
Esempio n. 8
0
 public string sendRequest(string xml)
 {
     try
     {
         var response = rp.ProcessRequest(ticket, xml);
         return(response);
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Esempio n. 9
0
 public string processRequestFromQB(string request)
 {
     try
     {
         return(rp.ProcessRequest(ticket, request));
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         return(null);
     }
 }
Esempio n. 10
0
 private async Task <string> processRequestFromQB(string request)
 {
     try
     {
         return(await Task.Run(() => rp.ProcessRequest(ticket, request)));
     }
     catch (Exception e)
     {
         ErrorList.Add(DateTime.Now, e);
         return(null);
     }
 }
Esempio n. 11
0
        public static string DoRequest(XmlDocument doc)
        {
            RequestProcessor2 rp       = null;
            string            ticket   = null;
            string            response = null;
            bool errorOccurred         = false;
            int  maxTries = 1;
            int  tries    = 0;

            do
            {
                try
                {
                    tries++;
                    rp = new RequestProcessor2();
                    rp.OpenConnection("QBMT1", "QBMigrationTool");
                    ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                    CheckIfBuildTypeAndQuickBooksFileMatch(rp.GetCurrentCompanyFileName(ticket));
                    response = rp.ProcessRequest(ticket, doc.OuterXml);

                    if (errorOccurred)
                    {
                        Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "DoRequest Retry succeeded.");
                        errorOccurred = false;
                    }
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "Error in DoRequest.  Retrying.  Details: " + e.ToString());
                    //MessageBox.Show("Outer: " + doc.OuterXml);
                    errorOccurred = true;
                }
                catch (Exception e)
                {
                    Logging.RototrackErrorLog("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "Error in DoRequest.  Retrying.  Details: " + e.ToString());
                    break;
                }
                finally
                {
                    if (ticket != null)
                    {
                        rp.EndSession(ticket);
                    }
                    if (rp != null)
                    {
                        rp.CloseConnection();
                    }
                }
            } while (errorOccurred && tries <= maxTries);

            return(response);
        }
Esempio n. 12
0
 public bool QueryQB(string query, out string response)
 {
     response = "";
     try
     {
         response = qbRequestProcessor.ProcessRequest(ticket, query);
     }
     catch (Exception ex)
     {
         lastError = "Error = " + ex.Message;
         return(false);
     }
     return(true);
 }
Esempio n. 13
0
 public string Transmit(string request)
 {
     try
     {
         this.ConnectToQB();
         string resp = rp.ProcessRequest(ticket, request);
         //				this.disconnectFromQB();
         return(resp);
     }
     catch (Exception e)
     {
         Logger.LogException(e);
         return(null);
     }
 }
        public override XmlDocument Load(string queryToExecute = "", XmlDocument xDoc = null)
        {
            ConnectToQuickBooks();
            if ((QBProcessor == null) || String.IsNullOrWhiteSpace(SessionID))
            {
                return(null);
            }
            string resultXML = QBProcessor.ProcessRequest(SessionID, QBInputRequests.GetAllItems(ItemType));

            if (xDoc == null)
            {
                xDoc = new XmlDocument();
            }
            xDoc.LoadXml(resultXML);
            return(xDoc);
        }
Esempio n. 15
0
        public void Export()
        {
            bool sessionBegun    = false;
            bool connectionOpen  = false;
            RequestProcessor2 rp = null;

            //Create the Request Processor object
            rp = new RequestProcessor2();

            //Create the XML document to hold our request
            XmlDocument requestXmlDoc = new XmlDocument();

            //Add the prolog processing instructions
            requestXmlDoc.AppendChild(requestXmlDoc.CreateXmlDeclaration("1.0", null, null));
            requestXmlDoc.AppendChild(requestXmlDoc.CreateProcessingInstruction("qbxml", "version=\"8.0\""));

            //Create the outer request envelope tag
            XmlElement outer = requestXmlDoc.CreateElement("QBXML");

            requestXmlDoc.AppendChild(outer);

            //Create the inner request envelope & any needed attributes
            XmlElement inner = requestXmlDoc.CreateElement("QBXMLMsgsRq");

            outer.AppendChild(inner);
            inner.SetAttribute("onError", "stopOnError");
            BuildGeneralDetailReportQueryRq(requestXmlDoc, inner);

            //Connect to QuickBooks and begin a session
            rp.OpenConnection2("", "Sample Code from OSR", QBXMLRPConnectionType.localQBD);
            connectionOpen = true;
            //string ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
            string ticket = rp.BeginSession("C:\\Users\\Public\\Documents\\Intuit\\QuickBooks\\Company Files\\PIYPQB.QBW", QBFileMode.qbFileOpenSingleUser);

            sessionBegun = true;

            //Send the request and get the response from QuickBooks
            string responseStr = rp.ProcessRequest(ticket, requestXmlDoc.OuterXml);

            //End the session and close the connection to QuickBooks
            rp.EndSession(ticket);
            sessionBegun = false;
            rp.CloseConnection();
            connectionOpen = false;

            WalkGeneralDetailReportQueryRs(responseStr);
        }
Esempio n. 16
0
        public string ProcessRequest(string xml)
        {
            RequestProcessor2 MyQbXMLRP2 = new RequestProcessor2();

            MyQbXMLRP2.OpenConnection2("", appName, QBXMLRPConnectionType.localQBD);

            string ticket = MyQbXMLRP2.BeginSession("", QBFileMode.qbFileOpenDoNotCare);

            // The variable “xmlRequestSet” in the following line represents a fully formed qbXML request set;
            //This snippet omitted the code that assembled the request set in order to keep the
            //example focused on the session and the connection.
            string sendXMLtoQB = MyQbXMLRP2.ProcessRequest(ticket, xml);

            MyQbXMLRP2.CloseConnection();

            return(sendXMLtoQB);
        }
Esempio n. 17
0
        // Submit request into Quickbooks and return response
        public string submitRequest(string ticket, string request)
        {
            string response = "";

            try {
                response = rp.ProcessRequest(ticket, request);
            } catch (Exception ex) {
                // Send Error to the Error Log
                string excep = DateTime.Now.ToString() + " [QBParser-submitRequest] " + ex.Message;
                File.AppendAllText("ErrorLog.txt", excep + Environment.NewLine);

                response = "";
                rp.EndSession(ticket);
                rp.CloseConnection();
            }

            return(response);
        }
Esempio n. 18
0
		//connects to quickbooks
		//parameters: request, qbxml string; log, optl bool that prints completed steps to console if true
		//returns string containing xml document on success, empty string on error
		static private string queryQuickBooks(string request, bool log = false)
		{
			RequestProcessor2 rp = null;
			string ticket = null;
			string response = "";
			
			try
			{
				rp = new RequestProcessor2();

				rp.OpenConnection2("", "Proof of Concept", QBXMLRPConnectionType.localQBD);
				if (log) Console.WriteLine("Log: Connection opened");

				ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
				if (log) Console.WriteLine("Log: Session started");

				response = rp.ProcessRequest(ticket, request);
				if (log) Console.WriteLine("Log: Request processed");
			}
			catch (System.Runtime.InteropServices.COMException ex)
			{
				Console.WriteLine("ERROR Connection problem: " + ex.Message);
			}
			finally
			{
				if (ticket != null)
				{
					rp.EndSession(ticket);
					if (log) Console.WriteLine("Log: Session ended");
				}
				if (rp != null)
				{
					rp.CloseConnection();
					if (log) Console.WriteLine("Log: Connection closed");
				}
			}

			return response;
		}
Esempio n. 19
0
        protected string ReadText(QuickBooksXmlEntity module, string data = null)
        {
            RequestProcessor2 request = null;
            string            input   = string.Format(RequestTemp, module.Req, data);

            if (module.RemoveId)
            {
                input = input.Replace("  requestID=\"whatever\"", "");
            }

            string response = "";

            try
            {
                request  = QuickBooksConection2();
                response = request.ProcessRequest(Ticket, input);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                //LogClass.WriteLogLine(string.Format("ERROR Table{0}: {1} *:* {2}", datamap.Req, ex.StackTrace, ex.Message));
                //MessageBox.Show("COM Error Description = " + ex.Message, "COM error");
                //return;
            }
            catch (Exception ex)
            {
                // -- log
            }
            finally
            {
                if (Ticket != null)
                {
                    request?.EndSession(Ticket);
                }
                request?.CloseConnection();
            }

            return(response);
        }
Esempio n. 20
0
        public static string DoRequestRaw(string rawXML)
        {
            RequestProcessor2 rp       = null;
            string            ticket   = null;
            string            response = null;

            try
            {
                rp = new RequestProcessor2();
                rp.OpenConnection("QBMT1", "QBMigrationTool");
                ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                CheckIfBuildTypeAndQuickBooksFileMatch(rp.GetCurrentCompanyFileName(ticket));
                response = rp.ProcessRequest(ticket, rawXML);
                return(response);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show("COM Error Description = " + ex.Message, "COM error");
                return(ex.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "Error in DoRequestRaw.  Details: " + e.ToString(), "Exception");
                return(e.Message);
            }
            finally
            {
                if (ticket != null)
                {
                    rp.EndSession(ticket);
                }
                if (rp != null)
                {
                    rp.CloseConnection();
                }
            }
        }
Esempio n. 21
0
        public void Export(out string responseStrEx, out string responseStrPL)
        {
            Config.InitConfig();

            bool sessionBegun    = false;
            bool connectionOpen  = false;
            RequestProcessor2 rp = null;

            //try
            //{

            rp = new RequestProcessor2();

            //Expense Type
            XmlDocument requestExXmlDoc = new XmlDocument();

            requestExXmlDoc.AppendChild(requestExXmlDoc.CreateXmlDeclaration("1.0", null, null));
            requestExXmlDoc.AppendChild(requestExXmlDoc.CreateProcessingInstruction("qbxml", "version=\"8.0\""));
            XmlElement outerEx = requestExXmlDoc.CreateElement("QBXML");

            requestExXmlDoc.AppendChild(outerEx);
            XmlElement innerEx = requestExXmlDoc.CreateElement("QBXMLMsgsRq");

            outerEx.AppendChild(innerEx);
            innerEx.SetAttribute("onError", "stopOnError");
            ExpenseQueryRq(requestExXmlDoc, innerEx);

            //Profit and Loss
            XmlDocument requestPLXmlDoc = new XmlDocument();

            requestPLXmlDoc.AppendChild(requestPLXmlDoc.CreateXmlDeclaration("1.0", null, null));
            requestPLXmlDoc.AppendChild(requestPLXmlDoc.CreateProcessingInstruction("qbxml", "version=\"8.0\""));
            XmlElement outerPL = requestPLXmlDoc.CreateElement("QBXML");

            requestPLXmlDoc.AppendChild(outerPL);
            XmlElement innerPL = requestPLXmlDoc.CreateElement("QBXMLMsgsRq");

            outerPL.AppendChild(innerPL);
            innerPL.SetAttribute("onError", "stopOnError");
            ProfitAndLossQueryRq(requestPLXmlDoc, innerPL);

            rp.OpenConnection2("", "QuickBooks Connector", QBXMLRPConnectionType.localQBD);

            connectionOpen = true;
            string ticket = "";

            //try
            //{

            //ticket = rp.BeginSession("C:\\Users\\Public\\Documents\\Intuit\\QuickBooks\\Company Files\\PIYPQB.QBW", QBFileMode.qbFileOpenSingleUser);

            ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);

            //if (Config.ConfigVars["qbfilename"].ToString() != "")
            //    ticket = rp.BeginSession(Config.ConfigVars["qbfilename"].ToString(), QBFileMode.qbFileOpenSingleUser);
            //else
            //    ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);

            //}
            //catch (Exception e)
            //{
            //    Helper.Log.Write("Message " + e.Message);
            //}

            sessionBegun = true;

            //Send the request and get the response from QuickBooks
            responseStrEx = rp.ProcessRequest(ticket, requestExXmlDoc.OuterXml);
            responseStrPL = rp.ProcessRequest(ticket, requestPLXmlDoc.OuterXml);

            //End the session and close the connection to QuickBooks
            rp.EndSession(ticket);
            sessionBegun = false;
            rp.CloseConnection();
            connectionOpen = false;


            //}
            //    catch (Exception e)
            //    {
            //        Helper.Log.Write(e.Message);
            //    }
        }
Esempio n. 22
0
 internal XElement ProcessRequest(string ticket, string inputRequest)
 {
     return(XElement.Parse(_requestProcessor.ProcessRequest(ticket, inputRequest)));
 }
Esempio n. 23
0
        private void AddCustomer_Click(object sender, System.EventArgs e)
        {
            //step1: verify that Name is not empty
            String name = CustName.Text.Trim();

            if (name.Length == 0)
            {
                MessageBox.Show("Please enter a value for Name.", "Input Validation");
                return;
            }

            //step2: create the qbXML request
            XmlDocument inputXMLDoc = new XmlDocument();

            inputXMLDoc.AppendChild(inputXMLDoc.CreateXmlDeclaration("1.0", null, null));
            inputXMLDoc.AppendChild(inputXMLDoc.CreateProcessingInstruction("qbxml", "version=\"13.0\""));
            XmlElement qbXML = inputXMLDoc.CreateElement("QBXML");

            inputXMLDoc.AppendChild(qbXML);
            XmlElement qbXMLMsgsRq = inputXMLDoc.CreateElement("QBXMLMsgsRq");

            qbXML.AppendChild(qbXMLMsgsRq);
            qbXMLMsgsRq.SetAttribute("onError", "stopOnError");
            XmlElement custAddRq = inputXMLDoc.CreateElement("CustomerAddRq");

            qbXMLMsgsRq.AppendChild(custAddRq);
            custAddRq.SetAttribute("requestID", "1");
            XmlElement custAdd = inputXMLDoc.CreateElement("CustomerAdd");

            custAddRq.AppendChild(custAdd);
            custAdd.AppendChild(inputXMLDoc.CreateElement("Name")).InnerText = name;
            if (Phone.Text.Length > 0)
            {
                custAdd.AppendChild(inputXMLDoc.CreateElement("Phone")).InnerText = Phone.Text;
            }

            if (rbtEuro.Checked)
            {
                var currency = inputXMLDoc.CreateNode(XmlNodeType.Element, "FullName", "");
                currency.InnerText = "EURO";
                var currencyId = inputXMLDoc.CreateNode(XmlNodeType.Element, "ListID", "");
                currencyId.InnerText = "8000002A-1217255359";

                var currencyRef = inputXMLDoc.CreateElement("CurrencyRef");
                //currencyRef.AppendChild(currency);
                currencyRef.AppendChild(currencyId);
                custAdd.AppendChild(currencyRef);
            }

            //< CurrencyRef >
            //< ListID > 8000002A-1217255359 </ ListID >
            //   < FullName > Euro </ FullName
            //</ CurrencyRef >

            //-< CurrencyRef >
            //< !--opt, not in QBOE, v8.0-- >
            //< ListID > IDTYPE </ ListID >
            //< !--opt-- >
            //< FullName > STRTYPE </ FullName >
            //< !--opt, max length = 64 for QBD | QBCA | QBUK | QBAU-- >
            //</ CurrencyRef >

            string input = inputXMLDoc.OuterXml;
            //step3: do the qbXMLRP request
            RequestProcessor2 rp       = null;
            string            ticket   = null;
            string            response = null;

            try
            {
                rp = new RequestProcessor2();
                rp.OpenConnection("", Configuration.AppName);
                var qBfile = "";
                if (!string.IsNullOrEmpty(txtQbFile.Text))
                {
                    qBfile = txtQbFile.Text;
                }
                ticket = rp.BeginSession(qBfile, QBFileMode.qbFileOpenDoNotCare);

                response = rp.ProcessRequest(ticket, input);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show("COM Error Description = " + ex.Message, "COM error");
                return;
            }
            finally
            {
                if (ticket != null)
                {
                    rp.EndSession(ticket);
                }
                if (rp != null)
                {
                    rp.CloseConnection();
                }
            };

            //step4: parse the XML response and show a message
            XmlDocument outputXMLDoc = new XmlDocument();

            outputXMLDoc.LoadXml(response);
            XmlNodeList qbXMLMsgsRsNodeList = outputXMLDoc.GetElementsByTagName("CustomerAddRs");

            if (qbXMLMsgsRsNodeList.Count == 1) //it's always true, since we added a single Customer
            {
                System.Text.StringBuilder popupMessage = new System.Text.StringBuilder();

                XmlAttributeCollection rsAttributes = qbXMLMsgsRsNodeList.Item(0).Attributes;
                //get the status Code, info and Severity
                string retStatusCode     = rsAttributes.GetNamedItem("statusCode").Value;
                string retStatusSeverity = rsAttributes.GetNamedItem("statusSeverity").Value;
                string retStatusMessage  = rsAttributes.GetNamedItem("statusMessage").Value;
                popupMessage.AppendFormat("statusCode = {0}, statusSeverity = {1}, statusMessage = {2}",
                                          retStatusCode, retStatusSeverity, retStatusMessage);

                //get the CustomerRet node for detailed info

                //a CustomerAddRs contains max one childNode for "CustomerRet"
                XmlNodeList custAddRsNodeList = qbXMLMsgsRsNodeList.Item(0).ChildNodes;
                if (custAddRsNodeList.Count == 1 && custAddRsNodeList.Item(0).Name.Equals("CustomerRet"))
                {
                    XmlNodeList custRetNodeList = custAddRsNodeList.Item(0).ChildNodes;

                    foreach (XmlNode custRetNode in custRetNodeList)
                    {
                        if (custRetNode.Name.Equals("ListID"))
                        {
                            popupMessage.AppendFormat("\r\nCustomer ListID = {0}", custRetNode.InnerText);
                        }
                        else if (custRetNode.Name.Equals("Name"))
                        {
                            popupMessage.AppendFormat("\r\nCustomer Name = {0}", custRetNode.InnerText);
                        }
                        else if (custRetNode.Name.Equals("FullName"))
                        {
                            popupMessage.AppendFormat("\r\nCustomer FullName = {0}", custRetNode.InnerText);
                        }
                    }
                } // End of customerRet

                MessageBox.Show(popupMessage.ToString(), "QuickBooks response");
            } //End of customerAddRs
        }
Esempio n. 24
0
        public void Sync()
        {
            // Disable the buttons.
            IsExitEnabled      = false;
            IsTryEnabled       = false;
            IsStartOverEnabled = false;
            OnPropertyChanged("IsExitEnabled");
            OnPropertyChanged("IsTryEnabled");
            OnPropertyChanged("IsStartOverEnabled");

            // Reset error count.
            ValidationErrorCount = 0;
            SaveErrorCount       = 0;

            StatusText = string.Format("{0} - Starting.\r\n", DateTime.Now.ToString());
            OnPropertyChanged("StatusText");

            var service = new QuickBooksService();

            StatusText += string.Format("{0} - Connecting to QuickBooks.\r\n", DateTime.Now.ToString());
            OnPropertyChanged("StatusText");

            // QBXML request processor must always be closed after use.
            var req = new RequestProcessor2();

            try
            {
                req.OpenConnection2("", "BRIZBEE Integration Utility", QBXMLRPConnectionType.localQBD);
                var ticket = req.BeginSession("", QBFileMode.qbFileOpenDoNotCare);

                StatusText += string.Format("{0} - Syncing.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");

                // Get projects from the server.
                var projects = GetProjects();

                foreach (var project in projects)
                {
                    if (string.IsNullOrEmpty(project))
                    {
                        continue;
                    }

                    var split      = project.Split(':');
                    var name       = project; // Default to original name
                    var parentName = "";

                    // Customer and Job
                    if (split.Length > 1)
                    {
                        name       = split[1];
                        parentName = split[0];

                        // Prepare a new QBXML document to find the parent and its details.
                        var findQBXML    = service.MakeQBXMLDocument();
                        var findDocument = findQBXML.Item1;
                        var findElement  = findQBXML.Item2;

                        // Build the request to find the parent.
                        service.BuildCustomerQueryRq(findDocument, findElement, parentName);

                        // Make the request.
                        Logger.Debug(findDocument.OuterXml);
                        var findResponse = req.ProcessRequest(ticket, findDocument.OuterXml);
                        Logger.Debug(findResponse);

                        // Then walk the response.
                        var findWalkResponse = service.WalkCustomerQueryRs(findResponse);

                        if (findWalkResponse.Item1)
                        {
                            var found  = findWalkResponse.Item3;
                            var parent = found.FirstOrDefault();

                            // Prepare a new QBXML document to create the job with customer details.
                            var jobQBXML    = service.MakeQBXMLDocument();
                            var jobDocument = jobQBXML.Item1;
                            var jobElement  = jobQBXML.Item2;

                            var newJob = parent;
                            newJob.Name   = name;
                            newJob.ListId = "";

                            // Build the request to create the job.
                            service.BuildCustomerAddRqForJob(jobDocument, jobElement, newJob, parentName);

                            // Make the request.
                            Logger.Debug(jobDocument.OuterXml);
                            var jobResponse = req.ProcessRequest(ticket, jobDocument.OuterXml);
                            Logger.Debug(jobResponse);
                        }
                        else
                        {
                            // Prepare a new QBXML document to create the parent.
                            var custQBXML    = service.MakeQBXMLDocument();
                            var custDocument = custQBXML.Item1;
                            var custElement  = custQBXML.Item2;

                            // Build the request to create the parent.
                            service.BuildCustomerAddRqForCustomer(custDocument, custElement, parentName);

                            // Make the request.
                            Logger.Debug(custDocument.OuterXml);
                            var custResponse = req.ProcessRequest(ticket, custDocument.OuterXml);
                            Logger.Debug(custResponse);

                            // Prepare a new QBXML document to create the job.
                            var jobQBXML    = service.MakeQBXMLDocument();
                            var jobDocument = jobQBXML.Item1;
                            var jobElement  = jobQBXML.Item2;

                            // Build the request to create the job.
                            service.BuildCustomerAddRqForJob(jobDocument, jobElement, new QuickBooksCustomer()
                            {
                                Name = name
                            }, parentName);

                            // Make the request.
                            Logger.Debug(jobDocument.OuterXml);
                            var jobResponse = req.ProcessRequest(ticket, jobDocument.OuterXml);
                            Logger.Debug(jobResponse);
                        }
                    }

                    // Customer Only
                    else
                    {
                        // Prepare a new QBXML document.
                        var custQBXML    = service.MakeQBXMLDocument();
                        var custDocument = custQBXML.Item1;
                        var custElement  = custQBXML.Item2;

                        // Build the request to create the customer.
                        service.BuildCustomerAddRqForCustomer(custDocument, custElement, name);

                        // Make the request.
                        var custResponse = req.ProcessRequest(ticket, custDocument.OuterXml);
                    }
                }

                StatusText += string.Format("{0} - Finishing Up.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");

                StatusText += string.Format("{0} - Synced Successfully.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");

                // Close the QuickBooks connection.
                req.EndSession(ticket);
                req.CloseConnection();
                req = null;
            }
            catch (COMException cex)
            {
                Logger.Error(cex.ToString());

                if ((uint)cex.ErrorCode == 0x80040408)
                {
                    StatusText += string.Format("{0} - Sync failed. QuickBooks Desktop is not open.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }
                else
                {
                    StatusText += string.Format("{0} - Sync failed. {1}\r\n", DateTime.Now.ToString(), cex.Message);
                    OnPropertyChanged("StatusText");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());

                StatusText += string.Format("{0} - Sync failed. {1}\r\n", DateTime.Now.ToString(), ex.Message);
                OnPropertyChanged("StatusText");
            }
            finally
            {
                // Enable the buttons.
                IsExitEnabled      = true;
                IsTryEnabled       = true;
                IsStartOverEnabled = true;
                OnPropertyChanged("IsExitEnabled");
                OnPropertyChanged("IsTryEnabled");
                OnPropertyChanged("IsStartOverEnabled");

                // Try to close the QuickBooks connection if it is still open.
                if (req != null)
                {
                    req.CloseConnection();
                    req = null;
                }
            }
        }
Esempio n. 25
0
        public void Sync()
        {
            // Disable the buttons.
            IsExitEnabled      = false;
            IsTryEnabled       = false;
            IsStartOverEnabled = false;
            OnPropertyChanged("IsExitEnabled");
            OnPropertyChanged("IsTryEnabled");
            OnPropertyChanged("IsStartOverEnabled");

            // Reset error count.
            ValidationErrorCount = 0;
            SaveErrorCount       = 0;

            StatusText = string.Format("{0} - Starting.\r\n", DateTime.Now.ToString());
            OnPropertyChanged("StatusText");

            // Open the offset mapping file first, but only if one has been specified.
            List <OffsetMapping> offsetMappings = new List <OffsetMapping>(0);

            if (!string.IsNullOrEmpty(offsetFileName))
            {
                try
                {
                    Logger.Debug($"Opening offset mapping file at {offsetFileName}");

                    using (var reader = new StreamReader(offsetFileName))
                        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                        {
                            offsetMappings = csv.GetRecords <OffsetMapping>().ToList();
                        }

                    Logger.Debug($"There are {offsetMappings.Count} mappings");
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.ToString());

                    StatusText += string.Format("{0} - Sync failed. {1}\r\n", DateTime.Now.ToString(), ex.Message);
                    OnPropertyChanged("StatusText");

                    return;
                }
            }

            var service = new QuickBooksService();

            StatusText += string.Format("{0} - Connecting to QuickBooks.\r\n", DateTime.Now.ToString());
            OnPropertyChanged("StatusText");

            // QBXML request processor must always be closed after use.
            var req = new RequestProcessor2();

            try
            {
                req.OpenConnection2("", "BRIZBEE Integration Utility", QBXMLRPConnectionType.localQBD);
                var ticket          = req.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                var companyFileName = req.GetCurrentCompanyFileName(ticket);

                StatusText += string.Format("{0} - Syncing.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");

                // ------------------------------------------------------------
                // Collect the QuickBooks host details.
                // ------------------------------------------------------------

                // Prepare a new QBXML document.
                var hostQBXML    = service.MakeQBXMLDocument();
                var hostDocument = hostQBXML.Item1;
                var hostElement  = hostQBXML.Item2;
                service.BuildHostQueryRq(hostDocument, hostElement);

                // Make the request.
                var hostResponse = req.ProcessRequest(ticket, hostDocument.OuterXml);

                // Then walk the response.
                var hostWalkResponse = service.WalkHostQueryRsAndParseHostDetails(hostResponse);
                var hostDetails      = hostWalkResponse.Item3;

                // ------------------------------------------------------------
                // Collect the inventory items.
                // ------------------------------------------------------------

                var items = new List <QBDInventoryItem>();

                StatusText += string.Format("{0} - Collecting inventory items.\r\n", DateTime.Now.ToString());
                items       = SyncInventoryItems(service, ticket, req);

                // Cannot continue to sync if there are no items.
                if (items.Count == 0)
                {
                    throw new Exception("There are no inventory items to sync.");
                }

                // Apply the offset items.
                foreach (var item in items)
                {
                    var found = offsetMappings
                                .Where(o => o.InventoryItemFullName == item.FullName)
                                .FirstOrDefault();

                    if (found != null)
                    {
                        item.OffsetItemFullName = found.OffsetItemFullName;
                    }
                }

                // ------------------------------------------------------------
                // Collect the inventory sites.
                // ------------------------------------------------------------

                var sites = new List <QBDInventorySite>();

                // Attempt to sync sites even if they are not enabled or available.
                StatusText += string.Format("{0} - Collecting inventory sites.\r\n", DateTime.Now.ToString());
                sites       = SyncInventorySites(service, ticket, req);

                // ------------------------------------------------------------
                // Collect the units of measure.
                // ------------------------------------------------------------

                var units = new List <QBDUnitOfMeasureSet>();

                // Attempt to sync sites even if they are not enabled or available.
                StatusText += string.Format("{0} - Collecting unit of measure sets.\r\n", DateTime.Now.ToString());
                units       = SyncUnitOfMeasureSets(service, ticket, req);

                // ------------------------------------------------------------
                // Send the items to the server.
                // ------------------------------------------------------------

                // Build the payload.
                var payload = new
                {
                    InventoryItems    = items ?? new List <QBDInventoryItem>(),
                    InventorySites    = sites ?? new List <QBDInventorySite>(),
                    UnitOfMeasureSets = units ?? new List <QBDUnitOfMeasureSet>()
                };

                // Build the request to send the sync details.
                var syncHttpRequest = new RestRequest("api/QBDInventoryItems/Sync", Method.POST);
                syncHttpRequest.AddJsonBody(payload);
                syncHttpRequest.AddQueryParameter("productName", hostDetails.QBProductName);
                syncHttpRequest.AddQueryParameter("majorVersion", hostDetails.QBMajorVersion);
                syncHttpRequest.AddQueryParameter("minorVersion", hostDetails.QBMinorVersion);
                syncHttpRequest.AddQueryParameter("country", hostDetails.QBCountry);
                syncHttpRequest.AddQueryParameter("supportedQBXMLVersion", hostDetails.QBSupportedQBXMLVersions);
                syncHttpRequest.AddQueryParameter("hostname", Environment.MachineName);
                syncHttpRequest.AddQueryParameter("companyFilePath", companyFileName);

                // Execute request.
                var syncHttpResponse = client.Execute(syncHttpRequest);
                if ((syncHttpResponse.ResponseStatus == ResponseStatus.Completed) &&
                    (syncHttpResponse.StatusCode == System.Net.HttpStatusCode.OK))
                {
                    StatusText += string.Format("{0} - Synced Successfully.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }
                else
                {
                    StatusText += $"{DateTime.Now} - {syncHttpResponse.Content}";
                    StatusText += string.Format("{0} - Sync failed.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }

                // Close the QuickBooks connection.
                req.EndSession(ticket);
                req.CloseConnection();
                req = null;
            }
            catch (COMException cex)
            {
                Logger.Error(cex.ToString());

                if ((uint)cex.ErrorCode == 0x80040408)
                {
                    StatusText += string.Format("{0} - Sync failed. QuickBooks Desktop is not open.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }
                else
                {
                    StatusText += string.Format("{0} - Sync failed. {1}\r\n", DateTime.Now.ToString(), cex.Message);
                    OnPropertyChanged("StatusText");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());

                StatusText += string.Format("{0} - Sync failed. {1}\r\n", DateTime.Now.ToString(), ex.Message);
                OnPropertyChanged("StatusText");
            }
            finally
            {
                // Enable the buttons.
                IsExitEnabled      = true;
                IsTryEnabled       = true;
                IsStartOverEnabled = true;
                OnPropertyChanged("IsExitEnabled");
                OnPropertyChanged("IsTryEnabled");
                OnPropertyChanged("IsStartOverEnabled");

                // Try to close the QuickBooks connection if it is still open.
                if (req != null)
                {
                    req.CloseConnection();
                    req = null;
                }
            }
        }
        static void Main(string[] args)
        {
            // The QBXMLRP2 object
            RequestProcessor2 requestProcessor = null;

            // values QBXMLRP2 will return
            bool sessionBegun   = false;
            bool connectionOpen = false;

            // base XML doc vars
            XmlDocument xmlReqDoc   = null;
            XmlElement  qbxml       = null;
            XmlElement  qbxmlMsgsRq = null;

            // successful qbxml response vars
            string ticket      = null;
            string responseStr = null;
            string qbXmlReqObj = null;

            try // 1st - to initialize the base xml doc
            {
                requestProcessor = new RequestProcessor2();

                // Create a new XML document
                xmlReqDoc = new XmlDocument();
                // ROOT - <?xml version="1.0" encoding="utf-8"?>
                xmlReqDoc.AppendChild(xmlReqDoc.CreateXmlDeclaration("1.0", "utf-8", null));
                // ROOT - <?qbxml version="13.0"?>
                xmlReqDoc.AppendChild(xmlReqDoc.CreateProcessingInstruction("qbxml", "version=\"13.0\""));
                // ROOT - <QBXML>...</QBXML>
                qbxml = xmlReqDoc.CreateElement("QBXML");
                xmlReqDoc.AppendChild(xmlReqDoc.CreateElement("QBXML"));
                // child - <QBXMLMsgsRq>...</QBXMLMsgsRq>
                qbxmlMsgsRq = xmlReqDoc.CreateElement("QBXMLMsgsRq");
                qbxml.AppendChild(qbxmlMsgsRq);
                qbxmlMsgsRq.SetAttribute("onError", "stopOnError");
            }
            catch (Exception ex)
            {
                requestProcessor = null;
                LogQuickBooksData(logBase + "initialize-base-xml-doc.xml", ex.Message);
                return;
            }

            Console.WriteLine("__>> RSM - Base Xml doc built");

            try // 2nd - to build the invoice qbXML request objects
            {
                BuildInvoiceQueryRq(xmlReqDoc, qbxmlMsgsRq);
                // BuildInvoiceAddRq(xmlReqDoc, qbxmlMsgsRq);
            }
            catch (Exception ex)
            {
                requestProcessor = null;
                LogQuickBooksData(logBase + "build-qbxml-req-error.xml", ex.Message);
                return;
            }

            Console.WriteLine("__>> RSM - qbXML request object built");

            try // 3rd - to make a request to QuickBooks
            {
                requestProcessor.OpenConnection("", appName);
                connectionOpen = true;
                ticket         = requestProcessor.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                sessionBegun   = true;

                // send request and get response
                responseStr = requestProcessor.ProcessRequest(ticket, qbXmlReqObj);
            }
            catch (Exception ex)
            {
                requestProcessor = null;
                connectionOpen   = false;
                sessionBegun     = false;
            }
        }
Esempio n. 27
0
        private void AddCustomer_Click(object sender, System.EventArgs e)
        {
            //step1: verify that Name is not empty
            String name = CustName.Text.Trim();

            if (name.Length == 0)
            {
                MessageBox.Show("Please enter a value for Name.", "Input Validation");
                return;
            }

            //step2: create the qbXML request
            XmlDocument inputXMLDoc = new XmlDocument();

            inputXMLDoc.AppendChild(inputXMLDoc.CreateXmlDeclaration("1.0", null, null));
            inputXMLDoc.AppendChild(inputXMLDoc.CreateProcessingInstruction("qbxml", "version=\"2.0\""));
            XmlElement qbXML = inputXMLDoc.CreateElement("QBXML");

            inputXMLDoc.AppendChild(qbXML);
            XmlElement qbXMLMsgsRq = inputXMLDoc.CreateElement("QBXMLMsgsRq");

            qbXML.AppendChild(qbXMLMsgsRq);
            qbXMLMsgsRq.SetAttribute("onError", "stopOnError");
            XmlElement custAddRq = inputXMLDoc.CreateElement("CustomerAddRq");

            qbXMLMsgsRq.AppendChild(custAddRq);
            custAddRq.SetAttribute("requestID", "1");
            XmlElement custAdd = inputXMLDoc.CreateElement("CustomerAdd");

            custAddRq.AppendChild(custAdd);
            custAdd.AppendChild(inputXMLDoc.CreateElement("Name")).InnerText = name;
            if (Phone.Text.Length > 0)
            {
                custAdd.AppendChild(inputXMLDoc.CreateElement("Phone")).InnerText = Phone.Text;
            }

            string input = inputXMLDoc.OuterXml;
            //step3: do the qbXMLRP request
            RequestProcessor2 rp       = null;
            string            ticket   = null;
            string            response = null;

            try
            {
                rp = new RequestProcessor2();
                rp.OpenConnection("", "IDN CustomerAdd C# sample");
                ticket   = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                response = rp.ProcessRequest(ticket, input);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show("COM Error Description = " + ex.Message, "COM error");
                return;
            }
            finally
            {
                if (ticket != null)
                {
                    rp.EndSession(ticket);
                }
                if (rp != null)
                {
                    rp.CloseConnection();
                }
            };

            //step4: parse the XML response and show a message
            XmlDocument outputXMLDoc = new XmlDocument();

            outputXMLDoc.LoadXml(response);
            XmlNodeList qbXMLMsgsRsNodeList = outputXMLDoc.GetElementsByTagName("CustomerAddRs");

            if (qbXMLMsgsRsNodeList.Count == 1)              //it's always true, since we added a single Customer
            {
                System.Text.StringBuilder popupMessage = new System.Text.StringBuilder();

                XmlAttributeCollection rsAttributes = qbXMLMsgsRsNodeList.Item(0).Attributes;
                //get the status Code, info and Severity
                string retStatusCode     = rsAttributes.GetNamedItem("statusCode").Value;
                string retStatusSeverity = rsAttributes.GetNamedItem("statusSeverity").Value;
                string retStatusMessage  = rsAttributes.GetNamedItem("statusMessage").Value;
                popupMessage.AppendFormat("statusCode = {0}, statusSeverity = {1}, statusMessage = {2}",
                                          retStatusCode, retStatusSeverity, retStatusMessage);

                //get the CustomerRet node for detailed info

                //a CustomerAddRs contains max one childNode for "CustomerRet"
                XmlNodeList custAddRsNodeList = qbXMLMsgsRsNodeList.Item(0).ChildNodes;
                if (custAddRsNodeList.Count == 1 && custAddRsNodeList.Item(0).Name.Equals("CustomerRet"))
                {
                    XmlNodeList custRetNodeList = custAddRsNodeList.Item(0).ChildNodes;

                    foreach (XmlNode custRetNode in custRetNodeList)
                    {
                        if (custRetNode.Name.Equals("ListID"))
                        {
                            popupMessage.AppendFormat("\r\nCustomer ListID = {0}", custRetNode.InnerText);
                        }
                        else if (custRetNode.Name.Equals("Name"))
                        {
                            popupMessage.AppendFormat("\r\nCustomer Name = {0}", custRetNode.InnerText);
                        }
                        else if (custRetNode.Name.Equals("FullName"))
                        {
                            popupMessage.AppendFormat("\r\nCustomer FullName = {0}", custRetNode.InnerText);
                        }
                    }
                }                 // End of customerRet

                MessageBox.Show(popupMessage.ToString(), "QuickBooks response");
            }             //End of customerAddRs
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            Console.WriteLine("__>> Will start to do purchase order");

            // qb ops controls
            bool doPurchaseOrderAdd = false;
            bool doInvoiceQuery     = true;

            // qbxmlrp2 vars
            RequestProcessor2 qbRequestProcessor;
            string            ticket = null;
            string            purchaseOrderResponse = null;
            string            purchaseOrderInput    = null;

            /* - Main function wide xml vars - */
            bool sessionBegun                = false;
            bool connectionOpen              = false;
            RequestProcessor2 rp             = null;
            XmlDocument       reqXmlDoc      = null;
            XmlElement        qbxml          = null; // aka "outer"
            XmlElement        qbxmlMsgsRq    = null; // aka "inner"
            string            responseStr    = null;
            string            reqXmlDocOuter = null;

            try // to initialize main function base XML Document
            {
                rp = new RequestProcessor2();

                // XML document
                reqXmlDoc = new XmlDocument();

                // <?xml version="1.0" encoding="utf-8"?>
                reqXmlDoc.AppendChild(reqXmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));

                // <?qbxml version="13.0"?>
                reqXmlDoc.AppendChild(reqXmlDoc.CreateProcessingInstruction("qbxml", "version=\"13.0\""));

                // <QBXML>...</QBXML>
                qbxml = reqXmlDoc.CreateElement("QBXML");
                reqXmlDoc.AppendChild(qbxml);

                // <QBXMLMsgsRq>...</QBXMLMsgsRq>
                qbxmlMsgsRq = reqXmlDoc.CreateElement("QBXMLMsgsRq");
                qbxml.AppendChild(qbxmlMsgsRq);
                qbxmlMsgsRq.SetAttribute("onError", "stopOnError");
            }
            catch (Exception ex)
            {
                rp = null;
                LogQuickBooksData(MessageSetRq.logBase + "invoice-query\\StartingVarsError.xml", ex.Message);
                return;
            }

            try // to build the request message sets
            {
                reqXmlDocOuter = BuildInvoiceQueryRq(reqXmlDoc, qbxmlMsgsRq);
            }
            catch (Exception ex)
            {
                rp = null;
                LogQuickBooksData(MessageSetRq.logBase + "invoice-query\\RequestMessagesError.xml", ex.Message);
                return;
            }

            try // to send the MessageSetRequest
            {
                // QBXMLRPConnectionType.localQBD
                rp.OpenConnection("", appName);
                connectionOpen = true;
                ticket         = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                sessionBegun   = true;

                // send request and get response
                responseStr = rp.ProcessRequest(ticket, reqXmlDocOuter);

                LogQuickBooksData(
                    logBase + "invoice-query\\RedstoneInvoiceQueryResponse.xml",
                    responseStr
                    );

                // end the session and close the connection to quickbooks
                rp.EndSession(ticket);
                sessionBegun = false;
                rp.CloseConnection();
                connectionOpen = false;

                //TODO: Walk qbXML response
            }
            catch (Exception ex)
            {
                rp = null;
                LogQuickBooksData(
                    logBase + "invoice-query\\SendReqError.xml", ex.Message
                    );

                if (sessionBegun)
                {
                    rp.EndSession(ticket);
                }

                if (connectionOpen)
                {
                    rp.CloseConnection();
                }

                return;
            }

            Console.WriteLine("__>> Line 290 ish");

            //TODO: refactor this to conform to new way to constructing the Request Message Set
            if (doPurchaseOrderAdd)
            {
                //------------------------------------------------------------
                // to do a "PurchaseOrderAdd" op
                try
                {
                    //-- do the qbXMLRP request
                    qbRequestProcessor = new RequestProcessor2();
                    qbRequestProcessor.OpenConnection("", "Redstone Print and Mail Data Engineering");
                    ticket = qbRequestProcessor.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                    ////-- VERY IMPORTANT, invoke the function that actually constructs the qbXML
                    purchaseOrderInput = PurchaseOrderAdd_AddXml();

                    purchaseOrderResponse = qbRequestProcessor.ProcessRequest(ticket, purchaseOrderInput);
                    LogTxtData(@"C:\Temp\PurchaseOrderAddResponse_object.xml", purchaseOrderResponse);

                    if (ticket != null)
                    {
                        qbRequestProcessor.EndSession(ticket);
                    }

                    qbRequestProcessor.CloseConnection();
                }
                catch (Exception ex)
                {
                    qbRequestProcessor = null;
                    LogTxtData(@"C:\Temp\PurchaseOrderAddRequestError.xml", ex.Message);
                    return;
                }

                //------------------------------------------------------------
                // to parse the "PurchaseOrderAdd" response
                try
                {
                    XmlDocument outputXmlPurchaseOrderAdd = new XmlDocument();
                    outputXmlPurchaseOrderAdd.LoadXml(purchaseOrderResponse);
                    XmlNodeList qbXmlMsgsRsNodeList =
                        outputXmlPurchaseOrderAdd.GetElementsByTagName("PurchaseOrderAddRs");

                    if (qbXmlMsgsRsNodeList.Count == 1)
                    {
                        StringBuilder txtMessage = new StringBuilder();

                        XmlAttributeCollection rsAttributes = qbXmlMsgsRsNodeList.Item(0).Attributes;
                        // get statusCode, statusSeverity, statusMessage
                        string statusCode     = rsAttributes.GetNamedItem("statusCode").Value;
                        string statusSeverity = rsAttributes.GetNamedItem("statusSeverity").Value;
                        string statusMessage  = rsAttributes.GetNamedItem("statusMessage").Value;
                        txtMessage.AppendFormat(
                            "statusCode = {0}, statusSeverity = {1}, statusMessage = {2}",
                            statusCode, statusSeverity, statusMessage
                            );

                        // get PurchaseOrderAddRs > PurchaseOrderRet node
                        XmlNodeList purchaseOrderAddRsNodeList = qbXmlMsgsRsNodeList.Item(0).ChildNodes;
                        if (purchaseOrderAddRsNodeList.Item(0).Name.Equals("PurchaseOrderRet"))
                        {
                            XmlNodeList purchaseOrderAddRetNodeList = purchaseOrderAddRsNodeList.Item(0).ChildNodes;
                            foreach (XmlNode purchaseOrderAddRetNode in purchaseOrderAddRetNodeList)
                            {
                                if (purchaseOrderAddRetNode.Name.Equals("TxnID"))
                                {
                                    txtMessage.AppendFormat(
                                        "\r\n__>> Purchase_Order_Add TxnID = {0}",
                                        purchaseOrderAddRetNode.InnerText
                                        );
                                }
                                else if (purchaseOrderAddRetNode.Name.Equals("VendorRef"))
                                {
                                    txtMessage.AppendFormat(
                                        "\r\n__>> Purchase_Order_Add inner xml = {0}",
                                        purchaseOrderAddRetNode.InnerXml
                                        );
                                }
                            }
                        }

                        LogTxtData(@"C:\Temp\PurchaseOrderAddResponse.txt", txtMessage.ToString());
                    }
                }
                catch (Exception ex)
                {
                    const string customMessage = "JHA - Error while parsing purchase order response: ";
                    qbRequestProcessor = null;
                    LogTxtData(@"C:\Temp\PurchaseOrderAddResponseError.xml", customMessage + ex.Message);
                    return;
                }
            }
        }
Esempio n. 29
0
 public static string DoRequestRaw(string rawXML)
 {
     RequestProcessor2 rp = null;
     string ticket = null;
     string response = null;
     try
     {
         rp = new RequestProcessor2();
         rp.OpenConnection("QBMT1", "QBMigrationTool");
         ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
         CheckIfBuildTypeAndQuickBooksFileMatch(rp.GetCurrentCompanyFileName(ticket));
         response = rp.ProcessRequest(ticket, rawXML);
         return response;
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         MessageBox.Show("COM Error Description = " + ex.Message, "COM error");
         return ex.Message;
     }
     catch (Exception e)
     {
         MessageBox.Show("QBMigrationTool: " + RototrackConfig.GetBuildType() + ": " + "Error in DoRequestRaw.  Details: " + e.ToString(), "Exception");
         return e.Message;
     }
     finally
     {
         if (ticket != null)
         {
             rp.EndSession(ticket);
         }
         if (rp != null)
         {
             rp.CloseConnection();
         }
     }
 }
Esempio n. 30
0
        public void Reverse()
        {
            // Disable the buttons.
            IsExitEnabled      = false;
            IsTryEnabled       = false;
            IsStartOverEnabled = false;
            OnPropertyChanged("IsExitEnabled");
            OnPropertyChanged("IsTryEnabled");
            OnPropertyChanged("IsStartOverEnabled");

            // Reset error count.
            SaveErrorCount = 0;

            StatusText = string.Format("{0} - Starting.\r\n", DateTime.Now.ToString());
            OnPropertyChanged("StatusText");

            var service = new QuickBooksService();

            StatusText += string.Format("{0} - Connecting to QuickBooks.\r\n", DateTime.Now.ToString());
            OnPropertyChanged("StatusText");

            // QBXML request processor must always be closed after use.
            var req = new RequestProcessor2();

            try
            {
                req.OpenConnection2("", "BRIZBEE Integration Utility", QBXMLRPConnectionType.localQBD);
                var ticket          = req.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                var companyFileName = req.GetCurrentCompanyFileName(ticket);

                StatusText += string.Format("{0} - Reversing.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");


                // ------------------------------------------------------------
                // Collect the QuickBooks host details.
                // ------------------------------------------------------------

                // Prepare a new QBXML document.
                var hostQBXML    = service.MakeQBXMLDocument();
                var hostDocument = hostQBXML.Item1;
                var hostElement  = hostQBXML.Item2;
                service.BuildHostQueryRq(hostDocument, hostElement);

                // Make the request.
                var hostResponse = req.ProcessRequest(ticket, hostDocument.OuterXml);

                // Then walk the response.
                var hostWalkResponse = service.WalkHostQueryRsAndParseHostDetails(hostResponse);
                var hostDetails      = hostWalkResponse.Item3;


                // ------------------------------------------------------------
                // Prepare the reverse request.
                // ------------------------------------------------------------

                string   reverseTransactionType = Application.Current.Properties["ReverseTransactionType"] as string;
                string   transactionType        = "";
                string[] selectedTxnIds         = new string[] { };
                string   syncId = "";

                if (reverseTransactionType == "Punches")
                {
                    var selectedSync = Application.Current.Properties["SelectedSync"] as QuickBooksDesktopExport;

                    selectedTxnIds  = selectedSync.TxnIDs.Split(',');
                    transactionType = "TimeTracking";
                    syncId          = selectedSync.Id.ToString();
                }
                else if (reverseTransactionType == "Consumption")
                {
                    var selectedSync = Application.Current.Properties["SelectedSync"] as QBDInventoryConsumptionSync;

                    if (Path.GetFileName(companyFileName) != selectedSync.HostCompanyFileName)
                    {
                        throw new Exception("The open company file in QuickBooks is not the same as the one that was synced.");
                    }

                    selectedTxnIds  = selectedSync.TxnIDs.Split(',');
                    transactionType = selectedSync.RecordingMethod; // InventoryAdjustment, SalesReceipt, or Bill
                    syncId          = selectedSync.Id.ToString();
                }


                // ------------------------------------------------------------
                // Reverse the transaction.
                // ------------------------------------------------------------

                foreach (var txnId in selectedTxnIds)
                {
                    // Prepare a new QBXML document.
                    var delQBXML    = service.MakeQBXMLDocument();
                    var delDocument = delQBXML.Item1;
                    var delElement  = delQBXML.Item2;
                    service.BuildTxnDelRq(delDocument, delElement, transactionType, txnId); // InventoryAdjustment, SalesReceipt, TimeTracking, or Bill

                    // Make the request.
                    Logger.Debug(delDocument.OuterXml);
                    var delResponse = req.ProcessRequest(ticket, delDocument.OuterXml);
                    Logger.Debug(delResponse);

                    // Then walk the response.
                    var delWalkResponse = service.WalkTxnDelRs(delResponse);
                }

                // ------------------------------------------------------------
                // Send the request to the server.
                // ------------------------------------------------------------

                // Build the request.
                if (reverseTransactionType == "Consumption")
                {
                    var syncHttpRequest = new RestRequest("api/QBDInventoryConsumptionSyncs/Reverse", Method.POST);
                    syncHttpRequest.AddQueryParameter("id", syncId);

                    // Execute request.
                    var syncHttpResponse = client.Execute(syncHttpRequest);
                    if ((syncHttpResponse.ResponseStatus == ResponseStatus.Completed) &&
                        (syncHttpResponse.StatusCode == System.Net.HttpStatusCode.OK))
                    {
                        StatusText += string.Format("{0} - Reversed Successfully.\r\n", DateTime.Now.ToString());
                        OnPropertyChanged("StatusText");
                    }
                    else
                    {
                        StatusText += $"{DateTime.Now} - {syncHttpResponse.Content}";
                        StatusText += string.Format("{0} - Reverse failed.\r\n", DateTime.Now.ToString());
                        OnPropertyChanged("StatusText");
                    }
                }
                else
                {
                    StatusText += string.Format("{0} - Reversed Successfully.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }

                // Close the QuickBooks connection.
                req.EndSession(ticket);
                req.CloseConnection();
                req = null;
            }
            catch (COMException cex)
            {
                Logger.Error(cex.ToString());

                if ((uint)cex.ErrorCode == 0x80040408)
                {
                    StatusText += string.Format("{0} - Reverse failed. QuickBooks Desktop is not open.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }
                else
                {
                    StatusText += string.Format("{0} - Reverse failed. {1}\r\n", DateTime.Now.ToString(), cex.Message);
                    OnPropertyChanged("StatusText");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());

                StatusText += string.Format("{0} - Reverse failed. {1}\r\n", DateTime.Now.ToString(), ex.Message);
                OnPropertyChanged("StatusText");
            }
            finally
            {
                // Enable the buttons.
                IsExitEnabled      = true;
                IsTryEnabled       = true;
                IsStartOverEnabled = true;
                OnPropertyChanged("IsExitEnabled");
                OnPropertyChanged("IsTryEnabled");
                OnPropertyChanged("IsStartOverEnabled");

                // Try to close the QuickBooks connection if it is still open.
                if (req != null)
                {
                    req.CloseConnection();
                    req = null;
                }
            }
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            Console.WriteLine("__>> Will start to do purchase order");
            RequestProcessor2 qbRequestProcessor;
            string            ticket = null;
            string            purchaseOrderResponse = null;
            string            purchaseOrderInput    = null;

            // to add a purchase order
            try
            {
                //-- do the qbXMLRP request
                qbRequestProcessor = new RequestProcessor2();
                qbRequestProcessor.OpenConnection("", "Redstone Print and Mail Data Engineering");
                ticket = qbRequestProcessor.BeginSession("", QBFileMode.qbFileOpenDoNotCare);
                // // VERY IMPORTANT, invoke the function that actually constructs the qbXML
                purchaseOrderInput = PurchaseOrderAdd_AddXml();

                purchaseOrderResponse = qbRequestProcessor.ProcessRequest(ticket, purchaseOrderInput);
                LogTxtData(@"C:\Temp\PurchaseOrderAddResponse_object.xml", purchaseOrderResponse);

                if (ticket != null)
                {
                    qbRequestProcessor.EndSession(ticket);
                }

                qbRequestProcessor.CloseConnection();
            }
            catch (Exception ex)
            {
                qbRequestProcessor = null;
                LogTxtData(@"C:\Temp\PurchaseOrderAddRequestError.xml", ex.Message);
                return;
            }

            // to parse the response
            try
            {
                XmlDocument outputXmlPurchaseOrderAdd = new XmlDocument();
                outputXmlPurchaseOrderAdd.LoadXml(purchaseOrderResponse);
                XmlNodeList qbXmlMsgsRsNodeList = outputXmlPurchaseOrderAdd.GetElementsByTagName("PurchaseOrderAddRs");

                if (qbXmlMsgsRsNodeList.Count == 1)
                {
                    StringBuilder txtMessage = new StringBuilder();

                    XmlAttributeCollection rsAttributes = qbXmlMsgsRsNodeList.Item(0).Attributes;
                    // get statusCode, statusSeverity, statusMessage
                    string statusCode     = rsAttributes.GetNamedItem("statusCode").Value;
                    string statusSeverity = rsAttributes.GetNamedItem("statusSeverity").Value;
                    string statusMessage  = rsAttributes.GetNamedItem("statusMessage").Value;
                    txtMessage.AppendFormat(
                        "statusCode = {0}, statusSeverity = {1}, statusMessage = {2}",
                        statusCode, statusSeverity, statusMessage
                        );

                    // get PurchaseOrderAddRs > PurchaseOrderRet node
                    XmlNodeList purchaseOrderAddRsNodeList = qbXmlMsgsRsNodeList.Item(0).ChildNodes;
                    if (purchaseOrderAddRsNodeList.Item(0).Name.Equals("PurchaseOrderRet"))
                    {
                        XmlNodeList purchaseOrderAddRetNodeList = purchaseOrderAddRsNodeList.Item(0).ChildNodes;
                        foreach (XmlNode purchaseOrderAddRetNode in purchaseOrderAddRetNodeList)
                        {
                            if (purchaseOrderAddRetNode.Name.Equals("TxnID"))
                            {
                                txtMessage.AppendFormat(
                                    "\r\n__>> Purchase_Order_Add TxnID = {0}",
                                    purchaseOrderAddRetNode.InnerText
                                    );
                            }
                            else if (purchaseOrderAddRetNode.Name.Equals("VendorRef"))
                            {
                                txtMessage.AppendFormat(
                                    "\r\n__>> Purchase_Order_Add inner xml = {0}",
                                    purchaseOrderAddRetNode.InnerXml
                                    );
                            }
                        }
                    }

                    LogTxtData(@"C:\Temp\PurchaseOrderAddResponse.txt", txtMessage.ToString());
                }
            }
            catch (Exception ex)
            {
                const string customMessage = "JHA - Error while parsing purchase order response: ";
                qbRequestProcessor = null;
                LogTxtData(@"C:\Temp\PurchaseOrderAddResponseError.xml", customMessage + ex.Message);
                return;
            }

            try
            {
                //
            }
            catch (Exception ex)
            {
                //
            }
        }
Esempio n. 32
0
        private void ProcessInvoice(VendIvc invoice, ApexDataDataContext apexData)
        {
            PO po = apexData.POs.Where(s => s.Po1 == invoice.PO).SingleOrDefault(); //get the corresponding P/O

            if (po == null)
            {
                _StatusLines.Add(new StatusLine
                {
                    Invoice = invoice.Invoice,
                    PO      = invoice.PO.Trim(),
                    Message = "The invoice points to an invalid P/O!?"
                });
                return;
            }
            if (po.Vendor == null)
            {
                _StatusLines.Add(new StatusLine
                {
                    Invoice = invoice.Invoice,
                    PO      = invoice.PO.Trim(),
                    Message = "There is no vendor on this P/O"
                });
                return;
            }

            Job job = apexData.Jobs.Where(s => s.Job1 == po.Job).SingleOrDefault(); //get the job

            if (job == null)
            {
                _StatusLines.Add(new StatusLine
                {
                    Invoice = invoice.Invoice,
                    PO      = invoice.PO.Trim(),
                    Message = "There is no job on this P/O"
                });
                return;
            }

            QBJob qbjob = apexData.QBJobs.Where(s => s.ApexCompany == _ApexTargetCompany &&
                                                s.ApexJobID == po.Job).SingleOrDefault();

            if (qbjob == null)
            {
                _StatusLines.Add(new StatusLine
                {
                    Invoice = invoice.Invoice,
                    PO      = invoice.PO.Trim(),
                    Message = "This P/O has an invalid QuickBooks job reference"
                });
                return;
            }

            QBVendor qbvendor = apexData.QBVendors.Where(s => s.ApexCompany == _ApexTargetCompany &&
                                                         s.ApexVendorID == po.Vendor).SingleOrDefault();

            if (qbvendor == null)
            {
                _StatusLines.Add(new StatusLine
                {
                    Invoice = invoice.Invoice,
                    PO      = invoice.PO.Trim(),
                    Message = "This P/O has an invalid QuickBooks vendor reference"
                });
                return;
            }

            var qbxml = new QBXML();

            qbxml.ItemsElementName = new ItemsChoiceType99[1] {
                ItemsChoiceType99.QBXMLMsgsRq
            };
            var qbMsgsRq = new QBXMLMsgsRq();

            qbMsgsRq.onError = QBXMLMsgsRqOnError.continueOnError;

            var billaddrq = new BillAddRqType();

            billaddrq.requestID = "1";

            TermsRef termsref = new TermsRef
            {
                FullName = po.VendorTerms
            };

            string ApexGLRef = apexData.Costcodes
                               .Where(s => s.Schedule == "STD" && s.CostCode1 == po.POLines.Select(l => l.CostCode).FirstOrDefault())
                               .Select(s => s.GL).FirstOrDefault();

            if (String.IsNullOrEmpty(ApexGLRef))
            {
                ApexGLRef = "M";
            }

            string QBGLAcctFullName = GLAcctUtility.GLAcctList
                                      .Where(s => s.ApexCompany == _ApexTargetCompany && s.ApexGLRef == ApexGLRef)
                                      .Select(s => s.QBGLAcctFullName).SingleOrDefault();

            AccountRef accountref = new AccountRef
            {
                FullName = QBGLAcctFullName
            };

            AccountRef creditaccountref = new AccountRef
            {
                FullName = "Cash Discount on Payables"
            };

            //Classes in QuickBooks equate to Divisions in Apex for this client
            ClassRef classref = new ClassRef
            {
                FullName = apexData.Divisions.Where(s => s.Company == po.Company && s.Division1 == po.Division).Select(s => s.Name).SingleOrDefault()
            };

            CustomerRef customerref = new CustomerRef
            {
                ListID = qbjob.QBListID
            };

            ExpenseLineAdd expenseline = new ExpenseLineAdd
            {
                AccountRef  = accountref,
                Amount      = invoice.IvcAmt?.ToString("F2"),
                CustomerRef = customerref,
                Memo        = job.Job1 + " " + qbjob.QBJobName.Substring(0, qbjob.QBJobName.IndexOf(':'))
            };

            if (classref.FullName != null)
            {
                expenseline.ClassRef = classref;
            }

            ExpenseLineAdd[] expenseLines;

            if ((invoice.Discount ?? 0) != 0)  //Add an expense line for the discount amount if the discount is not zero
            {
                ExpenseLineAdd creditexpenseline = new ExpenseLineAdd
                {
                    AccountRef = creditaccountref,
                    Amount     = (0 - invoice.Discount ?? 0).ToString("F2"),
                    ClassRef   = classref,
                    Memo       = job.Job1 + " " + qbjob.QBJobName.Substring(0, qbjob.QBJobName.IndexOf(':'))
                };

                expenseLines    = new ExpenseLineAdd[2];
                expenseLines[0] = expenseline;
                expenseLines[1] = creditexpenseline;
            }
            else
            {
                expenseLines    = new ExpenseLineAdd[1];
                expenseLines[0] = expenseline;
            }

            VendorRef vendorref = new VendorRef
            {
                ListID = qbvendor.QBListID
            };

            var billadd = new BillAdd
            {
                DueDate        = invoice.PayDate?.ToString("yyyy-MM-dd"),
                Memo           = "From Apex",
                RefNumber      = invoice.Invoice,
                TermsRef       = termsref,
                TxnDate        = invoice.IvcDate?.ToString("yyyy-MM-dd"),
                ExpenseLineAdd = expenseLines,
                VendorRef      = vendorref
            };

            qbMsgsRq.Items = new object[1] {
                billaddrq
            };
            qbxml.Items = new object[1] {
                qbMsgsRq
            };
            billaddrq.BillAdd = billadd;

            XmlSerializer           serializer = new XmlSerializer(typeof(QBXML));
            XmlSerializerNamespaces ns         = new XmlSerializerNamespaces();

            ns.Add("", ""); //Don't use a namespace in the XML for QuickBooks
            MemoryStream ms = new MemoryStream();

            serializer.Serialize(ms, qbxml, ns);
            ms.Seek(0, SeekOrigin.Begin);
            var    sr         = new StreamReader(ms);
            string xmlRequest = sr.ReadToEnd();

            xmlRequest = xmlRequest.Replace("<?xml version=\"1.0\"?>", "<?xml version=\"1.0\"?><?qbxml version=\"4.0\"?>");
            if (DEBUGMODE)
            {
                File.WriteAllText("c:\\QB\\BillAddQBXML.xml", xmlRequest);
            }
            _Response = _Rp.ProcessRequest(_Ticket, xmlRequest);
            if (DEBUGMODE)
            {
                File.WriteAllText("c:\\QB\\BillAddResponse.xml", _Response);
            }

            QBXML  rsXML      = GetQbxml(serializer);
            string message    = ((BillAddRsType)((QBXMLMsgsRs)rsXML?.Items?[0])?.Items?[0]).statusMessage;
            string statuscode = ((BillAddRsType)((QBXMLMsgsRs)rsXML?.Items?[0])?.Items?[0]).statusCode;

            _StatusLines.Add(new StatusLine
            {
                Invoice    = invoice.Invoice,
                PO         = invoice.PO.Trim(),
                Message    = message,
                StatusCode = statuscode
            });

            if (statuscode == "0") //Apex's part is done now that the invoice has been successfully sent to QuickBooks to be paid
            {
                QBInvoice qbIvc = new QBInvoice
                {
                    Invoice  = invoice.Invoice,
                    PO       = invoice.PO,
                    SentDate = DateTime.Now
                };
                apexData.QBInvoices.InsertOnSubmit(qbIvc);

                invoice.IvcStatus = "P";
                apexData.SubmitChanges();
            }
        }