コード例 #1
0
ファイル: QBUtils.cs プロジェクト: ZochNet/QBMigrationTool
        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;
        }
コード例 #2
0
        public void Disconnect()
        {
            if (ticket != null && MyQbXMLRP2 != null)
            {
                MyQbXMLRP2.EndSession(ticket);
            }

            if (MyQbXMLRP2 != null)
            {
                MyQbXMLRP2.CloseConnection();
            }

            MyQbXMLRP2 = null;
            ticket     = null;
        }
コード例 #3
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);
        }
コード例 #4
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);
        }
コード例 #5
0
ファイル: QBConnect.cs プロジェクト: estvis/QBConnect
 private void disconnectFromQB()
 {
     if (ticket != null)
     {
         try
         {
             rp.EndSession(ticket);
             ticket = null;
             rp.CloseConnection();
             rp = null;
         }
         catch (Exception e)
         {
             ErrorList.Add(DateTime.Now, e);
         }
     }
 }
コード例 #6
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;
		}
コード例 #7
0
ファイル: Connector.cs プロジェクト: vlazarte/Conobra
        public void Disconnect()
        {
            if (Config.IsProduction == false)
            {
                return;
            }

            if (localhost == true)
            {
                return;
            }
            try
            {
                rp.EndSession(ticket);
                ticket = null;
                rp.CloseConnection();
            }
            catch (Exception ex)
            {
                throw new Exception("Error al desconectar a Quickbooks: " + ex.Message);
            }
        }
コード例 #8
0
 public void CloseSession()
 {
     if (_connectionIsOpen)
     {
         if (_session != null)
         {
             if (_log.IsDebugEnabled)
             {
                 _log.DebugFormat("Closing Session Ticket {0}", _sessionTicket);
             }
             _requestProcessor.EndSession(_sessionTicket);
             _session       = null;
             _sessionTicket = null;
         }
         if (_log.IsDebugEnabled)
         {
             _log.Debug("Closing Connection");
         }
         _requestProcessor.CloseConnection();
         _connectionIsOpen = false;
     }
 }
コード例 #9
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);
        }
コード例 #10
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();
                }
            }
        }
コード例 #11
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;
                }
            }
        }
コード例 #12
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                _Rp = new RequestProcessor2();
                _Rp.OpenConnection("", "Apex Interface");
                _Ticket            = _Rp.BeginSession("", Interop.QBXMLRP2.QBFileMode.qbFileOpenDoNotCare);
                _QBCompanyName     = Path.GetFileName(_Rp.GetCurrentCompanyFileName(_Ticket));
                _ApexTargetCompany = GetApexTargetCompany(_QBCompanyName);
                if (_ApexTargetCompany == "*") //invalid company open
                {
                    Application.Exit();
                    return;
                }
                lblApexCompany.Text    = "Quickbooks Company: " + Path.GetFileName(_QBCompanyName);
                lblApexCompany.Visible = true;
                lblApexCompany.Refresh();

                //For efficiency we are creating these items once and reusing them for each QuickBooks transfer
                XmlSerializer           serializer = new XmlSerializer(typeof(QBXML));
                XmlSerializerNamespaces ns         = new XmlSerializerNamespaces();
                ns.Add("", "");


                var qbxml = new QBXML();
                qbxml.ItemsElementName = new ItemsChoiceType99[1] {
                    ItemsChoiceType99.QBXMLMsgsRq
                };
                qbxml.Items = new object[1];
                var qbMsgsRq = new QBXMLMsgsRq();
                qbMsgsRq.Items   = new object[1];
                qbMsgsRq.onError = QBXMLMsgsRqOnError.stopOnError;

                Cursor.Current = Cursors.WaitCursor;

                try
                {
                    StatusLabel.Text = "Receiving jobs...";
                    TransferJobs(serializer, ns, qbxml, qbMsgsRq);

                    StatusLabel.Text = "Receiving vendors...";
                    TransferVendors(serializer, ns, qbxml, qbMsgsRq);

                    StatusLabel.Text = "Receiving terms...";
                    TransferTerms(serializer, ns, qbxml, qbMsgsRq);

                    if (DEBUGMODE)
                    {
                        StatusLabel.Text = "Receiving accounts...";
                        TransferAccounts(serializer, ns, qbxml, qbMsgsRq);

                        StatusLabel.Text = "Receiving classes...";
                        TransferClasses(serializer, ns, qbxml, qbMsgsRq);
                    }
                }
                finally
                {
                    StatusLabel.Text = "";
                    Cursor.Current   = Cursors.Default;
                }

                MessageBox.Show("QuickBooks data has been imported", "Importing complete");
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show("COM Error Description = " + ex.Message, "COM error");
                return;
            }
            finally
            {
                StatusLabel.Text = "";

                if (_Ticket != null)
                {
                    _Rp.EndSession(_Ticket);
                }
                if (_Rp != null)
                {
                    _Rp.CloseConnection();
                }
            };
        }
