public void PostFormDataTest() { FormData formData = new FormData("Contact Name", "Contact Email", "Contact Subject", "Message"); string reference = WebFormTools.PostFormData(formData); Console.WriteLine($"PostFormDataTest, reference={reference}."); if (WebFormTools.ReferenceValid(reference)) { return; } throw new InvalidReferenceException(reference); }
/// <summary> /// Handles the Click event of the execute control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void execute_Click(object sender, EventArgs e) { ClientErrors.Text = "Client Errors<br>..."; ServerErrors.Text = "Server Errors<br>..."; // Populate data for service call var data = new ServerServiceRequest(); PopulateFields(data); // Bail out, if we have errors if (HasClientErrors()) { return; } // Make sure that the user has not selected both customers and products var hasCustomerField = (data.Customer_CustID != null || data.Customer_FirstName != null || data.Customer_LastName != null || data.Customer_PhoneNumber != null); var hasProductField = (data.Product_ProdID != null || data.Product_ProdName != null || data.Product_ProdWeight != null || data.Product_Price != null // Ignore the instock field... ); if (hasCustomerField && hasProductField) { AppendClientError("Cannot have <b>both</b> customer and product fields filled"); return; } if (GeneratePurchaseOrder.Checked) { // Different fields are mandatory when generate P.O. is checked if (data.Customer_CustID == null && data.Customer_LastName == null && data.Customer_FirstName == null && data.Order_OrderID == null && data.Order_PoNumber == null && data.Order_OrderDate == null) { AppendClientError(@"At least one of the following fields must be filled: Customer custID, Customer lastName, <br> Customer firstName, Order orderID, Order poNumber or Order orderDate when 'Generate P.O.' is checked"); return; } } if (!data.HasOneOrMoreFieldsWithAValue()) { AppendClientError("Please fill in at least one of the fields"); return; } if (RequestType == PageType.Insert) { if (!EnforceRequiredInsertFieldsFilled(data)) { return; } } // Check maximum lengths, because Linq to SQL generates crappy messages on the server end DateTime parsed; if (data.Customer_PhoneNumber != null && !Regex.Match(data.Customer_PhoneNumber, @"^\d{3}-\d{3}-\d{4}$").Success) { AppendClientError("Please use the following format on phone numbers (xxx-xxx-xxxx)"); return; } else if (data.Order_OrderDate != null && !DateTime.TryParseExact(data.Order_OrderDate, "MM-dd-yy", CultureInfo.CurrentCulture, DateTimeStyles.None, out parsed)) { AppendClientError("Please use the following format for order dates (MM-DD-YY) and proper dates"); return; } switch (RequestType) { case PageType.Search: { var purchaseOrder = GeneratePurchaseOrder.Checked; var url = new Uri(ClientConfiguration.ServerUrl.ToString() + data.ToUrl(purchaseOrder)); var client = HttpWebRequest.Create(url); client.Method = "GET"; using (var responseStream = client.GetResponse().GetResponseStream()) using (var reader = new StreamReader(responseStream)) { SearchContent = reader.ReadToEnd(); try { var js = new JavaScriptSerializer(); var result = js.Deserialize <SearchResult>(SearchContent); SearchResult = result; if (purchaseOrder) { Server.Transfer("/Pages/PurchaseOrderPage.aspx"); } else { Server.Transfer("/Pages/SearchResultsPage.aspx"); } } catch (Exception) { // Check if we have a Json Error var js = new JavaScriptSerializer(); var error = js.Deserialize <JsonError>(SearchContent); AppendServerError(error.Message); } } break; } case PageType.Insert: { var url = ClientConfiguration.ServerUrl; var client = HttpWebRequest.Create(url); client.Method = "POST"; var js = new JavaScriptSerializer(); var json = js.Serialize(data); var requestContent = Encoding.ASCII.GetBytes(json); client.ContentLength = requestContent.Length; var requestStream = client.GetRequestStream(); requestStream.Write(requestContent, 0, requestContent.Length); requestStream.Close(); using (var responseStream = client.GetResponse().GetResponseStream()) using (var reader = new StreamReader(responseStream)) { var responseContent = reader.ReadToEnd(); try { var success = js.Deserialize <JsonSuccess>(responseContent); WebFormTools.MessageBoxShow(this, success.Message); } catch (Exception) { var error = js.Deserialize <JsonError>(responseContent); AppendServerError(error.Message); } } break; } case PageType.Update: { var url = ClientConfiguration.ServerUrl; var client = HttpWebRequest.Create(url); client.Method = "PUT"; var js = new JavaScriptSerializer(); var json = js.Serialize(data); var requestContent = Encoding.ASCII.GetBytes(json); client.ContentLength = requestContent.Length; using (Stream requestStream = client.GetRequestStream()) { requestStream.Write(requestContent, 0, requestContent.Length); } using (var responseStream = client.GetResponse().GetResponseStream()) using (var reader = new StreamReader(responseStream)) { var responseContent = reader.ReadToEnd(); try { var success = js.Deserialize <JsonSuccess>(responseContent); WebFormTools.MessageBoxShow(this, success.Message); } catch (Exception) { var error = js.Deserialize <JsonError>(responseContent); AppendServerError(error.Message); } } break; } } }
private void fileSubmitButton_Click(object sender, EventArgs e) // TODO: make a public event handler for messages meant for the user, // and replace any references to the user message box (errorLabel) // by firing off an event instead. { Spreadsheet spreadsheet; FormData formData; // Make sure this can only be ran once (for neatness I guess) Button goButton = ((Button)sender); goButton.Enabled = false; // Make sure the progress bar is at 0 to start with. ResetProgressBar(); // Get textbox value with the .xlsx file path string filePath = filePathTextBox.Text; // Check that the file exists. if (!File.Exists(filePath)) { UserMessageBox.Text = UserMessageBox.Text + "Could not find the file specified.\r\n"; goButton.Enabled = true; return; } /// Read xlsx file into a FormData object try { spreadsheet = ExcelTools.ReadExcelFile(filePath); } catch (FileFormatException) { string tempMessage = "The selected file is either corrupt, or not a valid Microsoft Excel document.\r\n"; UserMessageBox.Text += tempMessage; DebugTools.Log(tempMessage); goButton.Enabled = true; return; } formData = ExcelTools.SpreadsheetToFormData(spreadsheet); /// Submit the form with data read, saving the reference var reference = WebFormTools.PostFormDataAsync(formData); /// Wait for the form submission to finish, updating the loading bar in the meantime, /// but let the user know if something happens during submission / reference retreival. while (!reference.IsCompleted) { if (reference.IsCanceled) { string tempMessage = "Form submission cancelled.\r\n"; UserMessageBox.Text += tempMessage; DebugTools.Log(tempMessage); goButton.Enabled = true; return; } if (reference.IsFaulted) { string tempMessage = "Form submission failed due to an unknown error.\r\n"; UserMessageBox.Text += tempMessage; DebugTools.Log(tempMessage); goButton.Enabled = true; return; } // Update the progress bar. UpdateProgressBar(); // Make sure that the form doesn't hang while waiting. Refresh(); Application.DoEvents(); } // Change the progress bar to 100% and change the go button to show that we are done FillProgressBar(); goButton.Enabled = true; int errorCode = 0; string mockReference = "MockReference - 12345678"; foreach (int attempt in new[] { 1, 2 }) { try { if (attempt == 1) { errorCode = ExcelTools.AppendToExcelFile(reference.GetAwaiter().GetResult(), filePath); break; // no need to try again for attempt no. 2 } else { errorCode = ExcelTools.AppendToExcelFile(mockReference, filePath); break; } } catch (InvalidReferenceException error) { string errorMessage = $"{error.Message}\r\nFor demo purposes a mock reference was used: {mockReference}\r\n"; UserMessageBox.Text += errorMessage; DebugTools.Log(errorMessage); } catch (Exception error) { string tempMessage = $"An error has occured while saving the submission reference. Additional Info:\r\n{error.Message}\r\n"; UserMessageBox.Text += tempMessage; DebugTools.Log(tempMessage); } } switch (errorCode) { case 0: break; case 1: string errorMessage = "File specified was empty.\r\n"; UserMessageBox.Text += errorMessage; DebugTools.Log(errorMessage); goButton.Enabled = true; return; case 2: errorMessage = "Failed to get write permissions to the file.\r\n"; UserMessageBox.Text += errorMessage; DebugTools.Log(errorMessage); goButton.Enabled = true; break; } goButton.Enabled = true; ExcelTools.DisplatResults(filePath, this); }