// Open Quickbooks Connection, Begin Session and return ticket public string openSession(string qbFile) { string ticket = ""; try { //Obtain Request Processor Object rp = new RequestProcessor2(); //Open Connection rp.OpenConnection(APP_CODE, APP_NAME); //Begin Session ticket = rp.BeginSession(qbFile, QBFileMode.qbFileOpenDoNotCare); } catch (Exception ex) { // Send Error to the Error Log string excep = DateTime.Now.ToString() + " [QBParser-openSession] " + ex.Message; File.AppendAllText("ErrorLog.txt", excep + Environment.NewLine); if (rp != null) { rp.CloseConnection(); rp = null; } } return(ticket); }
// End used Session and Issue a new one public string issueNewSessionTicket(string qbFile, string oldTicket) { String newTicket = ""; try { // End Previous Used Session rp.EndSession(oldTicket); //Begin New Session newTicket = rp.BeginSession(qbFile, QBFileMode.qbFileOpenDoNotCare); } catch (Exception ex) { // Send Error to the Error Log string excep = DateTime.Now.ToString() + " [QBParser-issueNewSessionTicket] " + ex.Message; File.AppendAllText("ErrorLog.txt", excep + Environment.NewLine); if (rp != null) { rp.CloseConnection(); rp = null; } } return(newTicket); }
static string QBConnect(string data) { RequestProcessor2 rp = null; string ticket = null; string response = null; try { rp = new RequestProcessor2(); rp.OpenConnection("", "Ghost QuickBooks XML Bridge"); ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare); response = rp.ProcessRequest(ticket, data); } catch (System.Runtime.InteropServices.COMException ex) { return("COM Error Description = " + ex.Message + "\n"); } finally { if (ticket != null) { rp.EndSession(ticket); } if (rp != null) { rp.CloseConnection(); } }; return(response); }
private void ConnectToQuickBooks() { if ((QBProcessor != null) && (!String.IsNullOrWhiteSpace(SessionID))) { return; } if (QBProcessor == null) { SessionID = String.Empty; //QBProcessor is null.. if ((File.Exists(QuickbookFileName)) && (!String.IsNullOrWhiteSpace(ApplicationName))) { QBProcessor = new RequestProcessor2(); QBProcessor.OpenConnection(ApplicationID, ApplicationName); } } if (QBProcessor != null) { //Session ID is Null or empty .. let us establish the session SessionID = QBProcessor.BeginSession(QuickbookFileName, QBFileMode.qbFileOpenMultiUser); return; } }
public void DisconnectFromQB() { if (ticket != null) { try { rp.EndSession(ticket); ticket = null; } catch (Exception e) { Logger.LogException(e); } } if (rp != null) { try { rp.CloseConnection(); rp = null; } catch (Exception e) { Logger.LogException(e); } } }
public bool OpenConnection(string strAppName, string qbFileName) { qbRequestProcessor = new RequestProcessor2(); qbRequestProcessor.OpenConnection("", strAppName); ticket = qbRequestProcessor.BeginSession(qbFileName, QBFileMode.qbFileOpenDoNotCare); return(true); }
public QuickbooksClient(string companyFileLocation, string applicationName) { companyFile = companyFileLocation; appName = applicationName; if (MyQbXMLRP2 == null) { MyQbXMLRP2 = new RequestProcessor2(); MyQbXMLRP2.OpenConnection2("", appName, QBXMLRPConnectionType.localQBD); } if (ticket == null) { try { ticket = MyQbXMLRP2.BeginSession(companyFile, QBFileMode.qbFileOpenDoNotCare); } catch (COMException ex) { throw ex; } catch (Exception e) { throw e; } } }
public QBSessionFactory(string appName, string appId, string qbXmlVersion, string fileName, FileMode fileMode, ConnectionType connectionType) { _log.Info("Instantiating new QBSession Factory"); _log.InfoFormat("App Name: {0}", appName); _log.InfoFormat("App Id: {0}", appId); _log.InfoFormat("QBXML Version: {0}", qbXmlVersion); _log.InfoFormat("File Name: {0}", fileName); _log.InfoFormat("File Mode: {0}", Enum.GetName(typeof(FileMode), fileMode)); _log.InfoFormat("Connection Type: {0}", Enum.GetName(typeof(ConnectionType), connectionType)); _requestProcessor = new RequestProcessor2Class(); _appName = appName; _appId = appId; _fileName = fileName; _qbXmlVersion = qbXmlVersion; //Converting enums to QBXMLRP2Lib namespace enums _fileMode = QBFileMode.qbFileOpenDoNotCare; _connectionType = QBXMLRPConnectionType.localQBD; //_fileMode = (QBFileMode)Enum.Parse( // typeof(QBFileMode), // Enum.GetName(typeof(FileMode), fileMode)); //_connectionType = (QBXMLRPConnectionType)Enum.Parse( // typeof(QBXMLRPConnectionType), // Enum.GetName(typeof(ConnectionType), connectionType)); _connectionIsOpen = false; }
//Subscribes this application to listen for Data event or UI extension event private static void SubscribeForEvents(QBSubscriptionType strType, string strData) { RequestProcessor2 qbRequestProcessor; try { // Get an instance of the qbXMLRP Request Processor and // call OpenConnection if that has not been done already. qbRequestProcessor = new RequestProcessor2(); qbRequestProcessor.OpenConnection("", strAppName); StringBuilder strRequest = new StringBuilder(); switch (strType) { case QBSubscriptionType.Data: strRequest = new StringBuilder(GetDataEventSubscriptionAddXML()); break; case QBSubscriptionType.UIExtension: strRequest = new StringBuilder(GetUIExtensionSubscriptionAddXML(strData)); break; default: return; } string strResponse = qbRequestProcessor.ProcessSubscription(strRequest.ToString()); //Parse the XML response to check the status XmlDocument outputXMLDoc = new XmlDocument(); outputXMLDoc.LoadXml(strResponse); XmlNodeList qbXMLMsgsRsNodeList = outputXMLDoc.GetElementsByTagName("DataEventSubscriptionAddRs"); if (qbXMLMsgsRsNodeList.Count == 1) { 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; if ((retStatusCode != "0") && (retStatusCode != "3180"))// 3180 : if subscription already subscribed. NOT A NEAT WAY TO DO THIS, NEED TO EXPLORE THIS { Console.WriteLine("Error while subscribing for events\n\terror Code - {0},\n\tSeverity - {1},\n\tError Message - {2}\n", retStatusCode, retStatusSeverity, retStatusMessage); return; } } } catch (Exception ex) { Console.WriteLine("Error while registering for QB events - " + ex.Message); qbRequestProcessor = null; return; } }
/// <summary> /// Connect with quickbooks and read/write data. /// </summary> /// <param name="xml"></param> /// <param name="qbFilePath"></param> /// <returns></returns> public static ResponseModel ProcessQuickBookRequest(string xml, string qbFilePath) { bool sessionBegun = false; bool connectionOpen = false; RequestProcessor2 rp = null; string ticket = string.Empty; ResponseModel response = null; try { //Create the Request Processor object rp = new RequestProcessor2(); //Connect to QuickBooks and begin a session rp.OpenConnection("12345", "Testing");//id of your .net project and name of your .net project. connectionOpen = true; //ticket = rp.BeginSession(ConfigurationManager.AppSettings["QuickBookFile"], QBFileMode.qbFileOpenDoNotCare); ticket = rp.BeginSession(qbFilePath, QBFileMode.qbFileOpenDoNotCare); sessionBegun = true; //Send the request and get the response from QuickBooks response = new ResponseModel { ResponseString = rp.ProcessRequest(ticket, xml), Succeeded = true }; //End the session and close the connection to QuickBooks rp.EndSession(ticket); sessionBegun = false; rp.CloseConnection(); connectionOpen = false; //WalkCustomerAddRs(responseStr); } catch (Exception e) { if (sessionBegun) { rp.EndSession(ticket); } if (connectionOpen) { rp.CloseConnection(); } response = new ResponseModel { Message = e.Message, Succeeded = false }; } return(response); }
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; }
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); }
private RequestProcessor2 QuickBooksConection2() { try { var request = new RequestProcessor2(); request.OpenConnection("QuickBooks Application", "QuickBooks Application"); Ticket = request.BeginSession("", QBFileMode.qbFileOpenDoNotCare); return(request); } catch (Exception ex) { // -- log } return(null); }
public void Disconnect() { if (ticket != null && MyQbXMLRP2 != null) { MyQbXMLRP2.EndSession(ticket); } if (MyQbXMLRP2 != null) { MyQbXMLRP2.CloseConnection(); } MyQbXMLRP2 = null; ticket = null; }
//if connection esists or established, return true; else return false public bool ConnectToQB() { if (m_ticket == null) { rp = new RequestProcessor2Class(); rp.OpenConnection(m_appID, m_appName); for (int i = 0; i < m_maxIterations; i++ ) { try { m_ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare); } catch (System.Runtime.InteropServices.COMException ex) { LogHelper.Error(ex); if (ex.ErrorCode == ERROR_CODE_MODAL_DIALOG) { int isClosed = WindowOperation.CloseModalDialog("qbw32"); //if (isClosed != WindowOperation.NOTCLOSED) //{ //m_ticket = rp.BeginSession("", QBFileMode.qbFileOpenDoNotCare); //} } //return "<QBStatus>" + ex.Message + "</Q>"; } catch (Exception ex) { LogHelper.Error(ex); } finally { if (m_ticket != null) { m_versions = rp.get_QBXMLVersionsForSession(m_ticket); m_maxVersion = m_versions[m_versions.Length - 1]; } } if (m_ticket != null) return true; } return false; } //return "ConnectToQB: Max Version:" + m_maxVersion; return true; }
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); }
private void disconnectFromQB() { if (ticket != null) { try { rp.EndSession(ticket); ticket = null; rp.CloseConnection(); rp = null; } catch (Exception e) { ErrorList.Add(DateTime.Now, e); } } }
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); }
private async Task <bool> connectToQB() { try { rp = new RequestProcessor2(); //RequestProcessor2(); //RequestProcessor2Class(); await Task.Run(() => rp.OpenConnection(appID, appName)); ticket = rp.BeginSession(companyFile, mode); string[] versions = (string[])rp.get_QBXMLVersionsForSession(ticket);//Array.ConvertAll<System.Array, string>(rp.get_QBXMLVersionsForSession(ticket),Convert.ToString); maxVersion = versions[versions.Length - 1]; return(true); } catch (Exception ex) { ErrorList.Add(DateTime.Now, ex); return(false); } }
//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; }
//Unsubscribes this application from listening to add/modify/delete custmor event private static void UnsubscribeForEvents(QBSubscriptionType strType, bool bSilent) { RequestProcessor2 qbRequestProcessor; try { // Get an instance of the qbXMLRP Request Processor and // call OpenConnection if that has not been done already. qbRequestProcessor = new RequestProcessor2(); qbRequestProcessor.OpenConnection("", strAppName); StringBuilder strRequest = new StringBuilder(GetSubscriptionDeleteXML(strType)); string strResponse = qbRequestProcessor.ProcessSubscription(strRequest.ToString()); //Parse the XML response to check the status XmlDocument outputXMLDoc = new XmlDocument(); outputXMLDoc.LoadXml(strResponse); XmlNodeList qbXMLMsgsRsNodeList = outputXMLDoc.GetElementsByTagName("SubscriptionDelRs"); 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; if ((retStatusCode != "0") && (!bSilent)) { Console.WriteLine("Error while unsubscribing from events\n\terror Code - {0},\n\tSeverity - {1},\n\tError Message - {2}\n", retStatusCode, retStatusSeverity, retStatusMessage); return; } } catch (Exception ex) { Console.WriteLine("Error while unsubscribing from QB events - " + ex.Message); qbRequestProcessor = null; return; } return; }
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); }
// CONNECTION TO QB private void ConnectToQB() { if (rp == null) { try { rp = new RequestProcessor2Class(); rp.OpenConnection2(AppID, AppName, QBXMLRPConnectionType.localQBD); if (CompanyFile == null) { CompanyFile = string.Empty; } ticket = rp.BeginSession(CompanyFile, mode); string[] versions = (string[])rp.get_QBXMLVersionsForSession(ticket); MaxVersion = versions[versions.Length - 1]; } catch (Exception e) { Logger.LogException(e); DisconnectFromQB(); } } }
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(); } } }
public bool Connect() { if (Config.IsProduction == false) { return(true); } if (localhost == true) { return(true); } if (ticket != string.Empty) { return(true); } try { rp = new RequestProcessor2(); rp.OpenConnection("", appName); ticket = rp.BeginSession(fileName, QBFileMode.qbFileOpenDoNotCare); if (ticket != string.Empty) { string[] versions = rp.get_QBXMLVersionsForSession(ticket); maxVersion = versions[versions.Length - 1]; } else { return(false); } } catch (Exception ex) { throw new Exception("Error al conectar a Quickbooks: " + ex.Message); } return(true); }
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); // } }
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; } } }
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(); } } }
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; } } }
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) { // } }
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; } } }
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 }
static void Main(string[] args) { // The QBXMLRP2 object RequestProcessor2 requestProcessor = null; // values QBXMLRP2 will return bool sessionBegun = false; bool connectionOpen = false; // base XML doc vars XmlDocument xmlReqDoc = null; XmlElement qbxml = null; XmlElement qbxmlMsgsRq = null; // successful qbxml response vars string ticket = null; string responseStr = null; string qbXmlReqObj = null; try // 1st - to initialize the base xml doc { requestProcessor = new RequestProcessor2(); // Create a new XML document xmlReqDoc = new XmlDocument(); // ROOT - <?xml version="1.0" encoding="utf-8"?> xmlReqDoc.AppendChild(xmlReqDoc.CreateXmlDeclaration("1.0", "utf-8", null)); // ROOT - <?qbxml version="13.0"?> xmlReqDoc.AppendChild(xmlReqDoc.CreateProcessingInstruction("qbxml", "version=\"13.0\"")); // ROOT - <QBXML>...</QBXML> qbxml = xmlReqDoc.CreateElement("QBXML"); xmlReqDoc.AppendChild(xmlReqDoc.CreateElement("QBXML")); // child - <QBXMLMsgsRq>...</QBXMLMsgsRq> qbxmlMsgsRq = xmlReqDoc.CreateElement("QBXMLMsgsRq"); qbxml.AppendChild(qbxmlMsgsRq); qbxmlMsgsRq.SetAttribute("onError", "stopOnError"); } catch (Exception ex) { requestProcessor = null; LogQuickBooksData(logBase + "initialize-base-xml-doc.xml", ex.Message); return; } Console.WriteLine("__>> RSM - Base Xml doc built"); try // 2nd - to build the invoice qbXML request objects { BuildInvoiceQueryRq(xmlReqDoc, qbxmlMsgsRq); // BuildInvoiceAddRq(xmlReqDoc, qbxmlMsgsRq); } catch (Exception ex) { requestProcessor = null; LogQuickBooksData(logBase + "build-qbxml-req-error.xml", ex.Message); return; } Console.WriteLine("__>> RSM - qbXML request object built"); try // 3rd - to make a request to QuickBooks { requestProcessor.OpenConnection("", appName); connectionOpen = true; ticket = requestProcessor.BeginSession("", QBFileMode.qbFileOpenDoNotCare); sessionBegun = true; // send request and get response responseStr = requestProcessor.ProcessRequest(ticket, qbXmlReqObj); } catch (Exception ex) { requestProcessor = null; connectionOpen = false; sessionBegun = false; } }