コード例 #13
0
        //THIS IS INVALUABLE
        //https://developer-static.intuit.com/qbSDK-current/Common/newOSR/index.html


        /*ALSO THIS NEEDS TO BE LOOKED AT AT SOME POINT - This is how we will map autofile records with Reckon invoices and bills for updating and adding new items to exisintg bills
         *
         * defMacro
         * Note that defMacro was introduced with SDK 2.0, so it only works with 2.0 and higher requests. You can use the defMacro attribute to assign a name to the TxnID or TxnListID that this aggregate will return. This way you can refer to the transaction by name in a later request. For example, if you were using the qbXML API and you defined an invoice add request with the name TxnID:RecvPmt1234, as shown below, then you could refer to that invoice by name in a later receive payment add request:
         *
         * <InvoiceAddRq>
         * <InvoiceAdd defMacro= "TxnID:RecvPmt1234">
         * . . .
         * <ReceivePaymentAddRq>
         * <ReceivePaymentAdd>
         * . . .
         * <TxnID useMacro="TxnID:RecvPmt1234"/>
         * . . .
         *
         * If you use macros with QBOE...
         * There may be a buug in the QBOE implementation of this feature. If this feature is not working for you in QBOE, try stripping the prefix "TxnID:" from the name of the useMacro. For example, defMacro="TxnID:RecvPmt1234" and useMacro="RecvPmt1234"
         */



        public bool connectToQB(string companyFile)
        {
            //int authflags = 0;
            //authflags = authflags | 0x01;



            //int authFlags = 0x1 - 0x2 - 0x4;

            //var qbXMLCOM = new RequestProcessor2();
            //var prefs = new AuthPreferences();
            //prefs = qbXMLCOM.AuthPreferences as AuthPreferences;
            //prefs.PutAuthFlags(authFlags);

            //qbXMLCOM.OpenConnection(appID, appName);

            //ticket = qbXMLCOM.BeginSession(companyFile, mode);
            //var versions = qbXMLCOM.get_QBXMLVersionsForSession(ticket);
            //maxVersion = versions.GetValue(versions.Length - 1).ToString();
            //return true;


            //Dim authFlags As Long
            //authFlags = 0
            //authFlags = authFlags Or & H8 &
            //authFlags = authFlags Or & H4 &
            //authFlags = authFlags Or & H2 &
            //authFlags = authFlags Or & H1 &
            //authFlags = authFlags Or & H80000000
            //Dim qbXMLCOM As QBXMLRP2Lib.RequestProcessor2
            //Dim prefs As QBXMLRP2Lib.AuthPreferences
            //Set prefs = qbXMLCOM.AuthPreferences
            //prefs.PutAuthFlags(authFlags)
            int authFlags = 0;

            authFlags = 0;
            authFlags = (int)(authFlags | 0x8L);
            authFlags = (int)(authFlags | 0x4L);
            authFlags = (int)(authFlags | 0x2L);
            authFlags = (int)(authFlags | 0x1L);
//            int authFlags = 0x1 - 0x2 - 0x4;
            //var rp = new RequestProcessor2();
            var prefs = (AuthPreferences)rp.AuthPreferences;  //new AuthPreferences();

//            prefs = (AuthPreferences)qbXMLCOM.AuthPreferences;
            prefs.PutAuthFlags(authFlags);
            try
            {
                rp.OpenConnection(appID, appName);
                ticket = rp.BeginSession(companyFile, mode);
                var versions = rp.get_QBXMLVersionsForSession(ticket);
                maxVersion = versions.GetValue(versions.Length - 1).ToString();
            }
            catch (Exception Ex)
            {
                if (Ex.Message != null && Ex.Message == "Could not start Reckon Accounts.")
                {
                    MessageBox.Show("Error: " + Ex.Message + Environment.NewLine + Environment.NewLine + "Please ensure you have Reckon running and the company file you wish to integrate open.");
                }
                else
                {
                    MessageBox.Show("Error: " + Ex.Message);
                }
                rp.CloseConnection();
                return(false);
            }
            return(true);
        }
