public void Customer_Get()
        {
            QueryService <Customer> customerQueryService = new QueryService <Customer>(this.ServiceContext);
            var customers = customerQueryService.ExecuteIdsQuery("Select * From Customer");

            Assert.IsNotNull(customers);
        }
Example #2
0
        public void BatchEntityTest()
        {
            ServiceContext context = Initializer.InitializeQBOServiceContextUsingoAuth();

            DataService.DataService service = new DataService.DataService(context);

            Customer customer      = CreateCustomer();
            Customer addedCustomer = service.Add(customer);

            Invoice invoice = QBOHelper.CreateInvoice(context);

            QueryService <Term> termContext = new QueryService <Term>(context);

            QueryService <TaxRate> taxRateContext = new QueryService <TaxRate>(context);
            QueryService <TaxCode> taxCodeContext = new QueryService <TaxCode>(context);
            QueryService <Item>    itemContext    = new QueryService <Item>(context);

            DataService.Batch batch = service.CreateNewBatch();
            batch.Add(addedCustomer, "UpdateCustomer", OperationEnum.update);
            batch.Add(invoice, "AddInvoice", OperationEnum.create);
            batch.Add(termContext.ExecuteIdsQuery("Select * from term").ToString(), "QueryTerm");
            batch.Add(taxRateContext.ExecuteIdsQuery("Select * from taxrate").ToString(), "QueryTaxRate");
            batch.Add(taxCodeContext.ExecuteIdsQuery("Select * from taxcode").ToString(), "QueryTaxCode");
            batch.Add(itemContext.ExecuteIdsQuery("Select * from item").ToString(), "QueryItem");

            batch.Execute();
            foreach (IntuitBatchResponse resp in batch.IntuitBatchItemResponses)
            {
                if (resp.ResponseType == ResponseType.Exception)
                {
                    Assert.Fail(resp.Exception.ToString());
                }
            }
        }
