Ejemplo n.º 1
1
        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);

             }

         }
Ejemplo n.º 2
0
        public IResponse QueryCustomerList()
        {
            // Add the request to the message set request object
            ICustomerQuery CustQ = requestMsgSet.AppendCustomerQueryRq();

            // Optionally, you can put filter on it.
            CustQ.ORCustomerListQuery.CustomerListFilter.MaxReturned.SetValue(5);

            // Do the request and get the response message set object
            IMsgSetResponse responseSet = SessionManager.DoRequests(requestMsgSet);

            // Uncomment the following to view and save the request and response XML
            //string requestXML = requestSet.ToXMLString();
            //Console.WriteLine(requestXML);
            //string responseXML = responseSet.ToXMLString();
            //Console.WriteLine(responseXML);

            IResponse response = responseSet.ResponseList.GetAt(0);

            //int statusCode = response.StatusCode;
            //string statusMessage = response.StatusMessage;
            //string statusSeverity = response.StatusSeverity;
            //Console.WriteLine("Status:\nCode = " + statusCode + "\nMessage = " + statusMessage + "\nSeverity = " + statusSeverity);

            return(response);
        }
Ejemplo n.º 3
0
 ///<summary>Runs the request that has been built.  QB connection must be open before calling this method.</summary>
 private static void DoRequests()
 {
     if (!ConnectionOpen)
     {
         return;
     }
     ResponseMsgSet = SessionManager.DoRequests(RequestMsgSet);
 }
Ejemplo n.º 4
0
        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);
        }
        private void modifyCustomer(ICustomerRet QBCustomer)
        {
            Console.WriteLine(QBCustomer.Name.GetValue() + ": " + QBCustomer.Email.GetValue());

            IMsgSetRequest requestMsgSet = _MySessionManager.CreateMsgSetRequest("US", 13, 0);

            ICustomerMod Query = requestMsgSet.AppendCustomerModRq();

            Query.ListID.SetValue(QBCustomer.ListID.GetValue());
            Query.EditSequence.SetValue(QBCustomer.EditSequence.GetValue());
            Query.Email.SetValue("");

            IMsgSetResponse responseMsgSet = _MySessionManager.DoRequests(requestMsgSet);

            //IResponseList rsList = responseMsgSet.ResponseList;
            //IResponse response = rsList.GetAt(0);

            //ICustomerRet QBCustomer = (ICustomerRet)response.Detail;

            //if (QBCustomer == null)
            //{
            //    throw new Exception("Sorry, sales order not found.");
            //}

            //string CustomerName = QBCustomer.Name.GetValue().ToString();
            ////string email = QBCustomer.Email.GetValue();

            //Console.WriteLine(CustomerName);
        }
Ejemplo n.º 6
0
        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();
            }
        }
        private IORItemRet QueryItem(QBSessionManager session, string itemFullName)
        {
            // query for the customer information

            IMsgSetRequest requestMsgSet = getLatestMsgSetRequest(session);

            requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;

            IItemQuery pItemQuery = requestMsgSet.AppendItemQueryRq();

            pItemQuery.ORListQuery.ListFilter.ORNameFilter.NameFilter.Name.SetValue(itemFullName);
            pItemQuery.ORListQuery.ListFilter.ORNameFilter.NameFilter.MatchCriterion.SetValue(ENMatchCriterion.mcContains);

            pItemQuery.OwnerIDList.Add("0");

            IMsgSetResponse responseMsgSet = session.DoRequests(requestMsgSet);

            // Uncomment the following to see the request and response XML for debugging
            //string rq = requestMsgSet.ToXMLString();
            //string rs = responseMsgSet.ToXMLString();

            //m_application.Messenger.AddInfo("Item Resquest: " + rq);
            //m_application.Messenger.AddInfo("Item Response: " + rs);

            // Interpret the response

            IResponseList rsList = responseMsgSet.ResponseList;

            //  Retrieve the one response corresponding to our single request

            IResponse response = rsList.GetAt(0);

            if (response.StatusCode != 0)
            {
                string msg = "";
                if (response.StatusCode == 1)  //No record found
                {
                    msg = "Item not found: " + itemFullName;
                }
                else
                {
                    msg = "Error getting item.  Status: " + response.StatusCode.ToString() + ", Message: " + response.StatusMessage;
                }

                throw new Exception(msg);
            }

            // We have one or more customers (expect one)

            IORItemRetList orItemRetList = response.Detail as IORItemRetList;

            int itemCount = orItemRetList.Count;

            if (itemCount > 1)
            {
                m_application.Messenger.AddWarning("Multiple items found: " + itemFullName);
            }

            return(orItemRetList.GetAt(0));
        }