コード例 #14
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
        }
コード例 #15
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)
            {
                //
            }
        }
コード例 #16
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;
                }
            }
        }
コード例 #17
0
        protected void SendApexInvoices()
        {
            using (ApexDataDataContext apexData = new ApexDataDataContext(_SqlConnBuilder.ConnectionString))
            {
                try
                {
                    _Rp = new RequestProcessor2();
                    _Rp.OpenConnection("", "Apex Interface");
                    _Ticket            = _Rp.BeginSession("", Interop.QBXMLRP2.QBFileMode.qbFileOpenDoNotCare);
                    _QBCompanyName     = Path.GetFileName(_Rp.GetCurrentCompanyFileName(_Ticket));
                    _ApexTargetCompany = GetApexTargetCompany(_QBCompanyName);
                    if (_ApexTargetCompany == "*") //invalid company open
                    {
                        Application.Exit();
                        return;
                    }
                    lblApexCompany.Text    = "Quickbooks Company: " + Path.GetFileName(_QBCompanyName);
                    lblApexCompany.Visible = true;
                    lblApexCompany.Refresh();

                    _StatusLines.Clear();

                    List <VendIvc> apexInvoiceList = (from ivc in apexData.VendIvcs
                                                      join po in apexData.POs on ivc.PO equals po.Po1
                                                      where ivc.IvcStatus == "A" &&
                                                      po.Company == _ApexTargetCompany
                                                      select ivc).ToList();

                    if (apexInvoiceList.Count == 0)
                    {
                        MessageBox.Show("There are no invoices to send.");
                    }
                    else
                    {
                        _InvoicesSent = true;  //We have a valid invoice to send so present the interface status report when complete

                        try
                        {
                            GLAcctUtility.GLAcctList = GLAcctUtility.BuildGLAcctList(apexData);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "G/L Setup Error");
                            return;
                        }

                        foreach (VendIvc invoice in apexInvoiceList)
                        {
                            decimal ponet         = apexData.POs.Where(s => s.Po1 == invoice.PO).Select(s => s.PoNet).SingleOrDefault() ?? 0;
                            decimal totalInvoiced = apexData.VendIvcs.Where(s => s.PO == invoice.PO).Sum(s => s.IvcAmt) ?? 0;

                            if (apexData.QBInvoices.Where(s => s.Invoice == invoice.Invoice && s.PO == invoice.PO).Any())
                            {
                                _StatusLines.Add(new StatusLine
                                {
                                    Invoice = invoice.Invoice,
                                    PO      = invoice.PO.Trim(),
                                    Message = "Duplicate invoice"
                                });
                            }
                            else
                            {
                                if (totalInvoiced != 0 && (totalInvoiced - ponet > _MaxDiffAmt))
                                {
                                    _StatusLines.Add(new StatusLine
                                    {
                                        Invoice = invoice.Invoice,
                                        PO      = invoice.PO.Trim(),
                                        Message = $"The total invoiced {totalInvoiced:c} exceeds the P/O Net amount {ponet:c} by over {_MaxDiffAmt:c}"
                                    });
                                }
                                else
                                {
                                    decimal ivcTotal = 0; decimal poTaxableAmt = 0;
                                    foreach (VendIvcL ivcLine in invoice.VendIvcLs)
                                    {
                                        ivcTotal += ivcLine.AmtIvc ?? 0;
                                        POLine poline = apexData.POLines.Where(s => s.Po == ivcLine.PO && s.PoLine1 == ivcLine.POLine).SingleOrDefault();
                                        if (poline?.Taxable == "Y")
                                        {
                                            poTaxableAmt += ivcLine.AmtIvc ?? 0;
                                        }
                                    }
                                    double poTaxRate = apexData.POs.Where(s => s.Po1 == invoice.PO).Select(s => s.TaxRate).SingleOrDefault() ?? 0;
                                    ivcTotal += poTaxableAmt * ((decimal)(poTaxRate * 0.01));

                                    decimal invoiceDiff = Math.Abs((invoice.IvcAmt ?? 0) - ivcTotal);

                                    if (ivcTotal != 0 && ((double)((invoiceDiff / ivcTotal)) > (_MaxDiffPct * 0.01) ||
                                                          invoiceDiff > _MaxDiffAmt))
                                    {
                                        //This enforces a business rule set by the client regarding tolerances when reconciling a vendor invoice
                                        _StatusLines.Add(new StatusLine
                                        {
                                            Invoice = invoice.Invoice,
                                            PO      = invoice.PO.Trim(),
                                            Message = $"The P/O lines invoiced {ivcTotal:c} are more than {_MaxDiffAmt:c} or {_MaxDiffPct}% different from the invoice amount {invoice.IvcAmt:c}"
                                        });
                                    }
                                    else
                                    {
                                        //Initial audits passed; process invoice
                                        ProcessInvoice(invoice, apexData);
                                    }
                                }
                            }
                        }
                    }
                }

                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();
                    }
                    UpdateStatus("Export complete");
                }
            };
        }
