public BeginGetRequestStream ( System callback, object state ) : System.IAsyncResult | ||
callback | System | |
state | object | |
return | System.IAsyncResult |
private async void SpeakAppBr_Click(object sender, EventArgs e) { MessageBox.Show("Sorry! I only listen to you in English!"); strLngFrom = "en"; btnFrom.Content = "English"; this.speechRecognizer.Recognizer.Grammars.Clear(); this.speechRecognizer.Recognizer.Grammars.AddGrammarFromPredefinedType("message", SpeechPredefinedGrammar.Dictation); await this.speechRecognizer.Recognizer.PreloadGrammarsAsync(); try { SpeechRecognitionUIResult recognitionResult = await this.speechRecognizer.RecognizeWithUIAsync(); if (recognitionResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded) { strTextToTranslate = recognitionResult.RecognitionResult.Text; String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; System.Net.WebRequest req = System.Net.WebRequest.Create(strTranslatorAccessURI); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; IAsyncResult writeRequestStreamCallback = (IAsyncResult)req.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), req); txtToTrans.Text = recognitionResult.RecognitionResult.Text; } else { //MessageBox.Show("Sorry! I didn't catch you."); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Gets the access token.(Async) will set the IsInitialized Variable when done /// </summary> /// <param name='cliendID'> /// Cliend I. /// </param> /// <param name='clientSecret'> /// Client secret. /// </param> public void GetAccessToken(string cliendID, string clientSecret) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); isInitialized = false; //Remove all the possible white spaces List <char> cliendIDList = cliendID.ToList(); cliendIDList.RemoveAll(c => c == ' '); this.clientID = new string(cliendIDList.ToArray()); cliendIDList.Clear(); List <char> clientSecretList = clientSecret.ToList(); clientSecretList.RemoveAll(c => c == ' '); this.clientSecret = new string(clientSecretList.ToArray()); clientSecretList.Clear(); // Create the request for the OAuth service that will string strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; System.Net.WebRequest req = System.Net.WebRequest.Create(strTranslatorAccessURI); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; // Important to note -- the call back here isn't that the request was processed by the server // but just that the request is ready for you to do stuff to it (like writing the details) // and then post it to the server. req.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), req); }
public void SendRequest(string postRequest, Microsoft.Phone.Controls.PerformanceProgressBar performanceProgressBar) { var bw = new System.ComponentModel.BackgroundWorker(); bw.DoWork += (s, args) => // This runs on a background thread. { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { performanceProgressBar.IsIndeterminate = true; performanceProgressBar.Visibility = System.Windows.Visibility.Visible; }); this.parameters = postRequest; this.request = WebRequest.Create(new Uri("http://192.168.1.71:8080/MobileApplication/mythapi")) as WebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetRequestStream(ReadCallback, request); }; bw.RunWorkerCompleted += (s, args) => { // Do your UI work here this will run on the UI thread. // Clear progress bar. performanceProgressBar.IsIndeterminate = false; performanceProgressBar.Visibility = System.Windows.Visibility.Collapsed; }; bw.RunWorkerAsync(); }
public void SendRequest(string postRequest) { this.parameters = postRequest; this.request = WebRequest.Create(new Uri("http://192.168.1.71:8080/MobileApplication/mythapi")) as WebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetRequestStream(ReadCallback, request); }
public void UploadAsync(string serverUrl, Action<string> callback) { var uri = new Uri(string.Format("{0}{1}?token={2}", serverUrl, Constants.UploadItemUrl, _token.Token), UriKind.Absolute); _webRequest = Create(uri); ((HttpWebRequest)_webRequest).AllowWriteStreamBuffering = true; _webRequest.Method = "POST"; _webRequest.ContentType = "multipart/form-data; boundary=" + _boundary; _webRequest.BeginGetRequestStream(asyncResult => GetValue(asyncResult, callback), null); }
public void GetAccessToken() { // Create the request for the OAuth service that will get us the access tokens. String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; System.Net.WebRequest req = System.Net.WebRequest.Create(strTranslatorAccessURI); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; IAsyncResult writeRequestStreamCallback = (IAsyncResult)req.BeginGetRequestStream(new AsyncCallback(BingRequestStreamReady), req); }
private static void BeginRequest(WebRequest request, Action<HttpStatusCode, string, OAuthTokens> onComplete, Action<Uri, Exception> onError, string data) { request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetRequestStream(HandleRequestCallback, new RequestContext<string, OAuthTokens> { Body = data, Request = request, OnComplete = onComplete, OnError = onError }); }
private static Stream GetRequestStreamInternal(WebRequest request) { // build the envent using (var revent = new ManualResetEvent(false)) { // start the async call IAsyncResult result = request.BeginGetRequestStream(CallStreamCallback, revent); // wait for event revent.WaitOne(); // return data stream return request.EndGetRequestStream(result); } }
private void btnTraslate_Click(object sender, RoutedEventArgs e) { if (txtToTrans.Text != "") { strTextToTranslate = txtToTrans.Text; String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; System.Net.WebRequest req = System.Net.WebRequest.Create(strTranslatorAccessURI); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; IAsyncResult writeRequestStreamCallback = (IAsyncResult)req.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), req); } else { MessageBox.Show("Please tell me what do you want to translate!?"); } }
private static void RequestAsync(WebRequest request, byte[] bodyBytes, Action<TrackResult> callback) { request.BeginGetRequestStream((r1) => { try { var stream = request.EndGetRequestStream(r1); stream.BeginWrite(bodyBytes, 0, bodyBytes.Length, (r2) => { try { stream.EndWrite(r2); stream.Dispose(); request.BeginGetResponse((r3) => { try { using (var response = request.EndGetResponse(r3)) { using (var reader = new StreamReader(response.GetResponseStream())) { if (callback != null) callback(new TrackResult(reader.ReadToEnd())); } } } catch (Exception ex) { HandleError(callback, ex); } }, null); } catch (Exception ex) { HandleError(callback, ex); } }, null); } catch(Exception ex) { HandleError(callback, ex); } }, null); }
private static Stream getRequestStream(WebRequest request) { Stream requestStream = null; ManualResetEvent getRequestFinished = new ManualResetEvent(false); AsyncCallback callBack = new AsyncCallback(ar => { var req = (HttpWebRequest)ar.AsyncState; requestStream = req.EndGetRequestStream(ar); getRequestFinished.Set(); }); var async = request.BeginGetRequestStream(callBack, request); getRequestFinished.WaitOne(); return requestStream; }
public Task <byte[]> UploadValuesTaskAsync(string address, NameValueCollection names) { return(Task <byte[]> .Factory.StartNew(() => { WebRequest request = this.GetWebRequest(new Uri(address)); request.ContentType = "text/plain; charset=utf-8"; request.Method = "POST"; byte[] data = null; request.BeginGetRequestStream(new AsyncCallback((IAsyncResult res) => { using (Stream postStream = request.EndGetRequestStream(res)) { StringBuilder postParamBuilder = new StringBuilder(); foreach (var key in names.Keys) { postParamBuilder.Append(String.Format("{0}={1}&", key, names[key])); } byte[] byteArray = Encoding.UTF8.GetBytes(postParamBuilder.ToString()); postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); request.BeginGetResponse(new AsyncCallback((IAsyncResult nres) => { using (Stream respStream = request.EndGetResponse(nres).GetResponseStream()) { data = new byte[respStream.Length]; respStream.Write(data, 0, data.Length); } }), null); } }), null); while (data == null) { } return data; })); }
public void OpenWriteAsync(Uri address, string method, object userToken) { if (address == null) { throw new ArgumentNullException("address"); } lock (locker) { SetBusy(); try { request = SetupRequest(address, method, new CallbackData(userToken)); request.BeginGetRequestStream(new AsyncCallback(OpenWriteAsyncCallback), null); } catch (Exception e) { WebException wex = new WebException("Could not start operation.", e); OnOpenWriteCompleted( new OpenWriteCompletedEventArgs(null, wex, false, userToken)); } } }
private void Start() { try { request = System.Net.WebRequest.Create(requestURI); request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy(); if (null != postData) { request.ContentLength = postData.Length; request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), request); } else { request.Method = "GET"; request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); } } catch (OutOfMemoryException e) { if (retryCount < retryMax) { System.Diagnostics.Debug.WriteLine(e.Message); ++retryCount; Random random = new Random(); Thread.Sleep(retryDelay * random.Next(retryCount * retryCount)); Start(); } else { OnException(e); } } catch (Exception e) { OnException(e); } }
public Task <byte[]> DownloadDataTaskAsync(string address) { return(Task <byte[]> .Factory.StartNew(() => { WebRequest request = this.GetWebRequest(new Uri(address)); byte[] data = null; AsyncCallback callback = new AsyncCallback((IAsyncResult res) => { using (Stream str = request.EndGetRequestStream(res)) { data = new byte[str.Length]; str.Write(data, 0, data.Length); } }); request.BeginGetRequestStream(callback, null); while (data == null) { } return data; })); }
public void OpenWriteAsync (Uri address, string method, object userToken) { if (address == null) throw new ArgumentNullException ("address"); lock (locker) { SetBusy (); try { request = SetupRequest (address, method, new CallbackData (userToken)); request.BeginGetRequestStream (new AsyncCallback (OpenWriteAsyncCallback), null); } catch (Exception e) { WebException wex = new WebException ("Could not start operation.", e); OnOpenWriteCompleted ( new OpenWriteCompletedEventArgs (null, wex, false, userToken)); } } }
internal void AttachBody(WebRequest request) { request.BeginGetRequestStream(EndAttachBody, request); }
internal Stream GetRequestStream(WebRequest request) { Stream stream = null; request.BeginGetRequestStream(a => { stream = request.EndGetRequestStream(a); allDone.Set(); }, null); allDone.WaitOne(TimeSpan.FromSeconds(30)); return stream; }
private static void SetPostData(object postdata, WebRequest request) { using (System.Threading.ManualResetEvent man = new System.Threading.ManualResetEvent(false)) { request.Method = "POST"; System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(postdata.GetType()); using (var mem = new System.IO.MemoryStream()) { serializer.WriteObject(mem, postdata); mem.Position = 0; request.ContentLength = mem.Length; request.BeginGetRequestStream((s) => { using (var postStream = request.EndGetRequestStream(s)) { mem.CopyTo(postStream); } man.Set(); }, null); man.WaitOne(); } } }
/// <devdoc> /// <para>Takes a byte array or an open file stream and writes it to a server</para> /// </devdoc> private void UploadBits(WebRequest request, Stream readStream, byte[] buffer, byte [] header, byte [] footer, CompletionDelegate completionDelegate, AsyncOperation asyncOp) { if (request.RequestUri.Scheme == Uri.UriSchemeFile) header = footer = null; UploadBitsState state = new UploadBitsState(request, readStream, buffer, header, footer, completionDelegate, asyncOp, m_Progress, this); Stream writeStream; if (state.Async) { request.BeginGetRequestStream(new AsyncCallback(UploadBitsRequestCallback), state); return; } else { writeStream = request.GetRequestStream(); } state.SetRequestStream(writeStream); while(!state.WriteBytes()); state.Close(); }
void BeginProcessRequest (HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; // FIXME: is distination really like this? Uri destination = message.Headers.To; if (destination == null) { if (source.Transport.ManualAddressing) throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address."); else destination = Via ?? RemoteAddress.Uri; } web_request = HttpWebRequest.Create (destination); web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; #if NET_2_1 var cmgr = source.GetProperty<IHttpCookieContainerManager> (); if (cmgr != null) ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer; #endif #if !MOONLIGHT // until we support NetworkCredential like SL4 will do. // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.) var httpbe = (HttpTransportBindingElement) source.Transport; string authType = null; switch (httpbe.AuthenticationScheme) { // AuthenticationSchemes.Anonymous is the default, ignored. case AuthenticationSchemes.Basic: authType = "Basic"; break; case AuthenticationSchemes.Digest: authType = "Digest"; break; case AuthenticationSchemes.Ntlm: authType = "Ntlm"; break; case AuthenticationSchemes.Negotiate: authType = "Negotiate"; break; } if (authType != null) { var cred = source.ClientCredentials; string user = cred != null ? cred.UserName.UserName : null; string pwd = cred != null ? cred.UserName.Password : null; if (String.IsNullOrEmpty (user)) throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType)); var nc = new NetworkCredential (user, pwd); web_request.Credentials = nc; // FIXME: it is said required in SL4, but it blocks full WCF. //web_request.UseDefaultCredentials = false; } #endif #if !NET_2_1 // FIXME: implement this to not depend on Timeout property web_request.Timeout = (int) timeout.TotalMilliseconds; #endif // There is no SOAP Action/To header when AddressingVersion is None. if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) || message.Version.Addressing.Equals (AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\""); message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace); } } // apply HttpRequestMessageProperty if exists. bool suppressEntityBody = false; #if !NET_2_1 string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey (pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname]; web_request.Headers.Clear (); web_request.Headers.Add (hp.Headers); web_request.Method = hp.Method; // FIXME: do we have to handle hp.QueryString ? if (hp.SuppressEntityBody) suppressEntityBody = true; } #endif if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { MemoryStream buffer = new MemoryStream (); Encoder.WriteMessage (message, buffer); if (buffer.Length > int.MaxValue) throw new InvalidOperationException ("The argument message is too large."); #if !NET_2_1 web_request.ContentLength = (int) buffer.Length; #endif web_request.BeginGetRequestStream (delegate (IAsyncResult r) { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (Stream s = web_request.EndGetRequestStream (r)) s.Write (buffer.GetBuffer (), 0, (int) buffer.Length); web_request.BeginGetResponse (GotResponse, result); } catch (Exception ex) { result.Complete (ex); } }, null); } else { web_request.BeginGetResponse (GotResponse, result); } }
private Stream GetRequestStream(WebRequest request) { AutoResetEvent autoResetEvent = new AutoResetEvent(false); IAsyncResult asyncResult = request.BeginGetRequestStream(r => autoResetEvent.Set(), null); autoResetEvent.WaitOne(); return request.EndGetRequestStream(asyncResult); }
internal void AttachBody(WebRequest request, Action<WebRequest> onRequestReady) { request.BeginGetRequestStream(new AsyncCallback(EndAttachBody), new object[] { request, onRequestReady }); }
public void UploadStringAsync (Uri address, string method, string data, object userToken) { if (address == null) throw new ArgumentNullException ("address"); if (data == null) throw new ArgumentNullException ("data"); lock (locker) { SetBusy (); try { CallbackData cbd = new CallbackData (userToken, encoding.GetBytes (data)); request = SetupRequest (address, method, cbd); request.BeginGetRequestStream (new AsyncCallback (UploadStringRequestAsyncCallback), cbd); } catch (Exception e) { WebException wex = new WebException ("Could not start operation.", e); OnUploadStringCompleted ( new UploadStringCompletedEventArgs (null, wex, false, userToken)); } } }
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { return(_internalWebRequest.BeginGetRequestStream(callback, state)); }
private void _IrosHPost(IntPtr handle, ref IrosHPostData data) { string url = Marshal.PtrToStringAnsi(data.url); string ctype = Marshal.PtrToStringAnsi(data.contentType); System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.ContentType = ctype; //req.Method = data.len > 0 ? "POST" : "GET"; req.Method = "POST"; TraceLogger(String.Format("{3}ing {2} bytes to {0} handle {1}", url, handle, data.len, req.Method)); byte[] buffer = new byte[data.len]; Marshal.Copy(data.data, buffer, 0, buffer.Length); WebTask t = new WebTask() { Req = req, Handle = handle, writeBack = data.writeBack }; _http[handle] = t; AsyncCallback doResponse = ar2 => { try { var resp = req.EndGetResponse(ar2); var rs = req.GetResponse().GetResponseStream(); t.Async = rs.BeginRead(t.ReceiveBuffer, 0, t.ReceiveBuffer.Length, AsyncReceive, t); } catch (WebException e) { ErrorLogger(String.Format("Error receiving from {0}: {1}", handle, e.ToString())); t.ReceiveDone = true; if (e.Response != null) { t.Status = (int)((HttpWebResponse)e.Response).StatusCode; } else { t.Status = 500; } } catch (Exception e) { ErrorLogger(String.Format("Error receiving from {0}: {1}", handle, e.ToString())); t.ReceiveDone = true; t.Status = 500; } }; t.ReceiveBuffer = new byte[0x10000]; if (buffer.Length > 0) { t.Async = req.BeginGetRequestStream(ar => { var s = req.EndGetRequestStream(ar); using (s) { s.Write(buffer, 0, buffer.Length); } t.Completed = t.Size = buffer.Length; TraceLogger(String.Format("Beginning GetResponse for {0}", handle)); t.Async = req.BeginGetResponse(doResponse, t); }, t); } else { TraceLogger(String.Format("Beginning GetResponse [no request data] for {0}", handle)); t.Async = req.BeginGetResponse(doResponse, t); } }
private void WriteAsync(ErrorReport report, WebRequest request) { var serializer = GlobalConfig.ServiceLocator.GetService<IErrorReportSerializer>(); request.ContentType = serializer.GetContentType(); var serializedObj = serializer.Serialize(report); request.BeginGetRequestStream(asyncResult => HandleWrite(asyncResult, serializedObj), request); }
private void UploadBits(WebRequest request, Stream readStream, byte[] buffer, int chunkSize, byte[] header, byte[] footer, CompletionDelegate uploadCompletionDelegate, CompletionDelegate downloadCompletionDelegate, AsyncOperation asyncOp) { if (request.RequestUri.Scheme == Uri.UriSchemeFile) { header = (byte[]) (footer = null); } UploadBitsState state = new UploadBitsState(request, readStream, buffer, chunkSize, header, footer, uploadCompletionDelegate, downloadCompletionDelegate, asyncOp, this.m_Progress, this); if (state.Async) { request.BeginGetRequestStream(new AsyncCallback(WebClient.UploadBitsRequestCallback), state); } else { Stream requestStream = request.GetRequestStream(); state.SetRequestStream(requestStream); while (!state.WriteBytes()) { } state.Close(); } }