static void ProductPackagingAndPackagingType() { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; var version = QBFCLatestVersion(sessionManager); short ver = Convert.ToInt16(version); requestMsgSet = GetLatestMsgSetRequest(sessionManager); //sessionManager.CreateMsgSetRequest("US", ver, 0);; requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; IUnitOfMeasureSetQuery query = requestMsgSet.AppendUnitOfMeasureSetQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); List<Packaging> items=new List<Packaging>(); IResponse response = responseMsgSet.ResponseList.GetAt(0); IUnitOfMeasureSetRetList unitOfMeasureSet = response.Detail as IUnitOfMeasureSetRetList; if (unitOfMeasureSet != null && unitOfMeasureSet.Count > 0) { for (var i = 0; i < unitOfMeasureSet.Count; i++) { IUnitOfMeasureSetRet unitOfMeasure = unitOfMeasureSet.GetAt(i); if (unitOfMeasure != null && unitOfMeasure.IsActive.GetValue()) { var baseunit = unitOfMeasure.BaseUnit; var p = new Packaging() { Name = unitOfMeasure.Name != null ? unitOfMeasure.Name.GetValue() : "", Description = unitOfMeasure.Name != null ? unitOfMeasure.Name.GetValue() : "", }; if(baseunit !=null) { p.Code = baseunit.Abbreviation != null ? baseunit.Abbreviation.GetValue() : ""; } if (string.IsNullOrEmpty(p.Code)) p.Code = p.Name; if (!string.IsNullOrEmpty(p.Name)) items.Add(p); } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); if (items.Any()) { var files = items.ToCsv(); DumpExportFilesAsync(files, MasterDataCollective.ProductPackaging.ToString()); DumpExportFilesAsync(files, MasterDataCollective.ProductPackagingType.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 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 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 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; }
///<summary>Ends the session and then closes the connection.</summary> private static void CloseConnection() { if (SessionBegun) { SessionManager.EndSession(); SessionBegun = false; } if (ConnectionOpen) { SessionManager.CloseConnection(); ConnectionOpen = false; } }
private void quit_btn_Click(object sender, EventArgs e) { if (_sessionBegun) { sessionManager.EndSession(); } if (_connectionOpen) { sessionManager.CloseConnection(); } this.Close(); }
public static IQBBase DoProcessRequest(IMsgSetRequest requestMsgSet) { try { SessionManager.OpenConnection("QuickBooks Application", "QuickBooks Application"); ConnectionOpen = true; SessionManager.BeginSession("", ENOpenMode.omDontCare); SessionBegun = true; IMsgSetResponse responseMsgSet = SessionManager.DoRequests(requestMsgSet); IResponseList responseList = responseMsgSet?.ResponseList; if (responseList == null) { return(null); } if (responseList.Count > 0) { IResponse response = responseList.GetAt(0); if (response.StatusCode != 0) { ErrorMessage = response.StatusMessage; return(null); } if (response.Detail != null) { return(response.Detail); } } } catch (Exception ex) { ErrorMessage = ex.Message; return(null); } finally { if (SessionBegun) { SessionManager?.EndSession(); } if (ConnectionOpen) { SessionManager?.CloseConnection(); } SessionManager = null; } return(null); }
public void Disconnect() { if (qbMgr != null) { qbMgr.EndSession(); } }
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 void EndSession() { if (isSessionBegun) { session.EndSession(); } }
public void DoItemServiceQuery() { 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", 13, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; BuildItemServiceQueryRq(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; WalkItemServiceQueryRs(responseMsgSet); } catch (Exception e) { Console.WriteLine(e.Message, "Error"); if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } }
/// <summary> /// Ends the session with the quickbooks service. /// </summary> private void EndSession() { if (_sessionInProgress) { _manager.EndSession(); _sessionInProgress = false; } }
private void disconnectQB() { if (_MySessionManager != null) { _MySessionManager.EndSession(); _MySessionManager.CloseConnection(); } }
public void CloseQBConnection(QBSessionManager sessionManager) { if (sessionManager != null) { sessionManager.EndSession(); sessionManager.CloseConnection(); } }
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 void DoInvoiceAdd() { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; try { sessionManager = new QBSessionManager(); IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 13, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; BuildInvoiceAddRq(requestMsgSet); sessionManager.OpenConnection("", "Invoice Add Console App"); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); sessionManager.EndSession(); sessionBegun = false; sessionManager.CloseConnection(); connectionOpen = false; WalkInvoiceAddRs(responseMsgSet); } catch (Exception ex) { Console.WriteLine(ex.Message); if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } }
public void Dispose() { if (!_isOnline) { return; } _sessionManager.ClearErrorRecovery(); _sessionManager.EndSession(); _sessionManager.CloseConnection(); }
public void Start() { // We want to know if we begun a session so we can end it if an // error happens bool isSessionBegun = false; // Create the session manager object using QBFC QBSessionManager sessionManager = new QBSessionManager(); try { // Open the connection and begin a session to QuickBooks sessionManager.OpenConnection("", "Newspaper Constructor"); //sessionManager.OpenConnection2("", "IDN InvoiceAdd C# sample",ENConnectionType.ctLocalQBDLaunchUI); sessionManager.BeginSession("", ENOpenMode.omDontCare); isSessionBegun = true; // Get the RequestMsgSet based on the correct QB Version IMsgSetRequest requestSet = sessionManager.CreateMsgSetRequest("US", 6, 0); // Initialize the message set request object requestSet.Attributes.OnError = ENRqOnError.roeStop; Action(sessionManager, requestSet); // Close the session and connection with QuickBooks sessionManager.EndSession(); isSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { MessageBox.Show("Возникла проблема при попытке подключится к QuickBooks. Убедитесь что QuickBooks запущен на этом компьютере и в нем открыта компания.\n\n" + ex.Message.ToString(), "Ой ой ой", MessageBoxButton.OK, MessageBoxImage.Error); if (isSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } IsFailed = true; } }
private void GetCustomers() { sessionManager = new QBSessionManager(); sessionManager.OpenConnection("appID", "Bluefire Integration TEST"); _connectionOpen = true; sessionManager.BeginSession(COMPANY_FILE, ENOpenMode.omDontCare); _sessionBegun = true; // Grab the list of customer names to populate our listbox IMsgSetRequest messageSet = sessionManager.CreateMsgSetRequest("CA", 12, 0); ICustomerQuery custQuery = messageSet.AppendCustomerQueryRq(); try { IMsgSetResponse responseSet = sessionManager.DoRequests(messageSet); sessionManager.EndSession(); _sessionBegun = false; IResponse response; ENResponseType responseType; for (int i = 0; i < responseSet.ResponseList.Count; i++) { response = responseSet.ResponseList.GetAt(i); if (response.Detail == null) { continue; } responseType = (ENResponseType)response.Type.GetValue(); if (responseType == ENResponseType.rtCustomerQueryRs) { ICustomerRetList custList = (ICustomerRetList)response.Detail; for (int custIndex = 0; custIndex < custList.Count; custIndex++) { ICustomerRet customer = (ICustomerRet)custList.GetAt(custIndex); if (customer != null && customer.CompanyName != null) { customer_listbox.Items.Add(customer.CompanyName.GetValue()); } } } } } catch (System.Runtime.InteropServices.COMException comEx) { // something bad happened; tell the user, smash his computer, whatever; its your choice MessageBox.Show(comEx.Message); } }
private void closeSession() { if (isSessionBegun) { sessionManager.EndSession(); isSessionBegun = false; } if (isConnectionOpen) { sessionManager.CloseConnection(); isConnectionOpen = false; } }
public void Execute(params object[] args) { m_application.Messenger.AddInfo("Executing import from QuickBooks."); int countOrdersAdded = 0; QBSessionManager session = null; try { // Start session with QuickBooks session = new QBSessionManager(); session.OpenConnection("123", "ArcLogistics PlugIn: QuickBooksPlugIns.ImportOrdersFromInvoicesCmd"); session.BeginSession("", ENOpenMode.omDontCare); IInvoiceRetList invoiceList = QueryInvoices(session); int invoiceCount = invoiceList.Count; for (int i = 0; i < invoiceCount; i++) { IInvoiceRet invoiceRet = invoiceList.GetAt(i); ESRI.ArcLogistics.DomainObjects.Order newOrder = MakeOrderFromInvoice(invoiceRet, session); m_application.Project.Orders.Add(newOrder); countOrdersAdded++; } } catch (Exception e) { m_application.Messenger.AddError("Error executing QuickBooksPlugIns.ImportOrdersFromInvoicesCmd: " + e.Message); } finally { // Close connection because we don't need it anymore if (session != null) { session.EndSession(); session.CloseConnection(); } m_application.Project.Save(); m_application.Messenger.AddInfo(countOrdersAdded.ToString() + " orders added."); } }
public void cerrar() { try { sessionManager.EndSession(); sessionBegun = false; sessionManager.CloseConnection(); connectionOpen = false; } catch (Exception err_002) { MessageBox.Show("Se produjo el error err_002"); // logs("Se produjo el error err_002 "); } }
private void button_Click(object sender, RoutedEventArgs e) { 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", 8, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; //Connect to QuickBooks and begin a session sessionManager.OpenConnection("", "WpfApplication1"); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; ICustomerAdd customerAddRq = requestMsgSet.AppendCustomerAddRq(); customerAddRq.Name.SetValue(Customer.Text); //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; QuickBooksID.Text = customerRet.ListID.GetValue(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } }
// IY: CODE FOR HANDLING DIFFERENT VERSIONS private double QBFCLatestVersion(QBSessionManager SessionManager) { // IY: Use oldest version to ensure that we work with any QuickBooks (US) IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0); msgset.AppendHostQueryRq(); // MessageBox.Show(msgset.ToXMLString()); // IY: Use SessionManager object to open a connection and begin a session // with QuickBooks. At this time, you should add interop.QBFCxLib into // your Project References SessionManager.OpenConnection("", "IDN InvoiceAdd C# sample"); SessionManager.BeginSession("", ENOpenMode.omDontCare); IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset); // IY: The response list contains only one response, // which corresponds to our single HostQuery request IResponse response = QueryResponse.ResponseList.GetAt(0); // IY: Please refer to QBFC Developers Guide/pg 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; //svers = supportedVersions.GetAt(i); } } // IY: Close the session and connection with QuickBooks SessionManager.EndSession(); SessionManager.CloseConnection(); return(LastVers); }
/// <summary> /// The EndSession. /// </summary> /// <param name="logsFile">The logsFile<see cref="StreamWriter"/>.</param> public void EndSession(StreamWriter logsFile) { try { if (isSessionBegun) { session.EndSession(); isSessionBegun = false; } } catch (Exception ex) { Console.WriteLine("Warning Error Occured During Execution, Please Refer to Logs...\n"); logsFile.WriteLine(DateTime.Now + "\tERROR\tError Message:\t" + ex.Message); logsFile.WriteLine(); logsFile.WriteLine(DateTime.Now + "\tERROR\tError Message:\tStack Trace:\t" + ex.StackTrace); logsFile.WriteLine(); } }
protected void FinishSession(bool finishSession) { if (finishSession) { if (sessionOpen) { sessionManager.EndSession(); } sessionOpen = false; } if (connectionOpen) { sessionManager.CloseConnection(); } connectionOpen = false; sessionManager = null; }
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; }
private void InputItem_Load(object sender, System.EventArgs e) { // IY: Create the session manager object using QBFC QBSessionManager sessionManager = new QBSessionManager(); // IY: We want to know if we begun a session so we can end it if an // error happens bool booSessionBegun = false; try { // IY: Get the RequestMsgSet based on the correct QB Version IMsgSetRequest requestSet = getLatestMsgSetRequest(sessionManager); // IY: Initialize the message set request object requestSet.Attributes.OnError = ENRqOnError.roeStop; // IY: Add the request to the message set request object IItemQuery ItemQ = requestSet.AppendItemQueryRq(); // IY: Optionally, you can put filter on it. // ItemQ.ORListQuery.ListFilter.MaxReturned.SetValue(30); // IY: Open the connection and begin a session to QuickBooks sessionManager.OpenConnection("", "IDN InvoiceAdd C# sample"); sessionManager.BeginSession("", ENOpenMode.omDontCare); booSessionBegun = true; // IY: Do the request and get the response message set object IMsgSetResponse responseSet = sessionManager.DoRequests(requestSet); // Uncomment the following to view and save the request and response XML //string requestXML = requestSet.ToXMLString(); //MessageBox.Show(requestXML); // SaveXML(requestXML); //string responseXML = responseSet.ToXMLString(); //MessageBox.Show(responseXML); // SaveXML(responseXML); IResponse response = responseSet.ResponseList.GetAt(0); //int statusCode = response.StatusCode; //string statusMessage = response.StatusMessage; //string statusSeverity = response.StatusSeverity; //MessageBox.Show("Status:\nCode = " + statusCode + "\nMessage = " + statusMessage + "\nSeverity = " + statusSeverity); IORItemRetList orItemRetList = response.Detail as IORItemRetList; if (!(orItemRetList.Count == 0)) { for (int ndx = 0; ndx <= (orItemRetList.Count - 1); ndx++) { IORItemRet orItemRet = orItemRetList.GetAt(ndx); // IY: The ortype property returns an enum // of the elements that can be contained in the OR object switch (orItemRet.ortype) { case ENORItemRet.orirItemServiceRet: { // orir prefix comes from OR + Item + Ret IItemServiceRet ItemServiceRet = orItemRet.ItemServiceRet; isTaxable = ItemServiceRet?.SalesTaxCodeRef?.FullName?.GetValue(); SetTaxableDefaultIfEmpty(ref isTaxable); cmboBx2_Item.Items.Add(ItemServiceRet?.FullName?.GetValue() + ":" + isTaxable); } break; case ENORItemRet.orirItemInventoryRet: { IItemInventoryRet ItemInventoryRet = orItemRet.ItemInventoryRet; isTaxable = ItemInventoryRet?.SalesTaxCodeRef?.FullName?.GetValue(); SetTaxableDefaultIfEmpty(ref isTaxable); cmboBx2_Item.Items.Add(ItemInventoryRet?.FullName?.GetValue() + ":" + isTaxable); } break; case ENORItemRet.orirItemNonInventoryRet: { IItemNonInventoryRet ItemNonInventoryRet = orItemRet.ItemNonInventoryRet; isTaxable = ItemNonInventoryRet?.SalesTaxCodeRef?.FullName?.GetValue(); SetTaxableDefaultIfEmpty(ref isTaxable); cmboBx2_Item.Items.Add(ItemNonInventoryRet?.FullName?.GetValue() + ":" + isTaxable); } break; } } // for loop } // if // IY: Close the session and connection with QuickBooks sessionManager.EndSession(); booSessionBegun = false; sessionManager.CloseConnection(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application"); if (booSessionBegun) { sessionManager.EndSession(); sessionManager.CloseConnection(); } } }
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 Dictionary<string,string> GetStockSiteCodeMapping() { var stockSiteCodeMappingList = new Dictionary<string, string>(); 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."); } sessionManager.ClearErrorRecovery(); } #endregion requestMsgSet.AppendInventorySiteQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse responseList = responseMsgSet.ResponseList.GetAt(0); IInventorySiteRetList inventorySiteRet = (IInventorySiteRetList)responseList.Detail; for (int i = 0; i < inventorySiteRet.Count;i++ ) { var name = inventorySiteRet.GetAt(i).Name.GetValue(); //Added in order to Exlude inventorysites without a contact if (inventorySiteRet.GetAt(i).Contact==null) //(string.IsNullOrEmpty(inventorySiteRet.GetAt(i).Contact.GetValue())) { continue; } var code = inventorySiteRet.GetAt(i).Contact.GetValue().Split(','); stockSiteCodeMappingList.Add(name,code[0]); } //if (inventorySiteRet != null && inventorySiteRet.GetAt(0).Contact != null) //{ // distributorCode = inventorySiteRet.GetAt(0).Contact.GetValue(); // sessionManager.EndSession(); // boolSessionBegun = false; // sessionManager.CloseConnection(); // return distributorCode; //} 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); var message = ex.Message + " "; throw new Exception(message); } return stockSiteCodeMappingList; }
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; } }
internal static void Products() { int productbrandcount = 0; int productsubbrandcount = 0; int productcount = 1; 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 IItemInventoryQuery itemInventoryQ = requestMsgSet.AppendItemInventoryQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IItemInventoryRetList itemInventoryRetList = response.Detail as IItemInventoryRetList; List<ProductImport> items= new List<ProductImport>(); List<ProductPricing> pricings=new List<ProductPricing>(); List<Packaging> packagings=new List<Packaging>(); List<ProductBrand> brands=new List<ProductBrand>(); if (itemInventoryRetList != null && itemInventoryRetList.Count > 0) { for (var i = 0; i < itemInventoryRetList.Count; i++) { IItemInventoryRet inventoryRet = itemInventoryRetList.GetAt(i); if(!inventoryRet.Sublevel.IsSet()) { productbrandcount++; } if (inventoryRet.Sublevel.IsSet()) { productsubbrandcount++; } if (inventoryRet.UnitOfMeasureSetRef!=null) { productcount++; } if (inventoryRet != null && inventoryRet.IsActive.GetValue()) { var p = new ProductImport { pCode = inventoryRet.FullName != null ? inventoryRet.Name.GetValue() : "", pDesc = inventoryRet.SalesDesc != null ? inventoryRet.SalesDesc.GetValue() : "", exfactory = inventoryRet.PurchaseCost != null ? Convert.ToDecimal(inventoryRet.PurchaseCost.GetAsString()) : 0m, vatclassName = inventoryRet.SalesTaxCodeRef != null ? inventoryRet.SalesTaxCodeRef.FullName.GetValue() : "", packagingTypeName = inventoryRet.UnitOfMeasureSetRef !=null?inventoryRet.UnitOfMeasureSetRef.FullName.GetValue():"", productBrandName = inventoryRet.ParentRef != null ? inventoryRet.ParentRef.FullName.GetValue() : "" }; items.Add(p); if (inventoryRet.ParentRef != null && inventoryRet.ParentRef.FullName != null ) { IItemInventoryRet b = GetInventoryByNameFilter(inventoryRet.ParentRef.FullName.GetValue()); if (b != null ) { var brand = new ProductBrand { Code = b.FullName != null ? b.FullName.GetValue() : "", Name = b.SalesDesc != null ? b.SalesDesc.GetValue() : "", Description = b.SalesDesc != null ? b.SalesDesc.GetValue() : "", supplierName = "NESTLE KENYA LIMITED" //b.PrefVendorRef.FullName.GetValue() }; if (!string.IsNullOrEmpty(brand.Code) && brands.All(n => n.Code != brand.Code)) brands.Add(brand); brands.Select(n => new {}); } } if(inventoryRet!=null && inventoryRet.UnitOfMeasureSetRef!=null)//p !=null && items.Any(n=>n.pCode==p.pCode)) { //Michael Added Code // if(p.exfactory==0) continue; //End of Michael Added Code var pricing = new ProductPricing { ProductCode = inventoryRet.FullName != null ? inventoryRet.Name.GetValue() : "", Exfactory = inventoryRet.PurchaseCost != null ? Convert.ToDecimal(inventoryRet.PurchaseCost.GetAsString()) : 0m, SellingPrice = inventoryRet.SalesPrice !=null?Convert.ToDecimal(inventoryRet.SalesPrice.GetValue()):0m, StartDate = DateTime.Today.ToShortDateString(), TierNameCode = "Default" }; pricings.Add(pricing); } } } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); if (items.Any()) { DumpExportFilesAsync(items.Where(p=>!string.IsNullOrEmpty(p.productBrandName) && p.exfactory >0m).ToCsv(), MasterDataCollective.SaleProduct.ToString()); } if (pricings.Any()) { DumpExportFilesAsync(pricings.ToCsv(), MasterDataCollective.Pricing.ToString()); } if (packagings.Any()) { DumpExportFilesAsync(packagings.ToCsv(), MasterDataCollective.ProductPackaging.ToString()); } if (brands.Any()) { DumpExportFilesAsync(brands.ToCsv(), MasterDataCollective.ProductBrand.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); } }
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); } }
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(); }
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 static IItemSalesTaxRet ItemSalesReturn(string Id) { IItemSalesTaxRet firstItem = null; 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; requestMsgSet.AppendItemSalesTaxQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse responseList = responseMsgSet.ResponseList.GetAt(0); IItemSalesTaxRetList itemSalesTaxRetList = (IItemSalesTaxRetList)responseList.Detail; for (int i = 0; i < itemSalesTaxRetList.Count; i++) { IItemSalesTaxRet item = itemSalesTaxRetList.GetAt(i); if(item.ListID.GetValue()==Id) { firstItem=item; break; } } 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"); var message = ex.Message + " "; throw new Exception(message); } return firstItem; }
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(); }
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; }
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 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; }
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; }
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; }
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 IItemInventoryRet GetProductByCode(string productCode) { bool boolSessionBegun = false; QBSessionManager sessionManager = new QBSessionManager(); IItemInventoryRet product = null; try { IMsgSetRequest requestMsgSet; IMsgSetResponse responseMsgSet; sessionManager.OpenConnection("", _appName); sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare); boolSessionBegun = true; requestMsgSet = GetLatestMsgSetRequest(sessionManager); requestMsgSet.Attributes.OnError = ENRqOnError.roeStop; // ISalesTaxCodeRetList 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 (var i = 0; i < itemInventoryRetList.Count; i++) { IItemInventoryRet inventoryRet = itemInventoryRetList.GetAt(i); if (inventoryRet != null && inventoryRet.IsActive.GetValue() && inventoryRet.Name.GetValue().Equals(productCode,StringComparison.InvariantCultureIgnoreCase)) { product= inventoryRet; break; } } } 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 product; }
internal static void GetDistributors() { List<DistributorImport> listOfDistributors=new List<DistributorImport>(); 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; IInventorySiteQuery inventorySiteQuery = requestMsgSet.AppendInventorySiteQueryRq(); responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse responseList = responseMsgSet.ResponseList.GetAt(0); var inventorySiteRet = (IInventorySiteRetList)responseList.Detail; var count = inventorySiteRet.Count; for (int i = 0; i < count;i++) { if(inventorySiteRet.GetAt(i)!=null &&inventorySiteRet.GetAt(i).SiteDesc!=null &&inventorySiteRet.GetAt(i).SiteDesc.GetValue()=="MainWarehouse") { var distributor = new DistributorImport() { DistributorCode = inventorySiteRet.GetAt(i).Name.GetValue(), MerchantNo ="", Name = inventorySiteRet.GetAt(i).Name.GetValue(), RegionName = "default", Pin="", VatRegNo = "", PayBillNo = "", Latitude = "", Longitude = "", }; listOfDistributors.Add(distributor); } else { continue; } } sessionManager.EndSession(); boolSessionBegun = false; sessionManager.CloseConnection(); if (listOfDistributors.Any()) { var files = listOfDistributors.ToCsv(); DumpExportFilesAsync(files, MasterDataCollective.Distributor.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); var message = ex.Message; throw new Exception(message); } // return distributorCode; }
public static void Do() { bool sessionBegun = false; bool connectionOpen = false; QBSessionManager sessionManager = null; try { //Create the session Manager object sessionManager = new QBSessionManager(); //Connect to QuickBooks and begin a session sessionManager.OpenConnection("", "GenerateInvoicePDFs"); connectionOpen = true; sessionManager.BeginSession("", ENOpenMode.omDontCare); sessionBegun = true; //Create the message set request object to hold our request IMsgSetRequest requestMsgSet = sessionManager.CreateMsgSetRequest("US", 13, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; string[] InvoiceList = { "30085", "30089" }; foreach (string invNum in InvoiceList) { IInvoiceQuery invQuery = requestMsgSet.AppendInvoiceQueryRq(); invQuery.ORInvoiceQuery.RefNumberList.Add(invNum); Console.WriteLine($"invNum: {invNum}"); } //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); // Check each response for (int index = 0; index < responseMsgSet.ResponseList.Count; index++) { IResponse response = responseMsgSet.ResponseList.GetAt(index); if (response.StatusCode != 0) { // Save the invoice number in the "not found" file // and display the error Console.WriteLine(". Error: " + response.StatusMessage); } else { Console.WriteLine(response.StatusCode); var detail = (IInvoiceQuery)response.Detail; Console.WriteLine(detail); } } if (requestMsgSet != null) { Marshal.FinalReleaseComObject(requestMsgSet); } } catch (Exception ex) { Console.WriteLine(ex.Message); } sessionManager.EndSession(); sessionManager.CloseConnection(); }
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); } }
protected Dictionary <string, string> QuickBooksExcuet(IMsgSetRequest requestMsgSet, string externalId = null) { try { SessionManager.OpenConnection("QuickBooks Application", "QuickBooks Application"); ConnectionOpen = true; SessionManager.BeginSession("", ENOpenMode.omDontCare); SessionBegun = true; IMsgSetResponse responseMsgSet = SessionManager.DoRequests(requestMsgSet); SessionManager.EndSession(); SessionBegun = false; SessionManager.CloseConnection(); ConnectionOpen = false; if (responseMsgSet != null) { IResponseList responseList = responseMsgSet.ResponseList; for (int i = 0; i < responseList.Count; i++) { IResponse response = responseList.GetAt(i); //check the status code of the response, 0=ok, >0 is warning if (response.StatusCode >= 0) { var result = new Dictionary <string, string>(); result.Add("StatusCode", response.StatusCode + ""); //the request-specific response is in the details, make sure we have some if (response.Detail != null) { //make sure the response is the type we're expecting ENResponseType responseType = (ENResponseType)response.Type.GetValue(); if (responseType == ENResponseType.rtCustomerAddRs) { //upcast to more specific type here, this is safe because we checked with response.Type check above ICustomerRet customerRet = (ICustomerRet)response.Detail; if (customerRet != null) { string newId = customerRet.ListID.GetValue(); result.Add("Message", "Customer has been Added successfully"); result.Add("ListID", newId); return(result); } } if (responseType == ENResponseType.rtCustomerModRs) { ICustomerRet ItemInventoryRet = (ICustomerRet)response.Detail; if (ItemInventoryRet != null) { string newId = ItemInventoryRet.ListID.GetValue(); result.Add("Message", $"Customer with Id {newId} has been updated Successfully"); return(result); } } if (responseType == ENResponseType.rtListDelRs) { IQBENListDelTypeType ListDelType = (IQBENListDelTypeType)response.Detail; result.Add("Message", $"Customer with Id {externalId} has been deleted Successfully"); return(result); } if (responseType == ENResponseType.rtAccountQueryRs) { IAccountRetList AccountRet = (IAccountRetList)response.Detail; for (int j = 0; j < AccountRet.Count; j++) { var acc = AccountRet.GetAt(j); string FullName = (string)acc.FullName.GetValue(); result.Add("Name", FullName); } } } else { result.Add("Error", response.StatusMessage); return(result); } } } } } catch (Exception ex) { if (SessionBegun) { SessionManager.EndSession(); } if (ConnectionOpen) { SessionManager.CloseConnection(); } return(new Dictionary <string, string>() { { "Error", ex.Message } }); } return(new Dictionary <string, string>()); }
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(); } } }
public void DoAction() { QBSessionManager sessionManager = new QBSessionManager(); bool booSessionBegun = false; try { booSessionBegun = true; sessionManager.OpenConnection("", "QB POC"); sessionManager.BeginSession("", ENOpenMode.omDontCare);// @"C:\Users\Public\Documents\Intuit\QuickBooks\Company Files\Joe's Business.qbw", ENOpenMode.omMultiUser); //@"C:\Users\Public\Documents\Intuit\QuickBooks\Company Files\Joe's Business.qbw", ENOpenMode.omSingleUser); // , ENOpenMode.omDontCare); IMsgSetRequest requestSet = getLatestMsgSetRequest(sessionManager); /* * ICheckAdd checkAddRq= requestSet.AppendCheckAddRq(); * checkAddRq.AccountRef.FullName.SetValue("Test Bank"); * checkAddRq.PayeeEntityRef.FullName.SetValue("Gene Simmoms"); * checkAddRq.Memo.SetValue("Test Check"); * checkAddRq.IsToBePrinted.SetValue(true); * * * IExpenseLineAdd expenseLineAdd = checkAddRq.ExpenseLineAddList.Append(); * expenseLineAdd.AccountRef.FullName.SetValue("Payroll Expenses"); * expenseLineAdd.Amount.SetValue(100.00); * expenseLineAdd.Memo.SetValue("CRM"); * checkAddRq.IncludeRetElementList.Add("TxnID"); * * IMsgSetResponse checkResponseMsgSet = sessionManager.DoRequests(requestSet); * IResponse checkResponse = checkResponseMsgSet.ResponseList.GetAt(0); * System.Diagnostics.Debug.WriteLine(checkResponseMsgSet.ToXMLString()); * * requestSet = getLatestMsgSetRequest(sessionManager); * ICheckQuery query = requestSet.AppendCheckQueryRq(); * IMsgSetResponse responseSet = sessionManager.DoRequests(requestSet); * System.Diagnostics.Debug.WriteLine(responseSet.ToXMLString()); */ requestSet = getLatestMsgSetRequest(sessionManager); var rq = requestSet.AppendCustomDetailReportQueryRq(); rq.CustomDetailReportType.SetValue(ENCustomDetailReportType.cdrtCustomTxnDetail); rq.IncludeColumnList.Add(ENIncludeColumn.icClearedStatus); rq.IncludeColumnList.Add(ENIncludeColumn.icTxnID); rq.ReportAccountFilter.ORReportAccountFilter.ListIDList.Add("8000002C-1508291427"); rq.ORReportPeriod.ReportPeriod.FromReportDate.SetValue(DateTime.Now.AddHours(-1)); rq.ORReportPeriod.ReportPeriod.ToReportDate.SetValue(DateTime.Now); rq.SummarizeRowsBy.SetValue(ENSummarizeRowsBy.srbItemDetail); IMsgSetResponse responseSet = sessionManager.DoRequests(requestSet); var rp = (IReportRet)responseSet.ResponseList.GetAt(0).Detail; System.Diagnostics.Debug.WriteLine("rows " + rp.NumRows.GetValue()); System.Diagnostics.Debug.WriteLine("cols " + rp.NumColumns.GetValue()); System.Diagnostics.Debug.WriteLine("list count " + rp.ReportData.ORReportDataList.Count); IORReportData data; for (int i = 0; i < rp.ReportData.ORReportDataList.Count - 1; ++i) { data = rp.ReportData.ORReportDataList.GetAt(i); if (data != null) { if (data.DataRow != null) { if (data.DataRow.ColDataList.Count > 1) { if (data.DataRow.ColDataList.GetAt(1).value.GetValue() == "3C3-1508291494") { System.Diagnostics.Debug.WriteLine(data.DataRow.ColDataList.GetAt(0).value.GetValue()); } } } } } } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } finally { if (booSessionBegun) { sessionManager.EndSession(); 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; }
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 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(); } } }
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; }
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; }
private void view_customers_Click(object sender, RoutedEventArgs e) { 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", 8, 0); requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue; //Connect to QuickBooks and begin a session sessionManager.OpenConnection("", "WpfApplication1"); connectionOpen = true; sessionManager.BeginSession(@"C:\Users\Public\Documents\Intuit\QuickBooks\Company Files\Imperial2.qbw", ENOpenMode.omDontCare); sessionBegun = true; ICustomerQuery customerQueryRq = requestMsgSet.AppendCustomerQueryRq(); //Send the request and get the response from QuickBooks IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); ICustomerRetList customerRetList = (ICustomerRetList)response.Detail; var customers = new List <Customer>(); if (customerRetList != null) { for (int i = 0; i < customerRetList.Count; i++) { ICustomerRet customerRet = customerRetList.GetAt(i); var customer = new Customer { Name = customerRet.Name.GetValue(), Id = customerRet.ListID.GetValue() //EditSequence = customerRet.EditSequence.GetValue() }; customers.Add(customer); } } dataGrid.ItemsSource = customers; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } finally { //End the session and close the connection to QuickBooks if (sessionBegun) { sessionManager.EndSession(); } if (connectionOpen) { sessionManager.CloseConnection(); } } }
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; }
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; }
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); } })); }