Ejemplo n.º 8
0
        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);
            }
        }
        static double QbfcLatestVersion(QBSessionManager manager)
        {
            var msgset = manager.CreateMsgSetRequest("US", 1, 0);

            msgset.AppendHostQueryRq();

            var queryResponse = manager.DoRequests(msgset);
            var response      = queryResponse.ResponseList.GetAt(0);
            var hostResponse  = response.Detail as IHostRet;

            Debug.Assert(hostResponse != null, "hostResponse != null");

            var supportedVersions = hostResponse.SupportedQBXMLVersionList;

            int    i;
            double lastVersion = 0;

            for (i = 0; i <= supportedVersions.Count - 1; i++)
            {
                var vers = Convert.ToDouble(supportedVersions.GetAt(i));

                if (vers > lastVersion)
                {
                    lastVersion = vers;
                }
            }

            return(lastVersion);
        }
Ejemplo n.º 10
0
        public IResponse DbGetResponseSet(ref QBSessionManager sessionManager, IMsgSetRequest requestMsgSet)
        {
            //Send the request and get the response from QuickBooks
            IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet);

            return(responseMsgSet.ResponseList.GetAt(0));
        }
Ejemplo n.º 11
0
        private double QBFCLatestVersion(QBSessionManager SessionManager)
        {
            // Use oldest version to ensure that this application work with any QuickBooks (US)
            IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0);

            msgset.AppendHostQueryRq();
            IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset);


            // The response list contains only one response,
            // which corresponds to our single HostQuery request
            IResponse response = QueryResponse.ResponseList.GetAt(0);

            // Please refer to QBFC Developers Guide for details on why
            // "as" clause was used to link this derrived class to its base class
            IHostRet  HostResponse      = response.Detail as IHostRet;
            IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList;

            int    i;
            double vers;
            double LastVers = 0;
            string svers    = null;

            for (i = 0; i <= supportedVersions.Count - 1; i++)
            {
                svers = supportedVersions.GetAt(i);
                vers  = Convert.ToDouble(svers);
                if (vers > LastVers)
                {
                    LastVers = vers;
                }
            }
            return(LastVers);
        }