コード例 #18
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;
                }
            }
        }
コード例 #19
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
        }
コード例 #20
0
ファイル: QBUtils.cs プロジェクト: ZochNet/QBMigrationTool
 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();
         }
     }
 }
コード例 #21
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;
                }
            }
        }
コード例 #22
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);
            //    }
        }
コード例 #23
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");


            // ------------------------------------------------------------
            // Ensure the vendor name is specified.
            // ------------------------------------------------------------

            if (string.IsNullOrEmpty(vendorFullName))
            {
                StatusText = string.Format("{0} - Must specify the InventoryConsumptionVendorName in the configuration.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");

                // Enable the buttons.
                IsExitEnabled      = true;
                IsTryEnabled       = true;
                IsStartOverEnabled = true;
                OnPropertyChanged("IsExitEnabled");
                OnPropertyChanged("IsTryEnabled");
                OnPropertyChanged("IsStartOverEnabled");

                return;
            }


            // ------------------------------------------------------------
            // Prepare the QuickBooks connection.
            // ------------------------------------------------------------

            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");

                // Determine the method of recording consumption.
                if (selectedMethod == "Inventory Adjustment")
                {
                    StatusText += string.Format("{0} - Using {1} method.\r\n", DateTime.Now.ToString(), selectedMethod);
                    OnPropertyChanged("StatusText");
                }
                else if (selectedMethod == "Sales Receipt")
                {
                    StatusText += string.Format("{0} - Using {1} method and {2} value.\r\n", DateTime.Now.ToString(), selectedMethod, selectedValue);
                    OnPropertyChanged("StatusText");
                }
                else if (selectedMethod == "Bill")
                {
                    StatusText += string.Format("{0} - Using {1} method and {2} value with {3} vendor.\r\n",
                                                DateTime.Now.ToString(), selectedMethod, selectedValue, vendorFullName);
                    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.
                Logger.Debug(hostDocument.OuterXml);
                var hostResponse = req.ProcessRequest(ticket, hostDocument.OuterXml);
                Logger.Debug(hostResponse);

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


                // ------------------------------------------------------------
                // Collect any unsynced consumption.
                // ------------------------------------------------------------

                var consumptions = GetConsumption();
                var txnIds       = new List <string>(consumptions.Count);

                if (consumptions.Count == 0)
                {
                    StatusText += string.Format("{0} - There is no inventory consumption to sync.\r\n", DateTime.Now.ToString());
                    OnPropertyChanged("StatusText");
                }
                else
                {
                    // ------------------------------------------------------------
                    // Record the unsynced consumptions.
                    // ------------------------------------------------------------

                    // Build the request to store consumptions.
                    if (selectedMethod == "Sales Receipt")
                    {
                        // Prepare a new QBXML document.
                        var consQBXML    = service.MakeQBXMLDocument();
                        var consDocument = consQBXML.Item1;
                        var consElement  = consQBXML.Item2;

                        service.BuildSalesReceiptAddRq(consDocument, consElement, consumptions, selectedValue.ToUpperInvariant());

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

                        // Then walk the response.
                        var walkReponse = service.WalkSalesReceiptAddRs(consResponse);
                        txnIds = walkReponse.Item3;
                    }
                    else if (selectedMethod == "Bill")
                    {
                        foreach (var consumption in consumptions)
                        {
                            // Prepare a new QBXML document.
                            var consQBXML    = service.MakeQBXMLDocument();
                            var consDocument = consQBXML.Item1;
                            var consElement  = consQBXML.Item2;

                            service.BuildBillAddRq(consDocument, consElement, consumption, vendorFullName, refNumber, selectedValue.ToUpperInvariant());

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

                            // Then walk the response.
                            var walkReponse = service.WalkBillAddRs(consResponse);
                            txnIds = txnIds.Concat(walkReponse.Item3).ToList();
                        }
                    }
                    else if (selectedMethod == "Inventory Adjustment")
                    {
                        // Prepare a new QBXML document.
                        var consQBXML    = service.MakeQBXMLDocument();
                        var consDocument = consQBXML.Item1;
                        var consElement  = consQBXML.Item2;

                        service.BuildInventoryAdjustmentAddRq(consDocument, consElement, consumptions, selectedValue.ToUpperInvariant());

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

                        // Then walk the response.
                        var walkReponse = service.WalkInventoryAdjustmentAddRs(consResponse);
                        txnIds = walkReponse.Item3;
                    }

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

                        var transactionType = "";

                        switch (selectedMethod)
                        {
                        case "Sales Receipt":
                            transactionType = "SalesReceipt";
                            break;

                        case "Bill":
                            transactionType = "Bill";
                            break;

                        case "Inventory Adjustment":
                            transactionType = "InventoryAdjustment";
                            break;
                        }

                        // Reverse the transactions.
                        foreach (var txnId in txnIds)
                        {
                            // 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, 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);
                        }
                    }
                    else
                    {
                        // Build the payload.
                        var payload = new
                        {
                            TxnIDs = txnIds,
                            Ids    = consumptions.Select(c => c.Id).ToArray()
                        };

                        // Build the request to send the sync details.
                        var syncHttpRequest = new RestRequest("api/QBDInventoryConsumptions/Sync", Method.POST);
                        syncHttpRequest.AddJsonBody(payload);
                        syncHttpRequest.AddQueryParameter("recordingMethod", selectedMethod);
                        syncHttpRequest.AddQueryParameter("valueMethod", selectedValue);
                        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 (DownloadFailedException)
            {
                StatusText += string.Format("{0} - Sync failed. Could not download consumption from the server.\r\n", DateTime.Now.ToString());
                OnPropertyChanged("StatusText");
            }
            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;
                }
            }
        }