/// <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> /// 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); }