Пример #1
0
        /// <summary>
        /// The starting point of the application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            try
            {
                // Handle requires arguments

                SessionContext session = ConsoleHelper.GetSessionArguments(args);
                if (session.IsValid())
                {
                    AuthenticationProvider authenticationProvider = new AuthenticationProvider(session.ClientId, session.ClientSecret);

                    // For this sample purpose we will select tha company to use.

                    SetSessionCompanyKeyAsync(session, authenticationProvider).Wait();

                    // For this sample purpose we will allow negative stock on this company.

                    SetAllowNegativeStockAsync(session, authenticationProvider).Wait();

                    // Display Main Menu

                    MenuOptions option = MenuOptions.Exit;
                    do
                    {
                        option = ConsoleHelper.GetMenuOption();
                        if (option != MenuOptions.Exit)
                        {
                            HandleMainMenuOptionAsync(session, authenticationProvider, option).Wait();
                        }
                    } while (option != MenuOptions.Exit);
                }
            }
            catch (Exception ex)
            {
                ConsoleHelper.WriteErrorLine(ex.Message);
                Console.ReadKey();
            }
        }
Пример #2
0
        private static async Task <int> HandleCustomersOperationAsync(SessionContext sessionContext, AuthenticationProvider authenticationProvider, CustomersMenuOptions option)
        {
            Console.WriteLine("");
            Console.WriteLine("selected option " + string.Format("{0:D} - {1}", option, option.ToName()));
            Console.WriteLine("");

            // Get the authorization access token

            CustomersController.AccountKey             = sessionContext.AccountKey;
            CustomersController.SubscriptionKey        = sessionContext.SubscriptionKey;
            CustomersController.CultureKey             = sessionContext.CultureKey;
            CustomersController.AuthenticationProvider = authenticationProvider;

            switch (option)
            {
            case CustomersMenuOptions.Sales_Customers_CustomerAllInOne:
                sessionContext.PartyKey = await CustomersController.CreateCustomerAndPartyAsync();

                break;

            case CustomersMenuOptions.Sales_Customers_PartyAndCustomer:
                sessionContext.PartyKey = await CustomersController.CreatePartyAndCustomerExtensionAsync();

                break;

            case CustomersMenuOptions.Sales_Customers_GetLastCustomer:
                sessionContext.PartyKey = await CustomersController.GetLastCustomerAsync(false);

                break;

            case CustomersMenuOptions.Sales_Customers_UpdateCityAddress:
                if (sessionContext.PartyKey == null)
                {
                    sessionContext.PartyKey = await CustomersController.GetLastCustomerAsync(true);
                }

                if (sessionContext.PartyKey != null)
                {
                    await CustomersController.UpdateCustomerCityAddressAsync(sessionContext.PartyKey);
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create a customer first.");
                }

                break;

            case CustomersMenuOptions.Sales_Customers_UpdatePaymentTerm:
                if (sessionContext.PartyKey == null)
                {
                    sessionContext.PartyKey = await CustomersController.GetLastCustomerAsync(true);
                }

                if (sessionContext.PartyKey != null)
                {
                    await CustomersController.UpdateCustomerPaymentTermAsync(sessionContext.PartyKey);
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create a customer first.");
                }

                break;

            case CustomersMenuOptions.Sales_Customers_DeleteCustomer:
                if (sessionContext.PartyKey == null)
                {
                    sessionContext.PartyKey = await CustomersController.GetLastCustomerAsync(true);
                }

                if (sessionContext.PartyKey != null)
                {
                    await CustomersController.DeleteCustomerExtensionAsync(sessionContext.PartyKey);

                    sessionContext.DeletedCustomerKey = sessionContext.PartyKey;
                    sessionContext.PartyKey           = null;
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create a customer first.");
                }

                break;

            case CustomersMenuOptions.Sales_Customers_AddCustomer:
                if (sessionContext.DeletedCustomerKey != null)
                {
                    await CustomersController.CreateCustomerExtensionAsync(sessionContext.DeletedCustomerKey);

                    sessionContext.PartyKey           = sessionContext.DeletedCustomerKey;
                    sessionContext.DeletedCustomerKey = null;
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must delete a customer first.");
                }

                break;

            case CustomersMenuOptions.Sales_Customers_DeleteAllParties:
                await CustomersController.DeleteAllPartiesCreatedOnSample();

                break;
            }

            return(0);
        }
        private static async Task <SalesItemPriceListLineResource> GetItemFirstPriceLineAsync(string itemKey)
        {
            SalesItemPriceListLineResource foundPriceListLine = null;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "salescore/salesItems/odata";

                    // build the odata expression

                    string odataExpression = string.Format("?$top=1&$filter=ItemKey eq '{0}' and IsActive eq true and IsSystem eq false and IsDeleted eq false", itemKey);

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Send

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                            throw new Exception("Unable to get the first sales price list.");
                        }

                        // Succeeded

                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ODataResponse <SalesItemResource> >(json);
                        IList <SalesItemResource> salesItems = objectResult.Items;

                        foundPriceListLine = salesItems[0].PriceListLines.FirstOrDefault();
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error getting the first sales price list.");
            }

            return(foundPriceListLine);
        }
        /// <summary>
        /// Creates the sales item extension to an existing asynchronous.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        public static async Task CreateSalesItemExtensionAsync(string itemKey)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(itemKey))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("CreateSalesItemExtensionAsync: 'itemKey' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            string itemTaxSchemaKey = await GetDefaultItemTaxSchemaAsync();

            try
            {
                // Build the customer that will be created

                SalesItemResource newSalesItem = new SalesItemResource()
                {
                    IncomeAccount = "71111",
                    BaseEntityKey = itemKey,
                    Unit          = "KM",
                    ItemTaxSchema = itemTaxSchemaKey
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "salesCore/salesItems/extension";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postSalesItemMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    // Build the json data

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string salesItemContent = JsonConvert.SerializeObject(newSalesItem, settings);
                    postSalesItemMessage.Content = new StringContent(salesItemContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", salesItemContent);

                    // Send

                    using (HttpResponseMessage responseContent = await client.SendAsync(postSalesItemMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to create the sales item extention for Item '{0}'.", itemKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("SalesItem extension created for Item '{0}': (Id = {1})", itemKey, result));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error creating the sales item extension for Item '{0}'.", itemKey));
            }
        }
        /// <summary>
        /// Creates a new Item and Sales Item Extension (AllInOne) asynchronous.
        /// </summary>
        /// <returns>The key of the created item.</returns>
        public static async Task <string> CreateSalesItemAndItemAsync()
        {
            // Generate a ItemKey (only for sample purpose)

            string itemKey = $"NewS{DateTime.Now.ToString("yyyyMMddHHmmss")}";

            string itemTaxSchemaKey = await GetDefaultItemTaxSchemaAsync();

            try
            {
                // Build the customer that will be created

                BaseSalesItemResource customer = new BaseSalesItemResource()
                {
                    ItemKey       = itemKey,
                    Description   = itemKey,
                    BaseUnit      = "MT",
                    Unit          = "KM",
                    ItemTaxSchema = itemTaxSchemaKey,
                    IncomeAccount = "71111",
                    ItemType      = "Item"
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "salesCore/salesItems";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postCustomerMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    // Build the json data

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string salesItemContent = JsonConvert.SerializeObject(customer, settings);
                    postCustomerMessage.Content = new StringContent(salesItemContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", salesItemContent);

                    // Send

                    using (HttpResponseMessage responseContent = await client.SendAsync(postCustomerMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            itemKey = string.Empty;

                            throw new Exception(string.Format("Unable to create the SalesItem '{0}'.", itemKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("SalesItem '{0}' created: (Id = {1})", itemKey, result));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error creating the SalesItem '{0}'.", itemKey));
            }

            return(itemKey);
        }
        /// <summary>
        /// Inserts the price on sales item asynchronous.
        /// </summary>
        public static async Task InsertPriceOnSalesItemAsync(string itemKey)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(itemKey))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("InsertPriceOnSalesItemAsync: 'itemKey' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            string priceListKey = await GetFirstPriceListAsync();

            try
            {
                SalesItemPriceListLineResource newPriceListLine = new SalesItemPriceListLineResource
                {
                    PriceList = priceListKey,
                    Unit      = "KM",
                    Price     = new MoneyResource()
                    {
                        Value    = 123,
                        Currency = "€"
                    }
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = string.Format("salesCore/salesItems/{0}/priceListLines", itemKey);
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postSalesItemMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string salesItemContent = JsonConvert.SerializeObject(newPriceListLine, settings);

                    postSalesItemMessage.Content = new StringContent(salesItemContent, Encoding.UTF8, "application/json");

                    // Send

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", salesItemContent);

                    using (HttpResponseMessage responseContent = await client.SendAsync(postSalesItemMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to create a new price line on salesItem '{0}", itemKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("SalesItem Line (ID {0}) created on SalesItem '{1}'", result, itemKey));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error creating the new price list line on salesItem '{0}'", itemKey));
            }
        }
        /// <summary>
        /// Creates a SalesItem Extension asynchronous.
        /// </summary>
        /// <returns>The key of the created item.</returns>
        public static async Task <string> CreateItemAndSalesItemExtensionAsync()
        {
            // For Sample purpose We will Create an Item And than create the SalesItem Extension.
            // Usefull when you allread have the Item and only want to add the salesitem extension.
            // (The same occurrs for all the other extensions).

            string itemKey = $"NewI{DateTime.Now.ToString("yyyyMMddHHmmss")}";

            string itemTaxSchemaKey = await GetDefaultItemTaxSchemaAsync();

            try
            {
                // Build the item that will be created

                ItemResource newItem = new ItemResource()
                {
                    ItemKey     = itemKey,
                    ItemType    = "Item",
                    BaseUnit    = "MT",
                    Description = itemKey
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "businessCore/items";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postItemMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    // Build the json data

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string itemContent = JsonConvert.SerializeObject(newItem, settings);
                    postItemMessage.Content = new StringContent(itemContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", itemContent);

                    // Send

                    using (HttpResponseMessage itemResponse = await client.SendAsync(postItemMessage))
                    {
                        // Get the response

                        if (!itemResponse.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", itemResponse.ToString()));
                            string errorResult = await((StreamContent)itemResponse.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));
                            itemKey = string.Empty;

                            throw new Exception(string.Format("Unable to create the Item '{0}'", itemKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)itemResponse.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Item '{0}' created: (Id = {1})", itemKey, result));

                        // Build the salesItems that will be created

                        SalesItemResource newSalesItems = new SalesItemResource()
                        {
                            IncomeAccount = "71111",
                            BaseEntityKey = itemKey,
                            Unit          = "KM",
                            ItemTaxSchema = itemTaxSchemaKey
                        };

                        // Build the request

                        request          = "salesCore/salesItems/extension";
                        resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                        client.SetDefaultRequestHeaders(CultureKey);

                        // It's a POST

                        HttpRequestMessage postSalesItemsMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                        // Build the json data

                        string salesItemsContent = JsonConvert.SerializeObject(newSalesItems, settings);
                        postSalesItemsMessage.Content = new StringContent(salesItemsContent, Encoding.UTF8, "application/json");

                        // Log Request

                        Console.WriteLine("Request - POST");
                        Console.WriteLine("{0}", resourceLocation);
                        Console.WriteLine("Request - BODY ");
                        Console.WriteLine("{0}", salesItemsContent);

                        // Send

                        using (HttpResponseMessage salesItemsResponse = await client.SendAsync(postSalesItemsMessage))
                        {
                            // Get the response

                            if (!salesItemsResponse.IsSuccessStatusCode)
                            {
                                ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", salesItemsResponse.ToString()));
                                string resultError = await((StreamContent)salesItemsResponse.Content).ReadAsStringAsync();
                                ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", resultError));
                                itemKey = string.Empty;

                                throw new Exception(string.Format("Unable to create the SalesItems '{0}'.", itemKey));
                            }

                            // Succeeded

                            result = await((StreamContent)salesItemsResponse.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteSuccessLine(string.Format("SalesItems '{0}' created: (Id = {1})", itemKey, result));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);

                itemKey = string.Empty;
                throw new Exception(string.Format("Error creating the SalesItems"));
            }

            return(itemKey);
        }
        public static async Task <string> GetOrderTypeWithoutFiscalDocumentTypeAsync()
        {
            string orderTypeKey = string.Empty;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "salescore/ordertypes/odata";

                    // build the odata expression

                    string odataExpression = string.Format("?$select=TypeKey&$top=1&$filter=Company eq '{0}' and OrderNature eq 'StandardOrder' and IsInternal eq false  and IsActive eq true and IsDeleted eq false and FiscalDocumentTypeId eq null and DeliveryOnInvoice eq false&$orderby=CreatedOn desc", CompanyKey);

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Send

                    Console.WriteLine("Request - GET");
                    Console.WriteLine("{0}", resourceLocation);

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to get the sales order type on company '{0}'.", CompanyKey));
                        }

                        // Succeeded

                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ODataResponse <SalesOrderTypeResource> >(json);
                        IList <SalesOrderTypeResource> salesOrderTypes = objectResult.Items;
                        if (salesOrderTypes.Count > 0)
                        {
                            orderTypeKey = salesOrderTypes[0].TypeKey;
                            ConsoleHelper.WriteSuccessLine(string.Format("Sales Order type '{0}' was obtained with success on company {1}.", orderTypeKey, CompanyKey));
                            Console.WriteLine("");
                        }
                        else
                        {
                            orderTypeKey = await CreateOrderTypeWithoutFiscalDocumentTypeAsync();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error getting sales order type.");
            }

            return(orderTypeKey);
        }
Пример #9
0
        /// <summary>
        /// Updates the customer payment term asynchronous.
        /// </summary>
        /// <param name="customer">The customer.</param>
        public static async Task UpdateCustomerPaymentTermAsync(string customer)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(customer))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("UpdateCustomerPaymentTermAsync: 'customer' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            // For sample purpose we will set then payment term to 90 days,

            string newPaymentTerm = "03";

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request
                    string request          = string.Format("salesCore/customerParties/{0}/paymentTerm", customer);
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request, customer);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a PUT

                    HttpRequestMessage putCustomerMessage = new HttpRequestMessage(HttpMethod.Put, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string customerContent = JsonConvert.SerializeObject(newPaymentTerm, settings);

                    putCustomerMessage.Content = new StringContent(customerContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - PUT");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", customerContent);

                    // Send

                    using (HttpResponseMessage responseContent = await client.SendAsync(putCustomerMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to update payment term on Customer '{0}'", customer));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Updated payment term on Customer '{0}')", customer));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error updating payment term on Customer '{0}", customer));
            }
        }
Пример #10
0
        /// <summary>
        /// Updates the customer city address asynchronous.
        /// </summary>
        /// <param name="customer">The customer.</param>
        public static async Task UpdateCustomerCityAddressAsync(string customer)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(customer))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("UpdateCustomerCityAddress: 'customer' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            // City is not really an attribute of the customer.
            // Its an attribute of the maid entity Party.
            // So we need to set it on Party
            // Generate city name for sample purpose only.

            string newCityName = $"NewCity {DateTime.Now.ToString("yyyyMMddHHmmss")}";

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request
                    string request          = string.Format("businessCore/parties/{0}/cityName", customer);
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request, customer);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a PUT

                    HttpRequestMessage putCustomerMessage = new HttpRequestMessage(HttpMethod.Put, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string customerContent = JsonConvert.SerializeObject(newCityName, settings);

                    putCustomerMessage.Content = new StringContent(customerContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - PUT");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", customerContent);

                    // Send

                    using (HttpResponseMessage responseContent = await client.SendAsync(putCustomerMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to update city name on Customer '{0}'.", customer));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Updated city name on Customer '{0}')", customer));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error updating city name on Customer '{0}'", customer));
            }
        }
Пример #11
0
        /// <summary>
        /// Gets the last created customer asynchronous.
        /// </summary>
        /// <param name="silentMode">if set to <c>true</c> console messages will not be displayed.</param>
        /// <returns>The key of the last created customer.</returns>
        public static async Task <string> GetLastCustomerAsync(bool silentMode = false)
        {
            string foundPartyKey = null;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "salescore/customerParties/odata";

                    // build the odata expression

                    string odataExpression = "?$select=PartyKey, PaymentTerm&$top=1&$filter= IsActive eq true and IsSystem eq false and IsDeleted eq false&$orderby=CreatedOn desc";

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    if (!silentMode)
                    {
                        // Log Request

                        Console.WriteLine("Request - GET");
                        Console.WriteLine("{0}", resourceLocation);
                    }

                    // Send

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (responseContent.IsSuccessStatusCode)
                        {
                            string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                            var objectResult = JsonConvert.DeserializeObject <ODataResponse <BaseCustomerResource> >(json);
                            IList <BaseCustomerResource> customers = objectResult.Items;

                            foundPartyKey = customers[0].PartyKey;

                            if (!silentMode)
                            {
                                ConsoleHelper.WriteSuccessLine(string.Format("The last customer was found with success. ('{0}' - PaymentTerm:{1})", foundPartyKey, customers[0].PaymentTerm));
                                Console.WriteLine("");
                            }
                        }
                        else
                        {
                            if (!silentMode)
                            {
                                ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                                string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                                ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                                throw new Exception("Unable to get the last customer.");
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error getting the last customer.");
            }

            return(foundPartyKey);
        }
Пример #12
0
        /// <summary>
        /// Creates a Customer Extension asynchronous.
        /// </summary>
        /// <returns>The key of the created party.</returns>
        public static async Task <string> CreatePartyAndCustomerExtensionAsync()
        {
            // For Sample purpose We will Create a Party And than create the Customer Extension.
            // Usefull when you allread have the Party and only want to add the customer extension.
            // (The same occurrs for all the other extensions).

            string partyKey = $"NewP{DateTime.Now.ToString("yyyyMMddHHmmss")}";

            string partyTaxSchemaKey = await GetDefaultPartyTaxSchemaAsync();

            try
            {
                // Build the party that will be created

                PartyResource newParty = new PartyResource()
                {
                    PartyKey       = partyKey,
                    SearchTerm     = partyKey,
                    Name           = "New Party",
                    CityName       = "Porto",
                    PostalZone     = "4000-047",
                    Telephone      = "223123345",
                    StreetName     = "Rua Santa Catarina",
                    BuildingNumber = "150 RC"
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "businessCore/parties";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postPartyMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    // Build the json data

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string partyContent = JsonConvert.SerializeObject(newParty, settings);
                    postPartyMessage.Content = new StringContent(partyContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", partyContent);

                    // Send

                    using (HttpResponseMessage partyResponse = await client.SendAsync(postPartyMessage))
                    {
                        // Get the response

                        if (!partyResponse.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", partyResponse.ToString()));
                            string errorResult = await((StreamContent)partyResponse.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));
                            partyKey = string.Empty;

                            throw new Exception(string.Format("Unable to create the Party '{0}'", partyKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)partyResponse.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Party '{0}' created : (Id = {1})", partyKey, result));

                        // Build the customer that will be created

                        CustomerResource newCustomer = new CustomerResource()
                        {
                            CustomerGroup   = "01",
                            PaymentMethod   = "NUM",
                            PaymentTerm     = "00",
                            PartyTaxSchema  = partyTaxSchemaKey,
                            Locked          = false,
                            OneTimeCustomer = false,
                            EndCustomer     = false,
                            BaseEntityKey   = partyKey
                        };

                        // Build the request

                        request          = "salesCore/customerParties/extension";
                        resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                        client.SetDefaultRequestHeaders(CultureKey);

                        // It's a POST

                        HttpRequestMessage postCustomerMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                        // Build the json data

                        string customerContent = JsonConvert.SerializeObject(newCustomer, settings);
                        postCustomerMessage.Content = new StringContent(customerContent, Encoding.UTF8, "application/json");

                        // Log Request

                        Console.WriteLine("Request - POST");
                        Console.WriteLine("{0}", resourceLocation);
                        Console.WriteLine("Request - BODY ");
                        Console.WriteLine("{0}", customerContent);

                        // Send

                        using (HttpResponseMessage customerResponse = await client.SendAsync(postCustomerMessage))
                        {
                            // Get the response

                            if (!customerResponse.IsSuccessStatusCode)
                            {
                                ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", customerResponse.ToString()));
                                string resultError = await((StreamContent)customerResponse.Content).ReadAsStringAsync();
                                ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", resultError));
                                partyKey = string.Empty;

                                throw new Exception(string.Format("Unable to create the Customer '{0}'.", partyKey));
                            }

                            // Succeeded

                            result = await((StreamContent)customerResponse.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteSuccessLine(string.Format("Customer '{0}' created: (Id = {1})", partyKey, result));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);

                throw new Exception(string.Format("Error creating the Customer '{0}'", partyKey));
            }

            return(partyKey);
        }
Пример #13
0
        private static async Task <int> HandleSalesInvoicesOperationAsync(SessionContext sessionContext, AuthenticationProvider authenticationProvider, SalesInvoicesMenuOptions option)
        {
            Console.WriteLine("");
            Console.WriteLine("selected option " + string.Format("{0:D} - {1}", option, option.ToName()));
            Console.WriteLine("");

            // Get the authorization access token

            SalesInvoicesController.AccountKey             = sessionContext.AccountKey;
            SalesInvoicesController.SubscriptionKey        = sessionContext.SubscriptionKey;
            SalesInvoicesController.CompanyKey             = sessionContext.CompanyKey;
            SalesInvoicesController.CultureKey             = sessionContext.CultureKey;
            SalesInvoicesController.AuthenticationProvider = authenticationProvider;

            switch (option)
            {
            case SalesInvoicesMenuOptions.Sales_Invoices_GetAll:
                await SalesInvoicesController.GetInvoicesAsync();

                break;

            case SalesInvoicesMenuOptions.Sales_Invoices_GetOdata:
                await SalesInvoicesController.GetTop5InvoicesAsync();

                break;

            case SalesInvoicesMenuOptions.Sales_Invoices_GetLastInvoice:
                sessionContext.InvoiceResource = await SalesInvoicesController.GetLastInvoiceAsync(false);

                break;

            case SalesInvoicesMenuOptions.Sales_Invoices_Create:
                await SalesInvoicesController.CreateInvoiceAsync();

                /// Just to update
                sessionContext.InvoiceResource = await SalesInvoicesController.GetLastInvoiceAsync(true);

                break;


            case SalesInvoicesMenuOptions.Sales_Invoices_Del:
                if (sessionContext.InvoiceResource == null)
                {
                    sessionContext.InvoiceResource = await SalesInvoicesController.GetLastInvoiceAsync(true);
                }

                if (sessionContext.InvoiceResource != null)
                {
                    await SalesInvoicesController.DeleteInvoiceAsync(sessionContext.InvoiceResource);

                    sessionContext.InvoiceResource = null;
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create an invoice first.");
                }

                break;
            }

            return(0);
        }
Пример #14
0
        private static async Task <int> HandleSalesItemsOperationAsync(SessionContext sessionContext, AuthenticationProvider authenticationProvider, SalesItemsMenuOptions option)
        {
            Console.WriteLine("");
            Console.WriteLine("selected option " + string.Format("{0:D} - {1}", option, option.ToName()));
            Console.WriteLine("");

            // Get the authorization access token

            SalesItemsController.AccountKey             = sessionContext.AccountKey;
            SalesItemsController.SubscriptionKey        = sessionContext.SubscriptionKey;
            SalesItemsController.CultureKey             = sessionContext.CultureKey;
            SalesItemsController.AuthenticationProvider = authenticationProvider;

            switch (option)
            {
            case SalesItemsMenuOptions.Sales_SalesItems_SalesItemAllInOne:
                sessionContext.ItemKey = await SalesItemsController.CreateSalesItemAndItemAsync();

                break;

            case SalesItemsMenuOptions.Sales_SalesItems_ItemAndSalesItem:
                sessionContext.ItemKey = await SalesItemsController.CreateItemAndSalesItemExtensionAsync();

                break;

            case SalesItemsMenuOptions.Sales_SalesItems_GetLastSalesItem:
                sessionContext.ItemKey = await SalesItemsController.GetLastCreatedSalesItemAsync(false);

                break;

            case SalesItemsMenuOptions.Sales_SalesItems_SetPrices:
                if (sessionContext.ItemKey == null)
                {
                    sessionContext.ItemKey = await SalesItemsController.GetLastCreatedSalesItemAsync(true);
                }

                if (sessionContext.ItemKey != null)
                {
                    await SalesItemsController.InsertPriceOnSalesItemAsync(sessionContext.ItemKey);
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create a salesItem first.");
                }

                break;

            case SalesItemsMenuOptions.Sales_SalesItems_UpdatePrice:
                if (sessionContext.ItemKey == null)
                {
                    sessionContext.ItemKey = await SalesItemsController.GetLastCreatedSalesItemAsync(true);
                }

                if (sessionContext.ItemKey != null)
                {
                    await SalesItemsController.SetNewPriceAsync(sessionContext.ItemKey);
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create a salesItem first.");
                }
                break;

            case SalesItemsMenuOptions.Sales_SalesItems_DeleteSalesItem:
                if (sessionContext.ItemKey == null)
                {
                    sessionContext.ItemKey = await SalesItemsController.GetLastCreatedSalesItemAsync(true);
                }

                if (sessionContext.ItemKey != null)
                {
                    await SalesItemsController.DeleteSalesItemExtensionAsync(sessionContext.ItemKey);

                    sessionContext.DeletedItemKey = sessionContext.ItemKey;
                    sessionContext.ItemKey        = null;
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must create a SalesItem first.");
                }

                break;

            case SalesItemsMenuOptions.Sales_SalesItems_AddSalesItem:
                if (sessionContext.DeletedItemKey != null)
                {
                    await SalesItemsController.CreateSalesItemExtensionAsync(sessionContext.DeletedItemKey);

                    sessionContext.ItemKey        = sessionContext.DeletedItemKey;
                    sessionContext.DeletedItemKey = null;
                }
                else
                {
                    ConsoleHelper.WriteErrorLine("You must delete a sales item first.");
                }

                break;

            case SalesItemsMenuOptions.Sales_SalesItems_DeleteAllItems:
                await SalesItemsController.DeleteAllItemsCreatedOnSample();

                break;
            }

            return(0);
        }
        /// <summary>
        /// Creates the order asynchronous.
        /// </summary>
        public static async Task CreateOrderAsync()
        {
            string orderTypeKey = await GetOrderTypeWithoutFiscalDocumentTypeAsync();

            try
            {
                // Build the order to be created

                SalesOrderResource newOrder = new SalesOrderResource()
                {
                    Company      = CompanyKey,
                    DocumentType = orderTypeKey,
                    DocumentDate = DateTime.UtcNow,
                    Serie        = DateTime.UtcNow.Year.ToString(),
                    Customer     = "SOFRIO",
                    Currency     = "EUR",
                };

                newOrder.Lines = new List <SalesOrderLineResource>
                {
                    new SalesOrderLineResource
                    {
                        Item     = "ARECA",
                        Quantity = 1,
                        ItemType = 1,
                        Price    = new MoneyResource
                        {
                            Value    = 50,
                            Currency = "€"
                        }
                    }
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "sales/orders";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postOrderMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string orderContent = JsonConvert.SerializeObject(newOrder, settings);

                    postOrderMessage.Content = new StringContent(orderContent, Encoding.UTF8, "application/json");

                    // Send
                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", orderContent);

                    using (HttpResponseMessage responseContent = await client.SendAsync(postOrderMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception("Unable to create the sales order.");
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Sales Order created: (Id = {0})", result));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error creating the sales order.");
            }
        }
Пример #16
0
        /// <summary>
        /// Creates a new Party and Customer Extension (AllInOne) asynchronous.
        /// </summary>
        /// <returns>The key of the created party.</returns>
        public static async Task <string> CreateCustomerAndPartyAsync()
        {
            // Generate a PartyKey (only for sample purpose)

            string partyKey = $"NewC{DateTime.Now.ToString("yyyyMMddHHmmss")}";

            string partyTaxSchemaKey = await GetDefaultPartyTaxSchemaAsync();

            try
            {
                // Build the customer that will be created

                BaseCustomerResource newCustomer = new BaseCustomerResource()
                {
                    CustomerGroup   = "01",
                    PaymentMethod   = "NUM",
                    PaymentTerm     = "00",
                    PartyTaxSchema  = partyTaxSchemaKey,
                    Locked          = false,
                    OneTimeCustomer = false,
                    EndCustomer     = false,
                    PartyKey        = partyKey,
                    SearchTerm      = partyKey,
                    Name            = partyKey,
                    StreetName      = "Avenida de Ceuta",
                    BuildingNumber  = "1000",
                    CityName        = "Lisboa",
                    PostalZone      = "1010-023",
                    Telephone       = "219877890"
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "salesCore/customerParties";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postCustomerMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    // Build the json data

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string customerContent = JsonConvert.SerializeObject(newCustomer, settings);
                    postCustomerMessage.Content = new StringContent(customerContent, Encoding.UTF8, "application/json");

                    // Log Request

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", customerContent);

                    // Send

                    using (HttpResponseMessage customerResponse = await client.SendAsync(postCustomerMessage))
                    {
                        // Get the response

                        if (!customerResponse.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", customerResponse.ToString()));
                            string errorResult = await((StreamContent)customerResponse.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));
                            partyKey = string.Empty;

                            throw new Exception(string.Format("Unable to create the Customer '{0}'.", partyKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)customerResponse.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Customer '{0}' created: (Id = {1})", partyKey, result));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                partyKey = string.Empty;
                throw new Exception(string.Format("Error creating the Customer '{0}'.", partyKey));
            }

            return(partyKey);
        }
        /// <summary>
        /// Deletes the order asynchronous.
        /// </summary>
        /// <param name="order">The order.</param>
        public static async Task DeleteOrderAsync(SalesOrderResource order)
        {
            // Validate Parameters

            if (order == null)
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("DeleteOrderAsync: 'order' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "sales/orders";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/{4}/{5}/{6}/{7}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request, order.Company, order.DocumentType, order.Serie, order.SeriesNumber);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a DELETE

                    HttpRequestMessage deleteOrderLineMessage = new HttpRequestMessage(HttpMethod.Delete, resourceLocation);

                    // Send

                    Console.WriteLine("Request - DEL");
                    Console.WriteLine("{0}", resourceLocation);

                    using (HttpResponseMessage responseContent = await client.SendAsync(deleteOrderLineMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                            throw new Exception("Unable to delete the last sales order.");
                        }

                        // Succeeded

                        ConsoleHelper.WriteSuccessLine(string.Format("Sales Order was deleted: Company {0} - {1}.{2}.{3})", order.Company, order.DocumentType, order.Serie, order.SeriesNumber));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error deleting the last sales order.");
            }
        }
Пример #18
0
        /// <summary>
        /// Gets the first 20 invoices asynchronous.
        /// </summary>
        public static async Task GetInvoicesAsync()
        {
            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "billing/invoices?page=1&pageSize=20";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Log Request

                    Console.WriteLine("Request - GET");
                    Console.WriteLine("{0}", resourceLocation);

                    // Send

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                            throw new Exception("Unable to list the invoices.");
                        }

                        // Succeeded

                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ListResponse <SalesInvoiceResource> >(json);
                        IList <SalesInvoiceResource> invoices = objectResult.Data;

                        ConsoleHelper.WriteSuccessLine("The invoices were obtained with success.");
                        Console.WriteLine("");
                        foreach (SalesInvoiceResource invoice in invoices)
                        {
                            Console.WriteLine("Invoice: Company {0} - {1}.{2}.{3} (id = {4})", invoice.Company, invoice.DocumentType, invoice.Serie, invoice.SeriesNumber, invoice.InvoiceId);
                        }

                        Console.WriteLine("");
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error creating the invoice.");
            }
        }
        public static async Task <string> CreateOrderTypeWithoutFiscalDocumentTypeAsync()
        {
            // the order type Key to be created.

            string orderTypeKey = "ECLTST";

            try
            {
                // Build the order type to be created

                SalesOrderTypeResource newOrderType = new SalesOrderTypeResource()
                {
                    Company     = CompanyKey,
                    TypeKey     = orderTypeKey,
                    OrderNature = "StandardOrder"
                };

                newOrderType.Lines = new List <SalesOrderTypeLineSerieResource>
                {
                    new SalesOrderTypeLineSerieResource
                    {
                        IsDefault = true,
                        Serie     = DateTime.UtcNow.Year.ToString(),
                    }
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "salesCore/orderTypes";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postOrderTypeMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string orderTypeContent = JsonConvert.SerializeObject(newOrderType, settings);

                    postOrderTypeMessage.Content = new StringContent(orderTypeContent, Encoding.UTF8, "application/json");

                    // Send
                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", orderTypeContent);

                    using (HttpResponseMessage responseContent = await client.SendAsync(postOrderTypeMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to create the sales order type '{0} on company '{1}'.", orderTypeKey, CompanyKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Sales Order type created: (Id = {0})", result));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error creating the sales order type '{0} on company '{1}'.", orderTypeKey, CompanyKey));
            }

            return(orderTypeKey);
        }
Пример #20
0
        /// <summary>
        /// Gets the company key asynchronous.
        /// </summary>
        /// <returns>The company key (if any).</returns>
        public static async Task <string> GetCompanyKeyAsync()
        {
            string companyKey = string.Empty;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    // SAMPLE: Get the companyKey for the first active existing company
                    Console.WriteLine("");
                    Console.WriteLine("As documents are company dependent entities, for this sample, we will need to");
                    Console.WriteLine("get the company key where we will be acting upon");

                    string request          = "corepatterns/companies/odata?$select=CompanyKey&$filter=IsActive eq true and IsSystem eq false and IsDeleted eq false &$top=1&$orderby=CreatedOn";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a GET

                    HttpRequestMessage getOrderMessage = new HttpRequestMessage(HttpMethod.Get, resourceLocation);

                    // Log Request

                    Console.WriteLine("Request - GET");
                    Console.WriteLine("{0}", resourceLocation);

                    // Send

                    using (HttpResponseMessage responseContent = await client.SendAsync(getOrderMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(String.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(String.Format("Content: {0}", result));

                            throw new Exception("Unable to get the company Key.");
                        }

                        // Succeeded
                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ODataResponse <CompanyResource> >(json);
                        IList <CompanyResource> companies = objectResult.Items;

                        companyKey = companies[0].CompanyKey;

                        ConsoleHelper.WriteSuccessLine(String.Format("Company Key: {0}", companyKey));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error geting the current company.");
            }

            return(companyKey);
        }
        /// <summary>
        /// Gets the last created salesItem asynchronous.
        /// </summary>
        /// <param name="silentMode">if set to <c>true</c> console messages will not be displayed.</param>
        /// <returns>The key of the last created salesItem.</returns>
        public static async Task <string> GetLastCreatedSalesItemAsync(bool silentMode = false)
        {
            string foundItemKey = null;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "salescore/salesItems/odata";

                    // build the odata expression

                    string odataExpression = "?$top=1&$filter= IsActive eq true and IsSystem eq false and IsDeleted eq false&$orderby=CreatedOn desc";

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    if (!silentMode)
                    {
                        // Log Request

                        Console.WriteLine("Request - GET");
                        Console.WriteLine("{0}", resourceLocation);
                    }

                    // Send

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (responseContent.IsSuccessStatusCode)
                        {
                            string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                            var objectResult = JsonConvert.DeserializeObject <ODataResponse <BaseSalesItemResource> >(json);
                            IList <BaseSalesItemResource> salesItems = objectResult.Items;

                            BaseSalesItemResource foundSalesItem = salesItems[0];
                            foundItemKey = foundSalesItem.ItemKey;

                            if (!silentMode)
                            {
                                ConsoleHelper.WriteSuccessLine(string.Format("The last salesItem was found with success. ('{0}')", foundItemKey));
                                Console.WriteLine("");
                                if (foundSalesItem.PriceListLines.Count > 0)
                                {
                                    Console.WriteLine("Prices List");
                                    foreach (SalesItemPriceListLineResource line in foundSalesItem.PriceListLines)
                                    {
                                        Console.WriteLine(string.Format("PriceList '{0}', Unit '{1}', Price {2:N}{3}", line.PriceList, line.Unit, line.Price.Value, line.Price.Currency));
                                    }
                                    Console.WriteLine("");
                                }
                            }
                        }
                        else
                        {
                            if (!silentMode)
                            {
                                ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                                string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                                ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                                throw new Exception("Unable to get the last salesItem.");
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error getting the last salesItem.");
            }

            return(foundItemKey);
        }
        /// <summary>
        /// Gets the top5 orders asynchronous.
        /// </summary>
        public static async Task GetTop5OrdersAsync()
        {
            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "sales/orders/odata";

                    // build the odata expression

                    string odataExpression = string.Format("?$inlinecount=allpages&$select=Company, DocumentType, Serie, SeriesNumber, Id&$top=5&$filter= Company eq '{0}' and BuyerCustomerParty eq '{1}'&$orderby=CreatedOn desc", CompanyKey, "SOFRIO");

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Send

                    Console.WriteLine("Request - GET");
                    Console.WriteLine("{0}", resourceLocation);

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception("Unable to list the sales orders.");
                        }

                        // Succeeded

                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ODataResponse <SalesOrderResource> >(json);
                        IList <SalesOrderResource> orders = objectResult.Items;

                        ConsoleHelper.WriteSuccessLine(string.Format("The top 5 sales orders for customer '{0}' on company '{1}' were obtained with success.", "SOFRIO", CompanyKey));
                        Console.WriteLine("");
                        foreach (SalesOrderResource order in orders)
                        {
                            Console.WriteLine("Sales Order: Company {0} - {1}.{2}.{3} (id = {4})", order.Company, order.DocumentType, order.Serie, order.SeriesNumber, order.OrderId);
                        }

                        Console.WriteLine("Sales Orders Count: {0}", orders.Count);
                        Console.WriteLine("");
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error creating the sales order.");
            }
        }
        /// <summary>
        /// Sets the new price asynchronous.
        /// </summary>
        public static async Task SetNewPriceAsync(string itemKey)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(itemKey))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("SetNewPriceAsync: 'itemKey' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            SalesItemPriceListLineResource lineResource = await GetItemFirstPriceLineAsync(itemKey);

            if (lineResource == null)
            {
                // Simply inset new line
                await InsertPriceOnSalesItemAsync(itemKey);

                return;
            }

            try
            {
                double newPrice = lineResource.Price.Value + 10D;

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request
                    string request          = string.Format("salesCore/salesItems/{0}/priceListLines/{1}/priceAmount", itemKey, lineResource.Id);
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a PUT

                    HttpRequestMessage putSalesItemMessage = new HttpRequestMessage(HttpMethod.Put, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string salesItemContent = JsonConvert.SerializeObject(newPrice, settings);

                    putSalesItemMessage.Content = new StringContent(salesItemContent, Encoding.UTF8, "application/json");

                    // Send

                    Console.WriteLine("Request - PUT");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", salesItemContent);

                    using (HttpResponseMessage responseContent = await client.SendAsync(putSalesItemMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to update the price in the first price list line of the SalesItem '{0}'", itemKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Update first price list line price on SalesItem: {0}", itemKey));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error updating the price in the first price list line of the SalesItem '{0}'", itemKey));
            }
        }
        /// <summary>
        /// Gets the last order asynchronous.
        /// </summary>
        /// <param name="silentMode">if set to <c>true</c> console messages will not be displayed.</param>
        /// <returns>The SalesOrder Resource.</returns>
        public static async Task <SalesOrderResource> GetLastOrderAsync(bool silentMode = false)
        {
            SalesOrderResource foundOrder = null;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "sales/orders/odata";

                    // build the odata expression

                    string odataExpression = string.Format("?$top=1&$filter= Company eq '{0}' and BuyerCustomerParty eq '{1}'&$orderby=CreatedOn desc", CompanyKey, "SOFRIO");

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Send

                    if (!silentMode)
                    {
                        Console.WriteLine("Request - GET");
                        Console.WriteLine("{0}", resourceLocation);
                    }

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (responseContent.IsSuccessStatusCode)
                        {
                            string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                            var objectResult = JsonConvert.DeserializeObject <ODataResponse <SalesOrderResource> >(json);
                            foundOrder = objectResult.Items.FirstOrDefault();

                            if (!silentMode)
                            {
                                ConsoleHelper.WriteSuccessLine(string.Format("The last sales order of customer '{0}' on company '{1}' was found with success.", "SOFRIO", CompanyKey));
                                Console.WriteLine("");
                            }

                            if (foundOrder != null && !silentMode)
                            {
                                Console.WriteLine("Sales Order: Company {0} - {1}.{2}.{3} (id = {4})", foundOrder.Company, foundOrder.DocumentType, foundOrder.Serie, foundOrder.SeriesNumber, foundOrder.OrderId);
                                Console.WriteLine("");
                                foreach (SalesOrderLineResource line in foundOrder.Lines.OrderBy(l => l.Index))
                                {
                                    Console.WriteLine("Order Line: (Id = {0}) - '{1}' '{2}' QTD = {3}", line.Id, line.Item, line.Description, line.Quantity);
                                }

                                Console.WriteLine("");
                            }
                        }
                        else
                        {
                            if (!silentMode)
                            {
                                ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                                string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                                ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                                throw new Exception("Unable to get the last sales order.");
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error getting the last sales order.");
            }

            return(foundOrder);
        }
        /// <summary>
        /// Deletes the salesItem extension asynchronous.
        /// </summary>
        /// <param name="salesItem">The salesItem.</param>
        public static async Task DeleteSalesItemExtensionAsync(string itemKey)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(itemKey))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("DeleteSalesItemExtensionAsync: 'itemKey' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = string.Format("salesCore/salesItems/{0}", itemKey);
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a DELETE

                    HttpRequestMessage deleteSalesItemMessage = new HttpRequestMessage(HttpMethod.Delete, resourceLocation);

                    // Log Request

                    Console.WriteLine("Request - DEL");
                    Console.WriteLine("{0}", resourceLocation);

                    // Send

                    using (HttpResponseMessage responseContent = await client.SendAsync(deleteSalesItemMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                            throw new Exception(string.Format("Unable to delete the salesItem extension for Party '{0}", itemKey));
                        }

                        // Succeeded

                        ConsoleHelper.WriteSuccessLine(string.Format("SalesItem Extension for Party '{0}' was deleted", itemKey));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error deleting the salesItem extension for Party '{0}'", itemKey));
            }
        }
        /// <summary>
        /// Inserts the line on order asynchronous.
        /// </summary>
        /// <param name="order">The order.</param>
        public static async Task InsertLineOnOrderAsync(SalesOrderResource order)
        {
            // Validate Parameters

            if (order == null)
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("InsertLineOnOrderAsync: 'order' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            try
            {
                SalesOrderLineResource newOrderLine = new SalesOrderLineResource
                {
                    Item     = "BLROSAS",
                    Quantity = 10,
                    ItemType = 1,

                    Price = new MoneyResource()
                    {
                        Value    = 20,
                        Currency = "€"
                    }
                };

                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request          = "sales/orders";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/{4}/{5}/{6}/{7}/documentLines", Constants.baseAppUrl, AccountKey, SubscriptionKey, request, order.Company, order.DocumentType, order.Serie, order.SeriesNumber);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a POST

                    HttpRequestMessage postOrderMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string orderContent = JsonConvert.SerializeObject(newOrderLine, settings);

                    postOrderMessage.Content = new StringContent(orderContent, Encoding.UTF8, "application/json");

                    // Send

                    Console.WriteLine("Request - POST");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", orderContent);

                    using (HttpResponseMessage responseContent = await client.SendAsync(postOrderMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception("Unable to create a new line on sales order.");
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Order Line (ID {0}) created on Sales Order: Company {1} - {2}.{3}.{4})", result, order.Company, order.DocumentType, order.Serie, order.SeriesNumber));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error creating the new line on sales order.");
            }
        }
        private static async Task <string> GetDefaultItemTaxSchemaAsync()
        {
            string foundItemTaxSchema = null;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "taxesCore/itemTaxSchemas/odata";

                    // build the odata expression

                    string odataExpression = "?$select=TaxCodeItemGroupKey&$top=1&$filter=(TaxCodeItemGroupKey eq 'IVA-TN' or TaxCodeItemGroupKey eq 'NORMAL') and IsActive eq true and IsDeleted eq false";

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Send

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                            throw new Exception("Unable to get the default ItemTaxSchema.");
                        }

                        // Succeeded

                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ODataResponse <ItemTaxSchemaResource> >(json);
                        IList <ItemTaxSchemaResource> itemTaxSchemas = objectResult.Items;

                        foundItemTaxSchema = itemTaxSchemas[0].ItemTaxSchema;
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error getting the default ItemTaxSchema.");
            }

            return(foundItemTaxSchema);
        }
        /// <summary>
        /// Sets the quantity on order's last line asynchronous.
        /// </summary>
        /// <param name="order">The order.</param>
        public static async Task SetQuantityOnOrderLastLineAsync(SalesOrderResource order)
        {
            // Validate Parameters

            if (order == null)
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("SetQuantityOnOrderLastLineAsync: 'order' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            var line = order.Lines
                       .Select(l => new {
                l.Id,
                l.Index,
                l.Quantity
            })
                       .OrderByDescending(l => l.Index).FirstOrDefault();

            if (line != null)
            {
                double quantity = line.Quantity + 2D;

                try
                {
                    // Create the HTTP client to perform the request

                    using (HttpClient client = new HttpClient())
                    {
                        await AuthenticationProvider.SetAccessTokenAsync(client);

                        // Build the request
                        string request          = "sales/orders";
                        string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/{4}/{5}/{6}/{7}/documentLines/{8}/quantity", Constants.baseAppUrl, AccountKey, SubscriptionKey, request, order.Company, order.DocumentType, order.Serie, order.SeriesNumber, line.Id);

                        client.SetDefaultRequestHeaders(CultureKey);

                        // It's a PUT

                        HttpRequestMessage putOrderMessage = new HttpRequestMessage(HttpMethod.Put, resourceLocation);

                        JsonSerializerSettings settings = new JsonSerializerSettings()
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver(),
                            Formatting       = Formatting.Indented
                        };

                        string orderContent = JsonConvert.SerializeObject(quantity, settings);

                        putOrderMessage.Content = new StringContent(orderContent, Encoding.UTF8, "application/json");

                        // Send

                        Console.WriteLine("Request - PUT");
                        Console.WriteLine("{0}", resourceLocation);
                        Console.WriteLine("Request - BODY ");
                        Console.WriteLine("{0}", orderContent);

                        using (HttpResponseMessage responseContent = await client.SendAsync(putOrderMessage))
                        {
                            // Get the response

                            if (!responseContent.IsSuccessStatusCode)
                            {
                                ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                                string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                                ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                                throw new Exception("Unable to update line quantity on sales order.");
                            }

                            // Succeeded

                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteSuccessLine(string.Format("Order Line Updated quantity on Sales Order: Company {0} - {1}.{2}.{3})", order.Company, order.DocumentType, order.Serie, order.SeriesNumber));
                        }
                    }
                }
                catch (Exception exception)
                {
                    ConsoleHelper.WriteErrorLine("Error found!");
                    ConsoleHelper.WriteErrorLine(exception.Message);
                    throw new Exception("Error creating the new line on sales order.");
                }
            }
        }
        private static async Task DeleteAllSalesItemsCreatedOnSample()
        {
            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request

                    string request = "salescore/salesItems/odata";

                    // build the odata expression

                    string partyKey      = $"NewS{DateTime.Now.ToString("yyyyMMddHHmmss")}".Substring(0, 8);
                    string otherPartyKey = $"NewI{DateTime.Now.ToString("yyyyMMddHHmmss")}".Substring(0, 8);

                    string odataExpression = string.Format("?$select=ItemKey&$filter= IsActive eq true and IsSystem eq false and IsDeleted eq false and (startswith(ItemKey, '{0}') or startswith(ItemKey, '{1}')) eq true and startswith(CreatedBy, 'application-user::')", partyKey, otherPartyKey);

                    // full request
                    request = string.Concat(request, odataExpression);

                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // Log Request

                    Console.WriteLine("");
                    Console.WriteLine("Get All Sales Items to delete");
                    Console.WriteLine("");
                    Console.WriteLine("Request - GET");
                    Console.WriteLine("{0}", resourceLocation);

                    // Send

                    using (HttpResponseMessage responseContent = await client.GetAsync(resourceLocation))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                            throw new Exception("Unable to get the sales items to delete.");
                        }

                        // Succeeded

                        string json = await((StreamContent)responseContent.Content).ReadAsStringAsync();

                        var objectResult = JsonConvert.DeserializeObject <ODataResponse <SalesItemResource> >(json);
                        IList <SalesItemResource> salesItems = objectResult.Items;

                        // Log

                        if (salesItems.Count == 0)
                        {
                            Console.WriteLine("");
                            ConsoleHelper.WriteSuccessLine("No sales items found to delete");
                            Console.WriteLine("");
                        }
                        else
                        {
                            Console.WriteLine("");
                            Console.WriteLine("Delete the salesItems found");
                            Console.WriteLine("");

                            foreach (SalesItemResource foundSalesItem in salesItems)
                            {
                                string foundItemKey = foundSalesItem.ItemKey;

                                // Build the request

                                request          = string.Format("salesCore/salesItems/{0}", foundItemKey);
                                resourceLocation = string.Format("{0}/api/{1}/{2}/{3}", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

                                client.SetDefaultRequestHeaders(CultureKey);

                                // It's a DELETE

                                HttpRequestMessage deleteCustomerMessage = new HttpRequestMessage(HttpMethod.Delete, resourceLocation);

                                // Log Request

                                Console.WriteLine("Request - DEL");
                                Console.WriteLine("{0}", resourceLocation);

                                // Send

                                using (HttpResponseMessage deleteResponseContent = await client.SendAsync(deleteCustomerMessage))
                                {
                                    // Get the response

                                    if (!deleteResponseContent.IsSuccessStatusCode)
                                    {
                                        ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", deleteResponseContent.ToString()));
                                        string result = await((StreamContent)deleteResponseContent.Content).ReadAsStringAsync();
                                        ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

                                        throw new Exception(string.Format("Unable to delete the sales items extension for Item '{0}'.", foundItemKey));
                                    }

                                    // Succeeded

                                    ConsoleHelper.WriteSuccessLine(string.Format("SalesItems extension for Item '{0}' was deleted", foundItemKey));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error deleting the sales items created by this sample.");
            }
        }
        /// <summary>
        /// Allows the negative stock on company asynchronous.
        /// </summary>
        /// <param name="companyKey">The company key.</param>
        public static async Task AllowNegativeStockOnCompanyAsync(string companyKey)
        {
            // Validate Parameters

            if (string.IsNullOrEmpty(companyKey))
            {
                ConsoleHelper.WriteErrorLine("");
                ConsoleHelper.WriteErrorLine("AllowNegativeStockAsync: 'companyKey' parameter is required");
                ConsoleHelper.WriteErrorLine("");

                return;
            }

            bool allowNegativeStock = true;

            try
            {
                // Create the HTTP client to perform the request

                using (HttpClient client = new HttpClient())
                {
                    await AuthenticationProvider.SetAccessTokenAsync(client);

                    // Build the request
                    string request          = "logisticsCore/logisticsSetups";
                    string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/{4}/negativeStock", Constants.baseAppUrl, AccountKey, SubscriptionKey, request, companyKey);

                    client.SetDefaultRequestHeaders(CultureKey);

                    // It's a PUT

                    HttpRequestMessage putStockMessage = new HttpRequestMessage(HttpMethod.Put, resourceLocation);

                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        Formatting       = Formatting.Indented
                    };

                    string stockContent = JsonConvert.SerializeObject(allowNegativeStock, settings);

                    putStockMessage.Content = new StringContent(stockContent, Encoding.UTF8, "application/json");

                    // Send

                    Console.WriteLine("Request - PUT");
                    Console.WriteLine("{0}", resourceLocation);
                    Console.WriteLine("Request - BODY ");
                    Console.WriteLine("{0}", stockContent);

                    using (HttpResponseMessage responseContent = await client.SendAsync(putStockMessage))
                    {
                        // Get the response

                        if (!responseContent.IsSuccessStatusCode)
                        {
                            ConsoleHelper.WriteErrorLine(string.Format("Failed. {0}", responseContent.ToString()));
                            string errorResult = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", errorResult));

                            throw new Exception(string.Format("Unable to allow negative stock on Company '{0}'.", companyKey));
                        }

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Negative stock has been allowed on Company '{0}'.", companyKey));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error allowing negative stock on Company '{0}'.", companyKey));
            }
        }