void aliveTimer_Tick(object sender, EventArgs e) { // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("command", "alive"); postParameters.Add("auth_id", "trimauthid"); // Create request and receive response string postURL = Helper.getUrl("communicator"); HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, Config.userAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); dynamic jsonResponse = JsonConvert.DeserializeObject(fullResponse); string command = jsonResponse["command"]; if ("start".Equals(command)) { videoSource.Start(); string streamSpeed = jsonResponse["stream_speed"]; streamTimer.Interval = Int32.Parse(streamSpeed); streamTimer.Start(); } else if ("stop".Equals(command)) { videoSource.Stop(); streamTimer.Stop(); } }
private void SendData() { // Read file data string fileName = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\img1.png"; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("uploaded_file", "img1.png"); postParameters.Add("uploaded_file", "png"); postParameters.Add("uploaded_file", new FormUpload.FileParameter(data, "img1.png", "application/image")); // Create request and receive response string postURL = "http://alednb:82/php_upload/upload.php"; string userAgent = "Someone"; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); }
public static ImagekitResponse Picture(Uri Image, string folder, string filename, bool UseUniqueFileName = true) { var imageObject = GetImageFileParameter(Image); var TimeStamp = Utils.ToUnixTime(DateTime.UtcNow); string Ser = string.Format("apiKey={0}&filename={1}×tamp={2}", Secret.ApiKey, filename, TimeStamp); var Sign = Utils.EncodeHMACSHA1(Ser, Encoding.ASCII.GetBytes(Secret.ApiPrivate)); var postParameters = new Dictionary <string, object> { { "folder", folder }, { "apiKey", Secret.ApiKey }, { "useUniqueFilename", UseUniqueFileName.ToString() }, { "filename", filename }, { "timestamp", TimeStamp }, { "signature", Sign }, { "file", imageObject } }; var response = FormUpload.MultipartFormDataPost(Secret.Address, postParameters); var encoding = ASCIIEncoding.ASCII; using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) { string responseText = reader.ReadToEnd(); return(JsonConvert.DeserializeObject <ImagekitResponse>(responseText)); } }
public static List <T> findDataByCondition <T>(string condition, string url) { try { Type type = typeof(T); string className = type.Name; List <T> list = new List <T>(); Dictionary <string, object> dict2 = new Dictionary <string, object>(); dict2.Add("tableName", className); dict2.Add("field", "*"); dict2.Add("condition", condition); // string postURL = Config.globalServiceURL + "service/findListByWhere/"; string postURL = url + "findDataByWhere/"; string userAgent = "Someone"; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, dict2); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); bool successFlag; string val_first = HttpWebResponseUtility.getValueByKeyName(fullResponse, out successFlag); if (successFlag == true) { list = (List <T>)JsonConvert.DeserializeObject <List <T> >(val_first); } return(list); } catch (Exception ce) { LogUtil.WriteLog(null, ce.Message); return(null); } }
private static void Unsubscribe(string roster) { // roster is a list of email addresses separated by \n Log("Unsubscribing everybody"); _vars.Clear(); _vars["unsubscribees"] = roster; _vars["send_unsub_ack_to_this_batch"] = 0; _vars["send_unsub_notifications_to_list_owner"] = 0; FormUpload.MultipartFormDataPost(_adminUrl + _removePage, "foobar", _vars, _cookies); }
private static void Subscribe(string members) { // members is a list of email addresses separated by \n Log("Subscribing everyone"); _vars.Clear(); _vars["subscribees"] = members; _vars["subscribe_or_invite"] = 0; _vars["send_welcome_msg_to_this_batch"] = 0; _vars["send_notifications_to_list_owner"] = 0; FormUpload.MultipartFormDataPost(_adminUrl + _addPage, "foobar", _vars, _cookies); }
public static void Upload(string file, string uploadurl, string uploadFormParam, HttpStatusCode expectedStatus = HttpStatusCode.OK) { //adapted from and many thanks to: http://www.briangrinstead.com/blog/multipart-form-post-in-c Log.Write("Attempting to upload {0} to {1} as form field {2}.".F(file, uploadurl, uploadFormParam)); string filename = Path.GetFileName(file); string fileformat = uploadFormParam; var maxfilesize = MaxFileSize == 0 ? 64 * 1024 * 1024 : MaxFileSize; // default 64 MB if not already known string content_type = "application/octet-stream"; try { // Read file data FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("MAX_FILE_SIZE", maxfilesize); postParameters.Add("fileformat", fileformat); postParameters.Add(uploadFormParam, new FormUpload.FileParameter(data, filename, content_type)); // Create request and receive response string postURL = uploadurl; string userAgent = "AutoPBW/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); HttpWebResponse response = FormUpload.MultipartFormDataPost(cookies, postURL, userAgent, postParameters); Log.Write("Connection status to {0} is {1} {2}: {3}".F(response.ResponseUri, (int)response.StatusCode, response.StatusCode, response.StatusDescription)); // Process response StreamReader responseReader = new StreamReader(response.GetResponseStream()); if (response.StatusCode != expectedStatus) { if (response.StatusCode == HttpStatusCode.OK) { Log.Write($"Warning while uploading {filename}: Expected http response {(int)expectedStatus} {new HttpResponseMessage(expectedStatus).ReasonPhrase} but received 200 {response.StatusDescription}\n"); } else { throw new WebException($"Could not upload {filename} to PBW, response {(int)response.StatusCode} {response.StatusDescription}. Try uploading it manually to see if there is an error."); } } response.Close(); } catch (Exception ex) { Log.Write($"Error while uploading {filename}:\n"); Log.Write(ex.ToString()); throw; } }
public static bool getFormSave(string uri, Dictionary <string, object> dict2) { string userAgent = "Someone"; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(uri, userAgent, dict2); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); bool successFlag; string val_first = HttpWebResponseUtility.getValueByKeyName(fullResponse, out successFlag); return(successFlag); }
private static void Unmoderate(string email) { Log("Unmoderating " + email); email = email.Replace("@", "%40"); _vars.Clear(); _vars["user"] = email; _vars[email + "_nomail"] = "off"; _vars[email + "_nodupes"] = "on"; _vars[email + "_plain"] = "on"; _vars[email + "_language"] = "en"; _vars["setmemberopts_btn"] = "Submit Your Changes"; FormUpload.MultipartFormDataPost(_adminUrl + _membersPage, "foobar", _vars, _cookies); }
public override Bitmap Decode(byte[] Data) { if (Data.Length < 0xC) { return(base.Decode(Data)); } if (BitConverter.ToUInt32(Data.Skip(8).Take(4).ToArray(), 0) != 0x66697661) { return(base.Decode(Data)); } Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("file", new FormUpload.FileParameter(Data, "img.avif", "image/avif")); postParameters.Add("targetformat", "png"); postParameters.Add("imagequality", "100"); postParameters.Add("imagesize", "option1"); postParameters.Add("customsize", ""); postParameters.Add("code", "83000"); postParameters.Add("filelocation", "local"); postParameters.Add("oAuthToken", ""); // Create request and receive response string postURL = "https://s12.aconvert.com/convert/convert-batch-win3.php"; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, "https://www.aconvert.com/", ProxyTools.UserAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); var Server = DataTools.ReadJson(fullResponse, "server"); var filename = DataTools.ReadJson(fullResponse, "filename"); var state = DataTools.ReadJson(fullResponse, "state"); if (state != "SUCCESS") { return(base.Decode(Data)); } //https://s12.aconvert.com/convert/p3r68-cdx67/aceyq-dv0y6.png var OutUrl = new Uri($"https://s{Server}.aconvert.com/convert/p3r68-cdx67/{filename}"); var Decoded = OutUrl.Download("https://www.aconvert.com/image/avif-to-png/", ProxyTools.UserAgent); return(base.Decode(Decoded)); }
public HttpWebResponse SplitPdf(String InputFilePath, String OutputFilePath, String Range) { String url = this.broker.RestEndpointURL + ":" + this.broker.RestEndpointPort + "/pdf/split"; string CT0 = "file"; string fullPath0 = InputFilePath; // @"C:\Users\Administrator\Desktop\Doctools\input-01.pdf"; FormUpload.FileParameter f0 = new FormUpload.FileParameter(File.ReadAllBytes(fullPath0), Path.GetFileName(InputFilePath), "multipart/form-data"); Dictionary <string, object> d = new Dictionary <string, object>(); d.Add(CT0, f0); d.Add("range", Range); string ua = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; HttpWebResponse Resp = FormUpload.MultipartFormDataPost(url, ua, d); String GeneratedFileName = ""; //Console.WriteLine("DEBUG:" + InputFilePath + "|" + OutputFilePath); //C:\Users\Administrator\Desktop\customers\CareFirst\Sample_Invoice_Combined_BlankPages.pdf|C:\Users\Administrator\Desktop\customers\CareFirst\Temp if (InputFilePath == OutputFilePath) { String RootPath = Path.GetDirectoryName(OutputFilePath) + "\\"; String FileNameWithoutExt = Path.GetFileNameWithoutExtension(OutputFilePath); String FileExtension = Path.GetExtension(OutputFilePath); GeneratedFileName = RootPath + FileNameWithoutExt + "_" + Range + FileExtension; } else { String RootPath = OutputFilePath + "\\"; String FileNameWithoutExt = Path.GetFileNameWithoutExtension(InputFilePath); String FileExtension = Path.GetExtension(InputFilePath); GeneratedFileName = RootPath + FileNameWithoutExt + "_" + Range + FileExtension; } //Console.WriteLine("Debug:" + GeneratedFileName); using (Stream output = File.OpenWrite(GeneratedFileName)) using (Stream input = Resp.GetResponseStream()) { input.CopyTo(output); } return(Resp); }
public string Deploy(string deploymentName, List <object> files) { Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("deployment-name", deploymentName); postParameters.Add("deployment-source", "C# Process Application"); postParameters.Add("enable-duplicate-filtering", "true"); postParameters.Add("data", files); // Create request and receive response string postURL = helper.RestUrl + "deployment/create"; HttpResponseMessage webResponse = FormUpload.MultipartFormDataPost(postURL, helper.RestUsername, helper.RestPassword, postParameters); using (var reader = new StreamReader(webResponse.Content.ReadAsStreamAsync().Result, Encoding.UTF8)) { var deployment = JsonConvert.DeserializeObject <Deployment>(reader.ReadToEnd()); return(deployment.Id); } }
// Transform an image PDF into a machine readable PDF //String PathToPdf, String OCRLanguage, String PathToJsonFile public HttpWebResponse GetTextInMachineReadablePDF(String InputFilePath, String Depth) { String url = this.broker.RestEndpointURL + ":" + this.broker.RestEndpointPort + "/pdf/text"; string CT0 = "file"; string fullPath0 = InputFilePath; FormUpload.FileParameter f0 = new FormUpload.FileParameter(File.ReadAllBytes(fullPath0), Path.GetFileName(InputFilePath), "multipart/form-data"); Dictionary <string, object> d = new Dictionary <string, object>(); d.Add(CT0, f0); d.Add("depth", Depth); string ua = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; HttpWebResponse Resp = FormUpload.MultipartFormDataPost(url, ua, d); return(Resp); }
void streamTimer_Tick(object sender, EventArgs e) { byte[] postData = Helper.convertImageToByteArray(pictureBoxOutput.Image); // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("auth_id", "trimauthid"); postParameters.Add("image", new FormUpload.FileParameter(postData, "image.jpg", "image/jpeg")); // Create request and receive response string postURL = Helper.getUrl("send"); HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, Config.userAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); }
public (string title, string artist) GetMetaData(string filepath) { var configuration = this.Configuration.GetValue <string>("ApiToken"); string URL = "https://api.audd.io/"; string boundary = "----" + System.Guid.NewGuid(); string Dateiname = Path.GetFileName(filepath); // Read file data byte[] data = null; using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { data = new byte[fs.Length]; fs.Read(data, 0, data.Length); } // Generate post objects var postParameters = new Dictionary <string, object>(); //postParameters.Add("name", "file"); postParameters.Add("file", new FileParameter(data, Dateiname, "application/octet-stream")); postParameters.Add("api_token", configuration); postParameters.Add("return", "timecode,apple_music,deezer,spotify"); string postURL = URL; string userAgent = "Someone"; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); var fullResponse = responseReader.ReadToEnd(); webResponse.Close(); var artistPattern = @"""artist"":""([a-zA-Z0-9\s]+)"""; var titlePattern = @"""title"":""([a-zA-Z0-9\s]+)"""; var artist = Regex.Match(fullResponse, artistPattern).Groups[1].ToString(); var title = Regex.Match(fullResponse, titlePattern).Groups[1].ToString(); return(artist, title); }
/// <summary> /// Upload advertisement's image to Reddit's AWS S3 bucket /// </summary> /// <param name="adS3Data">Object containing all the info needed for the authentication to S3</param> /// <param name="imgPathText">Image's path</param> /// <param name="ad">Advertisement to be created</param> private void UploadImage(AdS3Json adS3Data, string imgPathText, Advertisement ad) { var imgPath = Path.Combine(imgPathText, ad.ThumbnailName); if (File.Exists(imgPath)) { using (var fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read)) { var data = new byte[fs.Length]; fs.Read(data, 0, data.Length); var postParameters = new Dictionary <string, object> { { "acl", "public-read" }, { "key", adS3Data.Fields[1].Value }, { "X-Amz-Credential", adS3Data.Fields[2].Value }, { "X-Amz-Algorithm", adS3Data.Fields[3].Value }, { "X-Amz-Date", adS3Data.Fields[4].Value }, { "success_action_status", adS3Data.Fields[5].Value }, { "content-type", adS3Data.Fields[6].Value }, { "x-amz-storage-class", adS3Data.Fields[7].Value }, { "x-amz-meta-ext", adS3Data.Fields[8].Value }, { "policy", adS3Data.Fields[9].Value }, { "X-Amz-Signature", adS3Data.Fields[10].Value }, { "x-amz-security-token", adS3Data.Fields[11].Value }, { "file", new FormUpload.FileParameter(data, ad.ThumbnailName, adS3Data.Fields[6].Value) } }; FormUpload.MultipartFormDataPost("https://reddit-client-uploads.s3.amazonaws.com/", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", postParameters); } } else { throw new FileNotFoundException("File does not exist on the specified directory!"); } }
// [{ "x": 110, "y": 710, "width": 190, "height": 22, "backgroundColor": "#000000", "opacity": 1, "page": 1}] public HttpWebResponse AnnotatePdf(String InputFilePath, String OutputFilePath, String json) { String url = this.broker.RestEndpointURL + ":" + this.broker.RestEndpointPort + "/pdf/annotate"; string CT0 = "file"; string fullPath0 = InputFilePath; FormUpload.FileParameter f0 = new FormUpload.FileParameter(File.ReadAllBytes(fullPath0), Path.GetFileName(InputFilePath), "multipart/form-data"); Dictionary <string, object> d = new Dictionary <string, object>(); d.Add(CT0, f0); d.Add("json", json); string ua = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; HttpWebResponse Resp = FormUpload.MultipartFormDataPost(url, ua, d); String GeneratedFileName = ""; if (InputFilePath == OutputFilePath) { String RootPath = Path.GetDirectoryName(OutputFilePath) + "\\"; String FileNameWithoutExt = Path.GetFileNameWithoutExtension(OutputFilePath); String FileExtension = Path.GetExtension(OutputFilePath); GeneratedFileName = RootPath + FileNameWithoutExt + "_MR_" + FileExtension; } else { GeneratedFileName = OutputFilePath; } using (Stream output = File.OpenWrite(OutputFilePath)) using (Stream input = Resp.GetResponseStream()) { input.CopyTo(output); } return(Resp); }
public static string Send(string mssgBody, string userName, string webhook) { // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("username", userName); postParameters.Add("content", mssgBody); postParameters.Add("avatar_url", defaultAvatar); // Create request and receive response HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(webhook, defaultUserAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); //return string with response return(fullResponse); }
// Procedure to send the pdf: public string SendPDFToAthena(string practiceID, string patientID, string appointmentID, string departmentID, string internalNote, bool attachPDFToVisit, byte[] data) { string version = "{yourVersionHere}"; // preview1, v1, etc string key = "{yourKeyHere}"; string secret = "{yourSecretHere}"; // This references an api that is pretty much exactly like that found on the // athena website for asp.net examples. Get a token for authentication: APIConnection api = new APIConnection(version, key, secret, practiceID); string token = api.GetToken(); // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("appointmentid", appointmentID); postParameters.Add("internalnote", internalNote); //automatically close these docs (or leave out if you want them to be open for review) postParameters.Add("autoclose", "true"); //where to attach? You should modify these for your use case if (attachPDFToVisit) { postParameters.Add("documentsubclass", "ENCOUNTERDOCUMENT_PROGRESSNOTE"); } else { postParameters.Add("documentsubclass", "CLINICALDOCUMENT"); } postParameters.Add("file", new FormUpload.FileParameter(data, appointmentID + ".pdf", "application/pdf")); // Create request and receive response string postURL = Config.MDPUrl.Uri.ToString() + version + "/" + practiceID + "/patients/" + patientID + "/documents"; string userAgent = "Someone"; // The secret sauce: seems meaningless, but userAgent apparently must have a value string webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters, token); return(webResponse); }
public static string SendFile( string mssgBody, string filename, string fileformat, string filepath, string application, string userName, string webhook) { // Read file data FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("filename", filename); postParameters.Add("fileformat", fileformat); postParameters.Add("file", new FormUpload.FileParameter(data, filename, application /*"application/msexcel"*/)); postParameters.Add("username", userName); postParameters.Add("content", mssgBody); // Create request and receive response HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(webhook, defaultUserAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); Debug.Log("Discord: file success"); //return string with response return(fullResponse); }
private static async void Uploads(byte[] paramFileBytes, Action <string> componentText) { var postParameters = new Dictionary <string, object>(); postParameters.Add("file", new FileParameter(paramFileBytes, "file", "application/octet-stream")); postParameters.Add("api_token", "e1d593768b4a52f1f6229de45d64cd2d"); postParameters.Add("return", "timecode,apple_music,deezer,spotify"); var postURL = "https://api.audd.io/recognize"; var userAgent = "Someone"; var webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters); var stream = webResponse.GetResponseStream(); var responseReader = new StreamReader(stream); var fullResponse = responseReader.ReadToEnd(); webResponse.Close(); componentText?.Invoke(fullResponse); }
/// <summary> /// Executes an HTTP post request to the given URI, including the given Dictionary of post parameters as /// multipart/form-data. If cookieCollection is not null, includes the given cookies as a part of the request. /// <seealso cref="FormUpload"/> /// </summary> /// <param name="uri">Absolute URI</param> /// <param name="postParams">String-keyed dictionary of objects to be serialized into multipart/form-data</param> /// <param name="cookieCollection">Optional, cookies to be included with the request.</param> protected static void ExecutePostRequest(string uri, Dictionary <string, object> postParams, CookieCollection cookieCollection = null) { currentJson = null; currentRequest = null; currentResponse = null; CookieContainer jar = new CookieContainer(); if (cookieCollection != null) { jar.Add(cookieCollection); } try { currentResponse = FormUpload.MultipartFormDataPost( uri, "KerbalStuffWrapper by toadicus", postParams, jar ); } catch (WebException ex) { currentResponse = ex.Response as HttpWebResponse; } if (currentResponse.ContentType == "application/json") { var responseReader = new StreamReader(currentResponse.GetResponseStream()); string json = responseReader.ReadToEnd(); currentJson = Json.Deserialize(json); } }
private async Task <string> _uploadFile(FileAttachment at, UploadServerInfo server, string overrideFileName = null, string overrideMimeType = null) { var file = await _downloadFile(at.Url); if (at.MimeType.StartsWith("image/") && at.MimeType != "image/png" && at.MimeType != "image/jpeg" && at.MimeType != "image/gif") { var image = SKImage.FromBitmap(SKBitmap.Decode(file)); using (var p = image.Encode(SKEncodedImageFormat.Png, 100)) using (MemoryStream ms = new MemoryStream()) { p.AsStream().CopyTo(ms); file = ms.ToArray(); overrideMimeType = "image/png"; overrideFileName = "image.png"; } } var postParameters = new Dictionary <string, object> { { "file", new FormUpload.FileParameter(file, overrideFileName ?? at.FileName, overrideMimeType ?? at.MimeType) } }; using (var webResponse = FormUpload.MultipartFormDataPost(server?.UploadUrl, "MeBridgeBot/2", postParameters)) { var responseReader = new StreamReader(webResponse.GetResponseStream() ?? throw new NullReferenceException("Response stream is null")); var fullResponse = responseReader.ReadToEnd(); return(fullResponse); } }
/// <summary> /// Upload image to Imgur. /// </summary> /// <param name="isSocial">Sets if the string is for a social network post.</param> /// <returns>A Task object to be used in async methods</returns> private async Task UploadImage(bool isSocial) { //If string.IsNullOrEmpty(_imgurUrl) == true it means that user hasn't uploaded any images while current program's execution if (string.IsNullOrEmpty(_imgurUrl)) { var cookies = GetCookies(); var imgurData = new ImgurAlbumData(); var imgurImageData = new ImgurImageData(); var errorMessage = string.Empty; ProgressLabel.Content = "Checking captcha"; ProgressLabel.Visibility = Visibility.Visible; GeneralProgressBar.Visibility = Visibility.Visible; //Check if imgur asks for captcha first if (!checkCaptcha(cookies, ref imgurData, ref errorMessage)) { MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else { //We have an OK and album data from imgur to upload images if (imgurData.Success) { //Generate image ProgressLabel.Content = "Generating image"; var file = new FileInfo(CreateImage(true)); if (File.Exists(file.FullName)) { ProgressLabel.Content = "Uploading image"; //Upload image using as a multipart form var task = Task.Factory.StartNew(() => { using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { var data = new byte[fs.Length]; fs.Read(data, 0, data.Length); var postParameters = new Dictionary <string, object> { { "new_album_id", imgurData.Data.NewAlbumId }, { "file", new FormUpload.FileParameter(data, file.Name, MimeMapping.GetMimeMapping(file.FullName)) } }; using (var s = FormUpload.MultipartFormDataPost("http://imgur.com/upload", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", postParameters, cookies) .GetResponseStream()) { if (s != null) { using (var sr = new StreamReader(s, Encoding.UTF8)) { imgurImageData = JsonConvert.DeserializeObject <ImgurImageData>(sr.ReadToEnd()); } } } } }); //Wait for task completion await task; //If it isn't for a social site, show a textbox to allow the user to copy imgur's URL if (!isSocial) { ImgurDataGrid.Visibility = Visibility.Visible; ImgurUrlTxtBx.Text = $"http://imgur.com/{imgurImageData.Data.Hash}"; _imgurUrl = ImgurUrlTxtBx.Text; } //Otherwise store it for future use (to avoid unneeded HTTP calls) else { ImgurUrlTxtBx.Text = $"http://imgur.com/{imgurImageData.Data.Hash}"; _imgurUrl = ImgurUrlTxtBx.Text; } File.Delete(file.FullName); } else { MessageBox.Show("File does not exist on the specified directory!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MessageBox.Show("Try again later!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } ProgressLabel.Content = ""; ProgressLabel.Visibility = Visibility.Hidden; GeneralProgressBar.Visibility = Visibility.Hidden; } else { //Just show a textbox to allow the user to copy imgur's URL if (!isSocial) { ImgurDataGrid.Visibility = Visibility.Visible; } } }
/// <summary> /// Sends the given storage file with the LPImageData combined to the NodeJS server /// </summary> /// <param name="storageFile"> Image file that possibly contains the license plate of a car </param> /// <param name="pImageData"> This contains the location the image, lat and lon, lpImage is not used </param> /// <returns>OpenAlprData that contains the detected plate from an image <see cref="OpenAlprData"/></returns> private OpenAlprData UseOpenAlpr(StorageFile storageFile, LPImageData pImageData) { string CT = "file"; string fullPath = storageFile.Path; FormUpload.FileParameter f = null; for (int i = 1; i < 10; i++) { try { /*Try to read from a file until you succeed*/ f = new FormUpload.FileParameter(File.ReadAllBytes(fullPath), storageFile.Name, "multipart/form-data"); break; } catch (IOException e) { Thread.Sleep(1000 * i); Debug.WriteLine("File Load Exception OPENALPR " + i + " : " + e.ToString()); } } /*Build the post request*/ Dictionary <string, object> d = new Dictionary <string, object>(); d.Add(CT, f); d.Add("detected_lat", pImageData.lat); d.Add("detected_lon", pImageData.lon); string ua = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; /* I Don't know what this does*/ var wr = FormUpload.MultipartFormDataPost("http://localhost:8081/file_upload_alpr", ua, d); WebResponse wresp = null; string result = ""; try { Stream stream2 = wr.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); result = reader2.ReadToEnd(); Debug.WriteLine(string.Format("File uploaded {0}, server response is: {1}", "http://localhost:8081/file_upload_alpr", result)); } catch (Exception ex) { Debug.WriteLine("Error uploading file", ex); if (wresp != null) { wresp.Close(); wresp = null; } } finally { wr = null; } /*Build the response as a OpenAlprData*/ JsonObject jsonObject; OpenAlprData openAlprData = new OpenAlprData(); if (JsonObject.TryParse(result, out jsonObject)) { openAlprData.Parse(jsonObject); } return(openAlprData); }
public string APIKey = Globals.s2Captcha; //api key goes here public string SolveCaptchaV2(string _filePath) { try { if (_domain == "api.captcha.guru") { APIKey = HTMLObjects.sCaptchaGuru; } else if (_domain == "2captcha.com") { APIKey = HTMLObjects.s2Captcha; } byte[] data = System.IO.File.ReadAllBytes(_filePath); string filename = Path.GetFileName(_filePath); Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("filename", filename); postParameters.Add("fileformat", "JPEG"); postParameters.Add("min_len", "0"); postParameters.Add("max_len", "0"); postParameters.Add("header_acao", "0"); postParameters.Add("Access-Control-Allow-Origin", "*"); postParameters.Add("file", new FormUpload.FileParameter(data, filename, "application/msword")); string postURL = "http://" + _domain + "/in.php?key=" + APIKey; string userAgent = APIKey; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); string response = fullResponse; if (response.Length < 3) { return(response); } else { { if (response.Substring(0, 3) == "OK|") { string captchaID = response.Remove(0, 3); for (int i = 0; i < 24; i++) { HttpWebRequest getAnswer = (HttpWebRequest)WebRequest.Create("http://" + _domain + "/res.php?key=" + APIKey + "&action=get&id=" + captchaID); using (HttpWebResponse answerResp = getAnswer.GetResponse() as HttpWebResponse) using (StreamReader answerStream = new StreamReader(answerResp.GetResponseStream())) { string answerResponse = answerStream.ReadToEnd(); if (answerResponse.Length < 3) { return(answerResponse); } else { if (answerResponse.Substring(0, 3) == "OK|") { return(answerResponse.Remove(0, 3)); } else if (answerResponse != "CAPCHA_NOT_READY") { return(answerResponse); } } }Thread.Sleep(5000); } return("Timeout"); } else { return(response); } } } } catch { } return("Unknown error"); }