Exemple #1
0
        ///<summary>Pings the API service with the provided test settings to check if the settings will work and the API is available.</summary>
        public static bool IsApiAvailable(bool isProduction, string username, string password)
        {
            AvaTaxClient testClient = new AvaTaxClient("TestClient", "1.0", Environment.MachineName, isProduction?AvaTaxEnvironment.Production:AvaTaxEnvironment.Sandbox)
                                      .WithSecurity(username, password);

            return(testClient.Ping().authenticated ?? false);
        }
        public void Setup()
        {
            try
            {
                // Create a client and set up authentication
                Client = new AvaTaxClient(typeof(TransactionTests).Assembly.FullName,
                                          typeof(TransactionTests).Assembly.GetName().Version.ToString(),
                                          Environment.MachineName,
                                          AvaTaxEnvironment.Sandbox)
                         .WithSecurity(Environment.GetEnvironmentVariable("SANDBOX_USERNAME"), Environment.GetEnvironmentVariable("SANDBOX_PASSWORD"));

                // Verify that we can ping successfully
                var pingResult = Client.Ping();

                // Assert that ping succeeded
                Assert.NotNull(pingResult, "Should be able to call Ping");
                Assert.True(pingResult.authenticated, "Environment variables should provide correct authentication");

                //Get the default company.
                var defaultCompanyModel = Client.QueryCompanies(string.Empty, "isDefault EQ true", null, null, string.Empty).value.FirstOrDefault();

                DefaultCompanyId = defaultCompanyModel.id;

                // Create a basic company with nexus in the state of Washington
                TestCompany = Client.CompanyInitialize(new CompanyInitializationModel()
                {
                    city             = "Bainbridge Island",
                    companyCode      = Guid.NewGuid().ToString().Substring(0, 25),
                    country          = "US",
                    email            = "*****@*****.**",
                    faxNumber        = null,
                    firstName        = "Bob",
                    lastName         = "McExample",
                    line1            = "100 Ravine Lane",
                    mobileNumber     = "206 555 1212",
                    phoneNumber      = "206 555 1212",
                    postalCode       = "98110",
                    region           = "WA",
                    taxpayerIdNumber = "123456789",
                    name             = "Bob's Greatest Popcorn",
                    title            = "Owner/CEO"
                });

                // Add a delay after creating company
                System.Threading.Thread.Sleep(6 * 1000);

                // Assert that company setup succeeded
                Assert.NotNull(TestCompany, "Test company should be created");
                Assert.True(TestCompany.nexus.Count > 0, "Test company should have nexus");
                Assert.True(TestCompany.locations.Count > 0, "Test company should have locations");

                // Shouldn't fail
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception in SetUp: " + ex);
            }
        }
        public void Setup()
        {
            _client      = null;
            _testCompany = null;
            try
            {
                // Create a client and set up authentication
                _client = new AvaTaxClient(GetType().Name,
                                           GetType().GetTypeInfo().Assembly.ImageRuntimeVersion.ToString(),
                                           Environment.MachineName,
                                           AvaTaxEnvironment.Sandbox)
                          .WithSecurity(Environment.GetEnvironmentVariable("SANDBOX_USERNAME"), Environment.GetEnvironmentVariable("SANDBOX_PASSWORD"));

                // Verify that we can ping successfully
                var pingResult = _client.Ping();

                // Assert that ping succeeded
                Assert.NotNull(pingResult, "Should be able to call Ping");
                Assert.True(pingResult.authenticated, "Environment variables should provide correct authentication");

                _companyCode = Guid.NewGuid().ToString("N").Substring(0, 25);
                // Create a basic company with nexus in the state of Washington
                _testCompany = _client.CompanyInitialize(new CompanyInitializationModel()
                {
                    city             = "Bainbridge Island",
                    companyCode      = _companyCode,
                    country          = "US",
                    email            = "*****@*****.**",
                    faxNumber        = null,
                    firstName        = "Bob",
                    lastName         = "McExample",
                    line1            = "100 Ravine Lane",
                    mobileNumber     = "206 555 1212",
                    phoneNumber      = "206 555 1212",
                    postalCode       = "98110",
                    region           = "WA",
                    taxpayerIdNumber = "123456789",
                    name             = "Bob's Hardware Store",
                    title            = "Owner/CEO"
                });

                // Add a delay after creating a company
                System.Threading.Thread.Sleep(6 * 1000);

                // Assert that company setup succeeded
                Assert.NotNull(_testCompany, "Test company should be created");
                Assert.True(_testCompany.nexus.Count > 0, "Test company should have nexus");
                Assert.True(_testCompany.locations.Count > 0, "Test company should have locations");

                // Shouldn't fail
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception in SetUp: " + ex);
            }
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Connect to AvaTax
            var client = new AvaTaxClient("CodefellowsTestApp", "1.0",
                                          Environment.MachineName, AvaTaxEnvironment.Production)
                         .WithSecurity("*****@*****.**", "4C87ABA1091");

            // Test connection!
            var pingResult = client.Ping();

            Console.WriteLine(pingResult.ToString());

            // Find a tax code for Sushi!
            var taxCodeResult = client.ListTaxCodes("description contains Sushi", null, null, null);

            Console.WriteLine(taxCodeResult.ToString());

            // Let's sell some sushi!
            var t = new TransactionBuilder(client, null, DocumentType.SalesOrder, "ABC")
                    .WithLine(10.0m, 1, "PF160026", "Sushi for Lunch", null, null)
                    .WithAddress(TransactionAddressType.SingleLocation, "2000 Main Street", null, null,
                                 "Irvine", "CA", "92614", "US")
                    .Create();

            Console.WriteLine(t);
            Console.WriteLine("Your calculated t tax was {0}", t.totalTax);

            var t2 = new TransactionBuilder(client, "DEFAULT", DocumentType.SalesInvoice, "ABC")
                     .WithAddress(TransactionAddressType.ShipFrom, "123 Main Street", "Irvine", null, null, "CA", "92615", "US")
                     .WithAddress(TransactionAddressType.ShipTo, "100 Ravine Lane NE", "Bainbridge Island", null, null, "WA", "98110", "US")
                     .WithLine(100.0m)
                     .WithLine(1234.56m)          // Each line is added as a separate item on the invoice
                     .WithExemptLine(50.0m, "NT") // An exempt item
                     .WithLine(2000.0m)           // The 2 addresses below apply to this $2000 line item
                     .WithLineAddress(TransactionAddressType.ShipFrom, "123 Main Street", "Irvine", null, null, "CA", "92615", "US")
                     .WithLineAddress(TransactionAddressType.ShipTo, "1500 Broadway", "New York", null, null, "NY", "10019", "US")
                     //.WithLine(50.0m, "FR010000") // shipping costs
                     .Create();

            Console.WriteLine(t2);
            Console.WriteLine("Your calculated t2 tax was {0}", t2.totalTax);
        }
        public static async Task MainAsync(string[] args)
        {
            // Parse options and show helptext if insufficient
            g_Options = new Options();
            Parser.Default.ParseArguments(args, g_Options);
            if (!g_Options.IsValid())
            {
                var help = HelpText.AutoBuild(g_Options);
                Console.WriteLine(help.ToString());
                return;
            }

            // Parse server URI
            if (String.IsNullOrEmpty(g_Options.Environment) || !g_Options.Environment.StartsWith("http"))
            {
                Console.WriteLine($"Invalid URI: {g_Options.Environment}");
                return;
            }

            // Set up AvaTax
            g_Client = new AvaTaxClient("AvaTax-Connect", "1.0", Environment.MachineName, new Uri(g_Options.Environment))
                       .WithSecurity(g_Options.Username, g_Options.Password);

            // Attempt to connect
            PingResultModel ping = null;

            try {
                ping = g_Client.Ping();
            } catch (Exception ex) {
                Console.WriteLine("Unable to contact AvaTax:");
                HandleException(ex);
                return;
            }

            // Fetch the company
            FetchResult <CompanyModel> companies = null;

            try {
                companies = await g_Client.QueryCompaniesAsync(null, $"companyCode eq '{g_Options.CompanyCode}'", null, null, null);
            } catch (Exception ex) {
                Console.WriteLine("Exception fetching companies");
                HandleException(ex);
                return;
            }

            // Check if the company exists
            if (companies == null || companies.count != 1)
            {
                Console.WriteLine($"Company with code '{g_Options.CompanyCode}' not found.\r\nPlease provide a valid companyCode using the '-c' parameter.");
                return;
            }

            // Check if the company is flagged as a test
            if ((companies.value[0].isTest != true) && IsPermanent(g_Options.DocType))
            {
                Console.WriteLine($"Company with code '{g_Options.CompanyCode}' is not flagged as a test company.\r\nYour test is configured to use document type '{g_Options.DocType}'.\r\nThis is a permanent document type.\r\nWhen testing with permanent document types, AvaTax-Connect can only be run against a test company.");
                return;
            }

            // Did we authenticate?
            if (ping.authenticated != true)
            {
                Console.WriteLine("Authentication did not succeed.  Please check your credentials and try again.");
                Console.WriteLine($"       Username: {g_Options.Username}");
                Console.WriteLine($"       Password: REDACTED - PLEASE CHECK COMMAND LINE");
                Console.WriteLine($"    Environment: {g_Options.Environment}");
                return;
            }

            // Print out information about our configuration
            Console.WriteLine($"AvaTax-Connect Performance Testing Tool");
            Console.WriteLine($"=======================================");
            Console.WriteLine($"         User: {g_Options.Username}");
            Console.WriteLine($"      Account: {ping.authenticatedAccountId}");
            Console.WriteLine($"       UserId: {ping.authenticatedUserId}");
            Console.WriteLine($"  CompanyCode: {g_Options.CompanyCode}");
            Console.WriteLine($"          SDK: {AvaTaxClient.API_VERSION}");
            Console.WriteLine($"  Environment: {g_Options.Environment}");
            Console.WriteLine($"    Tax Lines: {g_Options.Lines}");
            Console.WriteLine($"         Type: {g_Options.DocType}");
            Console.WriteLine($"      Threads: {g_Options.Threads}");
            Console.WriteLine();
            Console.WriteLine("  Call   Server   DB       Svc      Net      Client    Total");

            // Use transaction builder
            var tb = new TransactionBuilder(g_Client, g_Options.CompanyCode, g_Options.DocType, "ABC");

            // Add lines
            for (int i = 0; i < g_Options.Lines; i++)
            {
                tb.WithLine(100.0m)
                .WithLineAddress(TransactionAddressType.PointOfOrderAcceptance, "123 Main Street", null, null, "Irvine", "CA", "92615", "US")
                .WithLineAddress(TransactionAddressType.PointOfOrderOrigin, "123 Main Street", null, null, "Irvine", "CA", "92615", "US")
                .WithLineAddress(TransactionAddressType.ShipFrom, "123 Main Street", null, null, "Irvine", "CA", "92615", "US")
                .WithLineAddress(TransactionAddressType.ShipTo, "123 Main Street", null, null, "Irvine", "CA", "92615", "US");
            }
            g_Model = tb.GetCreateTransactionModel();

            // Discard the first call?
            try {
                if (g_Options.DiscardFirstCall.HasValue && g_Options.DiscardFirstCall.Value)
                {
                    var t = g_Client.CreateTransaction(null, g_Model);
                }
            } catch (Exception ex) {
                Console.WriteLine("Cannot connect to AvaTax.");
                HandleException(ex);
                return;
            }

            // Connect to AvaTax and print debug information
            g_TotalDuration = new CallDuration();
            g_TotalMs       = 0;
            List <Task> threads = new List <Task>();

            for (int i = 0; i < g_Options.Threads; i++)
            {
                var task = Task.Run(ConnectThread);
                threads.Add(task);
            }
            await Task.WhenAll(threads);

            // Compute some averages
            double avg            = g_TotalMs * 1.0 / g_Count;
            double total_overhead = (g_TotalDuration.SetupDuration.TotalMilliseconds + g_TotalDuration.ParseDuration.TotalMilliseconds);
            double total_transit  = g_TotalDuration.TransitDuration.TotalMilliseconds;
            double total_server   = g_TotalDuration.ServerDuration.TotalMilliseconds;
            double avg_overhead   = total_overhead / g_Count;
            double avg_transit    = total_transit / g_Count;
            double avg_server     = total_server / g_Count;
            double pct_overhead   = total_overhead / g_TotalMs;
            double pct_transit    = total_transit / g_TotalMs;
            double pct_server     = total_server / g_TotalMs;

            // Print out the totals
            Console.WriteLine();
            Console.WriteLine($"Finished {g_Count} calls in {g_TotalMs} milliseconds.");
            Console.WriteLine($"    Average: {avg.ToString("0.00")}ms; {avg_overhead.ToString("0.00")}ms overhead, {avg_transit.ToString("0.00")}ms transit, {avg_server.ToString("0.00")}ms server.");
            Console.WriteLine($"    Percentage: {pct_overhead.ToString("P")} overhead, {pct_transit.ToString("P")} transit, {pct_server.ToString("P")} server.");
            Console.WriteLine($"    Total: {total_overhead} overhead, {total_transit} transit, {total_server} server.");
        }
        /// <summary>
        /// To debug this application, call app must be called with args[0] as username and args[1] as password
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            // Connect to the server
            var client = new AvaTaxClient("ConsoleTest", "1.0", Environment.MachineName, AvaTaxEnvironment.Sandbox);

            client.WithSecurity(args[0], args[1]);

            // Call Ping
            var pingResult = client.Ping();

            Console.WriteLine(pingResult.version);

            // Call fetch
            try {
                var companies = client.QueryCompanies(null, null, 0, 0, null);
                Console.WriteLine(companies.ToString());

                // Initialize a company and fetch it back
                var init = client.CompanyInitialize(new CompanyInitializationModel()
                {
                    city              = "Bainbridge Island",
                    companyCode       = Guid.NewGuid().ToString("N").Substring(0, 25),
                    country           = "US",
                    email             = "*****@*****.**",
                    faxNumber         = null,
                    firstName         = "Bob",
                    lastName          = "Example",
                    line1             = "100 Ravine Lane",
                    line2             = null,
                    line3             = null,
                    mobileNumber      = null,
                    name              = "Bob Example",
                    phoneNumber       = "206 555 1212",
                    postalCode        = "98110",
                    region            = "WA",
                    taxpayerIdNumber  = "123456789",
                    title             = "Owner",
                    vatRegistrationId = null
                });
                Console.WriteLine(init.ToString());

                // Fetch it back
                var fetchBack = client.GetCompany(init.id, "Locations");
                Console.WriteLine(fetchBack.ToString());

                // Execute a transaction
                var t = new TransactionBuilder(client, init.companyCode, DocumentType.SalesInvoice, "ABC")
                        .WithAddress(TransactionAddressType.SingleLocation, "123 Main Street", "Irvine", "CA", "92615", "US")
                        .WithLine(100.0m)
                        .WithExemptLine(50.0m, "NT")
                        .Create();
                Console.WriteLine(t.ToString());
            } catch (AvaTaxError ex) {
                Console.WriteLine(ex.error.ToString());
            } catch (Exception ex2) {
                Console.WriteLine(ex2.ToString());
            }

            // Finished
            Console.WriteLine("Done");
        }