private static void UpsertPrdNexus(AvaTaxClient prdClient, List <NexusModel> nexus) { //Get existing PRD nexus. var prdNexus = prdClient.ListNexusByCompany(PRD_COMPANY_ID, "nexusTaxTypeGroup EQ LandedCost", string.Empty, null, null, string.Empty).value; //Change the company ID to PRD. foreach (NexusModel indNexus in nexus) { //Check if the nexus already exists in the company. if (prdNexus.Select(pn => pn.country == indNexus.country).Any()) { continue; } try { indNexus.companyId = PRD_COMPANY_ID; var nexusToAdd = new List <NexusModel> { indNexus }; prdClient.CreateNexus(PRD_COMPANY_ID, nexusToAdd); } catch (AvaTaxError exc) { Console.WriteLine(string.Format("Error in adding nexus", exc.Message, exc.InnerException)); Console.WriteLine(string.Format("More information: {0}", exc.error)); continue; } catch (Exception exc) { Console.WriteLine(string.Format("Other error occurred in loading nexus: {0}", exc.Message)); } } }
/// <summary> /// Adds all LandedCost nexus to a company. /// </summary> /// <param name="URI">The URI.</param> /// <param name="USER">The user.</param> /// <param name="COMPANY_ID">The company identifier.</param> /// <param name="PASS">The pass.</param> private static void AddLcNexusToCompany(string URI, string USER, int COMPANY_ID, string PASS) { var client = new AvaTaxClient("lcNexusApp", ".1", "AvalaraAddLcNexusApp", new Uri(URI)) .WithSecurity(USER, PASS); var countriesAlreadyAssigned = client.ListNexusByCompany(COMPANY_ID, "nexusTaxTypeGroup EQ 'LandedCost'", "", null, null, "").value; var countries = client.ListNexusByCountry("", "nexusTaxTypeGroup EQ 'LandedCost'", null, null, "").value; List <NexusModel> countriesToAdd = new List <NexusModel>(); foreach (var country in countries) { if (countriesAlreadyAssigned.Any(cas => cas.country == country.country)) { continue; } countriesToAdd.Add(country); } client.CreateNexus(COMPANY_ID, countriesToAdd); Console.WriteLine(string.Format("Added {0} LandedCostNexus to company {1}.", countriesToAdd.Count, COMPANY_ID)); }
///<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 async Task FreeTaxRates() { // Create a client and set up authentication var 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")); // Call TaxRates for a few addresses and verify that the rates are nonzero var tr = await client.TaxRatesByAddressAsync("123 Main Street", null, null, "Irvine", "CA", "92615", "US"); Assert.NotNull(tr); Assert.True(tr.totalRate > 0.05m); // Washington tr = await client.TaxRatesByAddressAsync("100 Ravine Lane NE", null, null, "Bainbridge Island", "WA", "98110", "US"); Assert.NotNull(tr); Assert.True(tr.totalRate > 0.05m); // By postal code for New York tr = await client.TaxRatesByPostalCodeAsync("US", "10010"); Assert.NotNull(tr); Assert.True(tr.totalRate > 0.05m); }
public AvalaraCommand(AvalaraConfig settings, AvaTaxClient client) { _settings = settings; _companyCode = _settings.CompanyCode; _baseUrl = _settings.BaseApiUrl; _avaTax = client; }
static void Main(string[] args) { // Create a client and set up authentication var client = new AvaTaxClient("MyApp", "1.0", Environment.MachineName, AvaTaxEnvironment.Production) .WithSecurity("AvalaraUsername", "AvalaraPassword"); // Set to log data to review client.LogToFile("path for log files\\alavaraTest\\avataxapi.log"); // This is to test if we can connect to site, but does not work at Communicorp (PROBABLY BLOCKING) /* * // Verify that we can ping successfully * var pingResult = client.Ping(); * * * if (pingResult.authenticated == true) * { * Console.WriteLine("Success!"); * } * else if(pingResult.authenticated == false) * { * Console.WriteLine("Fail!"); * * } */ /* * // (This was from their example online) * // Create a simple transaction for $100 using the fluent transaction builder * //var t1 = new TransactionBuilder(client, "DEFAULT", DocumentType.SalesOrder, "123") */ // Send a hardcoded address that works for our location var transaction = new TransactionBuilder(client, "AvalaraCompanyCode", DocumentType.SalesOrder, "AvalaraCustomerCode") .WithAddress(TransactionAddressType.SingleLocation, "123 Main Street", null, null, "Columbus", "GA", "31999", "US") .WithLine(150.0m) .Create(); // Display the returned tax amount Console.WriteLine("Your calculated tax was {0}", transaction.totalTax); var tax = transaction.totalTax; #region Other way to log details // You can capture logs to disk like this: // Or you can hook the client to capture information about every API call like this: // Client.CallCompleted += MyEventHandler; #endregion // This line is used to stop console from closing (I add a breakpoint for it) Console.WriteLine("wait..."); }
public static async Task CalculateSingleAvalaraTaxAsync(ParametersHeader parameters) { const string licenseKey = "3C154FC03B81D3D5"; const int accountId = 2000160773; const string companyCode = "DEFAULT"; AvaTaxClient client = new AvaTaxClient("MyConsoleApp", "1.0", Environment.MachineName, AvaTaxEnvironment.Production) .WithSecurity(accountId, licenseKey); TransactionBuilder t1 = new TransactionBuilder(client, companyCode, DocumentType.SalesOrder, parameters.customer_code_string) .WithAddress(TransactionAddressType.SingleLocation, parameters.to_street, null, null, parameters.to_city, parameters.to_state.ToString(), parameters.to_zip, parameters.to_country) .WithDate(parameters.InvoiceDate) .WithReportingLocationCode("DEFAULT") .WithPurchaseOrderNumber(parameters.PoNumber); int i = 1; foreach (ParameterLine lineItem in parameters.line_items) { decimal qty = decimal.Zero; decimal.TryParse(lineItem.quantity, out qty); decimal unit_price = decimal.Zero; decimal.TryParse(lineItem.unit_price, out unit_price); string avaTaxCode = lineItem.avaTaxCode; string id = lineItem.id; t1.WithLine(unit_price, qty, avaTaxCode, lineItem.description, id, null, i.ToString()); i++; } try { TransactionModel tm = await t1.CreateAsync(); if (tm.lines != null) { foreach (TransactionLineModel line in tm.lines) { Guid.TryParse(line.itemCode, out Guid Id); var a = parameters.line_items.Find(l => l.id == Id.ToString()); a.taxAmount = line.taxCalculated ?? 0; Console.WriteLine(a.taxAmount); } } } catch (AvaTaxError ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.error); Console.ResetColor(); } }
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); } }
private static AvaTaxClient CreateAvaTaxClient(IAvaTaxSettings settings) { var machineName = Environment.MachineName; var avaTaxUri = new Uri(settings.ServiceUrl); var result = new AvaTaxClient(ApplicationName, ApplicationVersion, machineName, avaTaxUri) .WithSecurity(settings.AccountNumber, settings.LicenseKey); return(result); }
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 AvalaraCommand(AvalaraConfig settings, AvaTaxClient client, string environment) { _settings = settings; appEnvironment = (AppEnvironment)Enum.Parse(typeof(AppEnvironment), environment); noAccountCredentials = string.IsNullOrEmpty(_settings?.LicenseKey); _companyCode = _settings.CompanyCode; _baseUrl = _settings.BaseApiUrl; _avaTax = client; }
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")); } catch (Exception ex) { Assert.Fail("Exception in SetUp: " + ex); } }
public AvalaraCommand(AvalaraConfig settings, string environment) { _settings = settings; appEnvironment = (AppEnvironment)Enum.Parse(typeof(AppEnvironment), environment); hasAccountCredentials = !string.IsNullOrEmpty(_settings?.LicenseKey); _companyCode = _settings.CompanyCode; _baseUrl = _settings.BaseApiUrl; if (hasAccountCredentials) { _avaTax = new AvaTaxClient("four51_headstart", "v1", "four51_headstart", new Uri(settings.BaseApiUrl)).WithSecurity(settings.AccountID, settings.LicenseKey); } }
private static void ExtractSbxItems(AvaTaxClient sbxClient, List <ItemModel> itemModels) { //Get the fetch count of objects for the Sandbox company. int fetchCount = sbxClient.QueryItems(string.Format("companyId EQ {0}", SBX_COMPANY_ID), "classifications, parameters", null, null, string.Empty) .count; //Pull 1000 objects at a time. for (int i = 0; i < fetchCount; i += 1000) { itemModels.AddRange(sbxClient.QueryItems(string.Format("companyId EQ {0}", SBX_COMPANY_ID), "classifications, parameters", null, i, string.Empty).value); } }
static void Main(string[] args) { //Instantiate REST client var client = new AvaTaxClient("ItemMasterUpload", "YourAppVersionHere", "yourMachineNameHere", avaTaxEnvironment) .WithSecurity(USERNAME, PASSWORD); var itemModels = new List <ItemModel>(); //Load a list of Classification Systems into memory for easy lookup. var classificationSystems = client.ListProductClassificationSystems(string.Empty, null, null, string.Empty).value; //Open CSV OpenAndParseCsv(itemModels, classificationSystems); UpsertItems(client, itemModels); }
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 async Task NonJsonErrorResult() { AvaTaxError avataxError = null; try { // make a client that points to a server that will give a 404 for ping var client = new AvaTaxClient(GetType().Name, GetType().GetTypeInfo().Assembly.ImageRuntimeVersion.ToString(), Environment.MachineName, new Uri("https://www.google.com")); var result = await client.PingAsync().ConfigureAwait(false); } catch (AvaTaxError e) { avataxError = e; } Assert.NotNull(avataxError); Assert.True(avataxError.error.error.message.Contains("the response is in an unexpected format")); Assert.True(avataxError.error.error.details[0].description.ToLower().Contains("not found")); }
public void Initialize(IServiceCollection serviceCollection) { var snapshot = serviceCollection.BuildServiceProvider(); var configuration = snapshot.GetService <IConfiguration>(); var connectionString = configuration.GetConnectionString("VirtoCommerce.Tax") ?? configuration.GetConnectionString("VirtoCommerce"); serviceCollection.AddDbContext <AvaTaxDbContext>(options => options.UseSqlServer(connectionString)); serviceCollection.AddTransient <Func <IAvaTaxSettings, AvaTaxClient> >(provider => settings => { var machineName = Environment.MachineName; var avaTaxUri = new Uri(settings.ServiceUrl); var result = new AvaTaxClient(ApplicationName, ApplicationVersion, machineName, avaTaxUri) .WithSecurity(settings.AccountNumber, settings.LicenseKey); return(result); }); serviceCollection.AddTransient <IAddressValidationService, AddressValidationService>(); serviceCollection.AddTransient <IOrdersSynchronizationService, OrdersSynchronizationService>(); serviceCollection.AddTransient <IOrderTaxTypeResolver, OrderTaxTypeResolver>(); serviceCollection.AddOptions <AvaTaxSecureOptions>().Bind(configuration.GetSection("Tax:Avalara")).ValidateDataAnnotations(); }
static void Main(string[] args) { //Pull SBX Items, Classifications, and Parameters. //Instantiate REST client var sbxClient = new AvaTaxClient("ItemMasterExtract", "v0.1", ".NET Machine", sbxEnvironment) .WithSecurity(SBX_USERNAME, SBX_PASSWORD); var prdClient = new AvaTaxClient("ItemMasterLoad", "v0.1", ".NET Machine", prdEnvironment) .WithSecurity(PRD_USERNAME, PRD_PASSWORD); var itemModels = new List <ItemModel>(); var nexus = new List <NexusModel>(); //Load a list of Classification Systems into memory for easy lookup. var classificationSystems = sbxClient.ListProductClassificationSystems(string.Empty, null, null, string.Empty).value; ExtractSbxNexus(sbxClient, nexus); UpsertPrdNexus(prdClient, nexus); ExtractSbxItems(sbxClient, itemModels); UpsertItems(prdClient, itemModels); }
public AvaTaxWrapper() { _client = new AvaTaxClient("AppName", "AppVersion", "MachineName", new AvaTaxEnvironment()); }
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."); }
static void Main(string[] args) { // Parse options and show helptext if insufficient Options o = new Options(); Parser.Default.ParseArguments(args, o); if (!o.IsValid()) { var help = HelpText.AutoBuild(o); Console.WriteLine(help.ToString()); return; } // Parse server URI if (String.IsNullOrEmpty(o.Environment) || !o.Environment.StartsWith("http")) { Console.WriteLine($"Invalid URI: {o.Environment}"); return; } // Set up AvaTax var client = new AvaTaxClient("AvaTax-Connect", "1.0", Environment.MachineName, new Uri(o.Environment)) .WithSecurity(o.Username, o.Password); // Print out information about our configuration Console.WriteLine($"AvaTax-Connect Performance Testing Tool"); Console.WriteLine($"======================================="); Console.WriteLine($" SDK: {AvaTaxClient.API_VERSION}"); Console.WriteLine($" Environment: {o.Environment}"); Console.WriteLine($" User: {o.Username}"); Console.WriteLine($" Tax Lines: {o.Lines}"); Console.WriteLine($" Type: {o.DocType}"); Console.WriteLine(); Console.WriteLine(" Call Server Network Client Total"); // Use transaction builder var tb = new TransactionBuilder(client, "DEFAULT", o.DocType, "ABC") .WithAddress(TransactionAddressType.SingleLocation, "123 Main Street", null, null, "Irvine", "CA", "92615", "US"); // Add lines for (int i = 0; i < o.Lines; i++) { tb.WithLine(100.0m); } var ctm = tb.GetCreateTransactionModel(); // Discard the first call? if (o.DiscardFirstCall.HasValue && o.DiscardFirstCall.Value) { var t = client.CreateTransaction(null, ctm); } // Connect to AvaTax and print debug information int count = 0; CallDuration total = new CallDuration(); long totalms = 0; while (!Console.KeyAvailable) { count++; if (o.Calls.HasValue && count > o.Calls.Value) { Console.WriteLine("Done."); return; } // Make one tax transaction try { DateTime start = DateTime.UtcNow; var t = client.CreateTransaction(null, ctm); TimeSpan ts = DateTime.UtcNow - start; total.Combine(client.LastCallTime); totalms += ts.Milliseconds; // Write some information var cd = client.LastCallTime; Console.WriteLine($" {count.ToString("0000")} {cd.ServerDuration.TotalMilliseconds.ToString("0000.0000")}ms {cd.TransitDuration.TotalMilliseconds.ToString("0000.0000")}ms {(cd.SetupDuration.TotalMilliseconds + cd.ParseDuration.TotalMilliseconds).ToString("0000.0000")}ms {ts.TotalMilliseconds.ToString("0000.0000")}ms"); } catch (Exception ex) { Console.WriteLine($" {count.ToString("0000")} FAILED: {ex.Message}"); } } // Compute some averages double avg = totalms * 1.0 / count; double total_overhead = (total.SetupDuration.TotalMilliseconds + total.ParseDuration.TotalMilliseconds); double total_transit = total.TransitDuration.TotalMilliseconds; double total_server = total.ServerDuration.TotalMilliseconds; double avg_overhead = total_overhead / count; double avg_transit = total_transit / count; double avg_server = total_server / count; double pct_overhead = total_overhead / totalms; double pct_transit = total_transit / totalms; double pct_server = total_server / totalms; // Print out the totals Console.WriteLine(); Console.WriteLine($"Finished {count} calls in {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."); }
// This method is used to get adjust the tax rate for the user's order public override int CalculateTax2(string OrderID, double taxableAmount, string currencyCode, string[] priceCategories, string[] priceTaxLocales, double[] priceAmount, string[] taxLocaleId, ref double[] taxAmount) { #region |--This section of code shows what we have been passed if debug mode is "on"--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { // Used to help to see where these mesages are in the Storefront logs page LogMessage($"* *"); // Adds a space for easier viewing LogMessage($"* START *"); // Show when we start this process LogMessage($"* *"); // Shows what values are passed at beginning LogMessage($"OrderID is: {OrderID}"); // Tells the id for the order being calculated LogMessage($"TaxableAmount is: {taxableAmount.ToString()}"); // Tells the amount to be taxed (currently set to 0) LogMessage($"CurrencyCode is: {currencyCode}"); // Tells the type of currency used LogMessage($"PriceCategories is: {priceCategories.Length.ToString()}"); // Not Null, but empty LogMessage($"PriceTaxLocales is: {priceTaxLocales.Length.ToString()}"); // Not Null, but empty LogMessage($"PriceAmount is: {priceAmount.Length.ToString()}"); // Not Null, but empty LogMessage($"TaxLocaleId is: {taxLocaleId.Length.ToString()}"); // Shows the number of tax locales found for this order LogMessage($"TaxLocaleId[0] is: {taxLocaleId[0].ToString()}"); // Sends a number value which corresponds to the tax rate row in the tax rates table excel file // These Log the messages to a log .txt file // The logs an be found in the Logs folder in the storefront's deployment LogMessageToFile($"* *"); // Adds a space for easier viewing LogMessageToFile($"* START *"); // Show when we start this process LogMessageToFile($"* *"); // Shows what values are passed at beginning in .txt file LogMessageToFile($"OrderID is: {OrderID}"); // Tells the id for the order being calculated LogMessageToFile($"TaxableAmount is: {taxableAmount.ToString()}"); // Tells the amount to be taxed (currently set to 0) LogMessageToFile($"CurrencyCode is: {currencyCode}"); // Tells the type of currency used LogMessageToFile($"PriceCategories is: {priceCategories.Length.ToString()}"); // Not Null, but empty LogMessageToFile($"PriceTaxLocales is: {priceTaxLocales.Length.ToString()}"); // Not Null, but empty LogMessageToFile($"PriceAmount is: {priceAmount.Length.ToString()}"); // Not Null, but empty LogMessageToFile($"TaxLocaleId is: {taxLocaleId.Length.ToString()}"); // Shows the number of tax locales found for this order LogMessageToFile($"TaxLocaleId[0] is: {taxLocaleId[0].ToString()}"); // Sends a number value which corresponds to the tax rate row in the tax rates table excel file } #endregion #region |--This section is where we get and set the values from the shipping page where the user has entered their address info--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { // Shows the section where we get and display what has been added to the shipping page fields LogMessage($"* *"); LogMessage($"*Shipping Fields Section *"); LogMessage($"* *"); // Shows the section where we get and display what has been added to the shipping page fields in the .txt file LogMessageToFile($"* *"); LogMessageToFile($"*Shipping Fields Section *"); LogMessageToFile($"* *"); } // This section saves the user's shipping info to variables to use with calculating the tax rate to return // Listed in the same order as in the address book on the site var SFirstName = Storefront.GetValue("OrderField", "ShippingFirstName", OrderID); // This gets the first name that the user has on the shipping page var SLastName = Storefront.GetValue("OrderField", "ShippingLastName", OrderID); // This gets the last name that the user has on the shipping page var SAddress1 = Storefront.GetValue("OrderField", "ShippingAddress1", OrderID); // This gets the address field 1 that the user has on the shipping page var SAddress2 = Storefront.GetValue("OrderField", "ShippingAddress2", OrderID); // This gets the address field 2 that the user has on the shipping page var SCity = Storefront.GetValue("OrderField", "ShippingCity", OrderID); // This gets the city that the user has on the shipping page var SState = Storefront.GetValue("OrderField", "ShippingState", OrderID); // This gets the state that the user has on the shipping page var SPostalCode = Storefront.GetValue("OrderField", "ShippingPostalCode", OrderID); // This gets the zip code that the user has on the shipping page var SCountry = Storefront.GetValue("OrderField", "ShippingCountry", OrderID); // This gets the country that the user has on the shipping page // Get the handling charge to use with taxes var hCharge = Storefront.GetValue("OrderField", "HandlingCharge", OrderID); // This gets the handling charge for the order var sCharge = Storefront.GetValue("OrderField", "ShippingCharge", OrderID); // This gets the shipping charge for the order // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { // Log to show that we have retrieved the zipcode form the shipping page LogMessage($"Shipping FirstName: {SFirstName}"); // This gets the first name that the user has on the shipping page LogMessage($"Shipping LastName: {SLastName}"); // This gets the last name that the user has on the shipping page LogMessage($"Shipping Address1: {SAddress1}"); // This gets the address field 1 that the user has on the shipping page LogMessage($"Shipping Address2: {SAddress2}"); // This gets the address field 2 that the user has on the shipping page LogMessage($"Shipping City: {SCity}"); // This gets the city that the user has on the shipping page LogMessage($"Shipping State: {SState}"); // This gets the state that the user has on the shipping page LogMessage($"Shipping PostalCode: {SPostalCode}"); // This gets the zip code that the user has on the shipping page LogMessage($"Shipping Country: {SCountry}"); // This gets the country that the user has on the shipping page LogMessage($"Handling Charge: {hCharge}"); // This gets the zip code that the user has on the shipping page LogMessage($"Shipping Charge: {sCharge}"); // This gets the country that the user has on the shipping page // Log to show that we have retrieved the zipcode form the shipping page in the .txt file LogMessageToFile($"Shipping FirstName: {SFirstName}"); // This gets the first name that the user has on the shipping page LogMessageToFile($"Shipping LastName: {SLastName}"); // This gets the last name that the user has on the shipping page LogMessageToFile($"Shipping Address1: {SAddress1}"); // This gets the address field 1 that the user has on the shipping page LogMessageToFile($"Shipping Address2: {SAddress2}"); // This gets the address field 2 that the user has on the shipping page LogMessageToFile($"Shipping City: {SCity}"); // This gets the city that the user has on the shipping page LogMessageToFile($"Shipping State: {SState}"); // This gets the state that the user has on the shipping page LogMessageToFile($"Shipping PostalCode: {SPostalCode}"); // This gets the zip code that the user has on the shipping page LogMessageToFile($"Shipping Country: {SCountry}"); // This gets the country that the user has on the shipping page LogMessageToFile($"Handling Charge: {hCharge}"); // This gets the zip code that the user has on the shipping page LogMessageToFile($"Shipping Charge: {sCharge}"); // This gets the country that the user has on the shipping page } #endregion #region |--This is the section that connects and pulls info from avalara--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { // Shows the section where we change the tax rate LogMessage($"* *"); LogMessage($"* Tax Rates Section *"); LogMessage($"* *"); // Set the tax amount based on a few zipcodes and send it back to pageflex LogMessage($"Tax amount is: " + taxAmount[0].ToString() + " before we retrieve from Avalara"); // Shows the current tax amount (currently set to 0) // Shows the section where we change the tax rate in the .txt file LogMessageToFile($"* *"); LogMessageToFile($"* Tax Rates Section *"); LogMessageToFile($"* *"); // Set the tax amount based on a few zipcodes and send it back to pageflex in the .txt file LogMessageToFile($"Tax amount is: " + taxAmount[0].ToString() + " before we retrieve from Avalara"); // Shows the current tax amount (currently set to 0) } #region |--Database call to retrieve the subtotal should go here--| // TO DO: Database call to retrieve the subtotal should go here if can't get storefront access to work #endregion // Create a client and set up authentication var client = new AvaTaxClient("MyApp", "1.0", Environment.MachineName, AvaTaxEnvironment.Production) .WithSecurity("AvalaraUsername", "AvalaraPassword"); // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { // Show user creation passed LogMessage("Client created"); // Show user creation passed in the .txt file LogMessageToFile("Client created"); } // This creates the transaction that reaches out to alavara and gets the amount of tax for the user based on info we send // send client we created above in code, the company on alavara I created, typoe of transaction, and the company code I set up for company var transaction = new TransactionBuilder(client, "AvalaraCompanyCode", DocumentType.SalesOrder, "AvalaraCustomerCode") // Pass the variables we pulled from pageflex in the address line .WithAddress(TransactionAddressType.SingleLocation, SAddress1, SAddress2, null, SCity, SState, SPostalCode, SCountry) // Pass the amount of money to calculate tax on (This should be a variable once figure out what it is) .WithLine(150.0m) #region |--Here is where we will send the total retrieved from db call--| // Here is where we will send the total retrieved from db call //.WithLine(REPLACE WITH VARIABLE CONTAING TOTAL FROM DB CALL) #endregion // Run transaction .Create(); // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { // Log that we have created a transaction LogMessage("The transaction has been created"); // Log that we have created a transaction in the .txt file LogMessageToFile("The transaction has been created"); } // Retrieves the tax amount from Avalara and sets it to a variable // (It is returned as a decimal? so we havve to convert it to a decimal) // (The ?? 0 sets it to 0 if transaction.totalTax is null) decimal tax2 = transaction.totalTax ?? 0; // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { //Log what is returned LogMessage($"Your calculated tax was: {tax2}"); //Log what is returned in the .txt file LogMessageToFile($"Your calculated tax was: {tax2}"); } //Set the tax amount on pageflex to the returned value from Avalara taxAmount[0] = decimal.ToDouble(tax2); // Set our new tax rate to a value we choose (for testing) // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_SADEBUGGINGMODE] == "true") { LogMessage($"The zipcode was: " + SPostalCode); // Log message to inform we used this zipcode to get the amount returned LogMessage($"The new TaxAmount is: " + taxAmount[0].ToString()); // Shows the tax amount after we changed it // Send message saying we have completed this process LogMessage($"* *"); LogMessage($"* end *"); LogMessage($"* *"); // Log for .txt file LogMessageToFile($"The zipcode was: " + SPostalCode); // Log message to inform we used this zipcode to get the amount returned LogMessageToFile($"The new TaxAmount is: " + taxAmount[0].ToString()); // Shows the tax amount after we changed it // Send message saying we have completed this process in the .txt file LogMessageToFile($"* *"); LogMessageToFile($"* end *"); LogMessageToFile($"* *"); } // Kept for reference and future use // avalara logging doesn't work from inside extension // client.LogToFile("MySixthExtension\\avataxapi.log"); #endregion return(eSuccess); }
protected virtual async Task SendOrderToAvaTax(CustomerOrder order, string companyCode, Address sourceAddress, AvaTaxClient avaTaxClient) { if (!order.IsCancelled) { var createOrAdjustTransactionModel = AbstractTypeFactory <AvaCreateOrAdjustTransactionModel> .TryCreateInstance(); createOrAdjustTransactionModel.FromOrder(order, companyCode, sourceAddress); var transactionModel = await avaTaxClient.CreateOrAdjustTransactionAsync(string.Empty, createOrAdjustTransactionModel); } else { var voidTransactionModel = new VoidTransactionModel { code = VoidReasonCode.DocVoided }; var transactionModel = await avaTaxClient.VoidTransactionAsync(companyCode, order.Number, DocumentType.Any, voidTransactionModel); } }
/// <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"); }
private static void UpsertItems(AvaTaxClient client, List <ItemModel> itemModels) { foreach (ItemModel newItemModel in itemModels) { try { //Does the item already exist in this company? var existingItem = client.QueryItems(string.Format("itemCode EQ \"{0}\" AND companyId EQ {1}", newItemModel.itemCode, PRD_COMPANY_ID), string.Empty, null, null, string.Empty).value.FirstOrDefault(); //Yes, the item exists. Load the HS Codes to this item. if (existingItem != null) { var existingClassifications = client.ListItemClassifications(PRD_COMPANY_ID, existingItem.id, string.Empty, null, null, string.Empty).value; //Check if there are Classifications. if (newItemModel.classifications != null) { //Yes, load the Classifications. foreach (var cm in newItemModel.classifications) { ItemClassificationInputModel clsInputModel = new ItemClassificationInputModel { productCode = cm.productCode, systemCode = cm.systemCode }; //Does the classification already exist? And is it the same? var sameClassificationSystem = existingClassifications.Where(ec => ec.systemCode == cm.systemCode).FirstOrDefault(); var exactSameClassification = existingClassifications.Where(ec => ec.systemCode == cm.systemCode && ec.productCode == cm.productCode).FirstOrDefault(); //Classification does not exist. Add it. if (sameClassificationSystem == null) { client.CreateItemClassifications(PRD_COMPANY_ID, existingItem.id, new List <ItemClassificationInputModel> { clsInputModel }); continue; } //Classification exists, but is different. Update it. if (sameClassificationSystem != null && exactSameClassification == null) { client.UpdateItemClassification(PRD_COMPANY_ID, existingItem.id, sameClassificationSystem.id.Value, clsInputModel); } } } } else { //Item does not yet exist. Create a new Item. newItemModel.companyId = PRD_COMPANY_ID; client.CreateItems(PRD_COMPANY_ID, new List <ItemModel>() { newItemModel }); } } catch (AvaTaxError exc) { Console.WriteLine(string.Format("Error loading/updating item {0}", newItemModel.id)); Console.WriteLine(string.Format("More information: {0}", exc.error)); } catch (Exception exc) { Console.WriteLine(exc.Message); } } }
private static void ExtractSbxNexus(AvaTaxClient sbxClient, List <NexusModel> nexus) { nexus.AddRange(sbxClient.ListNexusByCompany(SBX_COMPANY_ID, "nexusTaxTypeGroup EQ LandedCost", string.Empty, null, null, string.Empty).value); }
// This method is used to get adjust the tax rate for the user's order public override int CalculateTax2(string OrderID, double taxableAmount, string currencyCode, string[] priceCategories, string[] priceTaxLocales, double[] priceAmount, string[] taxLocaleId, ref double[] taxAmount) { #region |--This section of code shows what we have been passed if debug mode is "on"--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Used to help to see where these mesages are in the Storefront logs page LogMessage($"* *"); // Adds a space for easier viewing LogMessage($"* START *"); // Show when we start this process LogMessage($"* *"); // Shows what values are passed at beginning LogMessage($"OrderID is: {OrderID}"); // Tells the id for the order being calculated LogMessage($"TaxableAmount is: {taxableAmount.ToString()}"); // Tells the amount to be taxed (currently set to 0) LogMessage($"CurrencyCode is: {currencyCode}"); // Tells the type of currency used LogMessage($"PriceCategories is: {priceCategories.Length.ToString()}"); // Not Null, but empty LogMessage($"PriceTaxLocales is: {priceTaxLocales.Length.ToString()}"); // Not Null, but empty LogMessage($"PriceAmount is: {priceAmount.Length.ToString()}"); // Not Null, but empty LogMessage($"TaxLocaleId is: {taxLocaleId.Length.ToString()}"); // Shows the number of tax locales found for this order LogMessage($"TaxLocaleId[0] is: {taxLocaleId[0].ToString()}"); // Sends a number value which corresponds to the tax rate row in the tax rates table excel file // These Log the messages to a log .txt file // The logs an be found in the Logs folder in the storefront's deployment LogMessageToFile($"* *"); // Adds a space for easier viewing LogMessageToFile($"* START *"); // Show when we start this process LogMessageToFile($"* *"); // Shows what values are passed at beginning in .txt file LogMessageToFile($"OrderID is: {OrderID}"); // Tells the id for the order being calculated LogMessageToFile($"TaxableAmount is: {taxableAmount.ToString()}"); // Tells the amount to be taxed (currently set to 0) LogMessageToFile($"CurrencyCode is: {currencyCode}"); // Tells the type of currency used LogMessageToFile($"PriceCategories is: {priceCategories.Length.ToString()}"); // Not Null, but empty LogMessageToFile($"PriceTaxLocales is: {priceTaxLocales.Length.ToString()}"); // Not Null, but empty LogMessageToFile($"PriceAmount is: {priceAmount.Length.ToString()}"); // Not Null, but empty LogMessageToFile($"TaxLocaleId is: {taxLocaleId.Length.ToString()}"); // Shows the number of tax locales found for this order LogMessageToFile($"TaxLocaleId[0] is: {taxLocaleId[0].ToString()}"); // Sends a number value which corresponds to the tax rate row in the tax rates table excel file } #endregion #region |--This section is where we get and set the values from the shipping page where the user has entered their address info--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Shows the section where we get and display what has been added to the shipping page fields LogMessage($"* *"); // Adds a space for easier viewing LogMessage($"*Shipping Fields Section *"); // Show when we reach the shipping fields section LogMessage($"* *"); // Shows the section where we get and display what has been added to the shipping page fields in the .txt file LogMessageToFile($"* *"); // Adds a space for easier viewing LogMessageToFile($"*Shipping Fields Section *"); // Show when we reach the shipping fields section LogMessageToFile($"* *"); } // This section saves the user's shipping info to variables to use with calculating the tax rate to return // Listed in the same order as in the address book on the site var SFirstName = Storefront.GetValue("OrderField", "ShippingFirstName", OrderID); // This gets the first name that the user has on the shipping page var SLastName = Storefront.GetValue("OrderField", "ShippingLastName", OrderID); // This gets the last name that the user has on the shipping page var SAddress1 = Storefront.GetValue("OrderField", "ShippingAddress1", OrderID); // This gets the address field 1 that the user has on the shipping page var SAddress2 = Storefront.GetValue("OrderField", "ShippingAddress2", OrderID); // This gets the address field 2 that the user has on the shipping page var SCity = Storefront.GetValue("OrderField", "ShippingCity", OrderID); // This gets the city that the user has on the shipping page var SState = Storefront.GetValue("OrderField", "ShippingState", OrderID); // This gets the state that the user has on the shipping page var SPostalCode = Storefront.GetValue("OrderField", "ShippingPostalCode", OrderID); // This gets the zip code that the user has on the shipping page var SCountry = Storefront.GetValue("OrderField", "ShippingCountry", OrderID); // This gets the country that the user has on the shipping page // Get the handling charge to use with taxes var hCharge = Storefront.GetValue("OrderField", "HandlingCharge", OrderID); // This gets the handling charge for the order var sCharge = Storefront.GetValue("OrderField", "ShippingCharge", OrderID); // This gets the shipping charge for the order // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log to show that we have retrieved the zipcode form the shipping page LogMessage($"Shipping FirstName: {SFirstName}"); // This logs the first name that the user has on the shipping page LogMessage($"Shipping LastName: {SLastName}"); // This logs the last name that the user has on the shipping page LogMessage($"Shipping Address1: {SAddress1}"); // This logs the address field 1 that the user has on the shipping page LogMessage($"Shipping Address2: {SAddress2}"); // This logs the address field 2 that the user has on the shipping page LogMessage($"Shipping City: {SCity}"); // This logs the city that the user has on the shipping page LogMessage($"Shipping State: {SState}"); // This logs the state that the user has on the shipping page LogMessage($"Shipping PostalCode: {SPostalCode}"); // This logs the zip code that the user has on the shipping page LogMessage($"Shipping Country: {SCountry}"); // This logs the country that the user has on the shipping page LogMessage($"Handling Charge: {hCharge}"); // This logs the zip code that the user has on the shipping page LogMessage($"Shipping Charge: {sCharge}"); // This logs the country that the user has on the shipping page // Log to show that we have retrieved the zipcode form the shipping page in the .txt file LogMessageToFile($"Shipping FirstName: {SFirstName}"); // This logs the first name that the user has on the shipping page LogMessageToFile($"Shipping LastName: {SLastName}"); // This logs the last name that the user has on the shipping page LogMessageToFile($"Shipping Address1: {SAddress1}"); // This logs the address field 1 that the user has on the shipping page LogMessageToFile($"Shipping Address2: {SAddress2}"); // This logs the address field 2 that the user has on the shipping page LogMessageToFile($"Shipping City: {SCity}"); // This logs the city that the user has on the shipping page LogMessageToFile($"Shipping State: {SState}"); // This logs the state that the user has on the shipping page LogMessageToFile($"Shipping PostalCode: {SPostalCode}"); // This logs the zip code that the user has on the shipping page LogMessageToFile($"Shipping Country: {SCountry}"); // This logs the country that the user has on the shipping page LogMessageToFile($"Handling Charge: {hCharge}"); // This logs the zip code that the user has on the shipping page LogMessageToFile($"Shipping Charge: {sCharge}"); // This logs the country that the user has on the shipping page } #endregion #region |--Database call to retrieve the subtotal--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Shows the section where we change the tax rate LogMessage($"* *"); // Adds a space for easier viewing LogMessage($"*Tax Rates Section Part 1*"); // Show when we reach the tax rates section LogMessage($"* *"); // Set the tax amount based on a few zipcodes and send it back to pageflex LogMessage($"Tax amount is: " + taxAmount[0].ToString() + " before we make our DB or Avalara calls"); // Shows the current tax amount (currently set to 0) // Shows the section where we change the tax rate in the .txt file LogMessageToFile($"* *"); // Adds a space for easier viewing LogMessageToFile($"*Tax Rates Section Part 1*"); // Show when we reach the tax rates section LogMessageToFile($"* *"); // Set the tax amount based on a few zipcodes and send it back to pageflex in the .txt file LogMessageToFile($"Tax amount is: " + taxAmount[0].ToString() + " before we make our DB or Avalara calls"); // Shows the current tax amount (currently set to 0) } // Get our DB logon info from the storefront string dataSource = Storefront.GetValue("ModuleField", _DATA_SOURCE, _UNIQUE_NAME); // This variable holds the datasource the user provided from the extension setup page string initialCatalog = Storefront.GetValue("ModuleField", _INITIAL_CATALOG, _UNIQUE_NAME); // This variable holds the datasource the user provided from the extension setup page string userID = Storefront.GetValue("ModuleField", _USER_ID, _UNIQUE_NAME); // This variable holds the datasource the user provided from the extension setup page string userPassword = Storefront.GetValue("ModuleField", _USER_PASSWORD, _UNIQUE_NAME); // This variable holds the datasource the user provided from the extension setup page // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log messages to show what was retrieved from the storefront LogMessage($"DB logon information:"); // This logs that we are logging the DB Logon information LogMessage($"Data Source is: {dataSource}"); // This logs the data source that the user has on the extension configuration page LogMessage($"Initial Catalog is: {initialCatalog}"); // This logs the initial catalog that the user has on the extension configuration page LogMessage($"User ID is: {userID}"); // This logs the user id that the user has on the extension configuration page LogMessage($"User Password is: {userPassword}"); // This logs the user password that the user has on the extension configuration page LogMessageToFile($"DB logon information:"); // This logs that we are logging the DB Logon information LogMessageToFile($"Data Source is: {dataSource}"); // This logs the data source that the user has on the extension configuration page LogMessageToFile($"Initial Catalog is: {initialCatalog}"); // This logs the initial catalog that the user has on the extension configuration page LogMessageToFile($"User ID is: {userID}"); // This logs the user id that the user has on the extension configuration page LogMessageToFile($"User Password is: {userPassword}"); // This logs the user password that the user has on the extension configuration page } // Our credentials to connect to the DB string connectionString = $"Data Source={dataSource};" + $"Initial Catalog={initialCatalog};" + $"User ID={userID};" + $"Password={userPassword};" + "Persist Security Info=True;" + "Connection Timeout=15"; // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { LogMessage($"Full Connection String: {connectionString}"); // This logs the full connection string to see it is all together properly LogMessageToFile($"Full Connection String: {connectionString}"); // This logs the full connection string to see it is all together properly } // The query to be ran on the DB /* * Query: SELECTS the "Order Group ID", the "Price"(Cast as money) , the "Shipping Charge"(Cast as money) , and the "Handling Charge"(Cast as money) * FROM three tables: "OrderedDocuments", "OrderGroups", and "Shipments" that have been INNER JOINED together based on the "OrderGroupID" * WHERE the "OrderGroupID" equals the orderID of our current order on the storefront */ string queryString = "SELECT OrderedDocuments.OrderGroupID," + "CAST(OrderedDocuments.Price / 100.00 as money) as Price," + "CAST(Shipments.ShippingAmount / 100.00 as money) as Shipping," + "CAST(OrderGroups.HandlingCharge / 100.00 as money) as Handling " + "FROM OrderedDocuments " + "INNER JOIN OrderGroups ON OrderGroups.OrderGroupID = OrderedDocuments.OrderGroupID " + "INNER JOIN Shipments ON Shipments.OrderGroupID = OrderedDocuments.OrderGroupID " + "WHERE OrderedDocuments.OrderGroupID = @orderID"; // This is how to call it using a stored procedure I currently have setup on "Interface DB" //string queryString = "USE [Interface] " + "DECLARE @return_value Int EXEC @return_value = [dbo].[GetRates] @OrderID = 1787 SELECT @return_value as 'Return Value'"; if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log to let the developer know we are trying to connect to DB using connection string LogMessage("starting DB connection"); // This logs that we are starting the DB connection process LogMessageToFile("starting DB connection"); // This logs that we are starting the DB connection process } try { // Setup the connection to the db using our credentials using (SqlConnection connection = new SqlConnection(connectionString)) { // Open the connection using what we have setup connection.Open(); if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log to let the developer know connection to DB was successful LogMessage("DB connection successful"); // This logs that the DB connection process was a success LogMessageToFile("DB connection successful"); // This logs that the DB connection process was a success } // Setup our query to call SqlCommand commandGetRates = new SqlCommand(queryString, connection); commandGetRates.Parameters.AddWithValue("@orderID", OrderID); if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log to let the developer know we finished running our query LogMessage("Query finished running"); // This logs that the query run has finished LogMessageToFile("Query finished running"); // This logs that the query run has finished } // Setup a reader to handle what our query returns using (SqlDataReader reader = commandGetRates.ExecuteReader()) { // Read back what our query retrieves while (reader.Read()) { if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log and show the results we retrieved from the DB LogMessage(string.Format("From DB Reader: OrderID: {0}, Price: {1}, Shipping: {2}, Handling: {3}", reader["OrderGroupID"], reader["Price"], reader["Shipping"], reader["Handling"])); LogMessageToFile(string.Format("From DB Reader: OrderID: {0}, Price: {1}, Shipping: {2}, Handling: {3}", reader["OrderGroupID"], reader["Price"], reader["Shipping"], reader["Handling"])); } // Filling the variables to hold our totals from the DB retrieval step subTotal = Convert.ToDecimal(reader["Price"]); // This gets the subtotal that the user has on the extension configuration page shippingCharge = Convert.ToDecimal(reader["Shipping"]); // This gets the shipping charge that the user has on the extension configuration page handlingCharge = Convert.ToDecimal(reader["Handling"]); // This gets the handling charge that the user has on the extension configuration page } // Calculate the total amount to be taxed by Avalara totalTaxableAmount = subTotal + shippingCharge + handlingCharge; if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log messages to show what we retrieved from DB and have stored into variables LogMessage($"Totals read from the DB and stored in variables"); // This logs that the DB read has finished and we are showing what is in the variables saved LogMessage($"subTotal: {subTotal}"); // This logs the subtotal variable LogMessage($"shippingCharge: {shippingCharge}"); // This logs the shipping charge variable LogMessage($"handlingCharge: {handlingCharge}"); // This logs the handling charge variable LogMessageToFile($"Totals read from the DB and stored in variables"); // This logs that the DB read has finished and we are showing what is in the variables saved LogMessageToFile($"subTotal: {subTotal}"); // This logs the subtotal variable LogMessageToFile($"shippingCharge: {shippingCharge}"); // This logs the shipping charge variable LogMessageToFile($"handlingCharge: {handlingCharge}"); // This logs the handling charge variable // Log message to show what the total taxable amount that will be sent to Avalara is LogMessage($"Total Taxable Amount: {totalTaxableAmount}"); // This logs the total taxable amount LogMessageToFile($"Total Taxable Amount: {totalTaxableAmount}"); // This logs the total taxable amount } // Always call Close when done reading. reader.Close(); } // Called by dispose, but good practice to close when done with connection. connection.Close(); } } catch { // Log issue with storefront and to file regardless of whether in debug mode or not LogMessage("Error in DB connection and data retrieval process"); // This logs that there was an error in the DB process LogMessageToFile("Error in DB connection and data retrieval process"); // This logs that there was an error in the DB process } #endregion #region |--This is the section that connects and pulls info from avalara--| // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Shows the section where we change the tax rate LogMessage($"* *"); // Adds a space for easier viewing LogMessage($"*Tax Rates Section Part 2*"); // Show when we reach the tax rates 2 section LogMessage($"* *"); // Set the tax amount based on a few zipcodes and send it back to pageflex LogMessage($"Tax amount is: " + taxAmount[0].ToString() + " before we make our Avalara call"); // Shows the current tax amount (currently set to 0) // Shows the section where we change the tax rate in the .txt file LogMessageToFile($"* *"); // Adds a space for easier viewing LogMessageToFile($"*Tax Rates Section Part 2*"); // Show when we reach the tax rates 2 section LogMessageToFile($"* *"); // Set the tax amount based on a few zipcodes and send it back to pageflex in the .txt file LogMessageToFile($"Tax amount is: " + taxAmount[0].ToString() + " before we make our Avalara call"); // Shows the current tax amount (currently set to 0) } // Get our Avalara logon info from the storefront string AVCompanyName = Storefront.GetValue("ModuleField", _AV_COMPANY_NAME, _UNIQUE_NAME); // This gets the company name that the user has on the extension configuration page string AVCompanyCode = Storefront.GetValue("ModuleField", _AV_COMPANY_CODE, _UNIQUE_NAME); // This gets the company code that the user has on the extension configuration page string AVuserID = Storefront.GetValue("ModuleField", _AV_USER_ID, _UNIQUE_NAME); // This gets the user id that the user has on the extension configuration page string AVuserPassword = Storefront.GetValue("ModuleField", _AV_USER_PASSWORD, _UNIQUE_NAME); // This gets the user password that the user has on the extension configuration page // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log messages to show what was retrieved from the storefront LogMessage($"Avalara logon information:"); // This logs that we are displaying the Avalara logon information LogMessage($"Company Name: {AVCompanyName}"); // This logs the company name variable LogMessage($"Company Code: {AVCompanyCode}"); // This logs the company code variable LogMessage($"AValara User ID: {AVuserID}"); // This logs the user id variable LogMessage($"Avalara User Password: {AVuserPassword}"); // This logs the user password variable LogMessageToFile($"Avalara logon information:"); // This logs that we are displaying the Avalara logon information LogMessageToFile($"Company Name: {AVCompanyName}"); // This logs the company name variable LogMessageToFile($"Company Code: {AVCompanyCode}"); // This logs the company code variable LogMessageToFile($"AValara User ID: {AVuserID}"); // This logs the user id variable LogMessageToFile($"Avalara User Password: {AVuserPassword}"); // This logs the user password variable } // Create a client and set up authentication var client = new AvaTaxClient("AvalaraTaxExtension", "1.0", Environment.MachineName, AvaTaxEnvironment.Production) .WithSecurity($"{AVuserID}", $"{AVuserPassword}"); // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Show user creation passed LogMessage("Client created"); // This logs that the Avalara client has been created // Show user creation passed in the .txt file LogMessageToFile("Client created"); // This logs that the Avalara client has been created } // This creates the transaction that reaches out to alavara and gets the amount of tax for the user based on info we send // send client we created above in code, the company on alavara I created, type of transaction, and the company code I set up for company var transaction = new TransactionBuilder(client, $"{AVCompanyName}", DocumentType.SalesOrder, $"{AVCompanyCode}") // Pass the variables we pulled from pageflex in the address line .WithAddress(TransactionAddressType.SingleLocation, SAddress1, SAddress2, null, SCity, SState, SPostalCode, SCountry) // Pass the amount of money to calculate tax on (This should be a variable once figure out what it is) .WithLine(totalTaxableAmount) // Run transaction .Create(); // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { // Log that we have created a transaction LogMessage("The transaction has been created"); // This logs that the Avalara transaction has been created // Log that we have created a transaction in the .txt file LogMessageToFile("The transaction has been created"); // This logs that the Avalara transaction has been created } // Retrieves the tax amount from Avalara and sets it to a variable // (It is returned as a decimal? so we havve to convert it to a decimal) // (The ?? 0 sets it to 0 if transaction.totalTax is null) decimal tax2 = transaction.totalTax ?? 0; // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { //Log what is returned LogMessage($"Your calculated tax was: {tax2}"); // This logs that the calculated tax for the order //Log what is returned in the .txt file LogMessageToFile($"Your calculated tax was: {tax2}"); // This logs that the calculated tax for the order } //Set the tax amount on pageflex to the returned value from Avalara taxAmount[0] = decimal.ToDouble(tax2); // Set our new tax rate to a value we choose (for testing) // Check if debug mode is turned on; If it is then we log these messages if ((string)ModuleData[_AT_DEBUGGING_MODE] == "true") { LogMessage($"The zipcode was: " + SPostalCode); // Log message to inform we used this zipcode to get the amount returned LogMessage($"The new TaxAmount is: " + taxAmount[0].ToString()); // Shows the tax amount after we changed it // Send message saying we have completed this process LogMessage($"* *"); // Adds a space for easier viewing LogMessage($"* end *"); // Show when we reach the end of the extension LogMessage($"* *"); // Log for .txt file LogMessageToFile($"The zipcode was: " + SPostalCode); // Log message to inform we used this zipcode to get the amount returned LogMessageToFile($"The new TaxAmount is: " + taxAmount[0].ToString()); // Shows the tax amount after we changed it // Send message saying we have completed this process in the .txt file LogMessageToFile($"* *"); // Adds a space for easier viewing LogMessageToFile($"* end *"); // Show when we reach the end of the extension LogMessageToFile($"* *"); } // Kept for reference and future use // avalara logging doesn't work from inside extension // client.LogToFile("MySixthExtension\\avataxapi.log"); #endregion return(eSuccess); }
// This method is used to get adjust the tax rate for the user's order public override int CalculateTax2(string OrderID, double taxableAmount, string currencyCode, string[] priceCategories, string[] priceTaxLocales, double[] priceAmount, string[] taxLocaleId, ref double[] taxAmount) { #region This section of code shows what we have been passed // Used to help to see where these mesages are in the Storefront logs page LogMessage($"* space *"); // Adds a space for easier viewing LogMessage($"* START *"); // Show when we start this process LogMessage($"* space *"); // Shows what values are passed at beginning LogMessage(OrderID); // Tells the id for the order being calculated LogMessage(taxableAmount.ToString()); // Tells the amount to be taxed (currently set to 0) LogMessage(currencyCode); // Tells the type of currency used LogMessage(priceCategories.Length.ToString()); // Not Null, but empty LogMessage(priceTaxLocales.Length.ToString()); // Not Null, but empty LogMessage(priceAmount.Length.ToString()); // Not Null, but empty LogMessage(taxLocaleId.Length.ToString()); // Shows the number of tax locales found for this order LogMessage(taxLocaleId[0].ToString()); // Sends a number value which corresponds to the tax rate row in the tax rates table excel file #endregion #region This section is where we set the tax rate based on several zipcodes entered by the user // Shows the section where we change the tax rate LogMessage($"* space *"); LogMessage($"* Tax Section *"); // Used to show where we change the tax rate LogMessage($"* space *"); // This section saves the user's shipping info to variables to use with calculating the tax rate to return // Listed in the same order as in the address book on the site var SFirstName = Storefront.GetValue("OrderField", "ShippingFirstName", OrderID); // This gets the first name that the user has on the shipping page var SLastName = Storefront.GetValue("OrderField", "ShippingLastName", OrderID); // This gets the last name that the user has on the shipping page var SAddress1 = Storefront.GetValue("OrderField", "ShippingAddress1", OrderID); // This gets the address field 1 that the user has on the shipping page var SAddress2 = Storefront.GetValue("OrderField", "ShippingAddress2", OrderID); // This gets the address field 2 that the user has on the shipping page var SCity = Storefront.GetValue("OrderField", "ShippingCity", OrderID); // This gets the city that the user has on the shipping page var SState = Storefront.GetValue("OrderField", "ShippingState", OrderID); // This gets the state that the user has on the shipping page var SPostalCode = Storefront.GetValue("OrderField", "ShippingPostalCode", OrderID); // This gets the zip code that the user has on the shipping page var SCountry = Storefront.GetValue("OrderField", "ShippingCountry", OrderID); // This gets the country that the user has on the shipping page // Log to show that we have retrieved the zipcode form the shipping page LogMessage($"Shipping FirstName: {SFirstName}"); // This gets the first name that the user has on the shipping page LogMessage($"Shipping LastName: {SLastName}"); // This gets the last name that the user has on the shipping page LogMessage($"Shipping Address1: {SAddress1}"); // This gets the address field 1 that the user has on the shipping page LogMessage($"Shipping Address2: {SAddress2}"); // This gets the address field 2 that the user has on the shipping page LogMessage($"Shipping City: {SCity}"); // This gets the city that the user has on the shipping page LogMessage($"Shipping State: {SState}"); // This gets the state that the user has on the shipping page LogMessage($"Shipping PostalCode: {SPostalCode}"); // This gets the zip code that the user has on the shipping page LogMessage($"Shipping Country: {SCountry}"); // This gets the country that the user has on the shipping page // Set the tax amount based on a few zipcodes and send it back to pageflex LogMessage(taxAmount[0].ToString()); // Shows the current tax amount (currently set to 0) // Create a client and set up authentication var client = new AvaTaxClient("MyApp", "1.0", Environment.MachineName, AvaTaxEnvironment.Production) .WithSecurity("AvalaraUsername", "AvalaraPassword"); LogMessage("Client created"); client.LogToFile("MySixthExtension\\avataxapi.log"); var transaction = new TransactionBuilder(client, "AvalaraCompanyCode", DocumentType.SalesOrder, "AvalaraCustomerCode") .WithAddress(TransactionAddressType.SingleLocation, SAddress1, SAddress2, null, SCity, SState, SPostalCode, SCountry) .WithLine(150.0m) .Create(); //var tax = transaction.totalTax; decimal tax2 = transaction.totalTax ?? 0; LogMessage($"Your calculated tax was: {tax2}"); // Console.WriteLine("Your calculated tax was {0}", transaction.totalTax); taxAmount[0] = decimal.ToDouble(tax2); // Set our new tax rate to a value we choose (for testing) LogMessage($"The zipcode was " + SPostalCode); // Log message to inform we used this zipcode to get the amount returned LogMessage(taxAmount[0].ToString()); // Shows the tax amount after we changed it /* * // Check if we have a few certain zipcodes to set the value to or just to use the default value * if (SPostalCode == "37876") * { * // Set the new tax amount * taxAmount[0] = 18.19; // Set our new tax rate to a value we choose (for testing) * LogMessage($"The zipcode was 37876"); // Log message to inform we used this zipcode to get the amount returned * LogMessage(taxAmount[0].ToString()); // Shows the tax amount after we changed it * } * else if (SPostalCode == "12345") * { * // Set the new tax amount * taxAmount[0] = 23.40; * LogMessage($"The zipcode was 12345"); * LogMessage(taxAmount[0].ToString()); * } * else if (SPostalCode == "01752") * { * // Set the new tax amount * taxAmount[0] = 3.43; * LogMessage($"The zipcode was 01752"); * LogMessage(taxAmount[0].ToString()); * } * else * { * // Set the new tax amount * taxAmount[0] = 13.37; * LogMessage($"Default tax was used"); * LogMessage(taxAmount[0].ToString()); * } * * // Send message saying we have completed this process * LogMessage($"* space *"); * LogMessage($"* end *"); * LogMessage($"* space *"); */ // Further reading if needed // Look at pg 436 and 467 invlovling address books if need to use them for zipcodes #endregion #region Using this will tell the storefront to calculate it's own tax using the tax tables // Unused, but keeping as a sidenote //taxAmount = null; #endregion #region This section shows how to get the zipcode and other fields from the user's profile. /* * * //this gets the zip code from the user profile, but we need the zip from the shipping form... * var discountPercentageString = Storefront.GetValue("UserField", "UserProfilePricingDiscount", CurrentUserId); * var PostalCodeString = Storefront.GetValue("UserField", "UserProfilePostalCode", CurrentUserId); * * // Used to help to see where these mesages are in the Storefront logs page * LogMessage($"* space *"); // Adds a space for easier viewing * LogMessage($"* START *"); // Show when we start this process * LogMessage($"* space *"); * * // Log the information retrieved from the user's profile fields * LogMessage($"Current User Id: {CurrentUserId}"); // Return the user's id * LogMessage($"User Zipcode: {PostalCodeString}"); // Return the user's zipcode * * // Send message saying we have completed this process * LogMessage($"* space *"); * LogMessage($"* end *"); // Return a message saying this process is finished * LogMessage($"* space *"); * */ #endregion return(eSuccess); }