/// <summary> /// Logs the execption event. /// </summary> private void LogExceptionEvent() { if (qosEvent == null) { return; } ExceptionTelemetry exceptionTelemetry = new ExceptionTelemetry(qosEvent.Exception) { Message = "The message has been removed due to PII" }; if (qosEvent.Exception is RestException) { object ex = qosEvent.Exception; HttpResponseMessageWrapper response = ex.GetType().GetProperty("Response").GetValue(ex, null) as HttpResponseMessageWrapper; PopulatePropertiesFromResponse(exceptionTelemetry.Properties, response); } exceptionTelemetry.Metrics.Add("Duration", qosEvent.Duration.TotalMilliseconds); PopulatePropertiesFromQos(exceptionTelemetry.Properties); try { #if DEBUG telemetryClient.TrackException(exceptionTelemetry); #endif } catch { // Ignore any error with capturing the telemetry } }
public HttpResponseMessageWrapper<string> Trace(HttpRequestMessage req) { // Log function entrance LoggingHelper.TraceFunction(); // get the user credentials User user = ResourceHelper.GetUserPassFromMessage(req); try { Stream stream; if (req.Content.Headers.ContentType.MediaType == "application/x-gzip") stream = new GZipStream(req.Content.ContentReadStream, CompressionMode.Decompress); else stream = req.Content.ContentReadStream; string error = WriteFile(user, stream); var response = new HttpResponseMessageWrapper<string>(req, error != null ? error : "OK", HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; // return the response return response; } catch (Exception ex) { // speech failed LoggingHelper.TraceError("Trace Write failed: " + ex.Message); return new HttpResponseMessageWrapper<string>(req, HttpStatusCode.InternalServerError); } }
public static DateTimeOffset?GetCreatedOn(this HttpResponseMessageWrapper wrapper) { var date = wrapper.Headers[ResponseDateHeader].FirstOrDefault(); var createdOn = default(DateTimeOffset); DateTimeOffset.TryParse(date, out createdOn); return(createdOn); }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { if (response != null && response.Response != null && response.Response.Headers != null) { response.Response.Headers.ETag = ETagStore.GetOrCreateETag(response.CurrentCacheKey); } return(response); }
private async Task <HiRezApiSession> TryFetchNewSessionAsync() { try { var sessionResponse = await this._apiClient.CreateSessionWithHttpMessagesAsync(); if (sessionResponse.Body.RetMsg != Constants.SESSION_APPROVED_RET_MSG) { var exMsg = $"Session was not approved: {sessionResponse.Body.RetMsg}"; switch (sessionResponse.Body.RetMsg) { case Constants.SESSION_REQUEST_LIMIT_REACHED_RET_MSG: throw new RequestLimitReachedException(exMsg); case Constants.SESSION_EXCEPTION_DEVELOPER_ACCESS_RET_MSG: throw new InvalidCredentialsException(exMsg); case Constants.SESSION_TIMESTAMP_INVALID_RET_MSG: throw new InvalidSessionException(exMsg); case Constants.SESSION_INVALID_SESSION_ID_RET_MSG: throw new InvalidSessionException(exMsg); } throw new SessionException(exMsg); } if (string.IsNullOrEmpty(sessionResponse.Body.SessionId)) { throw new SessionException("Session is missing from response."); } if (!sessionResponse.Body.Timestamp.TryParseApiDate(out DateTime sessionTimeStamp)) { throw new SessionException("Could not validate timestamp."); } // If a request reaches the API when the session expired we'll get an error // to prevent "most" of these issues we'll expire the session on the client a little bit earlier sessionTimeStamp = sessionTimeStamp.AddSeconds(-5); return(new HiRezApiSession(sessionTimeStamp, sessionResponse.Body.SessionId, this._apiClient.Platform, this._timeStampProvider)); } catch (Exception ex) when(ex is ErrorModelException || ex is HttpOperationException) { HttpResponseMessageWrapper response = (ex as ErrorModelException)?.Response ?? (ex as HttpOperationException)?.Response; // Observings indicate that a 404 response can occur when the API is "down" (probably due to deployment errors) if (response?.StatusCode == HttpStatusCode.NotFound) { throw new ApiUnavailableException("API is not available.", ex); } throw new SessionException("Failure creating a session.", ex); } }
protected RestApiException(SerializationInfo info, StreamingContext context) : base(info, context) { var requestString = info.GetString("Request"); var responseString = info.GetString("Response"); Request = JsonConvert.DeserializeObject <HttpRequestMessageWrapper>(requestString, SerializerSettings); Response = JsonConvert.DeserializeObject <HttpResponseMessageWrapper>(responseString, SerializerSettings); }
private static HttpResponseMessage CopyResponse(HttpResponseMessageWrapper responseWrapper) { var response = new HttpResponseMessage(responseWrapper.StatusCode); response.Content = CopyContent(responseWrapper); CopyHeaders(responseWrapper, response.Headers); response.ReasonPhrase = responseWrapper.ReasonPhrase; return(response); }
public HttpResponseMessageWrapper <string> Trace(HttpRequestMessage req) { // Log function entrance TraceLog.TraceFunction(); // get the username from the message if available // the creds may not exist for a device that hasn't registered but is uploading a crash report string username = null; var creds = GetUserFromMessageHeaders(req); if (creds != null) { username = creds.Name; } try { Stream stream; switch (req.Content.Headers.ContentType.MediaType) { case "application/x-gzip": stream = new GZipStream(req.Content.ReadAsStreamAsync().Result, CompressionMode.Decompress); break; case "application/json": stream = req.Content.ReadAsStreamAsync().Result; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(string)); string data = (string)ser.ReadObject(stream); var ms = new MemoryStream(); var tw = new StreamWriter(ms); tw.Write(data); tw.Flush(); ms.Position = 0; stream = ms; break; default: stream = req.Content.ReadAsStreamAsync().Result; break; } string error = WriteFile(username, stream); var response = new HttpResponseMessageWrapper <string>(req, error != null ? error : "OK", HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; // return the response return(response); } catch (Exception ex) { TraceLog.TraceException("Trace Write failed", ex); return(new HttpResponseMessageWrapper <string>(req, HttpStatusCode.InternalServerError)); } }
private static bool IsRetriableStatusCode(this HttpResponseMessageWrapper response) { if (response == null) { return(false); } return(KnownRetriableWebResponseStatusCodes.Any(x => x == response.StatusCode)); }
public static string ExtractAsyncErrorCode(this HttpResponseMessageWrapper response) { if (response == null) { throw new ArgumentNullException(nameof(response)); } var deserializedResponse = JsonConvert.DeserializeObject <AsyncOperationResponse>(response.Content); return(deserializedResponse?.Error?.Code); }
private static string FormatMessage(HttpResponseMessageWrapper response) { var result = $"The response contained an invalid status code {(int)response.StatusCode} {response.ReasonPhrase}"; if (!string.IsNullOrEmpty(response.Content)) { result += "\n\nBody: "; result += response.Content.Length < 300 ? response.Content : response.Content.Substring(0, 300); } return(result); }
/// <summary> /// Logs the execption event. /// </summary> private void LogExceptionEvent() { if (qosEvent == null) { return; } ExceptionTelemetry exceptionTelemetry = new ExceptionTelemetry(qosEvent.Exception) { Message = "The message has been removed due to PII" }; if (qosEvent.Exception is MsalServiceException) { MsalServiceException ex = qosEvent.Exception as MsalServiceException; exceptionTelemetry.Properties.Add("CorrelationId", ex.CorrelationId); exceptionTelemetry.Properties.Add("ErrorCode", ex.ErrorCode); exceptionTelemetry.Properties.Add("StatusCode", ex.StatusCode.ToString(CultureInfo.InvariantCulture)); } if (qosEvent.Exception is PartnerException) { PartnerException ex = qosEvent.Exception as PartnerException; exceptionTelemetry.Properties.Add("ErrorCategory", ex.ErrorCategory.ToString()); PopulatePropertiesFromResponse(exceptionTelemetry.Properties, ex.Response); if (ex.ServiceErrorPayload != null) { exceptionTelemetry.Properties.Add("ErrorCode", ex.ServiceErrorPayload.ErrorCode); } } else if (qosEvent.Exception is RestException) { object ex = qosEvent.Exception as object; HttpResponseMessageWrapper response = ex.GetType().GetProperty("Response").GetValue(ex, null) as HttpResponseMessageWrapper; PopulatePropertiesFromResponse(exceptionTelemetry.Properties, response); } exceptionTelemetry.Metrics.Add("Duration", qosEvent.Duration.TotalMilliseconds); PopulatePropertiesFromQos(exceptionTelemetry.Properties); try { telemetryClient.TrackException(exceptionTelemetry); } catch { // Ignore any error with capturing the telemetry } }
public HttpResponseMessageWrapper<string> Trace(HttpRequestMessage req) { // Log function entrance TraceLog.TraceFunction(); // get the username from the message if available // the creds may not exist for a device that hasn't registered but is uploading a crash report string username = null; var creds = GetUserFromMessageHeaders(req); if (creds != null) username = creds.Name; try { Stream stream; switch (req.Content.Headers.ContentType.MediaType) { case "application/x-gzip": stream = new GZipStream(req.Content.ReadAsStreamAsync().Result, CompressionMode.Decompress); break; case "application/json": stream = req.Content.ReadAsStreamAsync().Result; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(string)); string data = (string) ser.ReadObject(stream); var ms = new MemoryStream(); var tw = new StreamWriter(ms); tw.Write(data); tw.Flush(); ms.Position = 0; stream = ms; break; default: stream = req.Content.ReadAsStreamAsync().Result; break; } string error = WriteFile(username, stream); var response = new HttpResponseMessageWrapper<string>(req, error != null ? error : "OK", HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; // return the response return response; } catch (Exception ex) { TraceLog.TraceException("Trace Write failed", ex); return new HttpResponseMessageWrapper<string>(req, HttpStatusCode.InternalServerError); } }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { CacheControlHeaderValue value2 = new CacheControlHeaderValue { MaxAge = new TimeSpan?(TimeSpan.Zero), Public = true, MustRevalidate = true }; if (response.Response != null && response.Response.Headers != null) { response.Response.Headers.CacheControl = value2; } return(response); }
public void Initialize(ITelemetry telemetry) { if (telemetry is ExceptionTelemetry exceptionTelemetry) { Exception ex = exceptionTelemetry.Exception; if (ex is HttpOperationException httpEx) { HttpResponseMessageWrapper res = httpEx.Response; exceptionTelemetry.Properties["statusCode"] = ((int)res.StatusCode).ToString(); string content = res.Content; if (content.Length > 512) { content = content.Substring(0, 512); } exceptionTelemetry.Properties["responseText"] = content; } } }
private string GetResponseHeaderInfo(HttpResponseMessageWrapper response, string headerName) { if (response == null || response.Headers == null) { return(null); } if (response.Headers.ContainsKey(headerName)) { var header = response.Headers[headerName].Select(e => e.ToString()); if (header != null) { var headerStringBuilder = new StringBuilder(); foreach (var info in header) { headerStringBuilder.AppendLine(info); } return(headerStringBuilder.ToString().TrimEnd()); } } return(null); }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { response.CurrentCacheKey.Append(Thread.CurrentPrincipal.Identity.Name); return(response); }
public RestApiException(HttpRequestMessageWrapper request, HttpResponseMessageWrapper response) : this(FormatMessage(response), request, response) { }
public RestApiException(string message, HttpRequestMessageWrapper request, HttpResponseMessageWrapper response) : base(message) { Request = request; Response = response; }
public HttpResponseMessageWrapper <string> SpeechToText(HttpRequestMessage req) { TraceLog.TraceFunction(); HttpStatusCode code = AuthenticateUser(req); if (code != HttpStatusCode.OK) { // user not authenticated return(new HttpResponseMessageWrapper <string>(req, code)); } // get a free instance of the speech recognition engine SpeechRecognitionEngine sre = null; while (sre == null) { sre = GetSpeechEngine(); // if all SRE's are in use, wait one second and then try again if (sre == null) { Thread.Sleep(1000); } } try { // retrieve and set the stream to recognize Stream stream = req.Content.ReadAsStreamAsync().Result; IEnumerable <string> values = new List <string>(); if (req.Headers.Contains(HttpApplicationHeaders.SpeechEncoding) == true) { stream = GetStream(req); } sre.SetInputToAudioStream(stream, formatInfo); #if WRITEFILE || DEBUG string msg = WriteSpeechFile(CurrentUser.Name, stream); if (msg != null) { return(new HttpResponseMessageWrapper <string>(req, msg, HttpStatusCode.OK)); } #endif // initialize timing information DateTime start = DateTime.Now; string responseString = null; // recognize var result = sre.Recognize(); if (result == null) { responseString = "[unrecognized]"; } else { responseString = result.Text; } // get timing information DateTime end = DateTime.Now; TimeSpan ts = end - start; // trace the recognized speech string timing = String.Format(" {0}.{1} seconds", ts.Seconds.ToString(), ts.Milliseconds.ToString()); TraceLog.TraceLine(String.Format("Recognized '{0}' in{1}", responseString, timing), TraceLog.LogLevel.Detail); // construct the response responseString += timing; var response = new HttpResponseMessageWrapper <string>(req, responseString, HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; // reset the speech engine (this is time-consuming so do it on a new thread) //ParameterizedThreadStart threadStart = new ParameterizedThreadStart(ResetSpeechEngine); //Thread thread = new Thread(threadStart); //thread.Start(new SpeechInfo() { Engine = sre, SpeechByteArray = speechToParse }); // release engine instance ReleaseSpeechEngine(sre); // return the response return(response); } catch (Exception ex) { // speech failed TraceLog.TraceException("Speech recognition failed", ex); // release engine instance ReleaseSpeechEngine(sre); return(new HttpResponseMessageWrapper <string>(req, HttpStatusCode.InternalServerError)); } }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { ETagStore.Invalidate(response.CurrentCacheKey); return(response); }
public HttpResponseMessageWrapper<User> GetCurrentUser(HttpRequestMessage req) { User user = null; try { MembershipUser mu = Membership.GetUser(); // if authenticated by asp.net (meaning, logged in through website), use membership // user info. otherwise get authentication information from message if (mu != null) { user = new User() { Name = mu.UserName }; } else { user = ResourceHelper.GetUserPassFromMessage(req); HttpStatusCode code = ResourceHelper.AuthenticateUser(req, TaskStore); if (code != HttpStatusCode.OK) return new HttpResponseMessageWrapper<User>(req, code); // user not authenticated } } catch (Exception) { // membership database is unreachable return new HttpResponseMessageWrapper<User>(req, HttpStatusCode.InternalServerError); } TaskStore taskstore = TaskStore; try { // get the user and all of their top-level objects User dbUser = taskstore.Users. Include("ListTypes.Fields"). Include("Tags"). Include("TaskLists.Tasks.TaskTags"). Single<User>(u => u.Name == user.Name); // make sure the response isn't cached var response = new HttpResponseMessageWrapper<User>(req, dbUser, HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; return response; } catch (Exception) { // couldn't find user - return 404 Not Found return new HttpResponseMessageWrapper<User>(req, HttpStatusCode.NotFound); } }
public static string GetResponseId(this HttpResponseMessageWrapper wrapper) { return(wrapper.Headers[ResponseIdHeader].FirstOrDefault()); }
public HttpResponseMessageWrapper<string> SpeechToText(HttpRequestMessage req) { TraceLog.TraceFunction(); HttpStatusCode code = AuthenticateUser(req); if (code != HttpStatusCode.OK) { // user not authenticated return new HttpResponseMessageWrapper<string>(req, code); } // get a free instance of the speech recognition engine SpeechRecognitionEngine sre = null; while (sre == null) { sre = GetSpeechEngine(); // if all SRE's are in use, wait one second and then try again if (sre == null) Thread.Sleep(1000); } try { // retrieve and set the stream to recognize Stream stream = req.Content.ReadAsStreamAsync().Result; IEnumerable<string> values = new List<string>(); if (req.Headers.Contains(HttpApplicationHeaders.SpeechEncoding) == true) stream = GetStream(req); sre.SetInputToAudioStream(stream, formatInfo); #if WRITEFILE || DEBUG string msg = WriteSpeechFile(CurrentUser.Name, stream); if (msg != null) return new HttpResponseMessageWrapper<string>(req, msg, HttpStatusCode.OK); #endif // initialize timing information DateTime start = DateTime.Now; string responseString = null; // recognize var result = sre.Recognize(); if (result == null) responseString = "[unrecognized]"; else responseString = result.Text; // get timing information DateTime end = DateTime.Now; TimeSpan ts = end - start; // trace the recognized speech string timing = String.Format(" {0}.{1} seconds", ts.Seconds.ToString(), ts.Milliseconds.ToString()); TraceLog.TraceLine(String.Format("Recognized '{0}' in{1}", responseString, timing), TraceLog.LogLevel.Detail); // construct the response responseString += timing; var response = new HttpResponseMessageWrapper<string>(req, responseString, HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; // reset the speech engine (this is time-consuming so do it on a new thread) //ParameterizedThreadStart threadStart = new ParameterizedThreadStart(ResetSpeechEngine); //Thread thread = new Thread(threadStart); //thread.Start(new SpeechInfo() { Engine = sre, SpeechByteArray = speechToParse }); // release engine instance ReleaseSpeechEngine(sre); // return the response return response; } catch (Exception ex) { // speech failed TraceLog.TraceException("Speech recognition failed", ex); // release engine instance ReleaseSpeechEngine(sre); return new HttpResponseMessageWrapper<string>(req, HttpStatusCode.InternalServerError); } }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { response.CurrentCacheKey.Append(response.Response.RequestMessage.RequestUri.AbsolutePath); return(response); }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { response.CurrentCacheKey = new CacheKey(attribute.DeclaringType); return(response); }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { SynchronizedCacheManager.Instance.Set(response.CurrentCacheKey, response); return(response); }
public HttpResponseInfo(HttpResponseMessageWrapper response) : base(response) { ResponseStatusCode = response.StatusCode.ToString(); }
/// <summary> /// Populates the telemetry event properties based on the HTTP response message. /// </summary> /// <param name="eventProperties">The telemetry event properties to be populated.</param> /// <param name="response">The HTTP response used to populate the event properties.</param> private static void PopulatePropertiesFromResponse(IDictionary <string, string> eventProperties, HttpResponseMessageWrapper response) { if (response == null) { return; } eventProperties.Add("ReasonPhrase", response.ReasonPhrase); eventProperties.Add("StatusCode", response.StatusCode.ToString()); }
public static string GetSourceChannel(this HttpResponseMessageWrapper wrapper) { return(wrapper.Headers[ResponseChannelHeader].FirstOrDefault()); }
/// <summary> /// Initializes a new instance of the <see cref="HttpResponseInfo" /> class. /// </summary> /// <param name="response">The wrapper for the HTTP response.</param> public HttpResponseInfo(HttpResponseMessageWrapper response) : base(response) { response.AssertNotNull(nameof(response)); ResponseStatusCode = response.StatusCode.ToString(); }
public HttpResponseMessageWrapper<List<TaskList>> GetTaskListsForUser(HttpRequestMessage req, Guid id) { HttpStatusCode code = ResourceHelper.AuthenticateUser(req, TaskStore); if (code != HttpStatusCode.OK) return new HttpResponseMessageWrapper<List<TaskList>>(req, code); // user not authenticated TaskStore taskstore = TaskStore; User user = ResourceHelper.GetUserPassFromMessage(req); User dbUser = taskstore.Users.Single<User>(u => u.Name == user.Name && u.Password == user.Password); try { User requestedUser = taskstore.Users.Single<User>(u => u.ID == id); // if the requested user is not the same as the authenticated user, return 403 Forbidden if (requestedUser.ID != dbUser.ID) return new HttpResponseMessageWrapper<List<TaskList>>(req, HttpStatusCode.Forbidden); else { try { var tasklists = taskstore.TaskLists.Include("User").Include("Tasks").Where(tl => tl.UserID == id).ToList(); var response = new HttpResponseMessageWrapper<List<TaskList>>(req, tasklists, HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; return response; } catch (Exception) { // tasklists not found - return 404 Not Found return new HttpResponseMessageWrapper<List<TaskList>>(req, HttpStatusCode.NotFound); } } } catch (Exception) { // user not found - return 404 Not Found return new HttpResponseMessageWrapper<List<TaskList>>(req, HttpStatusCode.NotFound); } }
public HttpResponseMessageWrapper Invoke(HttpResponseMessageWrapper response) { AppendVaryByParamsCacheKey(response.CurrentCacheKey, response.Response.RequestMessage.RequestUri); return(response); }
public HttpResponseMessageWrapper<List<TaskList>> GetTaskLists(HttpRequestMessage req) { HttpStatusCode code = ResourceHelper.AuthenticateUser(req, TaskStore); if (code != HttpStatusCode.OK) // user not authenticated return new HttpResponseMessageWrapper<List<TaskList>>(req, code); TaskStore taskstore = TaskStore; User user = ResourceHelper.GetUserPassFromMessage(req); User dbUser = taskstore.Users.Single<User>(u => u.Name == user.Name && u.Password == user.Password); // get the tasklists for this user try { Guid id = dbUser.ID; var tasklists = taskstore.TaskLists.Where(tl => tl.UserID == id).Include(tl => tl.Tasks).ToList(); var response = new HttpResponseMessageWrapper<List<TaskList>>(req, tasklists, HttpStatusCode.OK); response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true }; return response; } catch (Exception) { // tasklists not found - return 404 Not Found return new HttpResponseMessageWrapper<List<TaskList>>(req, HttpStatusCode.NotFound); } }