Example #3
0
        /// <summary>
        /// QBO API Request
        /// </summary>
        public async Task <ActionResult> ApiCallService()
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    var principal = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";

                    // Create a QuickBooks QueryService using ServiceContext
                    QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);
                    CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();

                    string output = "Company Name: " + companyInfo.CompanyName + " Company Address: " + companyInfo.CompanyAddr.Line1 + ", " + companyInfo.CompanyAddr.City + ", " + companyInfo.CompanyAddr.Country + " " + companyInfo.CompanyAddr.PostalCode;
                    return(View("ApiCallService", (object)("QBO API call Successful!! Response: " + output)));
                }
                catch (IdsException ex)
                {
                    if (ex.Message == "Unauthorized-401")
                    {
                        // Expired tokens, refresh access token once to get new tokens and try QBO API call again.
                        var principal = User as ClaimsPrincipal;
                        var identity  = User.Identity as ClaimsIdentity;
                        var tokenResp = await auth2Client.RefreshTokenAsync(principal.FindFirst("refresh_token").Value);

                        if (tokenResp.AccessToken != null && tokenResp.RefreshToken != null)
                        {
                            identity.RemoveClaim(principal.FindFirst("access_token"));
                            identity.AddClaim(new Claim("access_token", tokenResp.AccessToken));
                            identity.RemoveClaim(principal.FindFirst("refresh_token"));
                            identity.AddClaim(new Claim("refresh_token", tokenResp.RefreshToken));
                            await ApiCallService();

                            return(View());
                        }
                        else
                        {
                            return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                        }
                    }
                    else
                    {
                        return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                    }
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
Example #4
0
        /// <summary>
        /// QBO API Request
        /// </summary>
        public ActionResult ApiCallService()
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    var principal = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";

                    // Create a QuickBooks QueryService using ServiceContext
                    QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);
                    CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();

                    string output = "Company Name: " + companyInfo.CompanyName + " Company Address: " + companyInfo.CompanyAddr.Line1 + ", " + companyInfo.CompanyAddr.City + ", " + companyInfo.CompanyAddr.Country + " " + companyInfo.CompanyAddr.PostalCode;
                    return(View("ApiCallService", (object)("QBO API call Successful!! Response: " + output)));
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string clientid     = ConfigurationManager.AppSettings["clientid"];
            string clientsecret = ConfigurationManager.AppSettings["clientsecret"];
            string redirectUrl  = ConfigurationManager.AppSettings["redirectUrl"];
            string environment  = ConfigurationManager.AppSettings["appEnvironment"];

            OAuth2Client auth2Client = new OAuth2Client(clientid, clientsecret, redirectUrl, environment);

            List <OidcScopes> scopes = new List <OidcScopes>();

            scopes.Add(OidcScopes.Accounting);
            string authorizeUrl = auth2Client.GetAuthorizationURL(scopes);

            string realmId = "9130348210523456";

            var principal = User as ClaimsPrincipal;
            OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value);

            // Create a ServiceContext with Auth tokens and realmId
            ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);

            serviceContext.IppConfiguration.MinorVersion.Qbo = "51";

            // Create a QuickBooks QueryService using ServiceContext
            QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);
            CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();

            string output = "Company Name: " + companyInfo.CompanyName + " Company Address: " + companyInfo.CompanyAddr.Line1 + ", " + companyInfo.CompanyAddr.City + ", " + companyInfo.CompanyAddr.Country + " " + companyInfo.CompanyAddr.PostalCode;
        }
        static void GetInvoice()
        {
            var access_token = "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..LwSTn4HRGxVVQwYR8gCKCA.CgUGG49Xm9AL33-FLxErp8PCWysuLdVhWKVWOsXAdD32ogoZws0hwicnQwgoeI_NuBPOZsEv-TjFxDMblx42udGfW74bfAb9JUr9m94miOSPCuZGsw7LlnOaAEXp4JHQka8SEStVWlGQ_3jGzwygIyaoVF9QmVuExfFBnE0ZXG1AEatZscqLke_BAq-hyi_8hIm5JihrUpVq6qHXfp6XotH4ucakDC8z4U-KORYSVYWgRStQFQy9W2z_-hA1xg-kA1j3vMP4UkfE0292ORpPp_NU-__ZnRyj42OMP71pjTZpCB87dWXPZX9Vt8P7icxnaYQ2ZQL_z_VxDFbRnlOCzxwN7e6ukmZLbo7FTsZjuIgevYE46dF7cHwWJKqnRTsL7addty6DXcscOoM_q5qswlz8So_Klrnn6xNZVcJpF20QdKMK01GPDRyDBciAS1kq-U8CvESKa13F_LKM7_c-6Lmmw0OdMlomLRSc_ljwpuooQmI6GcAl-RZkoiuLR7UtFgdk6L0X99triME1aggWo5hZ0iMPNuUj9SHd-gMMvQl4IyqcZ7MAqNkxVeEDxkPUsgAiHX78eEHBkcfYhrxBEaTf6NEoztKrV8NaATJkLFEifwqy_xc2gKLZdoVpD0t787VDiMhGvlOFi_fSdSPrCrucU0jPR2zhKzfnXjNasXYP3RdxngRtlNO8GGuMvvqf.havdNFIRyLJ2ocADbZtpdg";

            realmId = "123146024163879";
            OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(access_token);

            ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);

            serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/"; //sandbox
                                                                                                        //serviceContext.IppConfiguration.BaseUrl.Qbo = "https://quickbooks.api.intuit.com/";//prod

            serviceContext.IppConfiguration.Message.Request.SerializationFormat  = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
            serviceContext.IppConfiguration.Message.Response.SerializationFormat = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
            serviceContext.IppConfiguration.MinorVersion.Qbo = "8";

            //serviceContext.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true;
            //serviceContext.IppConfiguration.Logger.RequestLog.ServiceRequestLoggingLocation = @"C:\Users\nshrivastava\Documents\Logs";
            //serviceContext.RequestId = "897kjhjjhkh9";

            DataService commonServiceQBO = new DataService(serviceContext);

            Intuit.Ipp.Data.Item   item      = new Intuit.Ipp.Data.Item();
            List <Item>            results   = commonServiceQBO.FindAll <Item>(item, 1, 1).ToList <Item>();
            QueryService <Invoice> inService = new QueryService <Invoice>(serviceContext);
            Invoice In = inService.ExecuteIdsQuery("SELECT * FROM Invoice").FirstOrDefault();
        }
Example #7
0
        public static List <Customer> getCustomerList(RestProfile profile)
        {
            ServiceContext          serviceContext       = getServiceContext(profile);
            QueryService <Customer> customerQueryService = new QueryService <Customer>(serviceContext);

            return(customerQueryService.ExecuteIdsQuery("SELECT * FROM Customer").ToList <Customer>());
        }
