private string Create_Values() { string Data = ""; int SendingInt = 0; float SendingFloat = 0; Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Data = new string(Enumerable.Repeat(chars, 5).Select(s => s[random.Next(s.Length)]).ToArray()); SendingInt = random.Next(1, 40); double mantissa = (random.NextDouble() * 2.0) - 1.0; double exponent = Math.Pow(2.0, random.Next(-126, 128)); SendingFloat = (float)(mantissa * exponent); SendingData sending_data = new SendingData(); sending_data.FloatData = SendingFloat; sending_data.IntData = SendingInt; sending_data.StringData = Data; var content = JsonConvert.SerializeObject(sending_data); List_Data.Add(sending_data); return(content.ToString()); }
public void ToCartTest(SendingData sendingData) { int partId = sendingData.partId; int quantity = sendingData.quant; string st = sendingData.str; adorders.AddToCartAdmin(partId, quantity); }
private void AddCitizenFormManagement_ClickButton(object sender, EventArgs e) { SendingData.SendCitizen( addCitizenFormManagement.GetFamily, addCitizenFormManagement.GetName, addCitizenFormManagement.GetPatronymic, addCitizenFormManagement.GetEmail, addCitizenFormManagement.GetPhone, addCitizenFormManagement.GetPD ); }
private void AddMessageFormManagement_AddMessageClick(object sender, EventArgs e) { SendingData.SendTicket( addMessageFormManagement.GetMessage, Convert.ToInt32(addMessageFormManagement.GetCriterion), 0, Convert.ToInt32(addMessageFormManagement.GetTypeMessage), Convert.ToInt32(addMessageFormManagement.GetDepartment), Convert.ToInt32(addMessageFormManagement.GetCitizen) ); }
private void AddExecutiveFormManagement_ClickObject(object sender, EventArgs e) { SendingData.SendExecutive( addExecutiveFormManagement.GetFamily, addExecutiveFormManagement.GetName, addExecutiveFormManagement.GetPatronymic, addExecutiveFormManagement.GetEmail, addExecutiveFormManagement.GetPhone, addExecutiveFormManagement.GetPD, addExecutiveFormManagement.GetIdDepartment ); FillExecutivesList(); }
private void ReceiveCallback(IAsyncResult AR) { Socket current = (Socket)AR.AsyncState; int received; try { received = current.EndReceive(AR); } catch (SocketException) { current.Close(); clientSockets.Remove(current); return; } byte[] recBuf = new byte[received]; Array.Copy(buffer, recBuf, received); string text = Encoding.ASCII.GetString(recBuf); SendingData IncomingData = JsonConvert.DeserializeObject <SendingData>(text); StringBuilder sb = new StringBuilder(); sb.Append("Gelen String: "); sb.Append(IncomingData.StringData); sb.Append(",Gelen Float: "); sb.Append(IncomingData.FloatData.ToString()); sb.Append(", Gelen İnt: "); sb.Append(IncomingData.IntData.ToString()); List_Data.Add(IncomingData); if (dataGridView1.InvokeRequired) { dataGridView1.Invoke(new AddValueToGridviewDelegate(AddValueToGridview)); } else { dataGridView1.DataSource = null; dataGridView1.DataSource = List_Data; } byte[] data = Encoding.ASCII.GetBytes(sb.ToString()); current.Send(data); sb = null; current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); }
private SendingData BuildSendingData(Feedback feedback) { var result = new SendingData(new List <InitialPreview>(), new List <InitialPreviewConfig>()); var imgService = this.GetService <ImgService>(); if (!feedback.ImgIds.IsEmpty()) { foreach (var item in feedback.ImgIds) { var img = imgService.Get(item); if (img != null) { result.initialPreviewConfigs.Add(new InitialPreviewConfig(img.Name, "120px", "/api/img/remove", img.Id, new { feedbackId = feedback.Id })); result.initialPreviews.Add(new InitialPreview(img.Id, "file-preview-image", img.Name, img.Name)); } } } return(result); }
private SendingData SaveImgs(ICollection <IFormFile> files) { var result = new SendingData(new List <InitialPreview>(), new List <InitialPreviewConfig>()); try { foreach (var file in files) { var sendingData = SaveImg(file); result.initialPreviewConfigs.AddRange(sendingData.initialPreviewConfigs); result.initialPreviews.AddRange(sendingData.initialPreviews); } return(result); } catch (Exception ex) { _logger.LogError(ex.Message); } return(result); }
private SendingData SaveImg(IFormFile file) { var result = new SendingData(new List <InitialPreview>(), new List <InitialPreviewConfig>()); try { if (file != null && file.Length > 0) { var img = new Img(); img.Length = (int)file.Length; //get the file's name var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition); img.Name = parsedContentDisposition.FileName.ToString().Trim('"'); img.ContentType = file.ContentType; //get the bytes from the content stream of the file byte[] bytes = new byte[file.Length]; using (BinaryReader theReader = new BinaryReader(file.OpenReadStream())) { bytes = theReader.ReadBytes((int)file.Length); } //convert the bytes of image data to a string using the Base64 encoding img.Content = bytes; var imgId = this.GetService <ImgService>().Create(img); result.initialPreviewConfigs.Add(new InitialPreviewConfig(img.Name, "120px", "/api/img/remove", imgId, null)); result.initialPreviews.Add(new InitialPreview(imgId, "file-preview-image", img.Name, img.Name)); } } catch (Exception ex) { _logger.LogError(ex.Message); } return(result); }
public async static void SendMessage(string serverUri) { try { //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); //var httpHandler = new HttpClientHandler(); //httpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; var cacert = File.ReadAllText("keys/server-cert.pem"); var ssl = new SslCredentials(cacert); Channel channel = new Channel("127.0.0.1", 8888, ssl); var client = new DataSender.DataSenderClient(channel); // Отправка данных батчами using var call = client.SendRawData(); while (Program.Countries.Count != 0) { var curCountry = Program.Countries.Dequeue(); var data = new SendingData { Id = curCountry.Id, CountryName = curCountry.CountryName, CountryPopulation = curCountry.CountryPopulation, CountrySquare = curCountry.CountrySquare, CapitalName = curCountry.CapitalName, CapitalFoundation = curCountry.CapitalFoundation, TotalGdp = curCountry.TotalGDP, HumanGdp = curCountry.HumanGDP, GdpYear = curCountry.GDPYear, LanguageName = curCountry.LanguageName, LanguagePrevalencePlace = curCountry.LanguagePrevalencePlace, RegionName = curCountry.RegionName, RegionCenter = curCountry.RegionCenter }; await call.RequestStream.WriteAsync(data); } await call.RequestStream.CompleteAsync(); var reply = await call.ResponseAsync; Console.WriteLine(reply.ReplyStr); channel.ShutdownAsync().Wait(); } catch (Exception ex) { Console.WriteLine($"Ошибка во время отправки сообщения. {ex.Message}"); } }
/// <summary> /// Sends a web request with the data either in the query string or in the body. /// </summary> /// <param name="config"> /// The configuration for the data to be sent (e.g., contains the URL and request method). /// </param> /// <param name="context"> /// The context for the current form submission. /// </param> /// <param name="data"> /// The data to send. /// </param> /// <param name="sendInBody"> /// Send the data as part of the body (or in the query string)? /// </param> /// <param name="sendJson"> /// Send the data as json /// </param> /// <returns> /// True, if the request was a success; otherwise, false. /// </returns> /// <remarks> /// Parts of this function are from: http://stackoverflow.com/a/9772003/2052963 /// and http://stackoverflow.com/questions/14702902 /// </remarks> private SendDataResult SendData(SendDataConfiguration config, FormSubmissionContext context, IEnumerable <KeyValuePair <string, string> > data, bool sendInBody, bool sendJson) { // Construct a URL, possibly containing the data as query string parameters. var sendInUrl = !sendInBody; var sendDataResult = new SendDataResult(); var uri = new Uri(config.Url); var bareUrl = uri.GetLeftPart(UriPartial.Path); var keyValuePairs = data as KeyValuePair <string, string>[] ?? data.ToArray(); var strQueryString = ConstructQueryString(uri, keyValuePairs); var hasQueryString = !string.IsNullOrWhiteSpace(strQueryString); var requestUrl = hasQueryString && sendInUrl ? $"{bareUrl}?{strQueryString}" : config.Url; var enableLogging = WebConfigurationManager.AppSettings["Formulate:EnableLogging"]; var jsonMode = WebConfigurationManager.AppSettings["Formulate:Send Data JSON Mode"]; var isJsonObjectMode = "JSON Object".InvariantEquals(jsonMode); var isWrappedObjectMode = "Wrap JSON Object in Array".InvariantEquals(jsonMode); // Attempt to send the web request. try { // Construct web request. var request = (HttpWebRequest)WebRequest.Create(requestUrl); request.AllowAutoRedirect = false; request.UserAgent = WebUserAgent; request.Method = config.Method; // Send an event indicating that the data is about to be sent (which allows code // external to Formulate to modify the request). var sendContext = new SendingDataContext() { Configuration = config, Data = keyValuePairs, Request = request, SubmissionContext = context }; SendingData?.Invoke(sendContext); // Update the key/value pairs in case they got changed in the sending data event. // This only updates the methods that send the data in the body (as the URL has // already been set on the request). keyValuePairs = sendContext.Data as KeyValuePair <string, string>[] ?? sendContext.Data.ToArray(); // Send the data in the body (rather than the query string)? if (sendInBody) { if (sendJson) { // Variables. var json = default(string); // Send an event indicating that the data is about to be serialized to // JSON (which allows code external to Formulate to modify the JSON)? if (SerializingJson != null) { json = SerializingJson.Invoke(sendContext.Data); } else { // If sending as JSON, group duplicate keys/value pairs. var grouped = keyValuePairs.GroupBy(x => x.Key).Select(x => new { Key = x.Key, Value = x.Select(y => y.Value) }).ToDictionary(x => x.Key, x => x.Value.Count() > 1 ? x.Value.ToArray() as object : x.Value.FirstOrDefault()); // Convert data to JSON. if (isJsonObjectMode) { json = JsonConvert.SerializeObject(grouped); } else if (isWrappedObjectMode) { json = JsonConvert.SerializeObject(new[] { grouped }); } else { // Ideally, we can remove this "else" branch later. We never really want this // mode to be used, but it's here for legacy support in case anybody managed // to make use of this funky mode. json = JsonConvert.SerializeObject(new[] { grouped }); } } // Log JSON being sent. if (enableLogging == "true") { LogHelper.Info <SendDataHandler>("Sent URL: " + config.Url); LogHelper.Info <SendDataHandler>("Sent Data: " + JsonHelper.FormatJsonForLogging(json)); } // Write JSON data to the request request. var postBytes = Encoding.UTF8.GetBytes(json); request.ContentType = "application/json; charset=utf-8"; request.ContentLength = postBytes.Length; using (var postStream = request.GetRequestStream()) { postStream.Write(postBytes, 0, postBytes.Length); } } else { // Log data being sent. if (enableLogging == "true") { LogHelper.Info <SendDataHandler>("Sent URL: " + config.Url); LogHelper.Info <SendDataHandler>("Sent Data: " + strQueryString); } // Update the data (since the sending data event may have modified it). uri = new Uri(config.Url); strQueryString = ConstructQueryString(uri, keyValuePairs); // Write the data to the request stream. var postBytes = Encoding.UTF8.GetBytes(strQueryString); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postBytes.Length; var postStream = request.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); } } // Get and retain response. var response = (HttpWebResponse)request.GetResponse(); sendDataResult.HttpWebResponse = response; var responseStream = response.GetResponseStream(); var reader = new StreamReader(responseStream); var resultText = reader.ReadToEnd(); sendDataResult.ResponseText = resultText; sendDataResult.Success = true; } catch (Exception ex) { LogHelper.Error <SendDataHandler>(SendDataError, ex); sendDataResult.ResponseError = ex; sendDataResult.Success = false; } // Return the result of the request. return(sendDataResult); }
private void ClickObject(object sender, EventArgs e) { SendingData.SendDepartment(formManagment.GetNameDepartment); }