Ejemplo n.º 12
0
        public IResponseList LoadQBItemInventoryList(int maxRecords, QBSessionManager sessionManager)
        {
            // IMsgSetRequest requestMsgSet = null;
            QBSession     QBMgr        = null;
            IResponseList responseList = null;

            try
            {
                QBMgr = new QBSession();
                if (sessionManager == null)
                {
                    QBMgr.CreateQBSession(out sessionManager);
                }

                if (sessionManager != null)
                {
                    // Get the RequestMsgSet based on the correct QB Version
                    IMsgSetRequest requestSet = QBMgr.getLatestMsgSetRequest(sessionManager);

                    if (requestSet != null)
                    {
                        // Initialize the message set request object
                        requestSet.Attributes.OnError = ENRqOnError.roeStop;

                        IItemInventoryQuery itemInventory = requestSet.AppendItemInventoryQueryRq();

                        //Set field value for metaData
                        itemInventory.metaData.SetValue(ENmetaData.mdMetaDataAndResponseData); //"IQBENmetaDataType"

                        // Optionally, you can put filter on it.
                        if (maxRecords != 0)
                        {
                            itemInventory.ORListQueryWithOwnerIDAndClass.ListWithClassFilter.MaxReturned.SetValue(maxRecords);
                        }

                        // Do the request and get the response message set object
                        IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestSet);

                        //IItemInventoryRetList itemInventoryRetList = null;
                        if (responseMsgSet == null)
                        {
                            return(null);
                        }
                        responseList = responseMsgSet.ResponseList;
                        if (responseList == null)
                        {
                            return(null);
                        }

                        // string responseXML = responseMsgSet.ToXMLString();
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(responseList);
        }
Ejemplo n.º 13
0
        public IResponse GetMessageResponse(ref QBSessionManager sessionManager, ref IMsgSetRequest requestMsgSet)
        {
            // Send Request Get Responce
            //Send the request and get the response from QuickBooks
            IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet);
            IResponse       response       = responseMsgSet.ResponseList.GetAt(0);

            return(response);
        }
Ejemplo n.º 14
0
        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);
            }
        }
        private IInvoiceRetList QueryInvoices(QBSessionManager session)
        {
            // Create Message Set request

            IMsgSetRequest requestMsgSet = getLatestMsgSetRequest(session);

            requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;

            // Create the query object needed to perform InvoiceQueryRq

            IInvoiceQuery  pInvQuery  = requestMsgSet.AppendInvoiceQueryRq();
            IInvoiceFilter pInvFilter = pInvQuery.ORInvoiceQuery.InvoiceFilter;

            // set the date range to the current schedule date selected in ArcLogistics

            pInvFilter.ORDateRangeFilter.TxnDateRangeFilter.ORTxnDateRangeFilter.TxnDateFilter.FromTxnDate.SetValue(m_application.CurrentDate);
            pInvFilter.ORDateRangeFilter.TxnDateRangeFilter.ORTxnDateRangeFilter.TxnDateFilter.ToTxnDate.SetValue(m_application.CurrentDate);

            pInvQuery.IncludeLineItems.SetValue(true);

            // Do the request
            IMsgSetResponse responseMsgSet = session.DoRequests(requestMsgSet);

            // Uncomment the following to see the request and response XML for debugging
            //string rq = requestMsgSet.ToXMLString();
            //string rs = responseMsgSet.ToXMLString();

            //m_application.Messenger.AddInfo("Resquest: " + rq);
            //m_application.Messenger.AddInfo("Response: " + rs);

            // Interpret the response

            IResponseList rsList = responseMsgSet.ResponseList;

            //  Retrieve the one response corresponding to our single request

            IResponse response = rsList.GetAt(0);

            if (response.StatusCode != 0)
            {
                string msg = "";
                if (response.StatusCode == 1)  //No record found
                {
                    msg = "No invoices found for " + m_application.CurrentDate.ToShortDateString();
                }
                else
                {
                    msg = "Error getting invoices.  Status: " + response.StatusCode.ToString() + ", Message: " + response.StatusMessage;
                }

                throw new Exception(msg);
            }

            return(response.Detail as IInvoiceRetList);
        }
Ejemplo n.º 16
0
        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;
        }