Example #8
0
        public void TaxPaymentQueryTest()
        {
            QueryService <TaxPayment> entityQuery = new QueryService <TaxPayment>(qboContextoAuth);
            List <TaxPayment>         entities    = entityQuery.ExecuteIdsQuery("SELECT * FROM TaxPayment").ToList <TaxPayment>();

            Assert.IsTrue(entities.Count() > 0);
        }
        public async Task <ActionResult> CompanyInfo()
        {
            //Make QBO api calls using .Net SDK
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();

                try
                {
                    //Initialize OAuth2RequestValidator and ServiceContext
                    ServiceContext serviceContext = base.IntializeContext(realmId);
                    DataService    dataService    = new DataService(serviceContext);


                    //Query/Read CompanyInfo
                    QueryService <CompanyInfo> querySvc = new QueryService <CompanyInfo>(serviceContext);//CompanyInfo call
                    CompanyInfo companyInfo             = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault();



                    return(View("Index", (object)("QBO API calls Success!")));
                }
                catch (Exception ex)
                {
                    return(View("Index", (object)"QBO API calls Failed!"));
                }
            }
            else
            {
                return(View("Index", (object)"QBO API call Failed!"));
            }
        }
Example #10
0
        public static CompanyInfo GetCompanyInfo(ServiceContext context)
        {
            QueryService <CompanyInfo> entityQuery = new QueryService <CompanyInfo>(context);
            List <CompanyInfo>         companyInfo = entityQuery.ExecuteIdsQuery("SELECT * FROM CompanyInfo").ToList <CompanyInfo>();

            return(companyInfo[0]);
        }
        public void AccountQueryUsingoAuth(ServiceContext qboContextoAuth)
        {
            QueryService <Account> entityQuery = new QueryService <Account>(qboContextoAuth);
            Account existing = Helper.FindOrAddAccount(qboContextoAuth, AccountTypeEnum.Bank, AccountClassificationEnum.Expense);

            List <Account> test = entityQuery.ExecuteIdsQuery("SELECT * FROM Account where Id='" + existing.Id + "'").ToList <Account>();
        }
Example #12
0
 /// <summary>
 /// Sync the items in to QBO.
 /// </summary>
 /// <param name="controller"></param>
 /// <param name="syncObjects"></param>
 /// <returns></returns>
 internal Syncdto SyncServiceItems(object controller, Syncdto syncObjects)
 {
     try
     {
         foreach (Item ItemItem in syncObjects.ItemList)
         {
             string EXISTING_ITEM_QUERY       = string.Format("select * from Item where active = true and name = '{0}'", ItemItem.Name.Trim());
             QueryService <Item> queryService = new QueryService <Item>(dataserviceFactory.getServiceContext);
             Item resultFound = queryService.ExecuteIdsQuery(EXISTING_ITEM_QUERY).FirstOrDefault <Item>();
             if (resultFound == null)
             {
                 Item entity = dataService.Add <Item>(ItemItem);
                 syncObjects.QboId             = entity.Id;
                 syncObjects.IsServiceItemSync = true;
             }
         }
         syncObjects = syncRepository.Save(controller, syncObjects);
         return(syncObjects);
     }
     catch (Intuit.Ipp.Exception.FaultException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.InvalidTokenException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.SdkException ex)
     {
         throw ex;
     }
 }
Example #13
0
        public ActionResult AddVendor(VendorModel objVendorModel)
        {
            if (Session["realmId"] != null)
            {
                string realmId = Session["realmId"].ToString();
                try
                {
                    string AccessToken = Session["access_token"].ToString();
                    var    principal   = User as ClaimsPrincipal;
                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(AccessToken);

                    // Create a ServiceContext with Auth tokens and realmId
                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "23";
                    DataService commonServiceQBO = new DataService(serviceContext);
                    // Create a QuickBooks QueryService using ServiceContext

                    PhysicalAddress vendorAddr   = new PhysicalAddress();
                    EmailAddress    vendoremail  = new EmailAddress();
                    TelephoneNumber mobileNumber = new TelephoneNumber();
                    WebSiteAddress  websiteaddr  = new WebSiteAddress();
                    Vendor          vendor       = new Vendor();
                    //Mandatory Fields
                    vendor.GivenName  = objVendorModel.FirstName;
                    vendor.Title      = objVendorModel.Title;
                    vendor.MiddleName = objVendorModel.MiddleName;
                    vendor.FamilyName = objVendorModel.LastName;
                    vendor.AcctNum    = objVendorModel.AccountNo;

                    vendor.Balance     = Convert.ToDecimal(objVendorModel.BalanceAmount);
                    vendor.CompanyName = objVendorModel.Company;

                    vendorAddr.City             = objVendorModel.City;
                    vendorAddr.Country          = objVendorModel.Country;
                    vendoremail.Address         = objVendorModel.Email;
                    mobileNumber.FreeFormNumber = objVendorModel.MobileNumber;
                    websiteaddr.URI             = objVendorModel.Website;

                    vendor.BillAddr         = vendorAddr;
                    vendor.PrimaryEmailAddr = vendoremail;
                    vendor.Mobile           = mobileNumber;
                    vendor.WebAddr          = websiteaddr;
                    Vendor resultVendor = commonServiceQBO.Add(vendor) as Vendor;
                    QueryService <Vendor> querySvcVendor = new QueryService <Vendor>(serviceContext);
                    List <Vendor>         vendorListData = querySvcVendor.ExecuteIdsQuery("SELECT * FROM Vendor").OrderByDescending(x => x.Id).ToList();
                    var    tt             = vendorListData.FirstOrDefault();
                    Vendor resultCustomer = commonServiceQBO.FindById(tt) as Vendor;
                    return(RedirectToAction("VendorList", "VendorQuickBook"));
                }
                catch (Exception ex)
                {
                    return(View("ApiCallService", (object)("QBO API call Failed!" + " Error message: " + ex.Message)));
                }
            }
            else
            {
                return(View("ApiCallService", (object)"QBO API call Failed!"));
            }
        }
