/// <summary>
        /// Gets the first 20 orders asynchronous.
        /// </summary>
        public static async Task GetOrdersAsync()
        {
            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?page=1&pageSize=20";
                    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 result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                            ConsoleHelper.WriteErrorLine(string.Format("Content: {0}", result));

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

                        // Succeeded

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

                        var objectResult = JsonConvert.DeserializeObject <ListResponse <SalesOrderResource> >(json);
                        IList <SalesOrderResource> orders = objectResult.Data;

                        ConsoleHelper.WriteSuccessLine("The sales orders were obtained with success.");
                        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("");
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception("Error creating the order.");
            }
        }
        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);
        }
        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);
        }
        /// <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.");
            }
        }
示例#5
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);
        }
        /// <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>
        /// 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.");
            }
        }
示例#10
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);
        }
示例#11
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);
        }
示例#12
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));
            }
        }
示例#13
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));
            }
        }
示例#14
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);
        }
        /// <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);
        }
        /// <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>
        /// 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>
        /// 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.");
            }
        }
        /// <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>
        /// 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.");
                }
            }
        }
        /// <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>
        /// 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.");
            }
        }
        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));
            }
        }