Ejemplo n.º 17
0
        public IResponseList GetPreferences(QBSessionManager sessionManager)
        {
            IMsgSetRequest requestMsgSet = null;
            QBSession      QBMgr         = null;
            IResponseList  responseList  = null;

            try
            {
                QBMgr = new QBSession();
                if (sessionManager == null)
                {
                    QBMgr.CreateQBSession(out sessionManager);
                }

                if (sessionManager != null)
                {
                    // Get the RequestMsgSet based on the correct QB Version
                    IMsgSetRequest requestSet = QBMgr.getLatestMsgSetRequest(sessionManager);

                    if (requestSet != null)
                    {
                        // Initialize the message set request object
                        requestSet.Attributes.OnError = ENRqOnError.roeStop;

                        BuildPreferencesQueryRq(requestSet);

                        // Do the request and get the response message set object
                        IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestSet);

                        if (responseMsgSet == null)
                        {
                            return(null);
                        }
                        responseList = responseMsgSet.ResponseList;
                        if (responseList == null)
                        {
                            return(null);
                        }

                        //WalkPreferencesQueryRs(responseSet);

                        //Close the session and connection with QuickBooks
                        //QBMgr.CloseQBConnection(sessionManager);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return(responseList);
        }
Ejemplo n.º 18
0
        public IResponseList GetQBAccountInfo(QBSessionManager sessionManager)
        {
            //bool sessionBegun = false;
            //bool connectionOpen = false;
            QBSession     QBMgr        = null;
            IResponseList responseList = null;

            try
            {
                QBMgr = new QBSession();
                if (sessionManager == null)
                {
                    //Create the session Manager object
                    QBMgr.CreateQBSession(out sessionManager);
                }

                // Get the RequestMsgSet based on the correct QB Version
                IMsgSetRequest requestMsgSet = QBMgr.getLatestMsgSetRequest(sessionManager);

                requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;

                // BuildAccountQueryRq(requestMsgSet);

                IAccountQuery AccountQueryRq = requestMsgSet.AppendAccountQueryRq();

                //Send the request and get the response from QuickBooks
                IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet);

                if (responseMsgSet == null)
                {
                    return(null);
                }
                responseList = responseMsgSet.ResponseList;
                if (responseList == null)
                {
                    return(null);
                }


                //WalkAccountQueryRs(responseMsgSet);

                //End the session and close the connection to QuickBooks
                //Close the session and connection with QuickBooks
                //QBMgr.CloseQBConnection(sessionManager);
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return(responseList);
        }
Ejemplo n.º 19
0
        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);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Obtain a list of all QuickBooks accounts.
        /// </summary>
        /// <returns>a list of quickbooks accounts</returns>
        private List <QuickbooksAccount> getAccounts(ENAccountType type)
        {
            List <QuickbooksAccount> account    = new List <QuickbooksAccount>();
            IMsgSetRequest           msgRequest = qbMgr.CreateMsgSetRequest("US", 4, 0);

            msgRequest.Attributes.OnError = ENRqOnError.roeStop;
            IAccountQuery query = msgRequest.AppendAccountQueryRq();

            query.ORAccountListQuery.AccountListFilter.AccountTypeList.Add(type);
            IMsgSetResponse response   = qbMgr.DoRequests(msgRequest);
            IAccountRetList qbAccounts = (IAccountRetList)response.ResponseList.GetAt(0).Detail;


            for (int i = 0; qbAccounts != null && i < qbAccounts.Count; i++)
            {
                account.Add(new QuickbooksAccount()
                {
                    Name = qbAccounts.GetAt(i).FullName.GetValue()
                });
            }

            return(account);
        }
 /// <summary>
 /// The DoRequests.
 /// </summary>
 /// <param name="requestSet">The requestSet<see cref="IMsgSetRequest"/>.</param>
 /// <param name="logsFile">The logsFile<see cref="StreamWriter"/>.</param>
 /// <returns>The <see cref="IMsgSetResponse"/>.</returns>
 public IMsgSetResponse DoRequests(IMsgSetRequest requestSet, StreamWriter logsFile)
 {
     try { return(session.DoRequests(requestSet)); }
     catch (Exception ex)
     {
         isSessionBegun = false;
         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();
         return(null);
     }
 }
        protected IResponse GetResponse(IMsgSetRequest request)
        {
            IResponse res = null;

            try
            {
                IMsgSetResponse responseSet = sessionManager.DoRequests(request);
                res = responseSet.ResponseList.GetAt(0);
            }
            catch (Exception ex)
            {
                throw new Exception("Exception while retrieving response from QuickBooks", ex);
            }
            return(res);
        }
Ejemplo n.º 23
0
        public QBResponceItem Inventoryadjustment(QBSessionManager sessionManager, IAccountRetList accountInfo, IPreferencesRet PreferencesRet, IItemInventoryRet inventoryItem)
        {
            QBResponceList qbResponceData  = null;
            QBSession      QBMgr           = null;
            QBResponceItem _qbResponceItem = null;

            try
            {
                QBMgr = new QBSession();
                if (sessionManager == null)
                {
                    QBMgr.CreateQBSession(out sessionManager);
                }

                if (sessionManager != null && inventoryItem != null && accountInfo != null)
                {
                    // Get the RequestMsgSet based on the correct QB Version
                    IMsgSetRequest requestSet = QBMgr.getLatestMsgSetRequest(sessionManager);

                    if (requestSet != null)
                    {
                        // Initialize the message set request object
                        requestSet.Attributes.OnError = ENRqOnError.roeStop;

                        BuildInventoryAdjustmentAddRq(requestSet, accountInfo, PreferencesRet, inventoryItem);

                        // Uncomment the following to view and save the request and response XML
                        //string requestXML = requestSet.ToXMLString();
                        //MessageBox.Show(requestXML);

                        // Do the request and get the response message set object
                        IMsgSetResponse responseSet = sessionManager.DoRequests(requestSet);

                        //string responseXML = responseSet.ToXMLString();
                        //MessageBox.Show(responseXML);

                        _qbResponceItem = WalkInventoryAdjustmentAddRs(responseSet);

                        //Close the session and connection with QuickBooks
                        //QBMgr.CloseQBConnection(sessionManager);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(_qbResponceItem);
        }
Ejemplo n.º 24
0
        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();
                }
            }
        }
Ejemplo n.º 25
0
        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();
                }
            }
        }