Example #14
0
        public void ReimburseChargeQueryUsingoAuth()
        {
            QueryService <ReimburseCharge> entityQuery = new QueryService <ReimburseCharge>(qboContextoAuth);

            List <ReimburseCharge> entities = entityQuery.ExecuteIdsQuery("SELECT * FROM ReimburseCharge").ToList();

            Assert.IsTrue(entities.Count() > 0);
        }
        public Preferences PreferencesQueryASTCheckUsingoAuth(ServiceContext qboContextoAuth)
        {
            //Make sure minorversion=3 or more is used ServiceContext object
            QueryService <Preferences> entityQuery = new QueryService <Preferences>(qboContextoAuth);
            List <Preferences>         prefList    = entityQuery.ExecuteIdsQuery("SELECT * FROM Preferences").ToList <Preferences>();

            return(prefList[0]);
        }
        private Item QueryItemByName(ServiceContext serviceContext, string itemName)
        {
            QueryService <Item> querySvcItem = new QueryService <Item>(serviceContext);
            //As item name is unique we can query and get single item
            Item item = querySvcItem.ExecuteIdsQuery("SELECT * FROM Item WHERE Name = '" + itemName + "'").FirstOrDefault();

            return(item);
        }
Example #17
0
        public void ShipMethodQueryUsingoAuth()
        {
            QueryService <ShipMethod> entityQuery = new QueryService <ShipMethod>(qboContextoAuth);
            ShipMethod        existing            = Helper.FindOrAdd <ShipMethod>(qboContextoAuth, new ShipMethod());
            List <ShipMethod> entities            = entityQuery.ExecuteIdsQuery("Select * from Customer where Id='" + existing.Id + "'").ToList();

            Assert.IsTrue(entities.Count() > 0);
        }
Example #18
0
        public void CustomerTypeQueryUsingoAuth()
        {
            QueryService <CustomerType> entityQuery = new QueryService <CustomerType>(qboContextoAuth);
            CustomerType existing = Helper.FindOrAdd <CustomerType>(qboContextoAuth, new CustomerType());
            int          count    = entityQuery.ExecuteIdsQuery("Select * from CustomerType where Id='" + existing.Id + "'").Count;

            Assert.IsTrue(count > 0);
        }
Example #19
0
        public void OtherNameQueryUsingoAuth()
        {
            QueryService <OtherName> entityQuery = new QueryService <OtherName>(qboContextoAuth);
            OtherName existing = Helper.FindOrAdd <OtherName>(qboContextoAuth, new OtherName());
            int       count    = entityQuery.ExecuteIdsQuery("Select * from OtherName where Id='" + existing.Id + "'").Count;

            Assert.IsTrue(count > 0);
        }
        public void BudgetQueryUsingoAuth()
        {
            QueryService <Budget> entityQuery = new QueryService <Budget>(qboContextoAuth);
            //Budget existing = Helper.FindOrAdd<Budget>(qboContextoAuth, new Budget());
            List <Budget> entities = entityQuery.ExecuteIdsQuery("select * from Budget").ToList();

            Assert.IsTrue(entities.Count() >= 0);
        }
