Example #1
0
        /// <summary>
        /// Creates a Customer Extension.
        /// </summary>
        /// <returns>The task.</returns>
        public static async Task CreateCustomerExtensionAsync(string customer)
        {
            // Validate Parameters

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

                return;
            }

            string partyTaxSchemaKey = await GetDefaultPartyTaxSchemaAsync();

            try
            {
                // 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   = customer
                };

                // Create the HTTP client to perform the request

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

                    // Build the request

                    string request          = "salesCore/customerParties/extension";
                    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 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));

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

                        // Succeeded

                        string result = await((StreamContent)responseContent.Content).ReadAsStringAsync();
                        ConsoleHelper.WriteSuccessLine(string.Format("Customer extension created for Party '{0}': (Id = {1})", customer, result));
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
                throw new Exception(string.Format("Error creating the customer extension for Party '{0}'.", customer));
            }
        }
Example #2
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);
        }