private void UploadFile(string fileName, Stream data) { UriBuilder ub = new UriBuilder("/Image/UploadFile"); ub.Query = string.Format("filename={0}", fileName); WebClient c = new WebClient(); c.OpenWriteCompleted += (sender, e) => { PushData(data, e.Result); e.Result.Close(); data.Close(); }; c.OpenWriteAsync(ub.Uri); }
public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data, NameValueCollection values) { System.Net.WebClient webclient = new System.Net.WebClient(); // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file" //webclient.Download * (...); // Any method starting with "Download" webclient.DownloadData(address); // Noncompliant webclient.DownloadDataAsync(uriAddress, new object()); // Noncompliant webclient.DownloadDataTaskAsync(uriAddress); // Noncompliant webclient.DownloadFile(address, "filename"); // Noncompliant webclient.DownloadFileAsync(uriAddress, "filename"); // Noncompliant webclient.DownloadFileTaskAsync(address, "filename"); // Noncompliant webclient.DownloadString(uriAddress); // Noncompliant webclient.DownloadStringAsync(uriAddress, new object()); // Noncompliant webclient.DownloadStringTaskAsync(address); // Noncompliant // Should not raise for events webclient.DownloadDataCompleted += Webclient_DownloadDataCompleted; webclient.DownloadFileCompleted += Webclient_DownloadFileCompleted; webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged; webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted; //webclient.Open * (...); // Any method starting with "Open" webclient.OpenRead(address); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Make sure that this http request is sent safely.}} webclient.OpenReadAsync(uriAddress, new object()); // Noncompliant webclient.OpenReadTaskAsync(address); // Noncompliant webclient.OpenWrite(address); // Noncompliant webclient.OpenWriteAsync(uriAddress, "STOR", new object()); // Noncompliant webclient.OpenWriteTaskAsync(address, "POST"); // Noncompliant webclient.OpenReadCompleted += Webclient_OpenReadCompleted; webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted; //webclient.Upload * (...); // Any method starting with "Upload" webclient.UploadData(address, data); // Noncompliant webclient.UploadDataAsync(uriAddress, "STOR", data); // Noncompliant webclient.UploadDataTaskAsync(address, "POST", data); // Noncompliant webclient.UploadFile(address, "filename"); // Noncompliant webclient.UploadFileAsync(uriAddress, "filename"); // Noncompliant webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant webclient.UploadString(uriAddress, "data"); // Noncompliant webclient.UploadStringAsync(uriAddress, "data"); // Noncompliant webclient.UploadStringTaskAsync(uriAddress, "data"); // Noncompliant webclient.UploadValues(address, values); // Noncompliant webclient.UploadValuesAsync(uriAddress, values); // Noncompliant webclient.UploadValuesTaskAsync(address, "POST", values); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Should not raise for events webclient.UploadDataCompleted += Webclient_UploadDataCompleted; webclient.UploadFileCompleted += Webclient_UploadFileCompleted; webclient.UploadProgressChanged -= Webclient_UploadProgressChanged; webclient.UploadStringCompleted -= Webclient_UploadStringCompleted; webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted; }
protected void button2_Click(object sender, EventArgs e) { //FileUpload fi = FileUpload1; //byte[] bt = fi.FileBytes;//获取文件的Byte[] //ms = new MemoryStream(bt);//用Byte[],实例化ms UriBuilder url = new UriBuilder("http://localhost:81/test/uploadfile.ashx");//上传路径 url.Query = string.Format("filename={0}", Path.GetFileName("ttttt.tt"));//上传url参数 WebClient wc = new WebClient(); wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);//委托异步上传事件 wc.OpenWriteAsync(url.Uri);//开始异步上传 }
private void UploadFiles(MyFileInfo mfi, System.IO.FileStream data) { UriBuilder ub = new UriBuilder("http://localhost:3793/receiver.ashx"); ub.Query = string.Format("filename={0}&name={1}&address={2}&email={3}&golfid={4}", mfi.Name, fixText(txtName.Text), fixText(txtAdress.Text), fixText(txtEmail.Text), fixText(txtGolfID.Text)); //ub.Query = string.Format("filename={0}", mfi.Name); WebClient wc = new WebClient(); wc.OpenWriteCompleted += (sender, e) => { PushData(data, e.Result, mfi); e.Result.Close(); data.Close(); lbl.Text = "Fil(er) uppladdade!"; }; wc.OpenWriteAsync(ub.Uri); }
/// <summary>Opens a writeable stream for uploading data to a resource, asynchronously.</summary> /// <param name="webClient">The WebClient.</param> /// <param name="address">The URI for which the stream should be opened.</param> /// <param name="method">The HTTP method that should be used to open the stream.</param> /// <returns>A Task that contains the opened stream.</returns> public static Task <Stream> OpenWriteTask(this WebClient webClient, Uri address, string method) { TaskCompletionSource <Stream> tcs = new TaskCompletionSource <Stream>(address); OpenWriteCompletedEventHandler handler = null; handler = delegate(object sender, OpenWriteCompletedEventArgs e) { EAPCommon.HandleCompletion <Stream>(tcs, e, () => e.Result, delegate { webClient.OpenWriteCompleted -= handler; }); }; webClient.OpenWriteCompleted += handler; try { webClient.OpenWriteAsync(address, method, tcs); } catch (Exception exception) { webClient.OpenWriteCompleted -= handler; tcs.TrySetException(exception); } return(tcs.Task); }
private void Button_Click(object sender, RoutedEventArgs e) { this.Dispatcher.BeginInvoke(() => { FrameBorder.Visibility = Visibility.Collapsed; ResultBorder.Visibility = Visibility.Visible; }); Uri serviceUri = new Uri(Defines.BaseUri + "/services/account/uploadphoto"); WebClient client = new WebClient(); client.WriteStreamClosed += new WriteStreamClosedEventHandler((o, args) => { loadingTextBlock.Visibility = Visibility.Collapsed; resultPanel.Visibility = Visibility.Visible; Defines.MainPage.RefreshUserInfo(); }); client.OpenWriteCompleted += new OpenWriteCompletedEventHandler((o, args) => { WriteableBitmap bmp = new WriteableBitmap(frame.Source as BitmapSource); Stream encoded = bmp.ToImage().ToStreamByExtension("png"); encoded.Seek(0, SeekOrigin.Begin); byte[] data = new byte[encoded.Length]; encoded.Read(data, 0, (int)encoded.Length); args.Result.Write(data, 0, (int)data.Length); args.Result.Flush(); args.Result.Close(); }); client.OpenWriteAsync(serviceUri, "POST"); resultPhoto.Source = frame.Source; }
//保存照片 public void SaveImage() { DefaultCaputerSource dcs = Application.Current.Resources[DefaultCaputerName] as DefaultCaputerSource; if (dcs.CutImage != null) { IsBusy = true; if (tempid == null) { tempid = System.Guid.NewGuid().ToString(); } byte[] by = Convert.FromBase64String(GetBase64Image(dcs.CutImage)); Stream sr = new MemoryStream(by); WebClient webclient = new WebClient(); Uri uri = new Uri(Path + "?FileName=" + FileName + "&BlobId=" + tempid + "&EntityName=" + EntityName); webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted); webclient.Headers["Content-Type"] = "multipart/form-data"; webclient.OpenWriteAsync(uri, "POST", sr); webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed); } else { MessageBox.Show("请拍照!"); } }
private void guardarImagen() { WebClient client = new WebClient(); client.WriteStreamClosed += (s, a) => { if (a.Error == null) { //El archivo fue subido correctamente } }; client.OpenWriteCompleted += (s, a) => { if (a.Error == null) { //El Stream ha sido abierto correctamente //Escribe la secuencia de bytes en el Stream abierto Stream stream = a.Result; stream.Write(bytes, 0, bytes.Length); stream.Flush(); stream.Close(); } }; //Abre un Stream de escritura client.OpenWriteAsync(new Uri(string.Format("/Upload.aspx?n={0}", fileName), UriKind.RelativeOrAbsolute)); }
private void UploadImage(PhotoResult e) { //ShowProgress = true; byte[] sbytedata = ReadToEnd(e.ChosenPhoto); string s = sbytedata.ToString(); albId = app.albums[app.selectedAlbumIndex].id; username = (string)appSettings["myEmail"]; username = username.Substring(0, username.IndexOf("@"));// Get the username part of the email, without @ WebClient webClient = new WebClient(); string auth = "GoogleLogin auth=" + app.auth; webClient.Headers[HttpRequestHeader.Authorization] = auth; webClient.Headers[HttpRequestHeader.ContentType] = "image/jpeg"; //webClient.Headers[HttpRequestHeader.ContentLength]=(string) e.ChosenPhoto.Length; Uri uri = new Uri(string.Format("https://picasaweb.google.com/data/feed/api/user/{0}/albumid/{1}", username, albId)); webClient.AllowReadStreamBuffering = true; webClient.AllowWriteStreamBuffering = true; webClient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webClient_OpenWriteCompleted); webClient.OpenWriteAsync(uri, "POST", sbytedata); }
//private void MenuGroupReName_Click(object sender, RoutedEventArgs e) //{ // StackPanel stk = currentGroupStack; // TextBox tb = stk.FindName("txtGroupName") as TextBox; // TextBlock tblock = stk.FindName("tblkGroupName") as TextBlock; // tblock.Visibility = System.Windows.Visibility.Collapsed; // tb.Visibility = Visibility.Visible; // tb.Focus(); //} //private void StackPanel_MouseEnter(object sender, MouseEventArgs e) //{ //currentGroup = (sender as StackPanel).DataContext as tblProjectGroup; //currentGroupStack = sender as StackPanel; // treeView1.SelectItem(currentGroup); //} //private void txtGroupName_LostFocus(object sender, RoutedEventArgs e) //{ // StackPanel stk = (sender as TextBox).Parent as StackPanel; // TextBox tb = stk.FindName("txtGroupName") as TextBox; // TextBlock tblock = stk.FindName("tblkGroupName") as TextBlock; // tblock.Visibility = System.Windows.Visibility.Visible; // tb.Visibility = Visibility.Collapsed; // //} public static void SendFile(slPanel.Web.tblProjectGroup group, int projectid) { System.Windows.Controls.OpenFileDialog d = new OpenFileDialog(); d.Filter = "Image (*.png, *.jpg) |*.png;*.jpg"; // d.ShowDialog(); //try //{ // string filename = d.File.FullName; //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); // return; //} if (d.ShowDialog() == true) { Stream stream = d.File.OpenRead(); Uri u = new Uri(Application.Current.Host.Source, "../Upload.ashx/?filename=" + d.File.Name + "&projectid=" + projectid); // MessageBox.Show(u.ToString()); byte[] buffer = new byte[d.File.Length]; stream.Read(buffer, 0, (int)d.File.Length); stream.Close(); WebClient wc = new WebClient(); wc.OpenWriteCompleted += (s, ee) => { if (ee.Error != null) { MessageBox.Show(ee.Error.Message); return; } Stream outputStream = ee.Result; outputStream.Write(buffer, 0, buffer.Length); outputStream.Close(); MessageBox.Show("檔案上傳完成!"); group.GroupPicture = d.File.Name; group.IsPictureDownload = true; //System.Windows.Media.Imaging.BitmapImage img = new System.Windows.Media.Imaging.BitmapImage(new Uri(group.PicUrl)); }; wc.OpenWriteAsync(u); } }
void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.TaskResult != TaskResult.OK) { return; } WebClient webClient = new WebClient(); webClient.OpenWriteCompleted += (s, args) => { using (BinaryReader br = new BinaryReader(e.ChosenPhoto)) { using (BinaryWriter bw = new BinaryWriter(args.Result)) { long bCount = 0; long fileSize = e.ChosenPhoto.Length; byte[] bytes = new byte[2 * 1024]; do { bytes = br.ReadBytes(2 * 1024); bCount += bytes.Length; bw.Write(bytes); } while (bCount < fileSize); } } }; webClient.WriteStreamClosed += webClient_WriteStreamClosed; webClient.OpenWriteAsync(new Uri("http://www.cnblogs.com")); }
/// <summary> /// WebClient上传文件至服务器 /// </summary> /// <param name="fileNameFullPath">要上传的文件(全路径格式)</param> /// <param name="strUrlDirPath">Web服务器文件夹路径</param> public void UpLoadFile2( string fileNameFullPath, string saveFileName, string strUrlDirPath) { myFileStream = new FileStream(fileNameFullPath, FileMode.Open, FileAccess.Read); myBinaryReader = new BinaryReader(myFileStream); UriBuilder url = new UriBuilder(strUrlDirPath);//上传路径 url.Query = string.Format("filename={0}", saveFileName);//上传url参数 WebClient webClient = new WebClient(); webClient.OpenWriteCompleted+= new OpenWriteCompletedEventHandler(webClient_OpenWriteCompleted);//委托异步上传事件 webClient.Headers["User-Agent"] = "blah"; webClient.Credentials = CredentialCache.DefaultCredentials; webClient.OpenWriteAsync(url.Uri); }
private void UploadChunk(System.Uri uri , System.IO.Stream fs , System.ComponentModel.BackgroundWorker worker , System.ComponentModel.DoWorkEventArgs e, int chunkNumber, bool finished, Chunk addedChunk) { try { long length = fs.Length; byte[] buffer; int position = 0; int packetSize = 500 * 1024; System.UriBuilder ub = new System.UriBuilder(uri); if (ub.Query == string.Empty) { ub.Query = "chunk=" + chunkNumber; } else { ub.Query = ub.Query.TrimStart('?') + "&chunk=" + chunkNumber; } if (ub.Query == string.Empty) { ub.Query = "finished=" + (finished?1:0); } else { ub.Query = ub.Query.TrimStart('?') + "&finished=" + (finished?1:0); } while (position < length) { ub.Query = ub.Query.Replace("completed=1", "").Replace("completed=0", ""); if (position + packetSize > length) { buffer = new byte[length - position]; // If this is the last buffer for this file.. // .. set the completed flag for the handler //System.UriBuilder ub = new System.UriBuilder(uri); if (ub.Query == string.Empty) { ub.Query = "completed=1"; } else { ub.Query = ub.Query.TrimStart('?') + "&completed=1"; } uri = ub.Uri; } else { buffer = new byte[packetSize]; if (ub.Query == string.Empty) { ub.Query = "completed=0"; } else { ub.Query = ub.Query.TrimStart('?') + "&completed=0"; } uri = ub.Uri; } fs.Read(buffer, 0, buffer.Length); position += buffer.Length; // Mutex to ensure packets are sent in order System.Threading.AutoResetEvent mutex = new System.Threading.AutoResetEvent(false); System.Net.WebClient wc = new System.Net.WebClient(); wc.OpenWriteCompleted += (wc_s, wc_e) => { UploadPacketToHandler(buffer, wc_e.Result); currentDispatcher.BeginInvoke(() => { if (ub.Query.Contains("completed=1")) { addedChunk.IsDecompressing = true; } }); }; wc.WriteStreamClosed += (ws_s, ws_e) => { currentDispatcher.BeginInvoke(() => { addedChunk.SizeTransferred = position; if (ub.Query.Contains("completed=1")) { addedChunk.IsDecompressed = true; addedChunk.IsDecompressing = false; } }); mutex.Set(); }; wc.OpenWriteAsync(uri); mutex.WaitOne(); } fs.Close(); } catch (Exception ex) { //Handle errors here } }
private void UploadImage(ExtendedImage image) { var webClient = new WebClient(); webClient.OpenWriteCompleted += (sender, e) => { if (e.Error == null) { var pngEncoder = new PngEncoder(); using (e.Result) { pngEncoder.Encode(image, e.Result); } } }; webClient.WriteStreamClosed += (sender, e) => { if (e.Error == null) { MessageBox.Show("Image uploaded successfully"); } }; webClient.OpenWriteAsync(new Uri("http://localhost:5637/Wafers/UploadImage", UriKind.Absolute), "POST"); }
public void OpenWriteAsync_UserToken () { WebClient wc = new WebClient (); bool complete = false; int tid = Thread.CurrentThread.ManagedThreadId; wc.OpenWriteCompleted += delegate (object sender, OpenWriteCompletedEventArgs e) { Assert.AreEqual (Thread.CurrentThread.ManagedThreadId, tid, "ManagedThreadId"); CheckDefaults (wc); Assert.IsFalse (e.Cancelled, "Cancelled"); Assert.IsNull (e.Error, "Error"); Assert.AreEqual (String.Empty, e.UserState, "UserState"); CheckStream (e.Result, false, "Result.Before"); e.Result.Close (); CheckStream (e.Result, true, "Result.After"); complete = true; }; Enqueue (() => { wc.OpenWriteAsync (new Uri ("http://www.mono-project.com"), null, String.Empty); }); EnqueueConditional (() => complete); EnqueueTestComplete (); }
public static void SaveSettings() { JObject j = JObject.FromObject(Store); j.Add("FavLists", new JObject()); if (Store.FavLists != null) { foreach (FavList favList in Store.FavLists) { ((JObject) j["FavLists"]).Add(favList.HtmlName, JArray.FromObject(favList)); } } Uri uri = new Uri(String.Format("http://{0}/store.sh", AppSettings.IPAddress)); WebClient c = new WebClient(); c.OpenWriteCompleted += (sender, args) => { if (args.Error != null) return; using (StreamWriter sw = new StreamWriter(args.Result)) { sw.Write(j.ToString()); } }; c.OpenWriteAsync(uri); }
/// <summary> /// Uploads the file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="data">The data.</param> private async void UploadFile(string fileName, Stream data) { var systemPathInfo = new SystemPathsInfo(); SystemPathsInfo sysPathInfo; try { sysPathInfo = await systemPathInfo.BeginGetSystemPathsAsync(); } catch (Exception ex) { if (Debugger.IsAttached) { Debug.WriteLine(ex); Debugger.Break(); } return; } if (!Uri.IsWellFormedUriString(sysPathInfo.FileUploadURI, UriKind.Absolute)) return; var uri = new Uri(sysPathInfo.FileUploadURI); var docHandlerUrl = string.Format("{0}://{1}:{2}/{3}DocHandler.ashx", uri.Scheme, uri.Host, uri.Port, uri.LocalPath.Substring(1, uri.LocalPath.LastIndexOf("/", StringComparison.Ordinal))); var ub = new UriBuilder(docHandlerUrl) { Query = string.Format("LicenseFileName={0}", fileName) }; var c = new WebClient(); c.OpenWriteCompleted += (s1, e) => { PushData(data, e.Result); e.Result.Close(); data.Close(); }; c.OpenWriteAsync(ub.Uri); }
public void OpenWriteAsync_CloseStream () { WebClient wc = new WebClient (); bool complete_open = false; bool complete_close = false; int tid = Thread.CurrentThread.ManagedThreadId; wc.OpenWriteCompleted += delegate (object sender, OpenWriteCompletedEventArgs e) { CheckStream (e.Result, false, "Result.Before"); e.Result.Close (); CheckStream (e.Result, true, "Result.After"); complete_open = true; }; wc.WriteStreamClosed += delegate (object sender, WriteStreamClosedEventArgs e) { Assert.AreSame (wc, sender, "Sender"); Assert.AreEqual (Thread.CurrentThread.ManagedThreadId, tid, "ManagedThreadId"); CheckDefaults (wc); Assert.IsTrue (e.Error is SecurityException, "Error"); complete_close = true; }; Enqueue (() => { wc.OpenWriteAsync (new Uri ("http://www.mono-project.com"), null); }); EnqueueConditional (() => complete_open && complete_close); EnqueueTestComplete (); }
private void UploadFile(string fileName, FileStream fileStream, Image myImage) { UriBuilder ub = new UriBuilder(new Uri(App.Current.Host.Source,"../Image/SLUpload")); ub.Query = string.Format("filename={0}&Mag_id={1}&Mag_Issue={2}&Shoot={3}&ShootDate={4}&keywords={5}&description={6}&photographer={7}", fileName, myImage.Magid.ToString(), myImage.MagIssue, myImage.Shoot, myImage.ShootDate.ToString("dd-MMM-yyyy"), myImage.keywords, myImage.description, myImage.photographer ); WebClient c = new WebClient(); c.OpenWriteCompleted += (sender, e) => { PushData(fileStream, e.Result); e.Result.Close(); fileStream.Close(); }; c.OpenWriteAsync(ub.Uri); c.WriteStreamClosed += (sender, e) => { //MessageBox.Show(e.Error.Message); HtmlPage.Window.Navigate(new Uri(App.Current.Host.Source, "../")); }; }
private void UploadSysInfo(string text) { UriBuilder ub = new UriBuilder(_baseUrl + SysinfoUploadHandler); UnicodeEncoding encoding = new UnicodeEncoding(); byte[] bytes = encoding.GetBytes(text); MemoryStream readStream = new MemoryStream(bytes); WebClient webClient = new WebClient(); webClient.OpenWriteCompleted += (o, args) => { PushDataForSysInfo(readStream, args.Result); args.Result.Close(); readStream.Close(); }; webClient.OpenWriteAsync(ub.Uri); }
private void UploadNewPhoto(Stream stream) { const int BLOCK_SIZE = 4096; string AuthToken = App.auth; SetProgessIndicator(true); SystemTray.ProgressIndicator.Text = AppResources.showupload; if (AlbumIndex != -1) { Uri uri = new Uri(app.albums[AlbumIndex].href, UriKind.Absolute); WebClient wc = new WebClient(); wc.Headers[HttpRequestHeader.Authorization] = "GoogleLogin auth=" + AuthToken; wc.Headers[HttpRequestHeader.ContentLength] = stream.Length.ToString(); wc.Headers[HttpRequestHeader.ContentType] = "image/jpeg"; wc.AllowReadStreamBuffering = true; wc.AllowWriteStreamBuffering = true; wc.OpenWriteCompleted += (s, args) => { using (BinaryReader br = new BinaryReader(stream)) { using (BinaryWriter bw = new BinaryWriter(args.Result)) { long bCount = 0; long fileSize = stream.Length; byte[] bytes = new byte[BLOCK_SIZE]; do { bytes = br.ReadBytes(BLOCK_SIZE); bCount += bytes.Length; bw.Write(bytes); } while (bCount < fileSize); } } }; // Uploading is complete wc.WriteStreamClosed += (s, args) => { // MessageBox.Show(AppResources.photouploaded); SetProgessIndicator(false); GetImages(AlbumIndex); }; wc.OpenWriteAsync(uri, "POST"); } }
/// <summary> /// Uploads the file. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="data">The data.</param> /// <param name="sysOptions">The system options.</param> private static void UploadFile(string fileName, Stream data, ISystemOptionsInfo sysOptions) { if (!Uri.IsWellFormedUriString(sysOptions.FileProcessorURI, UriKind.Absolute)) return; var uri = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}?FileName={1}", sysOptions.FileProcessorURI, fileName)); using (var c = new WebClient()) { c.OpenWriteCompleted += (s1, e) => { var buffer = new byte[4096]; int bytesRead; while ((bytesRead = data.Read(buffer, 0, buffer.Length)) != 0) e.Result.Write(buffer, 0, bytesRead); e.Result.Close(); data.Dispose(); }; c.OpenWriteAsync(uri); } }
private void UploadFile(Stream data) { UriBuilder ub = new UriBuilder(_baseUrl + FileUploadHandler); WebClient webClient = new WebClient(); webClient.OpenWriteCompleted += (o, args) => { PushData(data, args.Result); args.Result.Close(); data.Close(); }; webClient.OpenWriteAsync(ub.Uri); }
public void OpenWriteAsync_MainThread () { DependencyObject TestPanel = this.TestPanel; Thread main_thread = Thread.CurrentThread; AssertFailedException afe = null; bool done = false; /* Check that the OpenWriteAsync events are executed on the main thread when the request was done on the main thread */ WebClient wc = new WebClient (); if (!RunningFromHttp) { EnqueueTestComplete (); return; } wc.UploadProgressChanged += new UploadProgressChangedEventHandler (delegate (object sender, UploadProgressChangedEventArgs dpcea) { try { Assert.IsTrue (TestPanel.CheckAccess ()); Assert.AreEqual (main_thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, "Equal thread ids in UploadProgressChanged"); } catch (AssertFailedException e) { afe = e; } }); wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler (delegate (object sender, OpenWriteCompletedEventArgs orcea) { try { Assert.IsTrue (TestPanel.CheckAccess ()); Assert.AreEqual (main_thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, "Equal thread ids in OpenWriteCompleted"); } catch (AssertFailedException e) { afe = e; } finally { done = true; } }); wc.WriteStreamClosed += new WriteStreamClosedEventHandler (delegate (object sender, WriteStreamClosedEventArgs wscea) { try { Assert.IsTrue (TestPanel.CheckAccess ()); Assert.AreEqual (main_thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, "Equal thread ids in WriteStreamClosed"); } catch (AssertFailedException e) { afe = e; } }); wc.OpenWriteAsync (IndexHtml); EnqueueConditional (() => done); Enqueue (() => { if (afe != null) throw afe; }); EnqueueTestComplete (); }
private void UploadFile(WebClient c, Stream data, string account) { var url = String.Format("https://picasaweb.google.com/data/feed/api/user/{0}/albumid/5606723136600202209", account); c.OpenWriteCompleted += (sender, e) => { PushData(data, e.Result); e.Result.Close(); data.Close(); }; c.WriteStreamClosed += (o, args) => { if (args.Error == null) { MessageBox.Show("Upload completed!"); } else { MessageBox.Show("Upload Error"); } }; Console.WriteLine("123"); c.OpenWriteAsync(new Uri(url)); }
public void OpenWriteAsync_Null () { WebClient wc = new WebClient (); wc.OpenWriteCompleted += delegate (object sender, OpenWriteCompletedEventArgs e) { Assert.Fail ("not called"); }; Uri uri = new Uri ("http://www.mono-project.com"); // note: null method == POST Assert.Throws<ArgumentNullException> (delegate { wc.OpenWriteAsync (null, "POST"); }, "null,POST"); Assert.Throws<ArgumentNullException> (delegate { wc.OpenWriteAsync (null, "POST", String.Empty); }, "null,POST,object"); }
public void Upload(Uri uri, Stream content) { OnProgress(0); try { var client = new WebClient(); client.OpenWriteCompleted += (s, args) => { var writeStream = args.Result; var totalLength = content.Length; var uploadedByteCount = 0; byte[] chunk; while (uploadedByteCount < totalLength) { chunk = new byte[ uploadedByteCount + ChunkSize < totalLength ? ChunkSize : totalLength - uploadedByteCount]; writeStream.Write(chunk, 0, chunk.Length); uploadedByteCount += chunk.Length; OnProgress(uploadedByteCount/(decimal) totalLength); } }; client.OpenWriteAsync(uri, "post"); } catch (Exception ex) { throw new UploadException("Upload failed", ex); } }
public void OpenWriteAsync_BadMethod () { WebClient wc = new WebClient (); bool complete = false; wc.OpenWriteCompleted += delegate (object sender, OpenWriteCompletedEventArgs e) { CheckDefaults (wc); Assert.IsFalse (e.Cancelled, "Cancelled"); Assert.IsTrue (e.Error is WebException, "Error"); Assert.IsTrue (e.Error.InnerException is NotSupportedException, "Error.InnerException"); Assert.IsNull (e.UserState, "UserState"); Assert.Throws<TargetInvocationException, WebException> (delegate { Assert.IsNotNull (e.Result, "Result"); }, "Result"); complete = true; }; Enqueue (() => { wc.OpenWriteAsync (new Uri ("http://www.mono-project.com"), "ZAP"); }); EnqueueConditional (() => complete); EnqueueTestComplete (); }
public void UpLoadNOFileName() { if (tempid == null) { tempid = System.Guid.NewGuid().ToString(); } OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = Filter, }; if (openFileDialog.ShowDialog() == true) { State = State.StartLoad; FileInfo fi = openFileDialog.File; // MessageBox.Show(fi.Length + "|||" + Int32.Parse(Limit) * 1000); //判断附件大小 if (Limit != null) { if (fi.Length > Int32.Parse(Limit) * 1000) { MessageBox.Show(fi.Name + "附件大小超过限制,不能上传!"); State = State.LoadError; return; } } this.FileName = fi.Name; StreamReader sr = fi.OpenText(); WebClient webclient = new WebClient(); Uri uri = new Uri(Path); webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted); webclient.Headers["Content-Type"] = "multipart/form-data"; webclient.OpenWriteAsync(uri, "POST", fi.OpenRead()); webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed); } }
public void OpenWriteAsync_UserThread () { DependencyObject TestPanel = this.TestPanel; Thread main_thread = Thread.CurrentThread; AssertFailedException afe = null; bool done = false; /* Check that the OpenWriteAsync events are executed on a threadpool thread when the request was not done on the main thread */ WebClient wc = new WebClient (); if (new Uri (wc.BaseAddress).Scheme != "http") { EnqueueTestComplete (); return; } wc.UploadProgressChanged += new UploadProgressChangedEventHandler (delegate (object sender, UploadProgressChangedEventArgs dpcea) { try { Assert.IsFalse (TestPanel.CheckAccess ()); Assert.AreNotEqual (main_thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, "Equal thread ids in UploadProgressChanged"); } catch (AssertFailedException e) { afe = e; done = true; } }); wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler (delegate (object sender, OpenWriteCompletedEventArgs orcea) { try { Assert.IsFalse (TestPanel.CheckAccess ()); Assert.AreNotEqual (main_thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, "Different thread ids in OpenWriteCompleted"); done = true; } catch (AssertFailedException e) { afe = e; done = true; } }); wc.WriteStreamClosed += new WriteStreamClosedEventHandler (delegate (object sender, WriteStreamClosedEventArgs wscea) { try { Assert.IsFalse (TestPanel.CheckAccess ()); Assert.AreNotEqual (main_thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, "Different thread ids in WriteStreamClosed"); } catch (AssertFailedException e) { afe = e; done = true; } }); Thread t = new Thread (delegate () { wc.OpenWriteAsync (new Uri ("index.html", UriKind.Relative)); }); t.Start (); EnqueueConditional (() => done); Enqueue (() => { if (afe != null) throw afe; }); EnqueueTestComplete (); }
void query_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e) { StringBuilder sb = new StringBuilder(); sb.AppendLine("An emergency situation is observed at following location-"); foreach (var item in e.Result) { //sb.AppendLine(item.GeoCoordinate.ToString()); sb.AppendLine(item.Information.Name); sb.AppendLine(item.Information.Description); sb.AppendLine(item.Information.Address.BuildingFloor); sb.AppendLine(item.Information.Address.BuildingName); sb.AppendLine(item.Information.Address.BuildingRoom); sb.AppendLine(item.Information.Address.BuildingZone); sb.AppendLine(item.Information.Address.City); //sb.AppendLine(item.Information.Address.Continent); sb.AppendLine(item.Information.Address.Country); //sb.AppendLine(item.Information.Address.CountryCode); sb.AppendLine(item.Information.Address.County); sb.AppendLine(item.Information.Address.District); sb.AppendLine(item.Information.Address.HouseNumber); sb.AppendLine(item.Information.Address.Neighborhood); sb.AppendLine(item.Information.Address.PostalCode); sb.AppendLine(item.Information.Address.Province); sb.AppendLine(item.Information.Address.State); //sb.AppendLine(item.Information.Address.StateCode); sb.AppendLine(item.Information.Address.Street); sb.AppendLine(item.Information.Address.Township); } Dispatcher.BeginInvoke(delegate() { // the below call puts the device to vibration mode for 2 seconds Microsoft.Devices.VibrateController.Default.Start(TimeSpan.FromSeconds(2.0)); // make UI changes MessageBox.Show(sb.ToString()); // send email and sms Uri EmailUri = new Uri(" http://antonioasaro.site50.net/mail_to_sms.php?cmd=send&[email protected]&msg=Emergency%20at%20UPenn"); WebClient wc = new WebClient(); // Write to the WebClient wc.OpenWriteAsync(EmailUri, "GET"); }); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="data"></param> private void UploadFile(string fileName,Stream data) { if (!Common.IsConnected) { MessageBox.Show("ネットワークに接続していません。"); return; } UriBuilder ub = new UriBuilder("http://192.168.0.214:80/IsEstimate/receiver.ashx"); ub.Query = string.Format("filename={0}" ,fileName); WebClient wc= new WebClient(); wc.OpenWriteCompleted +=(sender ,e) => { PushData(data,e.Result); e.Result.Close(); data.Close(); }; wc.OpenWriteAsync(ub.Uri); }
//upload image private void UploadPhoto(Stream stream) { const int BLOCK_SIZE = 4096; Uri uri = new Uri(global.galbumlist[global.selectedAlbumIndex].href, UriKind.Absolute); WebClient wc = new WebClient(); string AuthToken = global.gtoken; wc.Headers[HttpRequestHeader.Authorization] = "GoogleLogin auth=" + AuthToken; wc.Headers[HttpRequestHeader.ContentLength] = stream.Length.ToString(); wc.Headers[HttpRequestHeader.ContentType] = "image/jpeg"; wc.AllowReadStreamBuffering = true; wc.AllowWriteStreamBuffering = true; //write complete handler, readly used from - source1 wc.OpenWriteCompleted += (s, args) => { using (BinaryReader br = new BinaryReader(stream)) { using (BinaryWriter bw = new BinaryWriter(args.Result)) { long bCount = 0; long fileSize = stream.Length; byte[] bytes = new byte[BLOCK_SIZE]; do { bytes = br.ReadBytes(BLOCK_SIZE); bCount += bytes.Length; bw.Write(bytes); } while (bCount < fileSize); } } }; // what to do when writing is complete wc.WriteStreamClosed += (s, args) => { //Image Uploaded Successfully! MessageBox.Show(AppResources.p3_imageUploadedSuccess); GetImages();//refresh images list }; wc.OpenWriteAsync(uri, "POST");// Write to the WebClient }