Example #21
0
        public void CustomerQueryWithSpecialCharacterUsingoAuth()
        {
            QueryService <Customer> entityQuery = new QueryService <Customer>(qboContextoAuth);
            //List<Customer> entities = entityQuery.Where(c => c.DisplayName == "Customer\\'s Business").ToList();
            int count = entityQuery.ExecuteIdsQuery("Select * from Customer where DisplayName='Customer\\'s Business'").Count;

            Assert.IsTrue(count >= 0);
        }
        public void Item_GetAll()
        {
            QueryService <Item> service = new QueryService <Item>(ServiceContext);
            var r = service.ExecuteIdsQuery("Select * From Item");

            Assert.IsTrue(r.Any());
            Assert.IsNotNull(r);
        }
Example #23
0
        public void StatementChargeQueryUsingoAuth()
        {
            QueryService <StatementCharge> entityQuery = new QueryService <StatementCharge>(qboContextoAuth);
            StatementCharge        existing            = Helper.FindOrAdd <StatementCharge>(qboContextoAuth, new StatementCharge());
            List <StatementCharge> entities            = entityQuery.ExecuteIdsQuery("Select * from StatementCharge where Id =='" + existing.Id + "'").ToList();

            Assert.IsTrue(entities.Count() > 0);
        }
        public void CreditCardPaymentQueryTest()
        {
            QueryService <CreditCardPaymentTxn> entityQuery = new QueryService <CreditCardPaymentTxn>(qboContextoAuth);
            CreditCardPaymentTxn        existing            = Helper.FindOrAdd <CreditCardPaymentTxn>(qboContextoAuth, new CreditCardPaymentTxn());
            List <CreditCardPaymentTxn> entities            = entityQuery.ExecuteIdsQuery("SELECT * FROM CreditCardPayment where Id='" + existing.Id + "'").ToList <CreditCardPaymentTxn>();

            Assert.IsTrue(entities.Count() > 0);
        }
Example #25
0
        public void FixedAssetQueryUsingoAuth()
        {
            QueryService <FixedAsset> entityQuery = new QueryService <FixedAsset>(qboContextoAuth);
            FixedAsset existing = Helper.FindOrAdd <FixedAsset>(qboContextoAuth, new FixedAsset());
            int        count    = entityQuery.ExecuteIdsQuery("Select * from FixedAsset where Id='" + existing.Id + "'").Count;

            Assert.IsTrue(count > 0);
        }
Example #26
0
        public void PriceLevelQueryUsingoAuth()
        {
            QueryService <PriceLevel> entityQuery = new QueryService <PriceLevel>(qboContextoAuth);
            PriceLevel        existing            = Helper.FindOrAdd <PriceLevel>(qboContextoAuth, new PriceLevel());
            List <PriceLevel> entities            = entityQuery.ExecuteIdsQuery("Select * from Customer where Id == '" + existing.Id + "'").ToList();

            Assert.IsTrue(entities.Count() > 0);
        }
Example #27
0
        /// <summary>
        /// Return the customer id from timeactivity.
        /// </summary>
        /// <param name="invoicedto"></param>
        /// <returns></returns>
        private TimeActivity GetCustomerId(Invoicedto invoicedto)
        {
            string EXISTING_TimeActive_QUERY         = string.Format("select * from timeactivity where Id = '{0}'", invoicedto.timeQboId);
            QueryService <TimeActivity> queryService = new QueryService <TimeActivity>(dataserviceFactory.getServiceContext);
            TimeActivity resultFound = queryService.ExecuteIdsQuery(EXISTING_TimeActive_QUERY).FirstOrDefault <TimeActivity>();

            return(resultFound);
        }
