internal async Task <T> ExecuteRequestAsync <T>(Uri endPoint, HttpMethod method, RequestContext requestContext, bool expectErrorsOn200OK = false) { bool addCorrelationId = requestContext != null && !string.IsNullOrEmpty(requestContext.Logger.CorrelationId.ToString()); AddCommonHeaders(requestContext, addCorrelationId); HttpResponse response = null; Uri endpointUri = CreateFullEndpointUri(endPoint); var httpEvent = new HttpEvent(requestContext.CorrelationId.AsMatsCorrelationId()) { HttpPath = endpointUri, QueryParams = endpointUri.Query }; using (_telemetryManager.CreateTelemetryHelper(httpEvent)) { if (method == HttpMethod.Post) { response = await _httpManager.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext.Logger) .ConfigureAwait(false); } else { response = await _httpManager.SendGetAsync(endpointUri, _headers, requestContext.Logger).ConfigureAwait(false); } DecorateHttpEvent(method, requestContext, response, httpEvent); if (response.StatusCode != HttpStatusCode.OK || expectErrorsOn200OK) { try { httpEvent.OauthErrorCode = MsalError.UnknownError; // In cases where the end-point is not found (404) response.body will be empty. // CreateResponse handles throwing errors - in the case of HttpStatusCode <> and ErrorResponse will be created. if (!string.IsNullOrWhiteSpace(response.Body)) { var msalTokenResponse = JsonHelper.DeserializeFromJson <MsalTokenResponse>(response.Body); if (msalTokenResponse != null) { httpEvent.OauthErrorCode = msalTokenResponse?.Error; } if (response.StatusCode == HttpStatusCode.OK && expectErrorsOn200OK && !string.IsNullOrEmpty(msalTokenResponse.Error)) { ThrowServerException(response, requestContext); } } } catch (JsonException) // in the rare case we get an error response we cannot deserialize { // CreateErrorResponse does the same validation. Will be logging the error there. } } } return(CreateResponse <T>(response, requestContext, addCorrelationId)); }
public void TelemetryInternalApiSample() { var reqId = _telemetryManager.GenerateNewRequestId(); try { var e1 = new ApiEvent(new MsalLogger(Guid.NewGuid(), null)) { Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad" }; _telemetryManager.StartEvent(reqId, e1); // do some stuff... e1.WasSuccessful = true; _telemetryManager.StopEvent(reqId, e1); var e2 = new HttpEvent() { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2" }; _telemetryManager.StartEvent(reqId, e2); // do some stuff... e2.HttpResponseStatus = 200; _telemetryManager.StopEvent(reqId, e2); } finally { _telemetryManager.Flush(reqId, ClientId); } Assert.IsTrue(_myReceiver.EventsReceived.Count > 0); }
public void TelemetryInternalApiSample() { var correlationId = Guid.NewGuid().AsMatsCorrelationId(); try { var e1 = new ApiEvent(_logger, _crypto, correlationId) { Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad" }; _telemetryManager.StartEvent(e1); // do some stuff... e1.WasSuccessful = true; _telemetryManager.StopEvent(e1); var e2 = new HttpEvent(correlationId) { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2" }; _telemetryManager.StartEvent(e2); // do some stuff... e2.HttpResponseStatus = 200; _telemetryManager.StopEvent(e2); } finally { _telemetryManager.Flush(correlationId); } Assert.IsTrue(_myReceiver.EventsReceived.Count > 0); }
public ActionResult Index(string article) { var httpEvent = new HttpEvent { Data = article }; this.CurrentContext .EventSession .ToList() .ForEach(item => item.SendEvent(httpEvent)); return(Json("你的文章已推荐给所有人")); }
public async ValueTask <BaseProposedEvent> Transform( OriginalEvent originalEvent, CancellationToken cancellationToken ) { var httpEvent = new HttpEvent( originalEvent.EventDetails.EventType, originalEvent.EventDetails.Stream, Encoding.UTF8.GetString(originalEvent.Data) ); try { var response = await _client.PostAsync( "", new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(httpEvent)), cancellationToken ).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { throw new HttpRequestException($"Transformation request failed: {response.ReasonPhrase}"); } if (response.StatusCode == HttpStatusCode.NoContent) { return(new IgnoredEvent( originalEvent.EventDetails, originalEvent.Position, originalEvent.SequenceNumber )); } HttpEvent httpResponse = (await JsonSerializer.DeserializeAsync <HttpEvent>( await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), cancellationToken: cancellationToken ).ConfigureAwait(false)) !; return(new ProposedEvent( originalEvent.EventDetails with { EventType = httpResponse.EventType, Stream = httpResponse.StreamName }, Encoding.UTF8.GetBytes(httpResponse.Payload), originalEvent.Metadata, originalEvent.Position, originalEvent.SequenceNumber )); } catch (OperationCanceledException) { return(new NoEvent(originalEvent.EventDetails, originalEvent.Position, originalEvent.SequenceNumber)); } }
/// <summary> /// Populates fields on the GELF message that correspond to properties on an /// <see cref="HttpEvent"/> /// </summary> /// <param name="gelfMessage">The GELF message to populate</param> /// <param name="httpEvent">The HTTP diagnostic event</param> protected virtual void PopulateHttpFields(GelfMessage gelfMessage, HttpEvent httpEvent) { if (httpEvent == null) { return; } gelfMessage.Remote = httpEvent.Remote; gelfMessage.HttpMethod = httpEvent.Method; gelfMessage.HttpStatus = httpEvent.Status; if (httpEvent.Uri != null) { gelfMessage.Uri = httpEvent.Uri.ToString(); } }
internal async Task <T> ExecuteRequestAsync <T>(Uri endPoint, HttpMethod method, RequestContext requestContext) { bool addCorrelationId = (requestContext != null && !string.IsNullOrEmpty(requestContext.CorrelationId)); if (addCorrelationId) { _headers.Add(OAuth2Header.CorrelationId, requestContext.CorrelationId); _headers.Add(OAuth2Header.RequestCorrelationIdInResponse, "true"); } HttpResponse response = null; Uri endpointUri = CreateFullEndpointUri(endPoint); var httpEvent = new HttpEvent() { HttpPath = endpointUri, QueryParams = endpointUri.Query }; Client.Telemetry.GetInstance().StartEvent(requestContext.TelemetryRequestId, httpEvent); try { if (method == HttpMethod.Post) { response = await HttpRequest.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext).ConfigureAwait(false); } else { response = await HttpRequest.SendGetAsync(endpointUri, _headers, requestContext).ConfigureAwait(false); } httpEvent.HttpResponseStatus = (int)response.StatusCode; httpEvent.UserAgent = response.UserAgent; if (response.StatusCode != HttpStatusCode.OK) { httpEvent.OauthErrorCode = JsonHelper.DeserializeFromJson <TokenResponse>(response.Body).Error; } } finally { Client.Telemetry.GetInstance().StopEvent(requestContext.TelemetryRequestId, httpEvent); } return(CreateResponse <T>(response, requestContext, addCorrelationId)); }
public void TelemetryInternalApiSample() { Telemetry telemetry = new Telemetry(); // To isolate the test environment, we do not use a singleton here var myReceiver = new MyReceiver(); telemetry.RegisterReceiver(myReceiver.OnEvents); telemetry.ClientId = "a1b3c3d4"; var reqId = telemetry.GenerateNewRequestId(); try { var e1 = new ApiEvent() { Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad" }; telemetry.StartEvent(reqId, e1); // do some stuff... e1.WasSuccessful = true; telemetry.StopEvent(reqId, e1); var e2 = new HttpEvent() { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2" }; telemetry.StartEvent(reqId, e2); // do some stuff... e2.HttpResponseStatus = 200; telemetry.StopEvent(reqId, e2); } finally { telemetry.Flush(reqId); } Assert.IsTrue(myReceiver.EventsReceived.Count > 0); }
public void TelemetryEventCountsAreCorrectTest() { string[] reqIdArray = new string[5]; Task[] taskArray = new Task[5]; try { for (int i = 0; i < 5; i++) { var correlationId = Guid.NewGuid().AsMatsCorrelationId(); reqIdArray[i] = correlationId; Task task = new Task(() => { var e1 = new ApiEvent(_logger, _crypto, correlationId) { Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad" }; _telemetryManager.StartEvent(e1); // do some stuff... e1.WasSuccessful = true; _telemetryManager.StopEvent(e1); var e2 = new HttpEvent(correlationId) { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2" }; _telemetryManager.StartEvent(e2); // do some stuff... e2.HttpResponseStatus = 200; _telemetryManager.StopEvent(e2); var e3 = new HttpEvent(correlationId) { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeOtherUserAgent", QueryParams = "?a=3&b=4" }; _telemetryManager.StartEvent(e3); // do some stuff... e2.HttpResponseStatus = 200; _telemetryManager.StopEvent(e3); var e4 = new CacheEvent(CacheEvent.TokenCacheWrite, correlationId) { TokenType = CacheEvent.TokenTypes.AT }; _telemetryManager.StartEvent(e4); // do some stuff... _telemetryManager.StopEvent(e4); var e5 = new CacheEvent(CacheEvent.TokenCacheDelete, correlationId) { TokenType = CacheEvent.TokenTypes.RT }; _telemetryManager.StartEvent(e5); // do some stuff... _telemetryManager.StopEvent(e5); }); taskArray[i] = task; task.Start(); } Task.WaitAll(taskArray); } finally { foreach (string reqId in reqIdArray) { _telemetryManager.Flush(reqId); } } // Every task should have one default event with these counts foreach (Dictionary <string, string> telemetryEvent in _myReceiver.EventsReceived) { if (telemetryEvent[EventBase.EventNameKey] == "msal.default_event") { Assert.AreEqual("2", telemetryEvent[MsalTelemetryBlobEventNames.HttpEventCountTelemetryBatchKey]); Assert.AreEqual("2", telemetryEvent[MsalTelemetryBlobEventNames.CacheEventCountConstStrKey]); Assert.AreEqual("0", telemetryEvent[MsalTelemetryBlobEventNames.UiEventCountTelemetryBatchKey]); } } }
internal static void RaiseEvent(ProtocolDiagnosticHttpEvent pdEvent) { HttpEvent?.Invoke(pdEvent); }
public void ShouldDetectTextMimeTypes(string contentType) { HttpEvent.IsText(contentType).Should().BeTrue(); }
private void DecorateHttpEvent(HttpMethod method, RequestContext requestContext, HttpResponse response, HttpEvent httpEvent) { httpEvent.HttpResponseStatus = (int)response.StatusCode; httpEvent.UserAgent = response.UserAgent; httpEvent.HttpMethod = method.Method; IDictionary <string, string> headersAsDictionary = response.HeadersAsDictionary; if (headersAsDictionary.ContainsKey("x-ms-request-id") && headersAsDictionary["x-ms-request-id"] != null) { httpEvent.RequestIdHeader = headersAsDictionary["x-ms-request-id"]; } if (headersAsDictionary.ContainsKey("x-ms-clitelem") && headersAsDictionary["x-ms-clitelem"] != null) { XmsCliTelemInfo xmsCliTeleminfo = new XmsCliTelemInfoParser().ParseXMsTelemHeader( headersAsDictionary["x-ms-clitelem"], requestContext.Logger); if (xmsCliTeleminfo != null) { httpEvent.TokenAge = xmsCliTeleminfo.TokenAge; httpEvent.SpeInfo = xmsCliTeleminfo.SpeInfo; httpEvent.ServerErrorCode = xmsCliTeleminfo.ServerErrorCode; httpEvent.ServerSubErrorCode = xmsCliTeleminfo.ServerSubErrorCode; } } }
internal async Task <T> ExecuteRequestAsync <T>(Uri endPoint, HttpMethod method, RequestContext requestContext) { bool addCorrelationId = requestContext != null && !string.IsNullOrEmpty(requestContext.Logger.CorrelationId.ToString()); if (addCorrelationId) { _headers.Add(OAuth2Header.CorrelationId, requestContext.Logger.CorrelationId.ToString()); _headers.Add(OAuth2Header.RequestCorrelationIdInResponse, "true"); } HttpResponse response = null; var endpointUri = CreateFullEndpointUri(endPoint); var httpEvent = new HttpEvent() { HttpPath = endpointUri, QueryParams = endpointUri.Query }; using (_telemetryManager.CreateTelemetryHelper(requestContext.TelemetryRequestId, requestContext.ClientId, httpEvent)) { if (method == HttpMethod.Post) { response = await _httpManager.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext) .ConfigureAwait(false); } else { response = await _httpManager.SendGetAsync(endpointUri, _headers, requestContext).ConfigureAwait(false); } httpEvent.HttpResponseStatus = (int)response.StatusCode; httpEvent.UserAgent = response.UserAgent; httpEvent.HttpMethod = method.Method; IDictionary <string, string> headersAsDictionary = response.HeadersAsDictionary; if (headersAsDictionary.ContainsKey("x-ms-request-id") && headersAsDictionary["x-ms-request-id"] != null) { httpEvent.RequestIdHeader = headersAsDictionary["x-ms-request-id"]; } if (headersAsDictionary.ContainsKey("x-ms-clitelem") && headersAsDictionary["x-ms-clitelem"] != null) { XmsCliTelemInfo xmsCliTeleminfo = new XmsCliTelemInfoParser().ParseXMsTelemHeader(headersAsDictionary["x-ms-clitelem"], requestContext); if (xmsCliTeleminfo != null) { httpEvent.TokenAge = xmsCliTeleminfo.TokenAge; httpEvent.SpeInfo = xmsCliTeleminfo.SpeInfo; httpEvent.ServerErrorCode = xmsCliTeleminfo.ServerErrorCode; httpEvent.ServerSubErrorCode = xmsCliTeleminfo.ServerSubErrorCode; } } if (response.StatusCode != HttpStatusCode.OK) { try { httpEvent.OauthErrorCode = JsonHelper.DeserializeFromJson <MsalTokenResponse>(response.Body).Error; } catch (SerializationException) // in the rare case we get an error response we cannot deserialize { throw MsalExceptionFactory.GetServiceException( CoreErrorCodes.NonParsableOAuthError, CoreErrorMessages.NonParsableOAuthError, response); } } } return(CreateResponse <T>(response, requestContext, addCorrelationId)); }
public void TelemetryEventCountsAreCorrectTest() { string[] reqIdArray = new string[5]; Task[] taskArray = new Task[5]; try { for (int i = 0; i < 5; i++) { string reqId = _telemetryManager.GenerateNewRequestId(); reqIdArray[i] = reqId; Task task = new Task(() => { var e1 = new ApiEvent(new MsalLogger(Guid.NewGuid(), null)) { Authority = new Uri("https://login.microsoftonline.com"), AuthorityType = "Aad" }; _telemetryManager.StartEvent(reqId, e1); // do some stuff... e1.WasSuccessful = true; _telemetryManager.StopEvent(reqId, e1); var e2 = new HttpEvent() { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeUserAgent", QueryParams = "?a=1&b=2" }; _telemetryManager.StartEvent(reqId, e2); // do some stuff... e2.HttpResponseStatus = 200; _telemetryManager.StopEvent(reqId, e2); var e3 = new HttpEvent() { HttpPath = new Uri("https://contoso.com"), UserAgent = "SomeOtherUserAgent", QueryParams = "?a=3&b=4" }; _telemetryManager.StartEvent(reqId, e3); // do some stuff... e2.HttpResponseStatus = 200; _telemetryManager.StopEvent(reqId, e3); var e4 = new CacheEvent(CacheEvent.TokenCacheWrite) { TokenType = CacheEvent.TokenTypes.AT }; _telemetryManager.StartEvent(reqId, e4); // do some stuff... _telemetryManager.StopEvent(reqId, e4); var e5 = new CacheEvent(CacheEvent.TokenCacheDelete) { TokenType = CacheEvent.TokenTypes.RT }; _telemetryManager.StartEvent(reqId, e5); // do some stuff... _telemetryManager.StopEvent(reqId, e5); }); taskArray[i] = task; task.Start(); } Task.WaitAll(taskArray); } finally { foreach (string reqId in reqIdArray) { _telemetryManager.Flush(reqId, ClientId); } } // Every task should have one default event with these counts foreach (Dictionary <string, string> telemetryEvent in _myReceiver.EventsReceived) { if (telemetryEvent[EventBase.EventNameKey] == TelemetryEventProperties.MsalDefaultEvent) { Assert.AreEqual("2", telemetryEvent[TelemetryEventProperties.MsalHttpEventCount]); Assert.AreEqual("2", telemetryEvent[TelemetryEventProperties.MsalCacheEventCount]); Assert.AreEqual("0", telemetryEvent[TelemetryEventProperties.MsalUiEventCount]); } } }
private static IEnumerator Send(WWWForm form, EnumHTTPHead head) { string url = "http://" + ip + ":" + port + "/" + GetHeadString(head); WWW www = new WWW(url, form.data, cookies); //Debug.Log("request http url " + url + " cmdID, " + _cmdFormDic[form]); yield return(www); int cmdID = _cmdFormDic[form]; _cmdFormDic.Remove(form); if (www.error != null) { Debug.Log("serch fail..."); } else if (www.isDone) { if (www.bytes.Length == 0) { HttpEvent evt = new HttpEvent(cmdID.ToString()); _dispatcher.DispatchEventInstance(evt); yield break; } ByteArray receiveBytes = new ByteArray(); receiveBytes.WriteBytes(www.bytes); ReceivePackage pack = CmdUtil.ParseCmd(receiveBytes); if (pack.CmdID == (int)MsgType.ErrorMsg) { RetErrorMsg errorMsg = ProtoBuf.Serializer.Deserialize <RetErrorMsg>(pack.BodyStream); if (errorMsg.RetCode == 0) { Debug.Log("response http url success" + url); HttpEvent evt = new HttpEvent(cmdID.ToString()); _dispatcher.DispatchEventInstance(evt); } else { if (LoginServerErrorCode.ErrorCodeName == errorMsg.RetCode) { PopManager.ShowSimpleItem("用户名最多为4个汉字或8个英文字符"); } else if (LoginServerErrorCode.ErrorCodeAuthErr == errorMsg.RetCode) { PopManager.ShowSimpleItem("验证码错误,还可以输入" + errorMsg.Params + "次"); } else if (LoginServerErrorCode.ErrorCodeDb == errorMsg.RetCode) { PopManager.ShowSimpleItem("设置密码错误"); } else if (LoginServerErrorCode.ErrorCodePass == errorMsg.RetCode) { if (cmdID == (int)MsgType.CheckOldPassword) { PopManager.ShowSimpleItem("密码错误"); } else { PopManager.ShowSimpleItem("账号或密码错误"); } } else if (LoginServerErrorCode.ErrorCodeParam == errorMsg.RetCode) { if (cmdID == (int)MsgType.ChangePasswd || cmdID == (int)MsgType.SetPasswd || cmdID == (int)MsgType.CheckOldPassword) { PopManager.ShowSimpleItem("密码复杂度不够"); } else if (cmdID == (int)MsgType.AuthCode) { PopManager.ShowSimpleItem("获取验证码过于频繁"); HttpEvent evt = new HttpEvent(MsgType.ErrorMsg.ToString()); _dispatcher.DispatchEventInstance(evt); } else { PopManager.ShowSimpleItem("参数错误"); } } else if (LoginServerErrorCode.ErrorCodeIsBind == errorMsg.RetCode) { PopManager.ShowSimpleItem("手机号已被绑定"); } else if (LoginServerErrorCode.ErrorCodeMsgErr == errorMsg.RetCode) { PopManager.ShowSimpleItem("短信服务器出错"); } else if (LoginServerErrorCode.ErrorCodeTelErr == errorMsg.RetCode) { PopManager.ShowSimpleItem("手机号错误"); } else if (LoginServerErrorCode.ErrorCodeMaxMsg == errorMsg.RetCode) { PopManager.ShowSimpleItem("今天短信次数已用完"); } else if (LoginServerErrorCode.ErrorCodeMaxErr == errorMsg.RetCode) { PopManager.ShowSimpleItem("密码错误已超过最大限制"); } else if (LoginServerErrorCode.ErrorCodeExist == errorMsg.RetCode) { PopManager.ShowSimpleItem("用户名已存在"); } else if (LoginServerErrorCode.ErrorCodeUnBind == errorMsg.RetCode) { PopManager.ShowSimpleItem("未绑定手机"); } else if (LoginServerErrorCode.ErrorCodeSetAccountTm == errorMsg.RetCode) { ulong leftDays = errorMsg.Params / (24 * 60 * 60); if (leftDays >= 1) { PopManager.ShowSimpleItem("还需 " + (uint)leftDays + "天才可以修改用户名"); } else { ulong leftHours = errorMsg.Params / (60 * 60); if (leftHours >= 1) { PopManager.ShowSimpleItem("还需 " + (uint)leftHours + "小时才可以修改用户名"); } else { PopManager.ShowSimpleItem("还需 " + (uint)(errorMsg.Params / 60) + "分钟才可以修改用户名"); } } } else if (LoginServerErrorCode.ErrorCodeSignReward == errorMsg.RetCode) { PopManager.ShowSimpleItem("签到奖励领取失败"); } else if (LoginServerErrorCode.ErrorCodeSignIned == errorMsg.RetCode) { PopManager.ShowSimpleItem("已签到"); } else if (LoginServerErrorCode.ErrorCodeRoom == errorMsg.RetCode) { PopManager.ShowSimpleItem("未找到房间"); } else if (LoginServerErrorCode.ErrorCodeIsFull == errorMsg.RetCode) { PopManager.ShowSimpleItem("目标房间已满"); } else if (LoginServerErrorCode.ErrorCodeDb == errorMsg.RetCode) { PopManager.ShowSimpleItem("数据库错误"); } Log("http cmd error code:" + errorMsg.RetCode + " para:" + errorMsg.Params); } } else { Log("response http url success " + url + " CmdID:" + (MsgType)pack.CmdID); HttpEvent evt = new HttpEvent(pack.CmdID.ToString(), pack.BodyStream); _dispatcher.DispatchEventInstance(evt); } } }
internal async Task <T> ExecuteRequestAsync <T>(Uri endPoint, HttpMethod method, RequestContext requestContext, bool expectErrorsOn200OK = false, bool addCommonHeaders = true) { //Requests that are replayed by PKeyAuth do not need to have headers added because they already exist if (addCommonHeaders) { AddCommonHeaders(requestContext); } HttpResponse response = null; Uri endpointUri = AddExtraQueryParams(endPoint); var httpEvent = new HttpEvent(requestContext.CorrelationId.AsMatsCorrelationId()) { HttpPath = endpointUri, QueryParams = endpointUri.Query }; using (requestContext.CreateTelemetryHelper(httpEvent)) { using (requestContext.Logger.LogBlockDuration($"[Oauth2Client] Sending {method} request ")) { if (method == HttpMethod.Post) { response = await _httpManager.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext.Logger) .ConfigureAwait(false); } else { response = await _httpManager.SendGetAsync( endpointUri, _headers, requestContext.Logger, cancellationToken : requestContext.UserCancellationToken).ConfigureAwait(false); } } if (requestContext.ApiEvent != null) { requestContext.ApiEvent.DurationInHttpInMs += _httpManager.LastRequestDurationInMs; } DecorateHttpEvent(method, requestContext, response, httpEvent); if (response.StatusCode != HttpStatusCode.OK || expectErrorsOn200OK) { requestContext.Logger.Verbose("[Oauth2Client] Processing error response "); try { httpEvent.OauthErrorCode = MsalError.UnknownError; // In cases where the end-point is not found (404) response.body will be empty. // CreateResponse handles throwing errors - in the case of HttpStatusCode <> and ErrorResponse will be created. if (!string.IsNullOrWhiteSpace(response.Body)) { var msalTokenResponse = JsonHelper.DeserializeFromJson <MsalTokenResponse>(response.Body); if (msalTokenResponse != null) { httpEvent.OauthErrorCode = msalTokenResponse?.Error; } if (response.StatusCode == HttpStatusCode.OK && expectErrorsOn200OK && !string.IsNullOrEmpty(msalTokenResponse?.Error)) { ThrowServerException(response, requestContext); } } } catch (JsonException) // in the rare case we get an error response we cannot deserialize { // CreateErrorResponse does the same validation. Will be logging the error there. } } } return(CreateResponse <T>(response, requestContext)); }
private static async void BixListens_OnHttpEventReceived(object sender, HttpEvent e) { Log.Bulb($"{e.ID} Received new event"); var responseBuilder = new StringBuilder(); if (!IsNullOrEmpty(e.QueryString["UpdateState"])) { SendResponse(e.HttpListenerResponse, "OK"); Log.Bulb($"{e.ID} Proccessed event"); foreach (var bulb in Bulbs) { _client.UpdateLightStateAsync(bulb); } return; } if (!IsNullOrEmpty(e.QueryString["Log"])) { SendResponse(e.HttpListenerResponse, Log.GetMessages(), false); Log.Bulb($"{e.ID} Proccessed event"); return; } if (!IsNullOrEmpty(e.QueryString["BuildBulbs"])) { SendResponse(e.HttpListenerResponse, BuildCreateDevice()); Log.Bulb($"{e.ID} Proccessed event"); return; } if (!IsNullOrEmpty(e.QueryString["Status"])) { SendResponse(e.HttpListenerResponse, BuildStatus()); Log.Bulb($"{e.ID} Proccessed event"); return; } if (!IsNullOrEmpty(e.QueryString["ListColors"])) { SendResponse(e.HttpListenerResponse, ColorsTable); Log.Bulb($"{e.ID} Proccessed event"); return; } if (!IsNullOrEmpty(e.QueryString["ListLights"])) { var lights = Bulbs.Where(a => a.State != null).Select(a => a.State.Label).OrderBy(b1 => b1).ToList(); foreach (var light1 in lights) { responseBuilder.AppendLine(light1); } SendResponse(e.HttpListenerResponse, responseBuilder.ToString()); Log.Bulb($"{e.ID} Proccessed event"); return; } if (IsNullOrEmpty(e.QueryString["Light"])) { SendResponse(e.HttpListenerResponse, "Need a light"); Log.Bulb($"{e.ID} Proccessed event"); return; } var light = e.QueryString["Light"]; var bulbs = new List <LightBulb>(); if (light == "all") { lock (Bulbs) { bulbs.AddRange(Bulbs); } } else { var b = Bulbs.FirstOrDefault(a => a.State != null && a.State.Label == light); if (b != null) { bulbs.Add(b); } else { var bd = Bulbs.Where(a => a.State != null && a.State.Label.StartsWith(light)).ToList(); if (!bd.Any()) { SendResponse(e.HttpListenerResponse, $"Cant find light or starts with {light}"); return; } bulbs.AddRange(bd); } } //var t1 =UpdateBulbs(bulbs); //PowerCommand if (!IsNullOrEmpty(e.QueryString["Power"])) { var powerstate = e.QueryString["Power"].ToLower(); foreach (var bulb in bulbs) { lock (new object()) { var power = SetPower(bulb, e.ID, powerstate); responseBuilder.AppendLine($"Powered {light} from {powerstate} to {power.Result}"); } } } var goodCommand = false; //Set Color ushort hue = 0; ushort saturation = 0; ushort brightness = 0; ushort kelvin = 0; if (!IsNullOrEmpty(e.QueryString["Dim"])) { var dimStr = e.QueryString["Dim"].ToLower(); ushort dim; if (ushort.TryParse(dimStr, out dim)) { goodCommand = true; dim = (ushort)(65535 * (dim / 100.0)); brightness = dim; } else { responseBuilder.AppendLine($"Dim {dimStr} needs to be a whole number"); } } var colorStr = ""; if (!IsNullOrEmpty(e.QueryString["Color"])) { var isGood = true; colorStr = e.QueryString["Color"].ToLower(); if (IsNullOrEmpty(colorStr)) { isGood = false; responseBuilder.AppendLine("Color is empty"); } else if (colorStr.StartsWith("#") && colorStr.Length == 7) { var color = ColorTranslator.FromHtml(colorStr); colorStr = color.Name; } else if (colorStr.Length == 4 && ushort.TryParse(colorStr, out kelvin)) { if (kelvin < 2500 || kelvin > 9000) { responseBuilder.AppendLine($"Kelvin {kelvin} out of range (2500-9000)"); isGood = false; } else { hue = 255; saturation = 255; } } else if (BIXColors.Colors.ContainsKey(colorStr)) { var color = BIXColors.Colors[colorStr]; hue = color.LIFXHue; saturation = color.LIFXSaturation; } else { responseBuilder.AppendLine($"Cannot find color {colorStr}"); isGood = false; } if (!isGood) { SendResponse(e.HttpListenerResponse, responseBuilder.ToString()); Log.Bulb($"{e.ID} Proccessed event"); return; } goodCommand = true; } if (goodCommand) { foreach (var bulb in bulbs) { lock (new object()) { var t = SetColor(bulb, e.ID, hue, saturation, brightness, kelvin); responseBuilder.AppendLine( $"Set color for bulb {bulb.State.Label} to color {colorStr} hue: {hue} saturation: {saturation} brightness: {brightness} kelvin: {kelvin}"); } } } SendResponse(e.HttpListenerResponse, responseBuilder.ToString()); Log.Bulb($"{e.ID} Proccessed event"); }
internal async Task <T> ExecuteRequestAsync <T>(Uri endPoint, HttpMethod method, RequestContext requestContext) { bool addCorrelationId = requestContext != null && !string.IsNullOrEmpty(requestContext.Logger.CorrelationId.ToString()); if (addCorrelationId) { _headers.Add(OAuth2Header.CorrelationId, requestContext.Logger.CorrelationId.ToString()); _headers.Add(OAuth2Header.RequestCorrelationIdInResponse, "true"); } if (!string.IsNullOrWhiteSpace(requestContext.Logger.ClientName)) { _headers.Add(OAuth2Header.AppName, requestContext.Logger.ClientName); } if (!string.IsNullOrWhiteSpace(requestContext.Logger.ClientVersion)) { _headers.Add(OAuth2Header.AppVer, requestContext.Logger.ClientVersion); } HttpResponse response = null; Uri endpointUri = CreateFullEndpointUri(endPoint); var httpEvent = new HttpEvent(requestContext.TelemetryCorrelationId) { HttpPath = endpointUri, QueryParams = endpointUri.Query }; using (_telemetryManager.CreateTelemetryHelper(httpEvent)) { if (method == HttpMethod.Post) { response = await _httpManager.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext.Logger) .ConfigureAwait(false); } else { response = await _httpManager.SendGetAsync(endpointUri, _headers, requestContext.Logger).ConfigureAwait(false); } httpEvent.HttpResponseStatus = (int)response.StatusCode; httpEvent.UserAgent = response.UserAgent; httpEvent.HttpMethod = method.Method; IDictionary <string, string> headersAsDictionary = response.HeadersAsDictionary; if (headersAsDictionary.ContainsKey("x-ms-request-id") && headersAsDictionary["x-ms-request-id"] != null) { httpEvent.RequestIdHeader = headersAsDictionary["x-ms-request-id"]; } if (headersAsDictionary.ContainsKey("x-ms-clitelem") && headersAsDictionary["x-ms-clitelem"] != null) { XmsCliTelemInfo xmsCliTeleminfo = new XmsCliTelemInfoParser().ParseXMsTelemHeader( headersAsDictionary["x-ms-clitelem"], requestContext.Logger); if (xmsCliTeleminfo != null) { httpEvent.TokenAge = xmsCliTeleminfo.TokenAge; httpEvent.SpeInfo = xmsCliTeleminfo.SpeInfo; httpEvent.ServerErrorCode = xmsCliTeleminfo.ServerErrorCode; httpEvent.ServerSubErrorCode = xmsCliTeleminfo.ServerSubErrorCode; } } if (response.StatusCode != HttpStatusCode.OK) { try { httpEvent.OauthErrorCode = MsalError.UnknownError; // In cases where the end-point is not found (404) response.body will be empty. // CreateResponse handles throwing errors - in the case of HttpStatusCode <> and ErrorResponse will be created. if (!string.IsNullOrWhiteSpace(response.Body)) { var msalTokenResponse = JsonHelper.DeserializeFromJson <MsalTokenResponse>(response.Body); if (msalTokenResponse != null) { httpEvent.OauthErrorCode = msalTokenResponse.Error; } } } catch (SerializationException) // in the rare case we get an error response we cannot deserialize { // CreateErrorResponse does the same validation. Will be logging the error there. } } } return(CreateResponse <T>(response, requestContext, addCorrelationId)); }