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(); } }
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); } }
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)); } }
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(); }
protected async Task <T> BeforeSendRequestUploadFile <T, TInput>(string apiPath, Dictionary <string, object> postParameters, int userId) where T : MCResponseModelBase { _requestMessage = new HttpRequestMessage(); _requestMessage.Headers.Add("xdncode", _xdnCode); var token = await GetUserToken(userId); try { string requestURL = $"{_baseUrl}/{apiPath}"; string userAgent = "vietbank"; postParameters.Add("token", token); var response = await FormUpload.MultipartFormPost <T>(requestURL, userAgent, postParameters, "xdncode", _xdnCode, token); await _rpLog.InsertLog($"BeforeSendRequestUploadFile - {apiPath}", response == null? "response = null" : response.Dump()); return(response.Data); } catch (Exception exp) { await _rpLog.InsertLog($"BeforeSendRequestUploadFile - {apiPath}", exp.InnerException == null?exp.Dump() : exp.InnerException.Dump()); 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 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); }
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 CreatePackagePage() { InitializeComponent(); //#if DEBUG // requestURL = "https://us-central1-e0-rasvada.cloudfunctions.net/PageExpDisplay"; //#endif experiences = new ExperiencesList { Experience = new List <Experience> { new Experience() { Seasons = new List <string>() { } } } }; experiencesinpackage = new ExperiencesList { Experience = new List <Experience> { new Experience() { Seasons = new List <string>() { } } } }; experiencesinpackage.Experience.Clear(); try { Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("UserId", Application.Current.Properties["User"]); HttpWebResponse webResponse = FormUpload.MultipartFormPost(requestURL, "someone", postParameters, "", ""); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string returnResponseText = responseReader.ReadToEnd(); //rassavadaEntity = JsonConvert.DeserializeObject<RassavadaEntity>(returnResponseText); experiences = JsonConvert.DeserializeObject <ExperiencesList>(returnResponseText); webResponse.Close(); } catch (Exception e) { DisplayAlert("No Internet", "Please check your internet connection", "Ok"); } PlaceCollectionView.ItemsSource = experiences.Experience; }
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)); }
// GET: FormUploads/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } //FormUpload formUpload = db.FormUploads.Find(id); FormUpload formUpload = formUploadService.GetById((int)id); if (formUpload == null) { return(HttpNotFound()); } return(View(formUpload)); }
public IActionResult UploadFile(FormUpload formupload) { string strpath = System.IO.Path.GetExtension(formupload.myform.FileName); if (formupload.myform != null && (strpath == ".jpg" || strpath == ".jpeg" || strpath == ".gif" || strpath == ".png")) { { string filepath = $"{_env.WebRootPath}/images/{formupload.myform.FileName}"; var stream = System.IO.File.Create(filepath); formupload.myform.CopyTo(stream); return(Redirect("/FormUpload/Success")); } } return(Redirect("/FormUpload/Error")); }
public App() { string returnResponseText = ""; InitializeComponent(); APIHelper.InitialiseClient(); try { //#if DEBUG // requestURL = "https://us-central1-e0-rasvada.cloudfunctions.net/Register"; //#endif requestURL = "https://us-central1-e0-trouvailler.cloudfunctions.net/Register"; Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("UserId", Application.Current.Properties["User"]); HttpWebResponse webResponse = FormUpload.MultipartFormPost(requestURL, "someone", postParameters, "", ""); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); returnResponseText = responseReader.ReadToEnd(); webResponse.Close(); } catch (Exception e) { } //MainPage = new NavigationPage(new HomePage(new Models.RassavadaEntity() { })) if (Application.Current.Properties.ContainsKey("User")) { if (returnResponseText == "true") { MainPage = new NavigationPage(new HomePage()) { BarBackgroundColor = Color.FromHex("#0BBE22") }; } else { MainPage = new NavigationPage(new GetStartedPage()) { BarBackgroundColor = Color.FromHex("#0BBE22") }; } } else { MainPage = new NavigationPage(new LoginPage()) { BarBackgroundColor = Color.FromHex("#0BBE22") }; } }
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); }
// 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); }
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); } }
private async void Next(object sender, EventArgs e) { try { if (CostEntry.Text != "" && DetailEntry.Text != "" && NameEntry.Text != "") { await PopupNavigation.Instance.PushAsync(new LoadingPopup()); SaveSvg.IsEnabled = false; //package.Cost = float.Parse(CostEntry.Text); package.Detail = DetailEntry.Text; package.Name = NameEntry.Text; package.Cost = CostEntry.Text; var json = JsonConvert.SerializeObject(package); Dict = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); postParameters = Dict; postParameters.Add("UserId", Application.Current.Properties["User"]); HttpWebResponse webResponse = FormUpload.MultipartFormPost(requestURL, "someone", postParameters, "", ""); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); var returnResponseText = responseReader.ReadToEnd(); //postParameters. webResponse.Close(); await Navigation.PopToRootAsync(); Refresh.RefreshHome(); await PopupNavigation.Instance.PopAllAsync(); } else { await DisplayAlert("Complete form", "Please enter all the data to submit.", "Ok"); } } catch (Exception w) { await DisplayAlert("Server Down", "Please try again later", "Ok"); SaveSvg.IsEnabled = true; await PopupNavigation.Instance.PopAsync(); } }
private bool GetDetails() { try { Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("UserId", Application.Current.Properties["User"]); HttpWebResponse webResponse = FormUpload.MultipartFormPost(requestURL, "someone", postParameters, "", ""); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string returnResponseText = responseReader.ReadToEnd(); rassavadaEntity = JsonConvert.DeserializeObject <RassavadaEntity>(returnResponseText); webResponse.Close(); return(true); } catch (Exception e) { DisplayAlert("Server Error", "Please check your internet connection and try again", "Ok"); return(false); } }
public TransactionResult RemoveItemGallery(string userID, Guid itemId, string url) { try { var item = _dbContext.Item.FirstOrDefault(i => i.Id == itemId && i.UserId == userID); if (item != null) { if (item.ImageUrl == url) { item.ImageUrl = null; } else if (item.ImageUrl2 == url) { item.ImageUrl2 = null; } else if (item.ImageUrl3 == url) { item.ImageUrl3 = null; } else if (item.ImageUrl4 == url) { item.ImageUrl4 = null; } else if (item.ImageUrl5 == url) { item.ImageUrl5 = null; } _dbContext.SaveChanges(); var upload = new FormUpload(_environment.WebRootPath); upload.RemoveFile(url, "itemgallery"); } return(new TransactionResult(type: TransactionType.Success)); } catch { return(new TransactionResult(message: "Beklenmedik bir hata oluştu. Lütfen tekrar deneyiniz.", type: TransactionType.Error)); } }
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 JsonResult UploadImage(IFormFile file, PageContentTypes type, string itemid, string filename) { filename = Path.GetFileNameWithoutExtension(filename); var upload = new FormUpload(_environment.WebRootPath); if (file != null) { switch (type) { case PageContentTypes.Campaign: upload.SaveFile(file, filename, "campaign"); break; case PageContentTypes.Category: upload.SaveFile(file, filename, "categoryheader"); break; } } return(Json("OK")); }
// [{ "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 (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!"); } }
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); }
private async void PermisionValidator() { status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationWhenInUse); try { //#if DEBUG // requestURL = "https://us-central1-e0-rasvada.cloudfunctions.net/Register"; //#endif requestURL = "https://us-central1-e0-trouvailler.cloudfunctions.net/Register"; Dictionary <string, object> postParameters = new Dictionary <string, object>(); postParameters.Add("UserId", Application.Current.Properties["User"]); HttpWebResponse webResponse = FormUpload.MultipartFormPost(requestURL, "someone", postParameters, "", ""); StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string returnResponseText = responseReader.ReadToEnd(); webResponse.Close(); if (status == PermissionStatus.Granted) { if (returnResponseText == "false") { await Navigation.PushAsync(new GetStartedPage()); } else { App.Current.MainPage = new NavigationPage(new HomePage()); await Navigation.PopToRootAsync(); } } else { await DisplayAlert("Need Permissions", "You must grant us location permissions to use this app", "ok"); GetPermisions(); } } catch (Exception e) { await DisplayAlert("Connection Error", "Please check your internet connection", "Ok"); } }
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); }
// 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); }