Ejemplo n.º 26
0
    public void GetCreditMemoData()
    {
        // open connection and begin session before data fetch - intentionally skipped this code
        IMsgSetRequest   msgset          = null;
        ICreditMemoQuery creditMemoQuery = null;

        try
        {
            // during data fetch
            msgset          = sessionMgr.CreateMsgSetRequest("US", 13, 0);
            creditMemoQuery = msgset.AppendCreditMemoQueryRq();
            creditMemoQuery.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(new DateTime(2012, 3, 31), false);     // you can apply filters too
            IMsgSetResponse msgRes       = sessionMgr.DoRequests(msgset);
            IResponseList   responseList = msgRes.ResponseList;
            if (responseList.Count > 0)
            {
                IResponse          response       = responseList.GetAt(0);
                ICreditMemoRetList creditMemoList = response.Detail as ICreditMemoRetList;
                if (creditMemoList == null)
                {
                    return;
                }
                for (int i = 0; i <= creditMemoList.Count - 1; i++)
                {
                    ICreditMemoRet qbCreditMemo = creditMemoList.GetAt(i);
                    Console.WriteLine("Credit no.:" + qbCreditMemo.TxnNumber.GetValue() + " Customer:" + qbCreditMemo.CustomerRef.FullName.GetValue() + " Total:" + qbCreditMemo.TotalAmount.GetValue());
                }
            }
        }
        catch (Exception ex)
        {
            //handle exception here
        }
        finally
        {
            if (msgset != null)
            {
                Marshal.FinalReleaseComObject(msgset);
            }
            if (creditMemoQuery != null)
            {
                Marshal.FinalReleaseComObject(creditMemoQuery);
            }
        }
        // end session and close connection after data fetch - intentionally skipped this code
    }
Ejemplo n.º 27
0
        // 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);
        }
Ejemplo n.º 28
0
        // Code for handling different versions of QuickBooks
        private double QBFCLatestVersion(QBSessionManager SessionManager)
        {
            string Country           = ConfigurationManager.AppSettings["QBCountry"].ToString();
            short  qbXMLMajorVersion = 0;
            short  qbXMLMinorVersion = 0;

            short.TryParse(ConfigurationManager.AppSettings["QBXMLMajorVersion"].ToString(), out qbXMLMajorVersion);
            short.TryParse(ConfigurationManager.AppSettings["QBXMLMinorVersion"].ToString(), out qbXMLMinorVersion);

            // Use oldest version to ensure that this application work with any QuickBooks (US)
            IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest(Country, qbXMLMajorVersion, qbXMLMinorVersion);    //("US", 13, 0);

            msgset.AppendHostQueryRq();
            IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset);
            //MessageBox.Show("Host query = " + msgset.ToXMLString());
            //SaveXML(msgset.ToXMLString());


            // The response list contains only one response,
            // which corresponds to our single HostQuery request
            IResponse response = QueryResponse.ResponseList.GetAt(0);

            // Please refer to QBFC Developers Guide for details on why
            // "as" clause was used to link this derrived class to its base class
            IHostRet  HostResponse      = response.Detail as IHostRet;
            IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList;

            int    i;
            double vers;
            double LastVers = 0;
            string svers    = null;

            for (i = 0; i <= supportedVersions.Count - 1; i++)
            {
                svers = supportedVersions.GetAt(i);
                vers  = Convert.ToDouble(svers);
                if (vers > LastVers)
                {
                    LastVers = vers;
                }
            }
            return(LastVers);
        }
Ejemplo n.º 29
0
        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();
                }
            }
        }
Ejemplo n.º 30
0
        private void button1_Click(object sender, EventArgs e)
        {
            coni();


            requestMsgSetfr = sessionManager.CreateMsgSetRequest("US", 13, 0);
            requestMsgSetfr.Attributes.OnError = ENRqOnError.roeContinue;


            ICustomerQuery CustomerQueryRq = requestMsgSetfr.AppendCustomerQueryRq();

            CustomerQueryRq.metaData.SetValue(ENmetaData.mdMetaDataAndResponseData);

            IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSetfr);



            //richTextBox1.Text += responseMsgSet.ToXMLString();

            cerrar();
        }
        private void editCustomer_Click(object sender, EventArgs e)
        {
            _MySessionManager = SessionManager.NewQBSession();

            IMsgSetRequest requestMsgSet = _MySessionManager.CreateMsgSetRequest("US", 13, 0);

            ICustomerQuery Query = requestMsgSet.AppendCustomerQueryRq();

            IMsgSetResponse responseMsgSet = _MySessionManager.DoRequests(requestMsgSet);

            IResponseList rsList = responseMsgSet.ResponseList;

            IResponse response = rsList.GetAt(0);

            ICustomerRetList CustomerList = (ICustomerRetList)response.Detail;

            if (CustomerList == null)
            {
                throw new Exception("Sorry, no customers found.");
            }

            for (int i = 0; i <= CustomerList.Count - 1; i++)
            {
                ICustomerRet QBCustomer = CustomerList.GetAt(i);

                //string CustomerName = QBCustomer.Name.GetValue().ToString();
                //string listID = QBCustomer.ListID.GetValue();
                //string editSequence = QBCustomer.EditSequence.GetValue();
                if (QBCustomer.Email != null)
                {
                    string email = QBCustomer.Email.GetValue();

                    if (_emailsToDelete.Contains(email))
                    {
                        modifyCustomer(QBCustomer);
                    }
                }
            }
        }