Example #28
0
        /// <summary>
        /// Test QBO api call
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="refresh_token"></param>
        /// <param name="realmId"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task qboApiCall(string access_token, string refresh_token, string realmId)
        {
            try
            {
                if (realmId != "")
                {
                    output("Making QBO API Call.");

                    OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(access_token);

                    ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator);
                    serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/"; //sandbox
                                                                                                                //serviceContext.IppConfiguration.BaseUrl.Qbo = "https://quickbooks.api.intuit.com/";//prod

                    serviceContext.IppConfiguration.Message.Request.SerializationFormat  = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
                    serviceContext.IppConfiguration.Message.Response.SerializationFormat = Intuit.Ipp.Core.Configuration.SerializationFormat.Xml;
                    serviceContext.IppConfiguration.MinorVersion.Qbo = "8";


                    //serviceContext.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true;
                    //serviceContext.IppConfiguration.Logger.RequestLog.ServiceRequestLoggingLocation = @"C:\Users\nshrivastava\Documents\Logs";
                    //serviceContext.RequestId = "897kjhjjhkh9";

                    DataService            commonServiceQBO = new DataService(serviceContext);
                    Intuit.Ipp.Data.Item   item             = new Intuit.Ipp.Data.Item();
                    List <Item>            results          = commonServiceQBO.FindAll <Item>(item, 1, 1).ToList <Item>();
                    QueryService <Invoice> inService        = new QueryService <Invoice>(serviceContext);
                    Invoice In = inService.ExecuteIdsQuery("SELECT * FROM Invoice").FirstOrDefault();

                    output("QBO call successful.");
                    lblQBOCall.Visible = true;
                    lblQBOCall.Text    = "QBO Call successful";
                }
            }
            catch (IdsException ex)
            {
                if (ex.Message == "UnAuthorized-401" || ex.Message == "The remote server returned an error: (401) Unauthorized.")
                {
                    output("Invalid/Expired Access Token.");
                    //if you get a 401 token expiry then perform token refresh
                    await performRefreshToken(refresh_token);

                    if ((dictionary.ContainsKey("accessToken")) && (dictionary.ContainsKey("accessToken")) && (dictionary.ContainsKey("realmId")))
                    {
                        await qboApiCall(dictionary["accessToken"], dictionary["refreshToken"], dictionary["realmId"]);
                    }
                }
                else
                {
                    output(ex.Message);
                }
            }
            catch (Exception ex)
            {
                //Check Status Code 401 and then
                output("Invalid/Expired Access Token.");
            }
        }
Example #29
0
        public void PaymentQueryUsingoAuth()
        {
            QueryService <Payment> entityQuery = new QueryService <Payment>(qboContextoAuth);
            Payment        existing            = Helper.FindOrAdd <Payment>(qboContextoAuth, new Payment());
            List <Payment> entities            = entityQuery.ExecuteIdsQuery("SELECT * FROM Payment where Id='" + existing.Id + "'").ToList <Payment>();

            //List<Payment> entities = entityQuery.Where(c => c.Id == existing.Id).ToList();
            Assert.IsTrue(entities.Count() > 0);
        }
