/// <summary> /// Gets the root certificate from the device. /// </summary> /// <param name="acceptUntrustedCerts">Whether or not we should accept untrusted certificates.</param> /// <returns>The device certificate.</returns> #pragma warning disable 1998 public async Task <Certificate> GetRootDeviceCertificateAsync(bool acceptUntrustedCerts = false) { Certificate certificate = null; Uri uri = Utilities.BuildEndpoint(this.deviceConnection.Connection, RootCertificateEndpoint); HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter(); requestSettings.AllowUI = false; if (acceptUntrustedCerts) { requestSettings.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); } using (HttpClient client = new HttpClient(requestSettings)) { this.ApplyHttpHeaders(client, HttpMethods.Get); using (HttpResponseMessage response = await client.GetAsync(uri)) { using (IHttpContent messageContent = response.Content) { certificate = new Certificate(await messageContent.ReadAsBufferAsync()); } } } return(certificate); }
/// <summary> /// Submits the http get request to the specified uri. /// </summary> /// <param name="uri">The uri to which the get request will be issued.</param> /// <returns>Response data as a stream.</returns> #pragma warning disable 1998 private async Task <Stream> GetAsync(Uri uri) { IBuffer dataBuffer = null; HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter(); requestSettings.AllowUI = false; if (this.deviceConnection.Credentials != null) { requestSettings.ServerCredential = new PasswordCredential(); requestSettings.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; requestSettings.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(requestSettings)) { this.ApplyHttpHeaders(client, HttpMethods.Get); using (HttpResponseMessage response = await client.GetAsync(uri)) { if (!response.IsSuccessStatusCode) { throw await DevicePortalException.CreateAsync(response); } using (IHttpContent messageContent = response.Content) { dataBuffer = await messageContent.ReadAsBufferAsync(); } } } return((dataBuffer != null) ? dataBuffer.AsStream() : null); }
/// <summary> /// Submits the http post request to the specified uri. /// </summary> /// <param name="uri">The uri to which the post request will be issued.</param> /// <param name="requestStream">Optional stream containing data for the request body.</param> /// <param name="requestStreamContentType">The type of that request body data.</param> /// <returns>Task tracking the completion of the POST request</returns> #pragma warning disable 1998 private async Task <Stream> PostAsync( Uri uri, Stream requestStream = null, string requestStreamContentType = null) { HttpStreamContent requestContent = null; IBuffer dataBuffer = null; if (requestStream != null) { requestContent = new HttpStreamContent(requestStream.AsInputStream()); requestContent.Headers.Remove(ContentTypeHeaderName); requestContent.Headers.TryAppendWithoutValidation(ContentTypeHeaderName, requestStreamContentType); } HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter(); httpFilter.AllowUI = false; if (this.deviceConnection.Credentials != null) { httpFilter.ServerCredential = new PasswordCredential(); httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(httpFilter)) { this.ApplyHttpHeaders(client, HttpMethods.Post); using (HttpResponseMessage response = await client.PostAsync(uri, requestContent)) { if (!response.IsSuccessStatusCode) { throw await DevicePortalException.CreateAsync(response); } this.RetrieveCsrfToken(response); if (response.Content != null) { using (IHttpContent messageContent = response.Content) { dataBuffer = await messageContent.ReadAsBufferAsync(); } } } } return((dataBuffer != null) ? dataBuffer.AsStream() : null); }
private async Task <string> RequestStringAsync(Uri uri, bool checkCached) { Logger.Debug($"[{nameof(TumOnlineRequest)}] Request: {uri}"); if (checkCached && (SERVICE.VALIDITY != TumOnlineService.VALIDITY_NONE)) { string result = CacheDbContext.GetCacheLine(uri.ToString()); if (!string.IsNullOrEmpty(result)) { Logger.Debug($"Loaded cached request for: '{uri}'"); return(result); } Logger.Debug($"No cached request found for: '{uri}'"); } if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable) { Logger.Warn("Unable to request string - no internet."); return(null); } try { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.TryAppendWithoutValidation("User-Agent", GetUserAgent()); HttpResponseMessage response = await client.GetAsync(uri); IHttpContent content = response.Content; IBuffer buffer = await content.ReadAsBufferAsync(); using (DataReader dataReader = DataReader.FromBuffer(buffer)) { string result = dataReader.ReadString(buffer.Length); if (SERVICE.VALIDITY != TumOnlineService.VALIDITY_NONE) { CacheDbContext.UpdateCacheLine(uri.ToString(), DateTime.Now.Add(SERVICE.VALIDITY), result); } Logger.Debug($"[{nameof(TumOnlineRequest)}] Response: {result}"); return(result); } } catch (Exception e) { Logger.Error("Failed to request string from: " + uri, e); } return(null); }
/// <summary> /// Submits the http put request to the specified uri. /// </summary> /// <param name="uri">The uri to which the put request will be issued.</param> /// <param name="body">The HTTP content comprising the body of the request.</param> /// <returns>Task tracking the PUT completion.</returns> #pragma warning disable 1998 public async Task <Stream> PutAsync( Uri uri, IHttpContent body = null) { IBuffer dataBuffer = null; using (var httpFilter = new HttpBaseProtocolFilter()) { httpFilter.AllowUI = false; if (this.deviceConnection.Credentials != null) { httpFilter.ServerCredential = new PasswordCredential(); httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(httpFilter)) { this.ApplyHttpHeaders(client, HttpMethods.Put); // Send the request using (HttpResponseMessage response = await client.PutAsync(uri, body)) { if (!response.IsSuccessStatusCode) { throw await DevicePortalException.CreateAsync(response); } this.RetrieveCsrfToken(response); if (response.Content != null) { using (IHttpContent messageContent = response.Content) { dataBuffer = await messageContent.ReadAsBufferAsync(); } } } } } return((dataBuffer != null) ? dataBuffer.AsStream() : null); }
private static async Task <BitmapImage> GetMainSubStep_CookielessGetPic(string picUrl) { Uri myUri = new Uri(picUrl); HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, myUri); req.Headers.Host = new HostName(myUri.Host); req.Headers.Cookie.Clear(); HttpResponseMessage response = await client.SendRequestAsync(req); if (response == null) { return(null); } //HttpResponseMessage response if (response.StatusCode != HttpStatusCode.Ok) { return(null); } IHttpContent icont = response.Content; IBuffer buffer = await icont.ReadAsBufferAsync(); IRandomAccessStream irStream = new InMemoryRandomAccessStream(); BitmapImage img = new BitmapImage(); await irStream.WriteAsync(buffer); irStream.Seek(0); await img.SetSourceAsync(irStream); irStream.Dispose(); icont.Dispose(); response.Dispose(); req.Dispose(); return(img); }
/// <summary> /// Gets the root certificate from the device. /// </summary> /// <returns>The device certificate.</returns> #pragma warning disable 1998 private async Task <Certificate> GetDeviceCertificate() { Certificate certificate = null; bool useHttps = true; // try https then http while (true) { Uri uri = null; if (useHttps) { uri = Utilities.BuildEndpoint(this.deviceConnection.Connection, RootCertificateEndpoint); } else { Uri baseUri = new Uri(string.Format("http://{0}", this.deviceConnection.Connection.Authority)); uri = Utilities.BuildEndpoint(baseUri, RootCertificateEndpoint); } try { HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter(); requestSettings.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); requestSettings.AllowUI = false; using (HttpClient client = new HttpClient(requestSettings)) { this.ApplyHttpHeaders(client, HttpMethods.Get); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri); TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter(); while (!responseAwaiter.IsCompleted) { } using (HttpResponseMessage response = responseOperation.GetResults()) { this.RetrieveCsrfToken(response); using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); TaskAwaiter <IBuffer> readBufferAwaiter = bufferOperation.GetAwaiter(); while (!readBufferAwaiter.IsCompleted) { } certificate = new Certificate(bufferOperation.GetResults()); if (!certificate.Issuer.Contains(DevicePortalCertificateIssuer)) { certificate = null; throw new DevicePortalException( (HttpStatusCode)0, "Invalid certificate issuer", uri, "Failed to get the device certificate"); } } } } return(certificate); } catch (Exception e) { if (useHttps) { useHttps = false; } else { throw e; } } } }
/// <summary> /// Initializes a new instance of the <see cref="DevicePortalException"/> class. /// </summary> /// <param name="responseMessage">Http response message.</param> /// <param name="message">Optional exception message.</param> /// <param name="innerException">Optional inner exception.</param> /// <returns>async task</returns> public static async Task <DevicePortalException> CreateAsync( HttpResponseMessage responseMessage, string message = "", Exception innerException = null) { DevicePortalException error = new DevicePortalException( responseMessage.StatusCode, responseMessage.ReasonPhrase, responseMessage.RequestMessage != null ? responseMessage.RequestMessage.RequestUri : null, message, innerException); try { if (responseMessage.Content != null) { Stream dataStream = null; #if !WINDOWS_UWP using (HttpContent content = responseMessage.Content) { dataStream = new MemoryStream(); await content.CopyToAsync(dataStream).ConfigureAwait(false); // Ensure we point the stream at the origin. dataStream.Position = 0; } #else // WINDOWS_UWP IBuffer dataBuffer = null; using (IHttpContent messageContent = responseMessage.Content) { dataBuffer = await messageContent.ReadAsBufferAsync(); if (dataBuffer != null) { dataStream = dataBuffer.AsStream(); } } #endif // WINDOWS_UWP if (dataStream != null) { HttpErrorResponse errorResponse = DevicePortal.ReadJsonStream <HttpErrorResponse>(dataStream); error.HResult = errorResponse.ErrorCode; error.Reason = errorResponse.ErrorMessage; // If we didn't get the Hresult and reason from these properties, try the other ones. if (error.HResult == 0) { error.HResult = errorResponse.Code; } if (string.IsNullOrEmpty(error.Reason)) { error.Reason = errorResponse.Reason; } } } } catch (Exception) { // Do nothing if we fail to get additional error details from the response body. } return(error); }
/// <summary> /// Initializes a new instance of the <see cref="DevicePortalException"/> class. /// </summary> /// <param name="responseMessage">Http response message.</param> /// <param name="message">Optional exception message.</param> /// <param name="innerException">Optional inner exception.</param> public DevicePortalException( HttpResponseMessage responseMessage, string message = "", Exception innerException = null) : this( responseMessage.StatusCode, responseMessage.ReasonPhrase, responseMessage.RequestMessage != null ? responseMessage.RequestMessage.RequestUri : null, message, innerException) { try { if (responseMessage.Content != null) { Stream dataStream = null; #if !WINDOWS_UWP using (HttpContent content = responseMessage.Content) { dataStream = new MemoryStream(); Task copyTask = content.CopyToAsync(dataStream); copyTask.ConfigureAwait(false); copyTask.Wait(); // Ensure we point the stream at the origin. dataStream.Position = 0; } #else // WINDOWS_UWP IBuffer dataBuffer = null; using (IHttpContent messageContent = responseMessage.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); while (bufferOperation.Status != AsyncStatus.Completed) { } dataBuffer = bufferOperation.GetResults(); if (dataBuffer != null) { dataStream = dataBuffer.AsStream(); } } #endif // WINDOWS_UWP if (dataStream != null) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HttpErrorResponse)); HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream); this.HResult = errorResponse.ErrorCode; this.Reason = errorResponse.ErrorMessage; // If we didn't get the Hresult and reason from these properties, try the other ones. if (this.HResult == 0) { this.HResult = errorResponse.Code; } if (string.IsNullOrEmpty(this.Reason)) { this.Reason = errorResponse.Reason; } } } } catch (Exception) { // Do nothing if we fail to get additional error details from the response body. } }
/// <summary> /// Submits the http get request to the specified uri. /// </summary> /// <param name="uri">The uri to which the get request will be issued.</param> /// <returns>Response data as a stream.</returns> #pragma warning disable 1998 private async Task <Stream> Get(Uri uri) { IBuffer dataBuffer = null; HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter(); requestSettings.AllowUI = false; if (this.deviceConnection.Credentials != null) { requestSettings.ServerCredential = new PasswordCredential(); requestSettings.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; requestSettings.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(requestSettings)) { this.ApplyHttpHeaders(client, HttpMethods.Get); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri); TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter(); while (!responseAwaiter.IsCompleted) { } using (HttpResponseMessage response = responseOperation.GetResults()) { if (!response.IsSuccessStatusCode) { throw new DevicePortalException(response); } this.RetrieveCsrfToken(response); using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); while (bufferOperation.Status != AsyncStatus.Completed) { } dataBuffer = bufferOperation.GetResults(); } } } return((dataBuffer != null) ? dataBuffer.AsStream() : null); }
/// <summary> /// Submits the http post request to the specified uri. /// </summary> /// <param name="uri">The uri to which the post request will be issued.</param> /// <param name="requestStream">Optional stream containing data for the request body.</param> /// <param name="requestStreamContentType">The type of that request body data.</param> /// <param name="allowRetry">Allow the Post to be retried after issuing a Get call. Currently used for CSRF failures.</param> /// <returns>Task tracking the completion of the POST request</returns> #pragma warning disable 1998 private async Task <Stream> Post( Uri uri, Stream requestStream = null, string requestStreamContentType = null, bool allowRetry = true) { HttpStreamContent requestContent = null; IBuffer dataBuffer = null; if (requestStream != null) { requestContent = new HttpStreamContent(requestStream.AsInputStream()); requestContent.Headers.Remove(ContentTypeHeaderName); requestContent.Headers.TryAppendWithoutValidation(ContentTypeHeaderName, requestStreamContentType); } HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter(); httpFilter.AllowUI = false; if (this.deviceConnection.Credentials != null) { httpFilter.ServerCredential = new PasswordCredential(); httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(httpFilter)) { this.ApplyHttpHeaders(client, HttpMethods.Post); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.PostAsync(uri, requestContent); TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter(); while (!responseAwaiter.IsCompleted) { } using (HttpResponseMessage response = responseOperation.GetResults()) { if (!response.IsSuccessStatusCode) { // If this isn't a retry and it failed due to a bad CSRF // token, issue a GET to refresh the token and then retry. if (allowRetry && this.IsBadCsrfToken(response)) { await this.RefreshCsrfToken(); return(await this.Post(uri, requestStream, requestStreamContentType, false)); } throw new DevicePortalException(response); } this.RetrieveCsrfToken(response); if (response.Content != null) { using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); while (bufferOperation.Status != AsyncStatus.Completed) { } dataBuffer = bufferOperation.GetResults(); } } } } return((dataBuffer != null) ? dataBuffer.AsStream() : null); }
/// <summary> /// API for getting installation status. /// </summary> /// <returns>The status</returns> #pragma warning disable 1998 public async Task <ApplicationInstallStatus> GetInstallStatusAsync() { ApplicationInstallStatus status = ApplicationInstallStatus.None; Uri uri = Utilities.BuildEndpoint( this.deviceConnection.Connection, InstallStateApi); HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter(); httpFilter.AllowUI = false; if (this.deviceConnection.Credentials != null) { httpFilter.ServerCredential = new PasswordCredential(); httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(httpFilter)) { this.ApplyHttpHeaders(client, HttpMethods.Get); using (HttpResponseMessage response = await client.GetAsync(uri)) { if (response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.Ok) { // Status code: 200 if (response.Content != null) { Stream dataStream = null; IBuffer dataBuffer = null; using (IHttpContent messageContent = response.Content) { dataBuffer = await messageContent.ReadAsBufferAsync(); if (dataBuffer != null) { dataStream = dataBuffer.AsStream(); } } if (dataStream != null) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HttpErrorResponse)); HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream); if (errorResponse.Success) { status = ApplicationInstallStatus.Completed; } else { throw new DevicePortalException(response.StatusCode, errorResponse, uri); } } else { throw new DevicePortalException(HttpStatusCode.Conflict, "Failed to deserialize GetInstallStatus response."); } } } else if (response.StatusCode == HttpStatusCode.NoContent) { // Status code: 204 status = ApplicationInstallStatus.InProgress; } } else { throw await DevicePortalException.CreateAsync(response); } } } return(status); }
/// <summary> /// Gets the root certificate from the device. /// </summary> /// <param name="acceptUntrustedCerts">Whether or not we should accept untrusted certificates.</param> /// <returns>The device certificate.</returns> #pragma warning disable 1998 public async Task <Certificate> GetRootDeviceCertificateAsync(bool acceptUntrustedCerts = false) { Certificate certificate = null; Uri uri = Utilities.BuildEndpoint(this.deviceConnection.Connection, RootCertificateEndpoint); HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter(); requestSettings.AllowUI = false; if (acceptUntrustedCerts) { requestSettings.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); } using (HttpClient client = new HttpClient(requestSettings)) { this.ApplyHttpHeaders(client, HttpMethods.Get); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri); TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter(); while (!responseAwaiter.IsCompleted) { } using (HttpResponseMessage response = responseOperation.GetResults()) { using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); TaskAwaiter <IBuffer> readBufferAwaiter = bufferOperation.GetAwaiter(); while (!readBufferAwaiter.IsCompleted) { } certificate = new Certificate(bufferOperation.GetResults()); } } } return(certificate); }