Ejemplo n.º 32
0
        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;
        }
Ejemplo n.º 33
0
         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);

            }
          
        }
Ejemplo n.º 34
0
        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;
        }
Ejemplo n.º 35
0
        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;
        }
Ejemplo n.º 36
0
        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;
        }
Ejemplo n.º 37
0
        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;
        }
Ejemplo n.º 38
0
        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);

            }
          
        }
Ejemplo n.º 39
0
        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;
        }
Ejemplo n.º 40
0
        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();
        }
Ejemplo n.º 41
0
        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);

            }
       
        }
Ejemplo n.º 42
0
       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;
        }
Ejemplo n.º 43
0
        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;
        }
Ejemplo n.º 44
0
        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;
        }
Ejemplo n.º 45
0
        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();
        }
Ejemplo n.º 46
0
        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;
        }
Ejemplo n.º 47
0
        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);

            
            }

        }
Ejemplo n.º 48
0
        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;
        }
Ejemplo n.º 49
0
        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;
        }
Ejemplo n.º 50
0
          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;
          }
Ejemplo n.º 51
0
        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;
        }
Ejemplo n.º 52
0
         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;
          
         }
Ejemplo n.º 53
0
        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();
                }
            }
        }
Ejemplo n.º 54
0
        static double QBFCLatestVersion(QBSessionManager SessionManager)
        {
            IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0);
            msgset.AppendHostQueryRq();
            IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset);
            IResponse response = QueryResponse.ResponseList.GetAt(0);

            IHostRet HostResponse = response.Detail as IHostRet;
            IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList;

            int i;
            double vers;
            double LastVers = 0;
            string svers = null;

            for (i = 0; i <= supportedVersions.Count - 1; i++)
            {
                svers = supportedVersions.GetAt(i);
                vers = Convert.ToDouble(svers);
                if (vers > LastVers)
                {
                    LastVers = vers;
                }
            }
            return LastVers;
        }
Ejemplo n.º 55
0
          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;
          }
Ejemplo n.º 56
0
        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;
        }
Ejemplo n.º 57
0
        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();
                }
            }
        }
Ejemplo n.º 58
0
        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);

            }
          
        }
Ejemplo n.º 59
0
        private double QBFCLatestVersion(QBSessionManager SessionManager)
        {
            // Use oldest version to ensure that this application work with any QuickBooks (US)
            IMsgSetRequest msgset = SessionManager.CreateMsgSetRequest("US", 1, 0);
            msgset.AppendHostQueryRq();
            IMsgSetResponse QueryResponse = SessionManager.DoRequests(msgset);
            //MessageBox.Show("Host query = " + msgset.ToXMLString());
            //SaveXML(msgset.ToXMLString());

            // The response list contains only one response,
            // which corresponds to our single HostQuery request
            IResponse response = QueryResponse.ResponseList.GetAt(0);

            // Please refer to QBFC Developers Guide for details on why
            // "as" clause was used to link this derrived class to its base class
            IHostRet HostResponse = response.Detail as IHostRet;
            IBSTRList supportedVersions = HostResponse.SupportedQBXMLVersionList as IBSTRList;

            int i;
            double vers;
            double LastVers = 0;
            string svers = null;

            for (i = 0; i <= supportedVersions.Count - 1; i++)
            {
                svers = supportedVersions.GetAt(i);
                vers = Convert.ToDouble(svers);
                if (vers > LastVers)
                {
                    LastVers = vers;
                }
            }
            return LastVers;
        }
Ejemplo n.º 60
0
        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;
        }