Example #30
0
        public void CustomerQueryUsingoAuth()
        {
            QueryService <Customer> entityQuery = new QueryService <Customer>(qboContextoAuth);
            Customer existing = Helper.FindOrAdd <Customer>(qboContextoAuth, new Customer());
            //List<Customer> entities = entityQuery.Where(c => c.Id == existing.Id).ToList();
            List <Customer> entities = entityQuery.ExecuteIdsQuery("SELECT * FROM Customer where Id='" + existing.Id + "'").ToList <Customer>();

            Assert.IsTrue(entities.Count() > 0);
        }
        /// <summary>
        /// check for customer
        /// </summary>
        /// <param name="syncObjects"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public Syncdto IsCustSync(Syncdto syncObjects, SyncService service)
        {
            Dictionary<string, bool> isSync = new Dictionary<string, bool>();
            var custDataInDb = service.GetDatafromDBCustomer(syncObjects);

            if (custDataInDb.CustomerList.Count > 0)
            {
                custDataInDb.IsCustomerNodata = false;
                for (int i = 0; i < custDataInDb.CustomerList.Count; i++)
                {
                    string EXISTING_CUSTOMER_QUERY = string.Format("select * from customer where active = true and givenName = '{0}' and familyName = '{1}'", custDataInDb.CustomerList[i].GivenName.Trim(), custDataInDb.CustomerList[i].FamilyName.Trim());
                    QueryService<Customer> queryService = new QueryService<Customer>(service.ServiceContext);
                    Customer resultFound = queryService.ExecuteIdsQuery(EXISTING_CUSTOMER_QUERY).FirstOrDefault<Customer>();
                    if (resultFound != null)
                    {
                        custDataInDb.CustomerList[i].Id = resultFound.Id;
                        isSync.Add(custDataInDb.CustomerList[i].GivenName, true);
                    }
                    else
                    {
                        isSync.Add(custDataInDb.CustomerList[i].GivenName, false);
                    }
                }
                if (isSync.Where(x => x.Value == false).Any())
                {
                    custDataInDb.IsCustomerSync = false;
                }
                else
                {
                    custDataInDb.IsCustomerSync = true;
                }
            }
            else
            {
                custDataInDb.IsCustomerNodata = true;
                custDataInDb.IsCustomerSync = false;
            }
            return custDataInDb;
        }
 /// <summary>
 /// Return the customer id from timeactivity.
 /// </summary>
 /// <param name="invoicedto"></param>
 /// <returns></returns>
 private TimeActivity GetCustomerId(Invoicedto invoicedto)
 {
     string EXISTING_TimeActive_QUERY = string.Format("select * from timeactivity where Id = '{0}'", invoicedto.timeQboId);
     QueryService<TimeActivity> queryService = new QueryService<TimeActivity>(dataserviceFactory.getServiceContext);
     TimeActivity resultFound = queryService.ExecuteIdsQuery(EXISTING_TimeActive_QUERY).FirstOrDefault<TimeActivity>();
     return resultFound;
 }
 private void displayCustomers()
 {
     string consumerKey = ConfigurationSettings.AppSettings["consumerKey"];
     string consumerSecret = ConfigurationSettings.AppSettings["consumerSecret"];
     OAuthRequestValidator oauthRequestValidator = new OAuthRequestValidator(_ippRealmOAuthProfile.accessToken, _ippRealmOAuthProfile.accessSecret, consumerKey, consumerSecret);
     ServiceContext serviceContext = new ServiceContext(_ippRealmOAuthProfile.realmId, IntuitServicesType.QBO, oauthRequestValidator);
     DataService dataService = new DataService(serviceContext);
     QueryService<Customer> customerQueryService = new QueryService<Customer>(serviceContext);
     dataGridView1.DataSource = customerQueryService.ExecuteIdsQuery("Select * From Customer MaxResults 50").ToList();
 }
        /// <summary>
        /// check for employees
        /// </summary>
        /// <param name="syncObjects"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public Syncdto IsEmpSync(Syncdto syncObjects, SyncService service)
        {
            Dictionary<string, bool> isSync = new Dictionary<string, bool>();
            var empDataInDb = service.GetDatafromDBEmployee(syncObjects);
            if (empDataInDb.EmployeeList.Count > 0)
            {
                empDataInDb.IsEmployeeNoData = false;
                for (int i = 0; i < empDataInDb.EmployeeList.Count; i++)
                {
                    string EXISTING_EMPLOYEE_QUERY = string.Format("select * from employee where active = true and givenName='{0}' and familyName= '{1}'", empDataInDb.EmployeeList[i].GivenName.Trim(), empDataInDb.EmployeeList[i].FamilyName.Trim());

                    QueryService<Employee> queryService = new QueryService<Employee>(service.ServiceContext);
                    Employee resultFound = queryService.ExecuteIdsQuery(EXISTING_EMPLOYEE_QUERY).FirstOrDefault<Employee>();
                    if (resultFound != null)
                    {
                        empDataInDb.EmployeeList[i].Id = resultFound.Id;
                        //indexIterator = i+1;
                        isSync.Add(empDataInDb.EmployeeList[i].GivenName, true);
                    }
                    else
                    {
                        isSync.Add(empDataInDb.EmployeeList[i].GivenName, false);
                    }
                }
                if (isSync.Where(x => x.Value == false).Any())
                {
                    empDataInDb.IsEmployeeSync = false;
                }
                else
                {
                    empDataInDb.IsEmployeeSync = true;
                }
            }
            else
            {
                empDataInDb.IsEmployeeNoData = true;
                empDataInDb.IsEmployeeSync = false;
            }
            return empDataInDb;
        }
        /// <summary>
        /// Check for service item.
        /// </summary>
        /// <param name="syncObjects"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public Syncdto IsServiceItemSync(Syncdto syncObjects, SyncService service)
        {
            Dictionary<string, bool> isSync = new Dictionary<string, bool>();
            var itemDataInDb = service.GetDatafromDBItem(syncObjects);

            if (itemDataInDb.ItemList.Count>0)
            {
                itemDataInDb.IsServiceItemNodata = false;
                for (int i = 0; i < itemDataInDb.ItemList.Count; i++)
                {
                    string EXISTING_ITEM_QUERY = string.Format("select * from Item where active = true and name = '{0}'", itemDataInDb.ItemList[i].Name.Trim());
                    QueryService<Item> queryService = new QueryService<Item>(service.ServiceContext);
                    Item resultFound = queryService.ExecuteIdsQuery(EXISTING_ITEM_QUERY).FirstOrDefault<Item>();
                    if (resultFound != null)
                    {
                        itemDataInDb.ItemList[i].Id = resultFound.Id;
                        isSync.Add(itemDataInDb.ItemList[i].Name, true);
                    }
                    else
                    {
                        isSync.Add(itemDataInDb.ItemList[i].Name, false);
                    }
                }
                if (isSync.Where(x => x.Value == false).Any())
                {
                    itemDataInDb.IsServiceItemSync = false;

                }
                else
                {
                    itemDataInDb.IsServiceItemSync = true;
                }
            }
            else
            {
                itemDataInDb.IsServiceItemNodata = true;
                itemDataInDb.IsServiceItemSync = false;
            }
            return itemDataInDb;
        }
 /// <summary>
 /// Sync the employees in to QBO.
 /// </summary>
 /// <param name="controller"></param>
 /// <param name="syncObjects"></param>
 /// <returns></returns>
 public Syncdto SyncEmployees(object controller, Syncdto syncObjects)
 {
     try
     {
         for (int i = 0; i < syncObjects.EmployeeList.Count; i++)
         {
             string EXISTING_EMPLOYEE_QUERY = string.Format("select * from employee where active = true and givenName = '{0}' and familyName = '{1}'", syncObjects.EmployeeList[i].GivenName.Trim(), syncObjects.EmployeeList[i].FamilyName.Trim());
             QueryService<Employee> queryService = new QueryService<Employee>(dataserviceFactory.getServiceContext);
             Employee resultFound = queryService.ExecuteIdsQuery(EXISTING_EMPLOYEE_QUERY).FirstOrDefault<Employee>();
             if (resultFound == null)
             {
                 Employee entity = dataService.Add<Employee>(syncObjects.EmployeeList[i]);
                 syncObjects.EmployeeList[i] = entity;
                 syncObjects.IsEmployeeSync = true;
             }
             else
             {
                 syncObjects.EmployeeList[i] = resultFound;
             }
         }
         syncObjects = syncRepository.Save(controller, syncObjects);
         return syncObjects;
     }
     catch (Intuit.Ipp.Exception.FaultException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.InvalidTokenException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.SdkException ex)
     {
         throw ex;
     }
 }
 /// <summary>
 /// Sync the customer in to QBO
 /// </summary>
 /// <param name="controller"></param>
 /// <param name="syncObjects"></param>
 /// <returns></returns>
 internal Syncdto SyncCustomer(object controller, Syncdto syncObjects)
 {
     try
     {
         for (int i = 0; i < syncObjects.CustomerList.Count; i++)
         {
             string EXISTING_CUSTOMER_QUERY = string.Format("select * from customer where active = true and givenName = '{0}' and familyName = '{1}'", syncObjects.CustomerList[i].GivenName.Trim(), syncObjects.CustomerList[i].FamilyName.Trim());
             QueryService<Customer> queryService = new QueryService<Customer>(dataserviceFactory.getServiceContext);
             Customer resultFound = queryService.ExecuteIdsQuery(EXISTING_CUSTOMER_QUERY).FirstOrDefault<Customer>();
             if (resultFound == null)
             {
                 Customer entity = dataService.Add<Customer>(syncObjects.CustomerList[i]);
                 syncObjects.CustomerList[i] = entity;
                 syncObjects.IsCustomerSync = true;
             }
             else
             {
                 syncObjects.CustomerList[i] = resultFound;
             }
         }
         syncObjects = syncRepository.Save(controller, syncObjects);
         return syncObjects;
     }
     catch (Intuit.Ipp.Exception.FaultException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.InvalidTokenException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.SdkException ex)
     {
         throw ex;
     }
 }
 /// <summary>
 /// Sync the items in to QBO.
 /// </summary>
 /// <param name="controller"></param>
 /// <param name="syncObjects"></param>
 /// <returns></returns>
 internal Syncdto SyncServiceItems(object controller, Syncdto syncObjects)
 {
     try
     {
         foreach (Item ItemItem in syncObjects.ItemList)
         {
             string EXISTING_ITEM_QUERY = string.Format("select * from Item where active = true and name = '{0}'", ItemItem.Name.Trim());
             QueryService<Item> queryService = new QueryService<Item>(dataserviceFactory.getServiceContext);
             Item resultFound = queryService.ExecuteIdsQuery(EXISTING_ITEM_QUERY).FirstOrDefault<Item>();
             if (resultFound == null)
             {
                 Item entity = dataService.Add<Item>(ItemItem);
                 syncObjects.QboId = entity.Id;
                 syncObjects.IsServiceItemSync = true;
             }
         }
         syncObjects = syncRepository.Save(controller, syncObjects);
         return syncObjects;
     }
     catch (Intuit.Ipp.Exception.FaultException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.InvalidTokenException ex)
     {
         throw ex;
     }
     catch (Intuit.Ipp.Exception.SdkException ex)
     {
         throw ex;
     }
 }