private IORItemRet QueryItem(QBSessionManager session, string itemFullName) { // query for the customer information IMsgSetRequest requestMsgSet = getLatestMsgSetRequest(session); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; IItemQuery pItemQuery = requestMsgSet.AppendItemQueryRq(); pItemQuery.ORListQuery.ListFilter.ORNameFilter.NameFilter.Name.SetValue(itemFullName); pItemQuery.ORListQuery.ListFilter.ORNameFilter.NameFilter.MatchCriterion.SetValue(ENMatchCriterion.mcContains); pItemQuery.OwnerIDList.Add("0"); IMsgSetResponse responseMsgSet = session.DoRequests(requestMsgSet); // Uncomment the following to see the request and response XML for debugging //string rq = requestMsgSet.ToXMLString(); //string rs = responseMsgSet.ToXMLString(); //m_application.Messenger.AddInfo("Item Resquest: " + rq); //m_application.Messenger.AddInfo("Item Response: " + rs); // Interpret the response IResponseList rsList = responseMsgSet.ResponseList; // Retrieve the one response corresponding to our single request IResponse response = rsList.GetAt(0); if (response.StatusCode != 0) { string msg = ""; if (response.StatusCode == 1) //No record found { msg = "Item not found: " + itemFullName; } else { msg = "Error getting item. Status: " + response.StatusCode.ToString() + ", Message: " + response.StatusMessage; } throw new Exception(msg); } // We have one or more customers (expect one) IORItemRetList orItemRetList = response.Detail as IORItemRetList; int itemCount = orItemRetList.Count; if (itemCount > 1) { m_application.Messenger.AddWarning("Multiple items found: " + itemFullName); } return(orItemRetList.GetAt(0)); }
public bool CreateQBSession(out QBSessionManager sessionManager) { // We want to know if we begun a session so we can end it if an // error happens bool booSessionBegun = false; string QBDLicenceCertificateName = ConfigurationManager.AppSettings["QBDLicenceCertificateName"].ToString(); // Create the session manager object using QBFC sessionManager = null; try { sessionManager = new QBSessionManager(); // Open the connection and begin a session to QuickBooks //sessionManager.OpenConnection("", "IDN InvoiceAdd C# sample"); sessionManager.OpenConnection("", QBDLicenceCertificateName); sessionManager.BeginSession("", ENOpenMode.omDontCare); booSessionBegun = true; // Announcing QuickBooks version //string QBVer = Convert.ToString(QBFCLatestVersion(sessionManager)) + ".0"; //MessageBox.Show("The qbXML version v" + QBVer + " is detected. Applicaton will set its compatibility accordingly." + // "\n\nThis sample uses QBFC for all of its communication to QuickBooks." + // "\n\nClick OK to Continue", "Note", System.Windows.Forms.MessageBoxButtons.OK); // Get the RequestMsgSet based on the correct QB Version // requestSet = getLatestMsgSetRequest(sessionManager); } catch (Exception ex) { booSessionBegun = false; } return(booSessionBegun); }
public QuickBooksSession(string appId, string appName, Guid errorRecoveryId) { _appId = appId; _appName = appName; _errorRecoveryGuid = errorRecoveryId; try { _sessionManager = new QBSessionManager(); } catch (Exception ex) { throw new Exception("Can't create QBSessionManager. Make sure this assembly is compiled for X86 (not x64).", ex); } try { _sessionManager.OpenConnection(_appId, _appName); _sessionManager.BeginSession("", ENOpenMode.omDontCare); _isOnline = true; } catch (Exception ex) { ExceptionForm.ShowException("Cannot connect to QuickBooks", ex); } try { _sessionManager.ErrorRecoveryID.SetValue("{" + _errorRecoveryGuid.ToString() + "}"); ErrorRecovery(); } catch (Exception ex) { ExceptionForm.ShowException("QuickBooks error recovery did not succeed", ex); } }
static double QbfcLatestVersion(QBSessionManager manager) { var msgset = manager.CreateMsgSetRequest("US", 1, 0); msgset.AppendHostQueryRq(); var queryResponse = manager.DoRequests(msgset); var response = queryResponse.ResponseList.GetAt(0); var hostResponse = response.Detail as IHostRet; Debug.Assert(hostResponse != null, "hostResponse != null"); var supportedVersions = hostResponse.SupportedQBXMLVersionList; int i; double lastVersion = 0; for (i = 0; i <= supportedVersions.Count - 1; i++) { var vers = Convert.ToDouble(supportedVersions.GetAt(i)); if (vers > lastVersion) { lastVersion = vers; } } return(lastVersion); }
public bool TestConnect() { try { var qb = QuickBooksConection(); SessionManager.OpenConnection("QuickBooks Application", "QuickBooks Application"); ConnectionOpen = true; SessionManager.BeginSession("", ENOpenMode.omDontCare); SessionBegun = true; return(true); } catch (Exception ex) { ErrorMessage = ex.Message; return(false); } finally { if (SessionBegun) { SessionManager?.EndSession(); } if (ConnectionOpen) { SessionManager?.CloseConnection(); } SessionManager = null; } return(false); }
public ObservableCollection <customer> DbRead() { ObservableCollection <customer> Customers = new ObservableCollection <customer>(); QBSessionManager sessionManager = CreateSession(); IMsgSetRequest requestMsgSet = CreateRequestMessage(ref sessionManager); sessionManager = DbConnect(sessionManager); // Setup requestquery ICustomerQuery customerQueryReq = requestMsgSet.AppendCustomerQueryRq(); customerQueryReq = SetIncludedRetEliments(ref customerQueryReq); customerQueryReq = SetCustomerQuery(0, ref customerQueryReq); IResponse response = GetMessageResponse(ref sessionManager, ref requestMsgSet); ICustomerRetList customerRetList = (ICustomerRetList)response.Detail; if (customerRetList != null) { for (int i = 0; i < customerRetList.Count; i++) { ICustomerRet customerRet = customerRetList.GetAt(i); customer Customer = FillCustomer(customerRet); Customers.Add(Customer); } } return(Customers); }
public void OpenQB() { QBSessionManager sessionManager = null; try { sessionManager = new QBSessionManager(); IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("CA", 13, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; sessionManager.OpenConnection("QBAPI", "Quickbooks SDK Demo Test"); string qbFile = ConfigurationSettings.AppSettings["companyfile"].ToString(); Console.WriteLine(qbFile); sessionManager.BeginSession( qbFile, ENOpenMode.omMultiUser); ICustomerQuery customerQueryRq = requestMsgSet.AppendCustomerQueryRq(); customerQueryRq.ORCustomerListQuery.CustomerListFilter.ActiveStatus.SetValue(ENActiveStatus.asAll); IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); sessionManager.EndSession(); sessionManager.CloseConnection(); } catch (Exception ex) { System.Console.WriteLine(ex.Message); sessionManager.EndSession(); sessionManager.CloseConnection(); } }
public void vendorAdd(string name) { //open session to add vendor QBSessionManager sessionManager = new QBSessionManager(); sessionManager.OpenConnection("appID", "Create Vendor"); sessionManager.BeginSession("", ENOpenMode.omDontCare); IMsgSetRequest messageSet = sessionManager.CreateMsgSetRequest("US", 13, 0); IVendorAdd vendorAddRequest = messageSet.AppendVendorAddRq(); vendorAddRequest.Name.SetValue(name); //add vendor // name is the string passed from the list containing the vendors that need to be added to quickbooks IMsgSetResponse responseSet = sessionManager.DoRequests(messageSet); sessionManager.EndSession(); sessionManager.CloseConnection(); for (int i = 0; i < responseSet.ResponseList.Count; i++) { IResponse response = responseSet.ResponseList.GetAt(i); var code = response.StatusCode; string code2 = code.ToString(); string code3 = response.StatusMessage; if (response.StatusCode > 0) { } // MessageBox.Show(code3); } }
public QBResponceList InventoryadjustmentBulkOperation(QBSessionManager sessionManager, QBRequestItemSet qBRequestItemSet) { QBResponceList qbResponceData = null; QBSession QBMgr = null; QBResponceItem _qbResponceItem = null; QBMgr = new QBSession(); if (sessionManager == null) { QBMgr.CreateQBSession(out sessionManager); } if (sessionManager != null && qBRequestItemSet != null && qBRequestItemSet.QBRequestItemList != null && qBRequestItemSet.QBRequestItemList.Count > 0) { //Parallel.ForEach(qBRequestItemSet.QBRequestItemList, item => Process(item)); foreach (var data in qBRequestItemSet.QBRequestItemList) { if (data != null) { if (data.Action == QBAction.Modify) { //Update quntity. var responceItem = Inventoryadjustment(sessionManager, qBRequestItemSet.AccountList, qBRequestItemSet.PreferencesRet, data.ItemInventoryRet); } else { //Add Item CreatInventoryItem(sessionManager, qBRequestItemSet.AccountList, qBRequestItemSet.PreferencesRet, data.ItemInventoryRet); } } } } return(qbResponceData); }
protected void StartSession() { try { if (sessionManager == null) { sessionManager = new QBSessionManager(); } if (!connectionOpen) { sessionManager.OpenConnection(MaestroApplication.Instance.QuickBooksAppId, MaestroApplication.Instance.QuickBooksAppName); } connectionOpen = true; } catch (Exception ex) { FinishSession(true); throw new Exception("Exception while connecting to QuickBooks", ex); } try { if (!sessionOpen) { sessionManager.BeginSession(MaestroApplication.Instance.QuickBooksAppPath, ENOpenMode.omDontCare); } sessionOpen = true; } catch (Exception ex) { FinishSession(true); throw new Exception("Exception while starting QuickBooks session", ex); } }
private double QBFCLatestVersion(QBSessionManager SessionManager) { // Use oldest version to ensure that this application work with any QuickBooks (US) IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0); msgset.AppendHostQueryRq(); IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset); // The response list contains only one response, // which corresponds to our single HostQuery request IResponse response = QueryResponse.ResponseList.GetAt(0); // Please refer to QBFC Developers Guide for details on why // "as" clause was used to link this derrived class to its base class IHostRet HostResponse = response.Detail as IHostRet; IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList; int i; double vers; double LastVers = 0; string svers = null; for (i = 0; i <= supportedVersions.Count - 1; i++) { svers = supportedVersions.GetAt(i); vers = Convert.ToDouble(svers); if (vers > LastVers) { LastVers = vers; } } return(LastVers); }
public IResponse DbGetResponseSet(ref QBSessionManager sessionManager, IMsgSetRequest requestMsgSet) { //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); return(responseMsgSet.ResponseList.GetAt(0)); }
public bool Init(string AppID, string Application, string CompanyFile) { this.AppID = AppID; this.Application = Application; try { if (!sessionBegun) { sessionManager = new QBSessionManager(); sessionManager.OpenConnection(AppID, Application); connectionOpen = true; sessionManager.BeginSession(CompanyFile, ENOpenMode.omDontCare); sessionBegun = true; } } catch (Exception e) { if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } throw new QBException(00, e.ToString()); } return(sessionBegun); }
public void CloseQBConnection(QBSessionManager sessionManager) { if (sessionManager != null) { sessionManager.EndSession(); sessionManager.CloseConnection(); } }
public IResponseList LoadQBItemInventoryList(int maxRecords, QBSessionManager sessionManager) { // IMsgSetRequest requestMsgSet = null; QBSession QBMgr = null; IResponseList responseList = null; try { QBMgr = new QBSession(); if (sessionManager == null) { QBMgr.CreateQBSession(out sessionManager); } if (sessionManager != null) { // Get the RequestMsgSet based on the correct QB Version IMsgSetRequest requestSet = QBMgr.getLatestMsgSetRequest(sessionManager); if (requestSet != null) { // Initialize the message set request object requestSet.Attributes.OnError = ENRqOnError.roeStop; IItemInventoryQuery itemInventory = requestSet.AppendItemInventoryQueryRq(); //Set field value for metaData itemInventory.metaData.SetValue(ENmetaData.mdMetaDataAndResponseData); //"IQBENmetaDataType" // Optionally, you can put filter on it. if (maxRecords != 0) { itemInventory.ORListQueryWithOwnerIDAndClass.ListWithClassFilter.MaxReturned.SetValue(maxRecords); } // Do the request and get the response message set object IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestSet); //IItemInventoryRetList itemInventoryRetList = null; if (responseMsgSet == null) { return(null); } responseList = responseMsgSet.ResponseList; if (responseList == null) { return(null); } // string responseXML = responseMsgSet.ToXMLString(); } } } catch (Exception ex) { } return(responseList); }
public void coni() { sessionManager = new QBSessionManager(); sessionManager.OpenConnection("", "ITCO"); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; }
public IMsgSetRequest CreateRequestMessage(ref QBSessionManager sessionManager) { //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("UK", 12, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; return(requestMsgSet); }
public IResponse GetMessageResponse(ref QBSessionManager sessionManager, ref IMsgSetRequest requestMsgSet) { // Send Request Get Responce //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); return(response); }
public void DoAccountQuery() { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; QBSessionMgr QBMgr = null; try { //Create the session Manager object QBMgr = new QBSessionMgr(); QBMgr.CreateQBSession(out sessionManager); // Get the RequestMsgSet based on the correct QB Version IMsgSetRequest requestMsgSet = QBMgr.getLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; // BuildAccountQueryRq(requestMsgSet); IAccountQuery AccountQueryRq = requestMsgSet.AppendAccountQueryRq(); // Uncomment the following to view and save the request and response XML // string requestXML = requestSet.ToXMLString(); // MessageBox.Show(requestXML); //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); string responseXML = responseMsgSet.ToXMLString(); //MessageBox.Show(responseXML); WalkAccountQueryRs(responseMsgSet); //End the session and close the connection to QuickBooks //Close the session and connection with QuickBooks QBMgr.CloseQBConnection(sessionManager); } catch (Exception ex) { // MessageBox.Show(e.Message, "Error"); // MessageBox.Show(ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } finally { QBMgr.CloseQBConnection(sessionManager); } }
public static string buildSalesReceiptAddRqXML(Session sess, string[,] sales) { QBSessionManager sessionManager = new QBSessionManager(); IMsgSetRequest requestSet = sessionManager.CreateMsgSetRequest(sess.getCountry(), sess.getMajorVers(), sess.getMinorVers()); requestSet.Attributes.OnError = ENRqOnError.roeStop; buildSalesRequest(sales, requestSet); return(requestSet.ToXMLString()); }
private IInvoiceRetList QueryInvoices(QBSessionManager session) { // Create Message Set request IMsgSetRequest requestMsgSet = getLatestMsgSetRequest(session); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; // Create the query object needed to perform InvoiceQueryRq IInvoiceQuery pInvQuery = requestMsgSet.AppendInvoiceQueryRq(); IInvoiceFilter pInvFilter = pInvQuery.ORInvoiceQuery.InvoiceFilter; // set the date range to the current schedule date selected in ArcLogistics pInvFilter.ORDateRangeFilter.TxnDateRangeFilter.ORTxnDateRangeFilter.TxnDateFilter.FromTxnDate.SetValue(m_application.CurrentDate); pInvFilter.ORDateRangeFilter.TxnDateRangeFilter.ORTxnDateRangeFilter.TxnDateFilter.ToTxnDate.SetValue(m_application.CurrentDate); pInvQuery.IncludeLineItems.SetValue(true); // Do the request IMsgSetResponse responseMsgSet = session.DoRequests(requestMsgSet); // Uncomment the following to see the request and response XML for debugging //string rq = requestMsgSet.ToXMLString(); //string rs = responseMsgSet.ToXMLString(); //m_application.Messenger.AddInfo("Resquest: " + rq); //m_application.Messenger.AddInfo("Response: " + rs); // Interpret the response IResponseList rsList = responseMsgSet.ResponseList; // Retrieve the one response corresponding to our single request IResponse response = rsList.GetAt(0); if (response.StatusCode != 0) { string msg = ""; if (response.StatusCode == 1) //No record found { msg = "No invoices found for " + m_application.CurrentDate.ToShortDateString(); } else { msg = "Error getting invoices. Status: " + response.StatusCode.ToString() + ", Message: " + response.StatusMessage; } throw new Exception(msg); } return(response.Detail as IInvoiceRetList); }
public static QBResult AddSalesReceipt(SalesReceipt salesreceipt, string QBCompanyFile) { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; try { //Create the session Manager object sessionManager = new QBSessionManager(); //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 3, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; BuildSalesReceiptAddRq(requestMsgSet); //Connect to QuickBooks and begin a session sessionManager.OpenConnection("", "Sample Code from OSR"); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); //End the session and close the connection to QuickBooks sessionManager.EndSession(); sessionBegun = false; sessionManager.CloseConnection(); connectionOpen = false; WalkSalesReceiptAddRs(responseMsgSet); } catch (Exception e) { MessageBox.Show(e.Message, "Error"); if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } //var saleXml = SalesReceiptViewModel.BuildSalesReceiptAddRq(salesreceipt); //if (saleXml != null) //{ // var responseXml = QBPosContext.ProcessXML(saleXml.OuterXml, QBCompanyFile); // return GetQBResult(responseXml); //} //return null; }
public static string[,] extractCustomerAddResponse(String response, Session sess) { string[,] customers; QBSessionManager sessionManager = new QBSessionManager(); IMsgSetResponse responseSet = sessionManager.ToMsgSetResponse(response, sess.getCountry(), sess.getMajorVers(), sess.getMinorVers()); int count = responseSet.ResponseList.Count; customers = new string[count, 3]; customers = getCustomers(responseSet, count); return(customers); }
public IResponseList GetPreferences(QBSessionManager sessionManager) { IMsgSetRequest requestMsgSet = null; QBSession QBMgr = null; IResponseList responseList = null; try { QBMgr = new QBSession(); if (sessionManager == null) { QBMgr.CreateQBSession(out sessionManager); } if (sessionManager != null) { // Get the RequestMsgSet based on the correct QB Version IMsgSetRequest requestSet = QBMgr.getLatestMsgSetRequest(sessionManager); if (requestSet != null) { // Initialize the message set request object requestSet.Attributes.OnError = ENRqOnError.roeStop; BuildPreferencesQueryRq(requestSet); // Do the request and get the response message set object IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestSet); if (responseMsgSet == null) { return(null); } responseList = responseMsgSet.ResponseList; if (responseList == null) { return(null); } //WalkPreferencesQueryRs(responseSet); //Close the session and connection with QuickBooks //QBMgr.CloseQBConnection(sessionManager); } } } catch (Exception ex) { } finally { } return(responseList); }
///<summary>Creates a new QB connection and begins the session. Session will be left open until CloseConnection is called. Major and minor version refer to the implementation version of the paticular QB request you are trying to run. The connection will fail if the version you pass in does not support the type of request you are trying to run.</summary> private static void OpenConnection(short majorVer,short minorVer,string companyPath) { SessionManager=new QBSessionManager(); //Create the message set request object to hold our request. RequestMsgSet=SessionManager.CreateMsgSetRequest("US",majorVer,minorVer); RequestMsgSet.Attributes.OnError=ENRqOnError.roeContinue; //Connect to QuickBooks and begin a session SessionManager.OpenConnection("","Open Dental"); ConnectionOpen=true; SessionManager.BeginSession(companyPath,ENOpenMode.omDontCare); SessionBegun=true; }
public static string[,] extractSalesReceiptAddResponse(String response, Session sess) { string[,] sales; QBSessionManager sessionManager = new QBSessionManager(); IMsgSetResponse responseSet = sessionManager.ToMsgSetResponse(response, sess.getCountry(), sess.getMajorVers(), sess.getMinorVers()); int count = responseSet.ResponseList.Count; sales = new string[count, 2]; sales = getSalesReceipts(responseSet, count); return(sales); }
public static String queryAll(Session sess) { QBSessionManager sessionManager = new QBSessionManager(); IMsgSetRequest requestSet = sessionManager.CreateMsgSetRequest(sess.getCountry(), sess.getMajorVers(), sess.getMinorVers()); requestSet.Attributes.OnError = ENRqOnError.roeStop; IItemInventoryQuery ItemQ = requestSet.AppendItemInventoryQueryRq(); ItemQ.iterator.SetValue(ENiterator.itStart); ItemQ.ORListQueryWithOwnerIDAndClass.ListWithClassFilter.MaxReturned.SetValue(chunkSize); return(requestSet.ToXMLString()); }
public QBSessionManager OpenConnection() { /* 11/6/20 8:42 Pwd: Duk3Ha$ */ QBSessionManager qbData = new QBSessionManager(); qbData.OpenConnection("", "SA2QBook"); //qbData.OpenConnection(AppID,AppName) //qbData.BeginSession(qbFile,openMode) //qbData.BeginSession("Crown Meat Prototype 2_E2",ENOpenMode.omDontCare); qbData.BeginSession("", ENOpenMode.omDontCare); return(qbData); }
public IResponseList GetQBAccountInfo(QBSessionManager sessionManager) { //bool sessionBegun = false; //bool connectionOpen = false; QBSession QBMgr = null; IResponseList responseList = null; try { QBMgr = new QBSession(); if (sessionManager == null) { //Create the session Manager object QBMgr.CreateQBSession(out sessionManager); } // Get the RequestMsgSet based on the correct QB Version IMsgSetRequest requestMsgSet = QBMgr.getLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; // BuildAccountQueryRq(requestMsgSet); IAccountQuery AccountQueryRq = requestMsgSet.AppendAccountQueryRq(); //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); if (responseMsgSet == null) { return(null); } responseList = responseMsgSet.ResponseList; if (responseList == null) { return(null); } //WalkAccountQueryRs(responseMsgSet); //End the session and close the connection to QuickBooks //Close the session and connection with QuickBooks //QBMgr.CloseQBConnection(sessionManager); } catch (Exception ex) { } finally { } return(responseList); }
public IMsgSetRequest getLatestMsgSetRequest(QBSessionManager sessionManager) { // IY: Find and adapt to supported version of QuickBooks double supportedVersion = QBFCLatestVersion(sessionManager); // MessageBox.Show("supportedVersion = " + supportedVersion.ToString()); short qbXMLMajorVer = 0; short qbXMLMinorVer = 0; if (supportedVersion >= 6.0) { qbXMLMajorVer = 6; qbXMLMinorVer = 0; } else if (supportedVersion >= 5.0) { qbXMLMajorVer = 5; qbXMLMinorVer = 0; } else if (supportedVersion >= 4.0) { qbXMLMajorVer = 4; qbXMLMinorVer = 0; } else if (supportedVersion >= 3.0) { qbXMLMajorVer = 3; qbXMLMinorVer = 0; } else if (supportedVersion >= 2.0) { qbXMLMajorVer = 2; qbXMLMinorVer = 0; } else if (supportedVersion >= 1.1) { qbXMLMajorVer = 1; qbXMLMinorVer = 1; } else { qbXMLMajorVer = 1; qbXMLMinorVer = 0; MessageBox.Show("It seems that you are running QuickBooks 2002 Release 1. We strongly recommend that you use QuickBooks' online update feature to obtain the latest fixes and enhancements"); } // MessageBox.Show("qbXMLMajorVer = " + qbXMLMajorVer); // MessageBox.Show("qbXMLMinorVer = " + qbXMLMinorVer); // IY: Create the message set request object IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", qbXMLMajorVer, qbXMLMinorVer); return(requestMsgSet); }
///<summary>Creates a new QB connection and begins the session. Session will be left open until CloseConnection is called. Major and minor version refer to the implementation version of the paticular QB request you are trying to run. The connection will fail if the version you pass in does not support the type of request you are trying to run.</summary> private static void OpenConnection(short majorVer, short minorVer, string companyPath) { SessionManager = new QBSessionManager(); //Create the message set request object to hold our request. RequestMsgSet = SessionManager.CreateMsgSetRequest("US", majorVer, minorVer); RequestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; //Connect to QuickBooks and begin a session SessionManager.OpenConnection("", "Open Dental"); ConnectionOpen = true; SessionManager.BeginSession(companyPath, ENOpenMode.omDontCare); SessionBegun = true; }
public void Connect() { qbMgr = new QBSessionManager(); try { qbMgr.OpenConnection("EaglesoftDeposit", "Eaglesoft Deposit"); qbMgr.BeginSession("", ENOpenMode.omDontCare); } catch (Exception e) { if (e.Message.Equals("Could not start QuickBooks.")) throw new QuickbooksConnectionException(e.Message); else throw e; } }
public bool GetQBItems() { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; try { //Create the session Manager object sessionManager = new QBSessionManager(); //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 2, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; sessionManager.OpenConnection(MMSUtility.QBAppID, MMSUtility.QBAppName); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; //Send the request and get the response from QuickBooks IItemQuery itemQueryRq = requestMsgSet.AppendItemQueryRq(); IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IORItemRetList itemRetList = (IORItemRetList)response.Detail; if (itemRetList != null) { for (int i = 0; i < itemRetList.Count; i++) { IORItemRet itemRet = itemRetList.GetAt(i); if (itemRet.ItemServiceRet != null) { IItemServiceRet itemServiceRet = itemRet.ItemServiceRet; var item = new Item { Name = itemServiceRet.Name.GetValue(), //Description = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue(), Rate = itemServiceRet.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue(), ItemType = ItemType.Service, QuickBooksID = itemServiceRet.ListID.GetValue(), EditSequence = itemServiceRet.EditSequence.GetValue() }; QBitems1.Add(item); QBitems2.Add(item); QBitems3.Add(item); QBitems4.Add(item); } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); return false; } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } return true; }
internal static IItemInventoryRet QBAddInventory(string inventoryName, string inventoryDescription, double inventorySalePrice, string cogsAccountRef, string assetAccountRef, string incomeAccountRef) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string errecid = "{" + Guid.NewGuid().ToString() + "}"; sessionManager.ErrorRecoveryID.SetValue(errecid); sessionManager.EnableErrorRecovery = true; sessionManager.SaveAllMsgSetRequestInfo = true; #region error recovery if (sessionManager.IsErrorRecoveryInfo()) { IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; resMsgSet = sessionManager.GetErrorRecoveryStatus(); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { MessageBox.Show( "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { MessageBox.Show( "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { MessageBox.Show("No stored response was found."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { MessageBox.Show("Unable to store response."); } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; if (sCode == 0) { MessageBox.Show("Last request was processed and customer was added successfully!"); } else if (sCode > 0) { MessageBox.Show("There was a warning but last request was processed successfully!"); } else { MessageBox.Show("It seems that there was an error in processing last request"); reqMsgSet = sessionManager.GetSavedMsgSetRequest(); resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; ICustomerRet custRet = null; if (statCode == 0) { string resStr = null; custRet = resp.Detail as ICustomerRet; resStr = resStr + "Following inventory has been successfully submitted to QuickBooks:\n\n\n"; if (custRet.ListID != null) { resStr = resStr + "ListID Number = " + Convert.ToString(custRet.ListID.GetValue()) + "\n"; Log(resStr); } } Log(QBCRUDEAction.ErrorRecovery, "Customer", (custRet == null ? "" : custRet.FullName.GetValue()), resp); } } sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } #endregion IItemInventoryRet existingItemInventory = GetInventoryByNameFilter(inventoryName); if (existingItemInventory == null) { IItemInventoryAdd itemInventoryAddRq = requestMsgSet.AppendItemInventoryAddRq(); itemInventoryAddRq.Name.SetValue(inventoryName); //Product name itemInventoryAddRq.SalesDesc.SetValue(inventoryDescription); itemInventoryAddRq.SalesPrice.SetValue(inventorySalePrice); itemInventoryAddRq.IncomeAccountRef.FullName.SetValue(incomeAccountRef); //Sales //itemInventoryAddRq.PurchaseDesc.SetValue(purchaseDecription); //Product name //itemInventoryAddRq.PurchaseCost.SetValue(purchaseCost); //Product Price itemInventoryAddRq.COGSAccountRef.FullName.SetValue(cogsAccountRef); //"Sales" itemInventoryAddRq.AssetAccountRef.FullName.SetValue(assetAccountRef); //"Sales" responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IItemInventoryRet itemInventoryRet = (IItemInventoryRet)response.Detail; int statusCode = response.StatusCode; if (statusCode == 0) { Console.Write("success adding inventory"); } else if (statusCode == 3100) { Console.Write("inventory exists, use update"); } Log(QBCRUDEAction.Add, "Inventory", (itemInventoryRet == null ? "" : itemInventoryRet.FullName.GetValue()), response); return itemInventoryRet; } else { IItemInventoryMod itemInventoryModRq = requestMsgSet.AppendItemInventoryModRq(); itemInventoryModRq.Name.SetValue(inventoryName); itemInventoryModRq.SalesDesc.SetValue(inventoryDescription); itemInventoryModRq.SalesPrice.SetValue(inventorySalePrice); itemInventoryModRq.ListID.SetValue(existingItemInventory.ListID.GetValue()); itemInventoryModRq.EditSequence.SetValue(existingItemInventory.EditSequence.GetValue()); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IItemInventoryRet itemInventoryRet = (IItemInventoryRet)response.Detail; int statusCode = response.StatusCode; if (statusCode == 0) { Console.WriteLine("success adding inventory"); } else if (statusCode == 3100) { Console.WriteLine("inventory exists, use update"); } Log(QBCRUDEAction.Update, "Inventory", (itemInventoryRet == null ? "" : itemInventoryRet.FullName.GetValue()), response); sessionManager.ClearErrorRecovery(); sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); return itemInventoryRet; } } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return null; }
internal static IAccountRet QBAddAccount(string accountName, bool isActive, ENAccountType accountType, string accountNumber) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string errecid = "{" + Guid.NewGuid().ToString() + "}"; sessionManager.ErrorRecoveryID.SetValue(errecid); sessionManager.EnableErrorRecovery = true; sessionManager.SaveAllMsgSetRequestInfo = true; #region error recovery if (sessionManager.IsErrorRecoveryInfo()) { IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; resMsgSet = sessionManager.GetErrorRecoveryStatus(); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { MessageBox.Show( "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { MessageBox.Show( "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { MessageBox.Show("No stored response was found."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { MessageBox.Show("Unable to store response."); } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; if (sCode == 0) { MessageBox.Show("Last request was processed and customer was added successfully!"); } else if (sCode > 0) { MessageBox.Show("There was a warning but last request was processed successfully!"); } else { MessageBox.Show("It seems that there was an error in processing last request"); reqMsgSet = sessionManager.GetSavedMsgSetRequest(); resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; if (statCode == 0) { string resStr = null; ICustomerRet custRet = resp.Detail as ICustomerRet; resStr = resStr + "Following customer has been successfully submitted to QuickBooks:\n\n\n"; if (custRet.ListID != null) { resStr = resStr + "ListID Number = " + Convert.ToString(custRet.ListID.GetValue()) + "\n"; } Log(QBCRUDEAction.ErrorRecovery, "SalesReceipt", (custRet == null ? "" : custRet.FullName.GetValue()), resp); } } } sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } #endregion IAccountRet existingQB = GetAccountByNameFilter(accountName); IAccountRet accountRet = null; if (existingQB == null) { IAccountAdd accountAddRq = requestMsgSet.AppendAccountAddRq(); accountAddRq.Name.SetValue(accountName); accountAddRq.AccountType.SetValue(accountType); accountAddRq.AccountNumber.SetValue(accountNumber); accountAddRq.IsActive.SetValue(isActive); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); int statusCode = response.StatusCode; accountRet = response.Detail as IAccountRet; if (statusCode == 0) { Console.WriteLine("Success"); } else if (statusCode == 3100) { MessageBox.Show("Account with same name exists"); } Log(QBCRUDEAction.Add, "Account", (accountRet == null ? "" : accountRet.FullName.GetValue()), response); return accountRet; } else { IAccountMod customerModRq = requestMsgSet.AppendAccountModRq(); customerModRq.Name.SetValue(accountName); customerModRq.IsActive.SetValue(isActive); customerModRq.AccountType.SetValue(accountType); customerModRq.AccountNumber.SetValue(accountNumber); customerModRq.ListID.SetValue(existingQB.ListID.GetValue()); customerModRq.EditSequence.SetValue(existingQB.EditSequence.GetValue()); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); int statusCode = response.StatusCode; accountRet = response.Detail as IAccountRet; if (statusCode == 0) { Console.WriteLine("Success"); } Log(QBCRUDEAction.Update, "Account", (accountRet == null ? "" : accountRet.FullName.GetValue()), response); } sessionManager.ClearErrorRecovery(); sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); return accountRet; } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); // throw new Exception(ex.Message); } return null; }
static void GetSalesmenAndRoutes() { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; // ISalesTaxCodeRetList ISalesRepQuery repsQuery = requestMsgSet.AppendSalesRepQueryRq(); // repsQuery.ORListQuery.FullNameList.Add(name); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ISalesRepRetList repsList = response.Detail as ISalesRepRetList; var salemen = new List<Salesman>(); if (repsList != null && repsList.Count > 0) { var company = GetCurrentCompany(); for (var i = 0; i < repsList.Count; i++) { ISalesRepRet rep = repsList.GetAt(i); if (rep != null && rep.IsActive.GetValue()) { var result = new Salesman() { distributrCode =company!=null?company.CompanyName.GetValue(): "", name = rep.SalesRepEntityRef != null ? rep.Initial.GetValue() : "",//rep.SalesRepEntityRef != null ? rep.SalesRepEntityRef.FullName.GetValue() : "", salesmanCode = rep.SalesRepEntityRef != null ? rep.Initial.GetValue() : "", mobileNumber ="" }; salemen.Add(result); } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); if (salemen.Any()) { DumpExportFilesAsync(salemen.ToCsv(), MasterDataCollective.DistributorSalesman.ToString()); var routes = salemen.Select(n=>new { Name=n.name, Code = n.salesmanCode, Region="default" //todo=>Figute out how to determine regions for each route }).ToCsv(); DumpExportFilesAsync(routes, MasterDataCollective.Route.ToString()); } } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } }
public static IAccountRetList QBGetChartOfAccountAccount(ENAccountType enAccountType) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); IAccountRetList accountRetList; try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; IAccountQuery accQ = requestMsgSet.AppendAccountQueryRq(); accQ.ORAccountListQuery.AccountListFilter.AccountTypeList.Add(enAccountType); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); accountRetList = response.Detail as IAccountRetList; sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); int attemp = 0; if (ex.Message.Contains("Object reference not set to an instance of an object") && attemp < 3) { QBGetChartOfAccountAccount(enAccountType); attemp++; } else { MessageBox.Show(ex.Message); } return null; } return accountRetList; }
public string CreateMultiSampleInvoice(string arlNumbers, Identification identification) { int invoiceNumber = 0; List<string> tests = new List<string>(); string testIds = null; List<string> charges = new List<string>(); string chargeIds = null; try { //Data for invoice DbCommand.CommandType = CommandType.StoredProcedure; DbCommand.CommandText = "uspGetMultipleInvoicableSamples"; DbCommand.Parameters.Clear(); DbCommand.Parameters.Add("@ARLNumbers", System.Data.SqlDbType.NVarChar, 4000).Value = arlNumbers; DataTable returnDT = DbConnection.ExecuteQuery(DbCommand); Invoice invoice = new Invoice(); foreach (DataRow row in returnDT.Rows) { invoice.ARLNumber = Convert.ToInt32(row["ARLNumber"]); invoice.ClientName = row["ClientName"].ToString(); invoice.AccountingId = row["AccountingId"].ToString(); invoice.PONumber = row["PONumber"].ToString(); invoice.TermName = row["TermName"].ToString(); invoice.IncludeYN = (bool)false; } DbCommand.CommandType = CommandType.StoredProcedure; DbCommand.CommandText = "uspGetMultipleInvoicableSampleItems"; DbCommand.Parameters.Clear(); DbCommand.Parameters.Add("@ARLNumbers", System.Data.SqlDbType.NVarChar, 4000).Value = arlNumbers; DataTable returnDT2 = DbConnection.ExecuteQuery(dbCommand); SmartCollection<InvoiceItem> itemList = new SmartCollection<InvoiceItem>(); foreach (DataRow row in returnDT2.Rows) { InvoiceItem invoiceItem = new InvoiceItem(); invoiceItem.AccountingCode = row["AccountingCode"].ToString(); invoiceItem.Class = row["DepartmentName"].ToString(); invoiceItem.Other1 = row["TestName"].ToString(); invoiceItem.Other2 = row["AnalystName"].ToString(); invoiceItem.Description = row["Description"].ToString(); if (row["BasePrice"] != DBNull.Value) invoiceItem.Amount = Convert.ToDouble(row["BasePrice"]); if (row["Ordering"].ToString() != "5" && !tests.Contains(row["SampleTestId"].ToString())) tests.Add(row["SampleTestId"].ToString()); if (row["Ordering"].ToString() == "5" && !charges.Contains(row["SampleTestId"].ToString())) charges.Add(row["SampleTestId"].ToString()); itemList.Add(invoiceItem); } invoice.InvoiceItems = itemList; //SessionManager sessionManager = SessionManager.getInstance(); QBSessionManager sessionManager = new QBSessionManager(); sessionManager.OpenConnection2("", "LIMS2", ENConnectionType.ctLocalQBD); sessionManager.BeginSession("", ENOpenMode.omDontCare); //IMsgSetRequest requestMsgSet = sessionManager.getMsgSetRequest(); //IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 13, 0); IMsgSetRequest requestMsgSet = getLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; // ERROR RECOVERY: // All steps are described in QBFC Developers Guide, on pg 41 // under section titled "Automated Error Recovery" // (1) Set the error recovery ID using ErrorRecoveryID function // Value must be in GUID format // You could use c:\Program Files\Microsoft Visual Studio\Common\Tools\GuidGen.exe // to create a GUID for your unique ID string errecid = "{C5F2272F-4DAD-435F-8ABB-EB1AC0802D52}"; sessionManager.ErrorRecoveryID.SetValue(errecid); // (2) Set EnableErrorRecovery to true to enable error recovery sessionManager.EnableErrorRecovery = true; // (3) Set SaveAllMsgSetRequestInfo to true so the entire contents of the MsgSetRequest // will be saved to disk. If SaveAllMsgSetRequestInfo is false (default), only the // newMessageSetID will be saved. sessionManager.SaveAllMsgSetRequestInfo = true; // (4) Use IsErrorRecoveryInfo to check whether an unprocessed response exists. // If IsErrorRecoveryInfo is true: if (sessionManager.IsErrorRecoveryInfo()) { //string reqXML; //string resXML; IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; // a. Get the response status, using GetErrorRecoveryStatus resMsgSet = sessionManager.GetErrorRecoveryStatus(); // resXML = resMsgSet.ToXMLString(); // MessageBox.Show(resXML); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { // This case may occur when a transaction has failed after QB processed // the request but client app didn't get the response and started with // another company file. // MessageBox.Show("The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); int i = 0; } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { // MessageBox.Show("Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); int i = 0; } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { // Response was not successfully stored or stored properly // MessageBox.Show("No stored response was found."); int i = 0; } // 9003 = Not used else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { // MessageSetID is set with a string of size > 24 char //MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); int i = 0; } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { //MessageBox.Show("Unable to store response."); int i = 0; } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; //string sMessage = res.StatusMessage; //string sSeverity = res.StatusSeverity; //MessageBox.Show("StatusCode = " + sCode + "\n" + "StatusMessage = " + sMessage + "\n" + "StatusSeverity = " + sSeverity); if (sCode == 0) { //MessageBox.Show("Last request was processed and Invoice was added successfully!"); int i = 0; } else if (sCode > 0) { //MessageBox.Show("There was a warning but last request was processed successfully!"); int i = 0; } else { //MessageBox.Show("It seems that there was an error in processing last request"); // b. Get the saved request, using GetSavedMsgSetRequest reqMsgSet = sessionManager.GetSavedMsgSetRequest(); //reqXML = reqMsgSet.ToXMLString(); //MessageBox.Show(reqXML); // c. Process the response, possibly using the saved request resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; if (statCode == 0) { string resStr = null; IInvoiceRet invRet = resp.Detail as IInvoiceRet; resStr = resStr + "Following invoice has been successfully submitted to QuickBooks:\n\n\n"; if (invRet.TxnNumber != null) resStr = resStr + "Txn Number = " + Convert.ToString(invRet.TxnNumber.GetValue()) + "\n"; } // if (statusCode == 0) } // else (sCode) } // else (MessageSetStatusCode) // d. Clear the response status, using ClearErrorRecovery sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } IInvoiceAdd invAdd = requestMsgSet.AppendInvoiceAddRq(); invAdd.TemplateRef.FullName.SetValue("Copy 2 : Intuit Service Invoice"); // CustomerRef -> FullName if (invoice.ClientName != "") { invAdd.CustomerRef.FullName.SetValue(invoice.AccountingId); } // PO Number if (invoice.PONumber != "") { invAdd.PONumber.SetValue(invoice.PONumber); } // Terms if (invoice.TermName != "") { invAdd.TermsRef.FullName.SetValue(invoice.TermName); DateTime DT_DueDate = System.DateTime.Today; double dueInDays = getDueInDays(invoice.TermName); DT_DueDate = DT_DueDate.AddDays(dueInDays); invAdd.DueDate.SetValue(DT_DueDate); } // TxnDate DateTime DT_TxnDate = System.DateTime.Today; invAdd.TxnDate.SetValue(DT_TxnDate); // CustomerMsgRef -> FullName invAdd.CustomerMsgRef.FullName.SetValue("Thank you for your business."); //Line Items foreach (InvoiceItem item in invoice.InvoiceItems) { IORInvoiceLineAdd invLineAdd = invAdd.ORInvoiceLineAddList.Append(); if (item.AccountingCode != "") { invLineAdd.InvoiceLineAdd.ItemRef.FullName.SetValue(item.AccountingCode); } if (item.Class != "") { invLineAdd.InvoiceLineAdd.ClassRef.FullName.SetValue(item.Class); } if (item.Other1 != "") { invLineAdd.InvoiceLineAdd.Other1.SetValue(item.Other1); } if (item.Other2 != "") { invLineAdd.InvoiceLineAdd.Other2.SetValue(item.Other2); } if (item.Description != "") { invLineAdd.InvoiceLineAdd.Desc.SetValue(item.Description); } //invLineAdd.InvoiceLineAdd. if (item.AccountingCode != "DISCOUNT") invLineAdd.InvoiceLineAdd.Quantity.SetValue(Convert.ToDouble(1)); if (item.Amount.IsNotNull()) { invLineAdd.InvoiceLineAdd.ORRatePriceLevel.Rate.SetValue(Convert.ToDouble(item.Amount)); } if (item.Amount.IsNotNull()) { invLineAdd.InvoiceLineAdd.Amount.SetValue(Convert.ToDouble(item.Amount)); } } // Execute request in QB IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); //IMsgSetResponse responseMsgSet = processRequestFromQB(sessionManager, requestMsgSet); //sessionManager.endSession(); //sessionManager.closeConnection(); sessionManager.EndSession(); sessionManager.CloseConnection(); sessionManager = null; string[] status = new string[3]; if (responseMsgSet != null) status = parseInvoiceAddRs(responseMsgSet); string msg = ""; if (responseMsgSet != null & status[0] == "0") { IInvoiceRet retInv = responseMsgSet.ResponseList.GetAt(0).Detail as IInvoiceRet; IQBIntType new_inv_num = retInv.TxnNumber as IQBIntType; invoiceNumber = Convert.ToInt32(new_inv_num.GetValue()) - 1; msg = "Invoice was added successfully!"; foreach (string test in tests) testIds = testIds + test.ToString() + ","; if (testIds != null) testIds = testIds.Substring(0, testIds.Length - 1); foreach (string charge in charges) chargeIds = chargeIds + charge.ToString() + ","; if (chargeIds != null) chargeIds = chargeIds.Substring(0, chargeIds.Length - 1); DbCommand.CommandType = CommandType.StoredProcedure; DbCommand.CommandText = "uspSaveInvoiceNumberForTests"; DbCommand.Parameters.Clear(); DbCommand.Parameters.Add("@Tests", System.Data.SqlDbType.NVarChar, 4000).Value = testIds; if (chargeIds != null) DbCommand.Parameters.Add("@Charges", System.Data.SqlDbType.NVarChar, 4000).Value = chargeIds; else DbCommand.Parameters.Add("@Charges", System.Data.SqlDbType.NVarChar, 4000).Value = ""; DbCommand.Parameters.Add("@QBInvoiceNumber", System.Data.SqlDbType.Int).Value = invoiceNumber; DbConnection.ExecuteQuery(DbCommand); } else { //throw new Exception(status[2]); msg = "Could not add invoice."; if (status[2].IndexOf("Message") > 0) throw new Exception("Customer Message not found in QuickBooks."); else if (status[2].IndexOf("Customer") > 0) throw new Exception("Client not found in QuickBooks."); else if (status[2].IndexOf("Item") > 0) { string sub = status[2].Substring(status[2].IndexOf("\"") + 1); int len = sub.IndexOf("\""); throw new Exception("Item " + status[2].Substring(status[2].IndexOf("\"") + 1, len) + " not found in QuickBooks."); } else throw new Exception(status[2]); } msg = msg + "\n\n"; msg = msg + "Status Code = " + status[0] + "\n"; msg = msg + "Status Severity = " + status[1] + "\n"; msg = msg + "Status Message = " + status[2] + "\n"; } catch { throw; } return invoiceNumber.ToString(); }
private void QBUpdateCustomerRecord(Customer theCustomer) { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; try { //Create the session Manager object sessionManager = new QBSessionManager(); //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 2, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; sessionManager.OpenConnection(MMSUtility.QBAppID, MMSUtility.QBAppName); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; //modify the info ICustomerMod customerModRq = requestMsgSet.AppendCustomerModRq(); //if (theCustomer.FirstName.Length > 0) customerModRq.Name.SetValue(theCustomer.Name); //if (theCustomer.FirstName.Length > 0) customerModRq.FirstName.SetValue(theCustomer.FirstName); //if (theCustomer.LastName.Length > 0) customerModRq.LastName.SetValue(theCustomer.LastName); //if (theCustomer.Address.Length > 0) string szName = theCustomer.FirstName + " " + theCustomer.LastName; customerModRq.BillAddress.Addr1.SetValue(szName); customerModRq.BillAddress.Addr2.SetValue(theCustomer.Address); //if (theCustomer.City.Length > 0) customerModRq.BillAddress.City.SetValue(theCustomer.City); //if (theCustomer.State.Length > 0) customerModRq.BillAddress.State.SetValue(theCustomer.State); //if (theCustomer.Zip.Length > 0) customerModRq.BillAddress.PostalCode.SetValue(theCustomer.Zip); //if (theCustomer.Phone.Length > 0) customerModRq.Phone.SetValue(theCustomer.Phone); //if (theCustomer.Email.Length > 0) customerModRq.Email.SetValue(theCustomer.Email); //if (theCustomer.Company.Length > 0) customerModRq.CompanyName.SetValue(theCustomer.Company); //if (theCustomer.Terms.Length > 0) customerModRq.TermsRef.FullName.SetValue(theCustomer.Terms); customerModRq.ListID.SetValue(theCustomer.QuickBooksID); customerModRq.EditSequence.SetValue(theCustomer.EditSequence); //customerModRq.IsActive.SetValue(true); //Send the request to QuickBooks IMsgSetResponse responsMsgSet = sessionManager.DoRequests(requestMsgSet); } catch (Exception exe) { MMSUtility.LogFile(exe.Message, "", "QBUpdateCustomerRecord", exe.LineNumber(), "CustomerView"); MessageBox.Show(exe.Message, "Error: Failed to Update"); } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } }
public static bool CanConnect() { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; sessionManager.EndSession(); sessionManager.CloseConnection(); return boolSessionBegun; }catch(Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); MessageBox.Show(error); return false; } }
public IMsgSetRequest getLatestMsgSetRequest(QBSessionManager sessionManager) { // Find and adapt to supported version of QuickBooks double supportedVersion = QBFCLatestVersion(sessionManager); short qbXMLMajorVer = 0; short qbXMLMinorVer = 0; if (supportedVersion >= 6.0) { qbXMLMajorVer = 6; qbXMLMinorVer = 0; } else if (supportedVersion >= 5.0) { qbXMLMajorVer = 5; qbXMLMinorVer = 0; } else if (supportedVersion >= 4.0) { qbXMLMajorVer = 4; qbXMLMinorVer = 0; } else if (supportedVersion >= 3.0) { qbXMLMajorVer = 3; qbXMLMinorVer = 0; } else if (supportedVersion >= 2.0) { qbXMLMajorVer = 2; qbXMLMinorVer = 0; } else if (supportedVersion >= 1.1) { qbXMLMajorVer = 1; qbXMLMinorVer = 1; } else { qbXMLMajorVer = 1; qbXMLMinorVer = 0; // MessageBox.Show("It seems that you are running QuickBooks 2002 Release 1. We strongly recommend that you use QuickBooks' online update feature to obtain the latest fixes and enhancements"); } // Create the message set request object IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", qbXMLMajorVer, qbXMLMinorVer); return requestMsgSet; }
internal static ITransferInventoryRet ReturnInventory(QuickBooksReturnInventoryDocumentDto orderDoc) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; var salesmanCode = orderDoc.SalesmanCode; var fromSite = GetStockSiteBySalesperson(salesmanCode); var toSite =string.Empty; if (!string.IsNullOrEmpty(fromSite)) { toSite = GetIssuingWarehouse(fromSite); } if (string.IsNullOrEmpty(toSite)) { toSite = "Unspecified Site"; } ITransferInventoryAdd transferInventoryAddRq = requestMsgSet.AppendTransferInventoryAddRq(); transferInventoryAddRq.FromInventorySiteRef.FullName.SetValue(fromSite); transferInventoryAddRq.ToInventorySiteRef.FullName.SetValue(toSite); transferInventoryAddRq.TxnDate.SetValue(DateTime.Parse(DateTime.Now.ToString()));//orderDoc.DateOfIssue.ToString())); //Certain date form the incoming document foreach (var lineItem in orderDoc.LineItems) { ITransferInventoryLineAdd transferInventoryLineAddList = transferInventoryAddRq.TransferInventoryLineAddList.Append(); IItemInventoryRet product = GetProductByCode(lineItem.ProductCode); var prod = product.FullName.GetValue(); if (product != null) transferInventoryLineAddList.ItemRef.FullName.SetValue(product.FullName.GetValue()); transferInventoryLineAddList.QuantityToTransfer.SetValue(Convert.ToDouble(Math.Round(lineItem.Quantity, 2)));//Set the value of the qantity being transfered } responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); int statusCode = response.StatusCode; ITransferInventoryRet transferInventoryRet = response.Detail as ITransferInventoryRet; if (statusCode == 0) { Console.WriteLine("Success"); } else { MessageBox.Show(response.StatusMessage); } //sessionManager.ClearErrorRecovery(); sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); Log(QBCRUDEAction.Add, "TransferInventoryReturns", (transferInventoryRet == null ? "" : transferInventoryRet.RefNumber.GetValue()), response); return transferInventoryRet; } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return null; }
internal static List<InventoryImport> PullInitialInventory() { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); List<InventoryImport> inventory = new List<InventoryImport>(); var products=GetAllProducts(); var distributorInventoryList = new List<InventoryImport>(); var stockSiteCodMappingList = GetStockSiteCodeMapping(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; //ITransferInventoryQuery transferInventoryQuery = requestMsgSet.AppendTransferInventoryQueryRq(); ////Change from to the date in the lastdateofsync //var fileLocation = FileUtility.GetInventoryFile("LastDateOfSync"); //var from = FileUtility.ReadFile(fileLocation);// DateTime.Now.AddMonths(-1).ToString(); //if (string.IsNullOrWhiteSpace(from)) //{ // from = ConfigurationManager.AppSettings["lastDateOfSync"]; //} ////var fromDate = DateTime.Now.AddHours(-7).ToString(); //var newSyncDate = DateTime.Now.ToString(); //////if(from) ////transferInventoryQuery.ORTransferInventoryQuery.TxnFilterNoCurrency.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTime.Parse(from), false); ////transferInventoryQuery.ORTransferInventoryQuery.TxnFilterNoCurrency.ORDateRangeFilter.ModifiedDateRangeFilter.ToModifiedDate.SetValue(DateTime.Parse(newSyncDate), false); IItemSitesQuery itemSitesQuery = requestMsgSet.AppendItemSitesQueryRq(); var references = GetStockSiteReference(); // references.ToList().ForEach(s => itemSitesQuery.ORItemSitesQuery.ListIDList.Add(s.Key)); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse respons = responseMsgSet.ResponseList.GetAt(0); IItemSitesRetList lineRetList = respons.Detail as IItemSitesRetList; if (lineRetList != null) { var RetCount = lineRetList.Count; for (int i = 0; i < RetCount; i++) { if (lineRetList != null) { var TransferInventoryRet = lineRetList.GetAt(i); if (TransferInventoryRet != null) { if (TransferInventoryRet.InventorySiteRef == null || TransferInventoryRet.InventorySiteRef.FullName==null) { continue; } var siteName = TransferInventoryRet.InventorySiteRef.FullName.GetValue(); var salesman =stockSiteCodMappingList.ContainsKey(siteName)? stockSiteCodMappingList[siteName]:"Default";//GetStockSiteCode(siteName); var quantityOnHand = TransferInventoryRet.QuantityOnHand.GetValue(); var inventoryItemFullName=TransferInventoryRet.ORItemAssemblyORInventory.ItemInventoryRef.FullName.GetValue(); var product = products.FirstOrDefault(p=>p.pDesc==inventoryItemFullName); if(product!=null ) { var productCode = product.pCode; if(product.exfactory>0) { var distributorInventory = new InventoryImport() { ToSiteName = salesman, Balance = Convert.ToDecimal(quantityOnHand), ProductName = productCode }; distributorInventoryList.Add(distributorInventory); } } } } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); //var filename = "Stockline-Alidi Kenya Limited-" + DateTime.Now.ToString("yyyyMMdd"); distributorInventoryList = distributorInventoryList.GroupBy(n => new { n.ProductName, n.ToSiteName }) .Select(m => new InventoryImport { Balance = m.Sum(g => g.Balance), ProductName = m.Key.ProductName, ToSiteName = m.Key.ToSiteName }).ToList(); //DumpExportInventoryFileAsync(distributorInventoryList.ToCsv(), filename); //DumpExportInventoryFileAsync(newSyncDate, "LastDateOfSync"); //var filePath = FileUtility.GetInventoryFile(filename); //SendToDistributor(filePath); } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return distributorInventoryList.OrderBy(n=>n.ToSiteName).ThenBy(n=>n.ProductName).Distinct().ToList(); }
internal static IItemInventoryRet GetInventoryByNameFilter(string inventoryName) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); IItemInventoryRet itemInventoryRet = null; try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; IItemInventoryQuery itemInventoryQ = requestMsgSet.AppendItemInventoryQueryRq(); itemInventoryQ.ORListQueryWithOwnerIDAndClass.FullNameList.Add(inventoryName); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IItemInventoryRetList itemInventoryRetList = response.Detail as IItemInventoryRetList; if (itemInventoryRetList != null && itemInventoryRetList.Count > 0) { itemInventoryRet = itemInventoryRetList.GetAt(0); } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return itemInventoryRet; }
internal static ISalesOrderRet QBAddSalesOrder( QuickBooksOrderDocumentDto orderDoc, string externalOrderRef) { if (orderDoc.DocumentType != DocumentType.Order) throw new ArgumentException("document is not an an order"); var stockSiteRef = GetStockSiteBySalesperson(orderDoc.SalesmanCode); if (string.IsNullOrEmpty(stockSiteRef)) { stockSiteRef = "Unspecified Site"; } bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string errecid = "{" + Guid.NewGuid().ToString() + "}"; sessionManager.ErrorRecoveryID.SetValue(errecid); sessionManager.EnableErrorRecovery = true; sessionManager.SaveAllMsgSetRequestInfo = true; #region error recovery if (sessionManager.IsErrorRecoveryInfo()) { IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; resMsgSet = sessionManager.GetErrorRecoveryStatus(); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { MessageBox.Show( "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { MessageBox.Show( "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { MessageBox.Show("No stored response was found."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { MessageBox.Show("Unable to store response."); } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; if (sCode == 0) { MessageBox.Show("Last request was processed and customer was added successfully!"); } else if (sCode > 0) { MessageBox.Show("There was a warning but last request was processed successfully!"); } else { MessageBox.Show("It seems that there was an error in processing last request"); reqMsgSet = sessionManager.GetSavedMsgSetRequest(); resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; if (statCode == 0) { string resStr = null; ISalesOrderRet custRet = resp.Detail as ISalesOrderRet; resStr = resStr + "Following sale/order has been successfully submitted to QuickBooks:\n\n\n"; if (custRet.TxnID != null) { resStr = resStr + "ListID Number = " + Convert.ToString(custRet.TxnID.GetValue()) + "\n"; Log(resStr); } } } } sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } #endregion ISalesOrderAdd saleOrderAddRq = requestMsgSet.AppendSalesOrderAddRq(); //Set field value for MatchCriterion //inventorySiteQuery.ORInventorySiteQuery.InventorySiteFilter.ORNameFilter.NameFilter.MatchCriterion.SetValue(ENMatchCriterion.mcContains); ////Set field value for Name //inventorySiteQuery.ORInventorySiteQuery.InventorySiteFilter.ORNameFilter.NameFilter.Name.SetValue(orderDoc.SalesmanName); //var value=inventorySiteQuery.IncludeRetElementList.Count.ToString(); //var counted = inventorySiteQuery.ORInventorySiteQuery.FullNameList.Count.ToString(); // IInventorySiteRetList list=requestMsgSet.appendinventorys saleOrderAddRq.CustomerRef.FullName.SetValue(orderDoc.OutletName); saleOrderAddRq.DueDate.SetValue(Convert.ToDateTime(orderDoc.OrderDateRequired)); saleOrderAddRq.Memo.SetValue(orderDoc.Note); saleOrderAddRq.RefNumber.SetValue(externalOrderRef); //Get the Stock Site to be used to populate the inventory Site Ref saleOrderAddRq.TxnDate.SetValue(Convert.ToDateTime(orderDoc.DocumentDateIssued)); foreach (var lineItem in orderDoc.LineItems) { IItemInventoryRet product = GetProductByCode(lineItem.ProductCode); if (product == null) continue; ISalesOrderLineAdd saleOrderLineAddRq = saleOrderAddRq.ORSalesOrderLineAddList.Append().SalesOrderLineAdd; saleOrderLineAddRq.ItemRef.FullName.SetValue(product.FullName.GetValue()); saleOrderLineAddRq.Quantity.SetValue(Convert.ToDouble(lineItem.Quantity)); saleOrderLineAddRq.Amount.SetValue(Convert.ToDouble(Math.Round(lineItem.TotalNet,2))); //saleOrderLineAddRq if(!string.IsNullOrEmpty(lineItem.VATClass)) { saleOrderLineAddRq.SalesTaxCodeRef.FullName.SetValue(lineItem.VATClass); saleOrderLineAddRq.TaxAmount.SetValue(Convert.ToDouble(Math.Round(lineItem.TotalVat, 2))); } //saleOrderLineAddRq.InventorySiteRef.FullName.SetValue("ELDORET"); saleOrderLineAddRq.InventorySiteRef.FullName.SetValue(stockSiteRef); //This feature is not supported in the specified version of qbXML. //catch (Exception EX_NAME) { // Console.WriteLine(EX_NAME); // Log(EX_NAME.Message); //} saleOrderLineAddRq.Desc.SetValue(lineItem.ProductDescription); saleOrderLineAddRq.ORRatePriceLevel.Rate.SetValue(Convert.ToDouble(lineItem.LineItemValue)); } responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); int statusCode = response.StatusCode; ISalesOrderRet salesOrderRet = response.Detail as ISalesOrderRet; if (statusCode == 0) { Console.WriteLine("Success"); } else { MessageBox.Show(response.StatusMessage); } sessionManager.ClearErrorRecovery(); sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); Log(QBCRUDEAction.Add, "SalesOrder", (salesOrderRet == null ? "" : salesOrderRet.RefNumber.GetValue()), response); return salesOrderRet; } catch (Exception ex) { if (boolSessionBegun) { //sessionManager.EndSession(); //sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); throw new Exception(ex.Message); } return null; }
static double QBFCLatestVersion(QBSessionManager SessionManager) { IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0); msgset.AppendHostQueryRq(); IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset); IResponse response = QueryResponse.ResponseList.GetAt(0); IHostRet HostResponse = response.Detail as IHostRet; IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList; int i; double vers; double LastVers = 0; string svers = null; for (i = 0; i <= supportedVersions.Count - 1; i++) { svers = supportedVersions.GetAt(i); vers = Convert.ToDouble(svers); if (vers > LastVers) { LastVers = vers; } } return LastVers; }
internal static IReceivePaymentRet QbAddPayment(QuickBooksOrderDocumentDto receipt, string qbInvoiceTxnId, string accountRef, List<string> references) { if (receipt.DocumentType != DocumentType.Receipt) throw new ArgumentException("document is not an an Receipt"); bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string errecid = "{" + Guid.NewGuid().ToString() + "}"; sessionManager.ErrorRecoveryID.SetValue(errecid); sessionManager.EnableErrorRecovery = true; sessionManager.SaveAllMsgSetRequestInfo = true; #region error recovery if (sessionManager.IsErrorRecoveryInfo()) { IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; resMsgSet = sessionManager.GetErrorRecoveryStatus(); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { MessageBox.Show( "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { MessageBox.Show( "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { MessageBox.Show("No stored response was found."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { MessageBox.Show("Unable to store response."); } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; if (sCode == 0) { MessageBox.Show("Last request was processed and customer was added successfully!"); } else if (sCode > 0) { MessageBox.Show("There was a warning but last request was processed successfully!"); } else { MessageBox.Show("It seems that there was an error in processing last request"); reqMsgSet = sessionManager.GetSavedMsgSetRequest(); resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; if (statCode == 0) { string resStr = null; IReceivePaymentRet custRet = resp.Detail as IReceivePaymentRet; resStr = resStr + "Following customer has been successfully submitted to QuickBooks:\n\n\n"; if (custRet.TxnID != null) { resStr = resStr + "ListID Number = " + Convert.ToString(custRet.TxnID.GetValue()) + "\n"; } Log(QBCRUDEAction.ErrorRecovery, "Invoice", (custRet == null ? "" : custRet.RefNumber.GetValue()), resp); } } } sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } #endregion //var iterator =1; //IItemInventoryRet product = GetProductByCode(receiptLineItem.ProductCode); //if (product == null) continue; IReceivePaymentAdd receivePaymentAddRq = requestMsgSet.AppendReceivePaymentAddRq(); receivePaymentAddRq.CustomerRef.FullName.SetValue(receipt.OutletName); receivePaymentAddRq.TxnDate.SetValue(Convert.ToDateTime(receipt.DocumentDateIssued)); receivePaymentAddRq.RefNumber.SetValue(receipt.GenericReference.Substring((receipt.GenericReference.Length - 11), 11)); var paymentmethod = "Cash"; var quickBooksOrderDocLineItem = receipt.LineItems.FirstOrDefault(); if (quickBooksOrderDocLineItem != null && !string.IsNullOrEmpty(quickBooksOrderDocLineItem.PaymentType)) { paymentmethod = quickBooksOrderDocLineItem.PaymentType; } //var paymentmethod = quickBooksOrderDocLineItem.PaymentType; receivePaymentAddRq.PaymentMethodRef.FullName.SetValue(paymentmethod); receivePaymentAddRq.ARAccountRef.ListID.SetValue(accountRef); //decimal total = 0m; //foreach (var item in receipt.LineItems) //{ // total += item.LineItemValue; //} var total = receipt.LineItems.Sum(receiptLineItem => receiptLineItem.LineItemValue); receivePaymentAddRq.TotalAmount.SetValue(Convert.ToDouble(Math.Round(total, 2))); receivePaymentAddRq.ORApplyPayment.IsAutoApply.SetValue(true); try { // receivePaymentAddRq.SetValue(Convert.ToDouble(Math.Round(receiptLineItem.TotalVat, 2))); } catch (Exception e) { Console.WriteLine(e); Log(e.Message); } responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IReceivePaymentRet salesReceipRet = response.Detail as IReceivePaymentRet; int statusCode = response.StatusCode; if (statusCode == 0) { Console.WriteLine("Success"); } sessionManager.ClearErrorRecovery(); sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); Log(QBCRUDEAction.Add, "SalesReceipt", (salesReceipRet == null ? "" : salesReceipRet.RefNumber.GetValue()), response); return salesReceipRet; } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return null; }
private async void ExportSelected() { Application.Current.Dispatcher.BeginInvoke( new Action( delegate { try { string _appName = "Distributr QB Intergration"; string qdbpath = ConfigurationSettings.AppSettings["QuickBooksCompanyFilePath"]; QBSessionManager sessionManager = new QBSessionManager(); sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); HomeViewModel.GlobalStatus = string.Format("Exporting {0} sales to Quick Books ...", SalesOrdersList.Count(n => n.IsSelected)); int cnt = 0; Random random = new Random(); if (tabItem.Name=="TabSales") { foreach ( var sale in SalesOrdersList.Where(n => n.IsSelected)) { var order = PagedList.FirstOrDefault( p => p.GenericReference == sale.GenericReference); if (order != null && ExportAudits.All(p=>!p.Equals(order.GenericReference))) { string externalOrderRef = order.ExternalReference; //GetExternalOrderRef(random); var qbOrder = QBIntegrationMethods.AddOrder( order,externalOrderRef); if (qbOrder != null) { ExportAudits.Add(order.GenericReference); var quickBooksId = qbOrder.TxnID.GetValue(); string externalInvoiceRef = GetExternalOrderRef(random); var invoice = PagedList.FirstOrDefault( p => p.DocumentType == DocumentType.Invoice && p.ExternalReference == order.ExternalReference); if (invoice != null) { var account=SelectedTradeReceivableAccount.QBAccountId.ToString(CultureInfo.InvariantCulture); var inv= QBIntegrationMethods.AddInvoice( invoice, quickBooksId, order.OutletName, externalInvoiceRef, account); if(inv!=null) { var receipt = PagedList.FirstOrDefault( p => p.DocumentType == DocumentType.Receipt && p.ExternalReference == order.ExternalReference); if(receipt!=null) { var invoiceId = inv.TxnID.GetValue(); var accountRef = inv.ARAccountRef.ListID.GetValue(); // var rec = QBIntegrationMethods.AddSaleReceipt(receipt); var count = receipt.LineItems.Count; var references = new List<string>(); if(count>1) { for(int y=0;y<count;y++) { references.Add(GetExternalOrderRef(random)); } } var rec = QBIntegrationMethods.AddPayment(receipt, invoiceId, accountRef, references); } } } } } } } else if (tabItem.Name == "TabReturns") { foreach (var returnItem in ReturnInventoryItemList.Where(n => n.IsSelected)) { ReturnInventoryItem item = returnItem; var retItem = ReturnsList.FirstOrDefault( p => p.GenericReference == returnItem.GenericReference); if (retItem != null && ExportAudits.All(p => !p.Equals(retItem.GenericReference))) { var rec = QBIntegrationMethods.ReturnInventory(retItem); if (rec != null) { ExportAudits.Add(retItem.GenericReference); } } } } else if (tabItem.Name == "TabOrders") { foreach ( var sale in SalesOrdersList.Where(n => n.IsSelected)) { var order = PagedList.FirstOrDefault( p => p.GenericReference == sale.GenericReference); if (order != null && ExportAudits.All(p => !p.Equals(order.GenericReference))) { string externalOrderRef = order.ExternalReference; //GetExternalOrderRef(random); var qbOrder = QBIntegrationMethods.AddOrder(order, externalOrderRef); if (qbOrder!=null) { ExportAudits.Add(order.GenericReference); } } } } AcknowledgeAsync(); HomeViewModel.GlobalStatus =string.Format("Done..!"); if (tabItem.Name == "TabSales" || tabItem.Name == "TabOrders") { LoadClosedSalesOrders(); } else if (tabItem.Name == "TabReturns") { ShowReturns(); } sessionManager.EndSession(); // boolSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Quick Books Message", MessageBoxButton.OKCancel, MessageBoxImage.Information); } })); }
public string AddModQBInvoice(string szCustomerName, string szInvoiceQuickbookID, InvoiceItem invoiceItem1, DateTime jobDate, string itemA_ID) { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; string invoiceID = ""; bool bItemInvoice1 = false; try { //DateTime curDate = DateTime.Now; DateTime curDate = jobDate; //otherwise find for the lastest one /* int prevMonth = DateTime.Today.AddMonths(-1).Month; int curMonth = DateTime.Today.Month; int nextMonth = DateTime.Today.AddMonths(1).Month; int year = DateTime.Today.Year; */ //int prevMonth = curDate.AddMonths(-1).Month; int curMonth = curDate.Month; int nextMonth = curDate.AddMonths(1).Month; int year = curDate.Year; int nextyear = curDate.AddYears(1).Year; DateTime fromDate; DateTime toDate; Item item1 = pQBitems1[ItemComboBox1.SelectedIndex]; //Create the session Manager object sessionManager = new QBSessionManager(); //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 8, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; sessionManager.OpenConnection(MMSUtility.QBAppID, MMSUtility.QBAppName); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; //find the customer information ICustomerQuery search = requestMsgSet.AppendCustomerQueryRq(); search.ORCustomerListQuery.CustomerListFilter.ORNameFilter.NameFilter.MatchCriterion.SetValue(ENMatchCriterion.mcStartsWith); search.ORCustomerListQuery.CustomerListFilter.ORNameFilter.NameFilter.Name.SetValue(szCustomerName); IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ICustomerRetList customerRetList = (ICustomerRetList)response.Detail; if (customerRetList == null) { //MessageBox.Show("Cannot find customer in QB!\nPlease check QB for Customer Name."); return invoiceID; } ICustomerRet customerRet = customerRetList.GetAt(0); Customer customer = new Customer(); customer.Name = customerRet.Name.GetValue(); customer.QuickBooksID = customerRet.ListID.GetValue(); customer.EditSequence = customerRet.EditSequence.GetValue(); if (customerRet.FirstName != null) customer.FirstName = customerRet.FirstName.GetValue(); if (customerRet.LastName != null) customer.LastName = customerRet.LastName.GetValue(); bool notFound = true; if (szInvoiceQuickbookID.Length > 0) { //get the lastest associated invoices for the particular customer requestMsgSet.ClearRequests(); IInvoiceQuery invoiceQueryRq = requestMsgSet.AppendInvoiceQueryRq(); invoiceQueryRq.IncludeLineItems.SetValue(true); //if invoiceID exist, use that invoiceQueryRq.ORInvoiceQuery.TxnIDList.Add(szInvoiceQuickbookID); //Send the request and get the response from QuickBooks responseMsgSet = sessionManager.DoRequests(requestMsgSet); response = responseMsgSet.ResponseList.GetAt(0); IInvoiceRetList invoiceRetList1 = (IInvoiceRetList)response.Detail; if (invoiceRetList1 != null) { notFound = false; } } // there is no existing invoice based on id, then search for invoice on date if (notFound) { //get the from prevmonth to curmonth invoice if ((curDate.Day >= 1) && (curDate.Day <= 19)) { fromDate = new DateTime(year, curMonth, 1); toDate = new DateTime(year, curMonth, 20); } //get curmonth to nextmonth invoice else { if (nextMonth == 1) { fromDate = new DateTime(year, curMonth, 21); toDate = new DateTime(nextyear, nextMonth, 20); } else { //if next month is jan, then account for next year fromDate = new DateTime(year, curMonth, 21); toDate = new DateTime(year, nextMonth, 20); } } //get the lastest associated invoices for the particular customer requestMsgSet.ClearRequests(); IInvoiceQuery invoiceQueryRq = requestMsgSet.AppendInvoiceQueryRq(); invoiceQueryRq.IncludeLineItems.SetValue(true); invoiceQueryRq.ORInvoiceQuery.InvoiceFilter.EntityFilter.OREntityFilter.FullNameList.Add(szCustomerName); invoiceQueryRq.ORInvoiceQuery.InvoiceFilter.ORDateRangeFilter.TxnDateRangeFilter.ORTxnDateRangeFilter.TxnDateFilter.FromTxnDate.SetValue(fromDate); invoiceQueryRq.ORInvoiceQuery.InvoiceFilter.ORDateRangeFilter.TxnDateRangeFilter.ORTxnDateRangeFilter.TxnDateFilter.ToTxnDate.SetValue(toDate); //ENPaidStatus status = ENPaidStatus.psNotPaidOnly; //invoiceQueryRq.ORInvoiceQuery.InvoiceFilter.PaidStatus.SetValue(status); } //Send the request and get the response from QuickBooks responseMsgSet = sessionManager.DoRequests(requestMsgSet); response = responseMsgSet.ResponseList.GetAt(0); IInvoiceRetList invoiceRetList = (IInvoiceRetList)response.Detail; //check for FC int numIndex = -1; if (invoiceRetList != null) { numIndex = 0; IInvoiceRet invoiceRet1 = invoiceRetList.GetAt(numIndex); string refNum = invoiceRet1.RefNumber.GetValue(); if (refNum.StartsWith("FC")) { //get the next one if (invoiceRetList.Count > 1) numIndex = 1; else numIndex = -1; } } //if need new invoice if ((invoiceRetList == null) || (numIndex == -1)) { Invoice invoice = new Invoice(); invoice.Customer = customer; requestMsgSet.ClearRequests(); IInvoiceAdd invoiceAddRq = requestMsgSet.AppendInvoiceAddRq(); //get the current month DateTime invoiceDate; if ((curDate.Day >= 1) && (curDate.Day <= 19)) { invoiceDate = new DateTime(year, curMonth, 20); } //get next month else { if (nextMonth == 1) { invoiceDate = new DateTime(nextyear, nextMonth, 20); } else { //if next month is jan, then account for next year invoiceDate = new DateTime(year, nextMonth, 20); }; } invoiceAddRq.TxnDate.SetValue(invoiceDate); invoiceAddRq.CustomerRef.ListID.SetValue(invoice.Customer.QuickBooksID); ///////////////////////////////////////////////////////////////////////////////// if (invoiceItem1.Amount >= 0) { if (invoiceItem1.Amount == 0) { string msg = "Warning: Invoice = $0 for" + szCustomerName; MMSUtility.LogFile(msg, "", "AddModQBInvoice", 0, "QBBatchInvoiceDialog"); } IORInvoiceLineAdd orInvoiceLineAdd1 = invoiceAddRq.ORInvoiceLineAddList.Append(); orInvoiceLineAdd1.InvoiceLineAdd.ItemRef.ListID.SetValue(item1.QuickBooksID); orInvoiceLineAdd1.InvoiceLineAdd.ServiceDate.SetValue(invoiceItem1.Date); orInvoiceLineAdd1.InvoiceLineAdd.Amount.SetValue(invoiceItem1.Amount); orInvoiceLineAdd1.InvoiceLineAdd.Quantity.SetValue(invoiceItem1.Quantity); orInvoiceLineAdd1.InvoiceLineAdd.Desc.SetValue(invoiceItem1.Description); bItemInvoice1 = true; } //Send the request and get the response from QuickBooks responseMsgSet = sessionManager.DoRequests(requestMsgSet); response = responseMsgSet.ResponseList.GetAt(0); IInvoiceRet invoiceRet = (IInvoiceRet)response.Detail; if (bItemInvoice1) invoiceItem1.QuickBooksID = invoiceRet.ORInvoiceLineRetList.GetAt(0).InvoiceLineRet.TxnLineID.GetValue(); invoice.QuickBooksID = invoiceRet.TxnID.GetValue(); invoiceID = invoice.QuickBooksID; } else { //get the latest invoice IInvoiceRet invoiceRet = invoiceRetList.GetAt(numIndex); var invoice = new Invoice { Customer = customer, QuickBooksID = invoiceRet.TxnID.GetValue(), EditSequence = invoiceRet.EditSequence.GetValue() }; //invoiceRet.TxnNumber.GetValue(); requestMsgSet.ClearRequests(); IInvoiceMod invoiceModRq = requestMsgSet.AppendInvoiceModRq(); invoiceModRq.TxnID.SetValue(invoice.QuickBooksID); invoiceModRq.EditSequence.SetValue(invoice.EditSequence); //if no assocated item, then add new item to the current invoice //andy change this if (invoiceRet.ORInvoiceLineRetList != null) { for (int j = 0; j < invoiceRet.ORInvoiceLineRetList.Count; j++) { IORInvoiceLineRet ORInvoiceLineRet = invoiceRet.ORInvoiceLineRetList.GetAt(j); if (itemA_ID != ORInvoiceLineRet.InvoiceLineRet.TxnLineID.GetValue()) { IORInvoiceLineMod ORinvoicemod1 = invoiceModRq.ORInvoiceLineModList.Append(); ORinvoicemod1.InvoiceLineMod.TxnLineID.SetValue(ORInvoiceLineRet.InvoiceLineRet.TxnLineID.GetValue()); } } } //this add the new line if (invoiceItem1.Amount >= 0) { if (invoiceItem1.Amount == 0) { string msg = "Warning: Invoice = $0 for" + szCustomerName; MMSUtility.LogFile(msg, "", "AddModQBInvoice", 0, "QBBatchInvoiceDialog"); } IORInvoiceLineMod ORinvoicemod1 = invoiceModRq.ORInvoiceLineModList.Append(); ORinvoicemod1.InvoiceLineMod.TxnLineID.SetValue("-1"); ORinvoicemod1.InvoiceLineMod.ServiceDate.SetValue(invoiceItem1.Date); ORinvoicemod1.InvoiceLineMod.ItemRef.ListID.SetValue(item1.QuickBooksID); ORinvoicemod1.InvoiceLineMod.Amount.SetValue(invoiceItem1.Amount); ORinvoicemod1.InvoiceLineMod.Quantity.SetValue(invoiceItem1.Quantity); ORinvoicemod1.InvoiceLineMod.Desc.SetValue(invoiceItem1.Description); bItemInvoice1 = true; } //Send the request and get the response from QuickBooks responseMsgSet = sessionManager.DoRequests(requestMsgSet); response = responseMsgSet.ResponseList.GetAt(0); invoiceRet = (IInvoiceRet)response.Detail; invoice.QuickBooksID = invoiceRet.TxnID.GetValue(); invoiceID = invoice.QuickBooksID; int nIndex = invoiceRet.ORInvoiceLineRetList.Count - 1; if (bItemInvoice1) invoiceItem1.QuickBooksID = invoiceRet.ORInvoiceLineRetList.GetAt(nIndex).InvoiceLineRet.TxnLineID.GetValue(); } } catch (Exception ex) { MMSUtility.LogFile(ex.Message, "", "AddModQBInvoice", ex.LineNumber(), "QBBatchInvoiceDialog"); MessageBox.Show(ex.Message, "Error"); } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } return invoiceID; }
static void PullCustomers() { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); List<OutletImport> customers = new List<OutletImport>(); List<RouteRegionInfo> routeRegionInfos=new List<RouteRegionInfo>(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; ICustomerQuery custQ = requestMsgSet.AppendCustomerQueryRq(); // custQ.ORCustomerListQuery.FullNameList. responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ICustomerRetList customerRetList = response.Detail as ICustomerRetList; if (customerRetList != null && customerRetList.Count != 0) { var company = GetCurrentCompany(); for (var i = 0; i < customerRetList.Count; i++) { ICustomerRet customerRet = customerRetList.GetAt(i); if (customerRet != null && customerRet.IsActive.GetValue()) { var outlet = new OutletImport { DistributrCode = company != null ? company.CompanyName.GetValue() : "default", OutletName = customerRet.FullName != null ? customerRet.FullName.GetValue() : "", OutletCode = customerRet.Name != null ? customerRet.Name.GetValue() : "" }; if(customerRet.CustomerTypeRef !=null) outlet.Outletype = customerRet.CustomerTypeRef.FullName.GetValue(); if (customerRet.SalesTaxCodeRef != null) outlet.VatClassCode = "";//customerRet.SalesTaxCodeRef.FullName.GetValue(); if (customerRet.PriceLevelRef !=null) outlet.PricingTierCode = customerRet.PriceLevelRef.FullName.GetValue(); if (customerRet.SalesRepRef !=null) { outlet.RouteCode = customerRet.SalesRepRef.FullName.GetValue(); } else { continue; } if (customerRet.ShipAddress != null) { var address = customerRet.ShipAddress; var route= new RouteRegionInfo() { Salemanref = outlet.RouteCode, Region = address.State != null ? address.State.GetValue() : "" }; if (route != null && string.IsNullOrEmpty(route.Region)) routeRegionInfos.Add(route); } customers.Add(outlet); } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); if (customers.Any()) { DumpExportFilesAsync(customers.ToCsv(), MasterDataCollective.Outlet.ToString()); } if(routeRegionInfos.Any()) { } } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } }
static ICompanyRet GetCurrentCompany() { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); ICompanyRet companyRet = null; try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; ICompanyQuery company = requestMsgSet.AppendCompanyQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); companyRet = response.Detail as ICompanyRet; sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); return companyRet; } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); throw new Exception(ex.Message); } }
internal static async void PullInventory() { var fileLocation = FileUtility.GetInventoryFile("LastDateOfSync"); var fromDate = FileUtility.ReadFile(fileLocation); var newSyncDate = DateTime.Now.ToString(); bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { if(string.IsNullOrEmpty(fromDate)) { var results = PullInitialInventory(); var filename = "Stockline-Alidi Kenya Limited-Initial" + DateTime.Now.ToString("yyyyMMdd"); results = results.GroupBy(n => new { n.ProductName, n.ToSiteName }) .Select(m => new InventoryImport { Balance = m.Sum(g => g.Balance), ProductName = m.Key.ProductName, ToSiteName = m.Key.ToSiteName }).ToList(); DumpExportInventoryFileAsync(results.ToCsv(), filename); var filePath = FileUtility.GetInventoryFile(filename); bool success=await SendToDistributor(filePath); if (success) DumpExportInventoryFileAsync(newSyncDate, "LastDateOfSync"); } else { List<InventoryImport> inventory = new List<InventoryImport>(); var distributorsList = new List<string>(); var inventoryPerDistributor = new Dictionary<string, List<InventoryImport>>(); var distributorsCodeDictionary = new Dictionary<string, string>(); var distributorInventoryList = new List<InventoryImport>(); var stockSiteCodMappingList = GetStockSiteCodeMapping(); IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; ITransferInventoryQuery transferInventoryQuery = requestMsgSet.AppendTransferInventoryQueryRq(); transferInventoryQuery.ORTransferInventoryQuery.TxnFilterNoCurrency.ORDateRangeFilter. ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTime.Parse(fromDate), false); transferInventoryQuery.ORTransferInventoryQuery.TxnFilterNoCurrency.ORDateRangeFilter. ModifiedDateRangeFilter.ToModifiedDate.SetValue(DateTime.Parse(newSyncDate), false); transferInventoryQuery.IncludeLineItems.SetValue(true); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse respons = responseMsgSet.ResponseList.GetAt(0); ITransferInventoryRetList lineRetList = respons.Detail as ITransferInventoryRetList; if (lineRetList != null) { var RetCount = lineRetList.Count; for (int i = 0; i < RetCount; i++) { if (lineRetList != null) { var TransferInventoryRet = lineRetList.GetAt(i); if (TransferInventoryRet != null) { var fromSite = TransferInventoryRet.FromInventorySiteRef.FullName.GetValue(); var toSite = TransferInventoryRet.ToInventorySiteRef.FullName.GetValue(); var number = TransferInventoryRet.RefNumber.GetValue(); double lineItemsCount = 0.0; if (TransferInventoryRet.TransferInventoryLineRetList != null) { var toSiteName = TransferInventoryRet.ToInventorySiteRef.FullName.GetValue(); var fromSiteName = TransferInventoryRet.FromInventorySiteRef.FullName.GetValue(); var transferInventoryLineItemsCount = TransferInventoryRet.TransferInventoryLineRetList.Count; for (int j = 0; j < transferInventoryLineItemsCount; j++) { var productFullName = TransferInventoryRet.TransferInventoryLineRetList.GetAt(j).ItemRef.FullName. GetValue(); var lastColonIndex = productFullName.LastIndexOf(":"); var productCode = TransferInventoryRet.TransferInventoryLineRetList.GetAt(j).ItemRef.FullName. GetValue().Substring(lastColonIndex + 1); var productName = GetProductName(productCode); var balance = TransferInventoryRet.TransferInventoryLineRetList.GetAt(j). QuantityTransferred.GetValue(); var distributorInventory = new InventoryImport() { ToSiteName = stockSiteCodMappingList[toSite], Balance = Convert.ToDecimal(balance), ProductName = productCode }; distributorInventoryList.Add(distributorInventory); } Console.WriteLine(@"From {0} To {1} , the Ref number is {2}, Items Transfered {3}", fromSite, toSite, number, lineItemsCount); } } } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); var filename = "Stockline-Alidi Kenya Limited-" + DateTime.Now.ToString("yyyyMMdd"); distributorInventoryList = distributorInventoryList.GroupBy(n => new {n.ProductName, n.ToSiteName}) .Select( m => new InventoryImport { Balance = m.Sum(g => g.Balance), ProductName = m.Key.ProductName, ToSiteName = m.Key.ToSiteName }).ToList(); DumpExportInventoryFileAsync(distributorInventoryList.ToCsv(), filename); var filePath = FileUtility.GetInventoryFile(filename); bool success = await SendToDistributor(filePath); if(success) DumpExportInventoryFileAsync(newSyncDate, "LastDateOfSync"); } } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } }
internal static List<ProductImport> GetAllProducts() { var products = new List<ProductImport>(); bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); IItemInventoryRet itemInventoryRet = null; try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; IItemInventoryQuery itemInventoryQ = requestMsgSet.AppendItemInventoryQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IItemInventoryRetList itemInventoryRetList = response.Detail as IItemInventoryRetList; if (itemInventoryRetList != null && itemInventoryRetList.Count > 0) { for (int i = 0; i < itemInventoryRetList.Count; i++) { itemInventoryRet = itemInventoryRetList.GetAt(i); if(itemInventoryRet!=null) { var product = new ProductImport(); product.pDesc = itemInventoryRet.FullName.GetValue(); product.pCode = itemInventoryRet.Name.GetValue(); product.exfactory = itemInventoryRet.PurchaseCost != null ? Convert.ToDecimal(itemInventoryRet.PurchaseCost.GetAsString()) : 0m; products.Add(product); } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return products; }
private void QBAddCustomer(Customer theCustomer) { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; try { //Create the session Manager object sessionManager = new QBSessionManager(); //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 2, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; sessionManager.OpenConnection(MMSUtility.QBAppID, MMSUtility.QBAppName); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; ICustomerAdd customerAddRq = requestMsgSet.AppendCustomerAddRq(); customerAddRq.Name.SetValue(theCustomer.Name); customerAddRq.FirstName.SetValue(theCustomer.FirstName); customerAddRq.LastName.SetValue(theCustomer.LastName); string szName = theCustomer.FirstName + " " + theCustomer.LastName; customerAddRq.BillAddress.Addr1.SetValue(szName); customerAddRq.BillAddress.Addr2.SetValue(theCustomer.Address); customerAddRq.BillAddress.City.SetValue(theCustomer.City); customerAddRq.BillAddress.State.SetValue(theCustomer.State); customerAddRq.BillAddress.PostalCode.SetValue(theCustomer.Zip); customerAddRq.Phone.SetValue(theCustomer.Phone); customerAddRq.Email.SetValue(theCustomer.Email); customerAddRq.CompanyName.SetValue(theCustomer.Company); customerAddRq.IsActive.SetValue(theCustomer.Active); customerAddRq.TermsRef.FullName.SetValue(theCustomer.Terms); //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ICustomerRet customerRet = (ICustomerRet)response.Detail; theCustomer.QuickBooksID = customerRet.ListID.GetValue(); } catch (Exception exe) { string theName = theCustomer.LastName + "," + theCustomer.FirstName + "," + theCustomer.Address + ",C:" + theCustomer.City + ",S:" + theCustomer.State + "'Z:" + theCustomer.Zip + ",P" + theCustomer.Phone + ",E" + theCustomer.Email + ",A" + theCustomer.Active + ",T" + theCustomer.Terms; MMSUtility.LogFile(exe.Message, theName, "QBAddCustomer", exe.LineNumber(), "CustomerView"); MessageBox.Show(exe.Message, "Error"); } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } }
private bool QBGetCustomerRecord(Customer theCustomer) { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; bool nFound = false; try { //Create the session Manager object sessionManager = new QBSessionManager(); //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 2, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; sessionManager.OpenConnection(MMSUtility.QBAppID, MMSUtility.QBAppName); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; //find the customer info ICustomerQuery search = requestMsgSet.AppendCustomerQueryRq(); search.ORCustomerListQuery.CustomerListFilter.ORNameFilter.NameFilter.MatchCriterion.SetValue(ENMatchCriterion.mcStartsWith); search.ORCustomerListQuery.CustomerListFilter.ORNameFilter.NameFilter.Name.SetValue(theCustomer.Name); IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ICustomerRetList customerRetList = (ICustomerRetList)response.Detail; if (customerRetList != null) { ICustomerRet customerRet = customerRetList.GetAt(0); if (customerRet.ListID != null) theCustomer.QuickBooksID = customerRet.ListID.GetValue(); if (customerRet.EditSequence != null) theCustomer.EditSequence = customerRet.EditSequence.GetValue(); if (customerRet.FirstName != null) theCustomer.FirstName = customerRet.FirstName.GetValue(); if (customerRet.LastName != null) theCustomer.LastName = customerRet.LastName.GetValue(); if (customerRet.BillAddress != null) { if (customerRet.BillAddress.Addr1 != null) theCustomer.Address = customerRet.BillAddress.Addr1.GetValue(); if (customerRet.BillAddress.City != null) theCustomer.City = customerRet.BillAddress.City.GetValue(); if (customerRet.BillAddress.State != null) theCustomer.State = customerRet.BillAddress.State.GetValue(); if (customerRet.BillAddress.PostalCode != null) theCustomer.Zip = customerRet.BillAddress.PostalCode.GetValue(); } if (customerRet.Phone != null) theCustomer.Phone = customerRet.Phone.GetValue(); if (customerRet.Email != null) theCustomer.Email = customerRet.Email.GetValue(); if (customerRet.CompanyName != null) theCustomer.Company = customerRet.CompanyName.GetValue(); if (customerRet.IsActive != null) theCustomer.Active = customerRet.IsActive.GetValue(); if (customerRet.TermsRef != null) theCustomer.Terms = customerRet.TermsRef.FullName.GetValue(); nFound = true; } else { nFound = false; } } catch (Exception exe) { string thename = theCustomer.FirstName + " " + theCustomer.LastName; MMSUtility.LogFile(exe.Message, thename, "QBGetCustomerRecord", exe.LineNumber(), "CustomerView"); MessageBox.Show(exe.Message, "Error"); } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } return nFound; }
private static string GetIssuingWarehouse(string fromSite) { var stockSiteRef = string.Empty; bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string errecid = "{" + Guid.NewGuid().ToString() + "}"; sessionManager.ErrorRecoveryID.SetValue(errecid); sessionManager.EnableErrorRecovery = true; sessionManager.SaveAllMsgSetRequestInfo = true; #region error recovery if (sessionManager.IsErrorRecoveryInfo()) { IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; resMsgSet = sessionManager.GetErrorRecoveryStatus(); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { MessageBox.Show( "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { MessageBox.Show( "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { MessageBox.Show("No stored response was found."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { MessageBox.Show("Unable to store response."); } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; if (sCode == 0) { MessageBox.Show("Last request was processed and customer was added successfully!"); } else if (sCode > 0) { MessageBox.Show("There was a warning but last request was processed successfully!"); } else { MessageBox.Show("It seems that there was an error in processing last request"); reqMsgSet = sessionManager.GetSavedMsgSetRequest(); resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; if (statCode == 0) { string resStr = null; ISalesOrderRet custRet = resp.Detail as ISalesOrderRet; resStr = resStr + "Following sale/order has been successfully submitted to QuickBooks:\n\n\n"; if (custRet.TxnID != null) { resStr = resStr + "ListID Number = " + Convert.ToString(custRet.TxnID.GetValue()) + "\n"; Log(resStr); } } } } sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } #endregion IInventorySiteQuery inventorySiteQuery = requestMsgSet.AppendInventorySiteQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse responseList = responseMsgSet.ResponseList.GetAt(0); IInventorySiteRetList inventorySiteRet = (IInventorySiteRetList)responseList.Detail; var count = inventorySiteRet.Count; for (int i = 0; i < inventorySiteRet.Count; i++) { var iterationpoint = i; var siteRefName = inventorySiteRet.GetAt(i).Name != null ? inventorySiteRet.GetAt(i).Name.GetValue() : null; if (siteRefName != null && siteRefName == fromSite) { stockSiteRef = inventorySiteRet.GetAt(i).SiteAddress.Addr1.GetValue(); break; } } } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); throw new Exception(ex.Message); } return stockSiteRef; }
internal static IAccountRet GetAccountByNameFilter(string accountName) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); IAccountRet accountRet = null; try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; IAccountQuery accQ = requestMsgSet.AppendAccountQueryRq(); accQ.ORAccountListQuery.FullNameList.Add(accountName); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IAccountRetList accountRetList = response.Detail as IAccountRetList; if (accountRetList != null && accountRetList.Count != 0) { accountRet = accountRetList.GetAt(0); } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); throw new Exception(ex.Message); } return accountRet; }
private double QBFCLatestVersion(QBSessionManager SessionManager) { // Use oldest version to ensure that this application work with any QuickBooks (US) IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0); msgset.AppendHostQueryRq(); IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset); //MessageBox.Show("Host query = " + msgset.ToXMLString()); //SaveXML(msgset.ToXMLString()); // The response list contains only one response, // which corresponds to our single HostQuery request IResponse response = QueryResponse.ResponseList.GetAt(0); // Please refer to QBFC Developers Guide for details on why // "as" clause was used to link this derrived class to its base class IHostRet HostResponse = response.Detail as IHostRet; IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList; int i; double vers; double LastVers = 0; string svers = null; for (i = 0; i <= supportedVersions.Count - 1; i++) { svers = supportedVersions.GetAt(i); vers = Convert.ToDouble(svers); if (vers > LastVers) { LastVers = vers; } } return LastVers; }
internal static ISalesReceiptRet QBAddSalesReceipt(QuickBooksOrderDocumentDto receipt, string memo = "", string templateRefName = "Custom Sales Receipt") { if (receipt.DocumentType != DocumentType.Receipt) throw new ArgumentException("document is not an an Receipt"); bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string errecid = "{" + Guid.NewGuid().ToString() + "}"; sessionManager.ErrorRecoveryID.SetValue(errecid); sessionManager.EnableErrorRecovery = true; sessionManager.SaveAllMsgSetRequestInfo = true; #region error recovery if (sessionManager.IsErrorRecoveryInfo()) { IMsgSetRequest reqMsgSet = null; IMsgSetResponse resMsgSet = null; resMsgSet = sessionManager.GetErrorRecoveryStatus(); if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600")) { MessageBox.Show( "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001")) { MessageBox.Show( "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002")) { MessageBox.Show("No stored response was found."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004")) { MessageBox.Show("Invalid MessageSetID, greater than 24 character was given."); } else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005")) { MessageBox.Show("Unable to store response."); } else { IResponse res = resMsgSet.ResponseList.GetAt(0); int sCode = res.StatusCode; if (sCode == 0) { MessageBox.Show("Last request was processed and customer was added successfully!"); } else if (sCode > 0) { MessageBox.Show("There was a warning but last request was processed successfully!"); } else { MessageBox.Show("It seems that there was an error in processing last request"); reqMsgSet = sessionManager.GetSavedMsgSetRequest(); resMsgSet = sessionManager.DoRequests(reqMsgSet); IResponse resp = resMsgSet.ResponseList.GetAt(0); int statCode = resp.StatusCode; if (statCode == 0) { string resStr = null; ISalesReceiptRet custRet = resp.Detail as ISalesReceiptRet; resStr = resStr + "Following customer has been successfully submitted to QuickBooks:\n\n\n"; if (custRet.TxnID != null) { resStr = resStr + "ListID Number = " + Convert.ToString(custRet.TxnID.GetValue()) + "\n"; } Log(QBCRUDEAction.ErrorRecovery, "Invoice", (custRet == null ? "" : custRet.RefNumber.GetValue()), resp); } } } sessionManager.ClearErrorRecovery(); //MessageBox.Show("Proceeding with current transaction."); } #endregion ISalesReceiptAdd salesReceiptAddRq = requestMsgSet.AppendSalesReceiptAddRq(); salesReceiptAddRq.CustomerRef.FullName.SetValue(receipt.OutletName); //salesReceiptAddRq.TemplateRef.FullName.SetValue(templateRefName);//Custom Sales Receipt salesReceiptAddRq.Memo.SetValue(memo); salesReceiptAddRq.TxnDate.SetValue(Convert.ToDateTime(receipt.DocumentDateIssued)); salesReceiptAddRq.RefNumber.SetValue(receipt.GenericReference.Substring((receipt.GenericReference.Length - 11), 11)); foreach (var receiptLineItem in receipt.LineItems) { IItemInventoryRet product = GetProductByCode(receiptLineItem.ProductCode); if (product == null) continue; ISalesReceiptLineAdd salesReceiptLineAddRq = salesReceiptAddRq.ORSalesReceiptLineAddList.Append().SalesReceiptLineAdd; salesReceiptLineAddRq.Amount.SetValue(Convert.ToDouble(Math.Round(receiptLineItem.GrossValue,2))); //salesReceiptLineAddRq.Quantity.SetValue(1); salesReceiptLineAddRq.ORRatePriceLevel.Rate.SetValue(Convert.ToDouble(receiptLineItem.LineItemValue)); salesReceiptLineAddRq.Quantity.SetValue(Convert.ToDouble(receiptLineItem.Quantity)); salesReceiptLineAddRq.ItemRef.FullName.SetValue(product.FullName.GetValue()); salesReceiptLineAddRq.Desc.SetValue(receiptLineItem.ProductDescription); //salesReceiptLineAddRq. salesReceiptLineAddRq.Other1.SetValue(receiptLineItem.PaymentType); try { salesReceiptLineAddRq.TaxAmount.SetValue(Convert.ToDouble(Math.Round(receiptLineItem.TotalVat, 2))); } catch (Exception e) { Console.WriteLine(e); Log(e.Message); } } responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ISalesReceiptRet salesReceipRet = response.Detail as ISalesReceiptRet; int statusCode = response.StatusCode; if (statusCode == 0) { Console.WriteLine("Success"); } sessionManager.ClearErrorRecovery(); sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); Log(QBCRUDEAction.Add, "SalesReceipt", (salesReceipRet == null ? "" : salesReceipRet.RefNumber.GetValue()), response); return salesReceipRet; } catch (Exception ex) { if (boolSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); Log(error); MessageBox.Show(error); } return null; }
private void prepareQuery() { session.open(); request = session.getRequest(); sessionManager = session.getSession(); receivePaymentQuery = request.AppendReceivePaymentQueryRq(); receivePaymentQuery.IncludeLineItems.SetValue(true); }