public IHttpActionResult PostErrorData(ErrorData errorData) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.ErrorDatas.Add(errorData); try { db.SaveChanges(); } catch (DbUpdateException) { if (ErrorDataExists(errorData.ID)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = errorData.ID }, errorData)); }
public IHttpActionResult PutErrorData(int id, ErrorData errorData) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != errorData.ID) { return(BadRequest()); } db.Entry(errorData).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ErrorDataExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private FiskalyHttpError CreateFiskalyHttpError <T>(JsonRpcResponse <T> response) { ErrorData errorData = JsonConvert .DeserializeObject <ErrorData>(response.Error.Data.ToString()); FiskalyApiError errorBody = JsonConvert .DeserializeObject <FiskalyApiError>( Transformer.DecodeBase64Body(errorData.Response.Body)); string[] requestIdHeaders; errorData .Response .Headers .TryGetValue("x-request-id", out requestIdHeaders); string requestId = requestIdHeaders[0]; return(new FiskalyHttpError( response.Error.Code, errorBody.Error, errorBody.Message, errorBody.Code, requestId )); }
private void OnLoginCallback(long statusCode, string json) { switch (statusCode) { case 200: // Ok { // TODO: Get user id from the server UserData.Id = 1; onLoginFinishedListener.OnLoginSucceed(); break; } case 404: // Not Found { var errorMessage = ErrorData.FromJsonToErrorMessage(json); if (errorMessage == string.Empty) { errorMessage = NoticeMessages.AuthView.UnknownError; } onLoginFinishedListener.OnLoginFailed(errorMessage); break; } default: { var errorMessage = NoticeMessages.AuthView.UnknownError; onLoginFinishedListener.OnLoginFailed(errorMessage); break; } } }
private bool isCorrectUser(string id) { logger.Debug(Settings.MethodName()); logger.Trace("Parameters: id: " + id); long loggedInUserId; if (long.TryParse(id, out loggedInUserId)) { if (UserManager.IsLoggedIn(loggedInUserId)) { logger.Trace("Return: true"); return(true); } else { logger.Trace("Not logged in (1), Session expired or not logged in."); ErrorData errorData = new ErrorData("Not logged in.", "Session expired or not logged in."); throw new WebFaultException <ErrorData>(errorData, HttpStatusCode.Unauthorized); } } else { logger.Trace("Not logged in (2), Session expired or not logged in."); ErrorData errorData = new ErrorData("Incorrect user.", "The user could not be determined."); throw new WebFaultException <ErrorData>(errorData, HttpStatusCode.Unauthorized); } }
private void ReportErrorToUser(ApplicationUnhandledExceptionEventArgs e) { if (e.ExceptionObject != null) { errorDisplay = new ErrorDisplay(); // Attempt to get the stack trace with IL offsets string stackTraceIL = e.ExceptionObject.StackTraceIL(); ErrorData data = new ErrorData() { Message = e.ExceptionObject.Message, StackTrace = !string.IsNullOrEmpty(stackTraceIL) ? stackTraceIL : e.ExceptionObject.StackTrace }; errorDisplay.DataContext = data; // Size the error UI double width = Application.Current.RootVisual.RenderSize.Width * 0.67; errorDisplay.Width = width > errorDisplay.MaxWidth ? errorDisplay.MaxWidth : width; errorDisplay.Completed += new EventHandler <EventArgs>(errorDisplay_Completed); // Show the error MapApplication.Current.ShowWindow(StringResourcesManager.Instance.Get("ErrorCaption"), errorDisplay); } }
public override ErrorData Simulate(Transform vesselTransform, Vector3d targetDirection, Vector3d targetDirectionYaw, Vector3 targetPosition, Vector3 upDirection, float upWeighting, Vessel vessel) { float pitchError; float rollError; float yawError; float sideslip; sideslip = (float)Math.Asin(Vector3.Dot(vesselTransform.right, vessel.srf_velocity.normalized)) * Mathf.Rad2Deg; pitchError = (float)Math.Asin(Vector3d.Dot(Vector3d.back, VectorUtils.Vector3dProjectOnPlane(targetDirection, Vector3d.right))) * Mathf.Rad2Deg; yawError = (float)Math.Asin(Vector3d.Dot(Vector3d.right, VectorUtils.Vector3dProjectOnPlane(targetDirectionYaw, Vector3d.forward))) * Mathf.Rad2Deg; //roll Vector3 currentRoll = -vesselTransform.forward; Vector3 rollTarget; rollTarget = (targetPosition + Mathf.Clamp(upWeighting * (100f - Math.Abs(yawError * 1.6f) - (pitchError * 2.8f)), 0, float.PositiveInfinity) * upDirection) - vessel.CoM; rollTarget = Vector3.ProjectOnPlane(rollTarget, vesselTransform.up); rollError = VectorUtils.SignedAngle(currentRoll, rollTarget, vesselTransform.right) - sideslip * (float)Math.Sqrt(vessel.srf_velocity.magnitude) / 5; float pitchDownFactor = pitchError * (10 / ((float)Math.Pow(yawError, 2) + 10f) - 0.1f); rollError -= Mathf.Clamp(pitchDownFactor, -15, 0); ErrorData behavior = new ErrorData(pitchError, rollError, yawError); return(behavior); }
public override string Log(Error error) { var errorXml = ErrorXml.EncodeString(error); var id = Guid.NewGuid(); var token = Task.Run(() => GetAccessToken()).Result; if (string.IsNullOrWhiteSpace(token) && !httpContext.User.Identity.IsAuthenticated) { throw new SecurityException("Unauthenticated user"); } var innerException = error.Exception as ApiException; if (innerException != null && innerException.ErrorData != null) { Task.Run(() => apiClient.ErrorLog.Create(token, new ErrorData(Guid.NewGuid(), ApplicationName, error.HostName, error.Type, innerException.Source, innerException.ErrorData.ExceptionMessage, error.User, (int)innerException.StatusCode, error.Time.ToUniversalTime(), GetApiErrorAsXml(innerException.ErrorData)))); } var errorData = new ErrorData(id, ApplicationName, error.HostName, error.Type, error.Source, error.Message, error.User, error.StatusCode, error.Time.ToUniversalTime(), errorXml); Task.Run(() => apiClient.ErrorLog.Create(token, errorData)); return(id.ToString()); }
public void GetSpanEvent_DoesNotIncludesErrorAttributes_WhenThereIsAnError_IfErrorCollectionIsDisabled() { // ARRANGE _localConfig.errorCollector.enabled = false; PublishConfig(); var testError = new ErrorData("error message", "ErrorType", "stack trace", DateTime.UtcNow, null, false); var segments = new List <Segment>() { _baseGenericSegment.CreateSimilar(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(5), new List <KeyValuePair <string, object> >()) }; segments[0].ErrorData = testError; var immutableTransaction = BuildTestTransaction(segments, sampled: true, hasIncomingPayload: true); var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName); var metricStatsCollection = new TransactionMetricStatsCollection(transactionMetricName); var transactionAttributes = _transactionAttribMaker.GetAttributes(immutableTransaction, transactionMetricName, TimeSpan.FromSeconds(1), immutableTransaction.Duration, metricStatsCollection); // ACT var spanEvents = _spanEventMaker.GetSpanEvents(immutableTransaction, TransactionName, transactionAttributes).ToList(); var spanEvent = spanEvents[1]; var rootSpanEvent = spanEvents[0]; var errorEventAttributes = new AttributeValueCollection(transactionAttributes, AttributeDestinations.ErrorEvent); // ASSERT NrAssert.Multiple( () => CollectionAssert.DoesNotContain(errorEventAttributes.GetAttributeValuesDic(AttributeClassification.Intrinsics).Keys, "spanId"), () => CollectionAssert.DoesNotContain(spanEvent.AgentAttributes().Keys, "error.class"), () => CollectionAssert.DoesNotContain(rootSpanEvent.AgentAttributes().Keys, "error.class") ); }
protected override void CreateData() { _data = new List <Error> { ErrorData.GenerateSampleError(), ErrorData.GenerateSampleError(TestConstants.ErrorId2) }; }
public static ApiResponse Error(Context context, ErrorData errorData, params string[] data) { switch (errorData.Type) { case General.Error.Types.BadRequest: return(BadRequest(context)); case General.Error.Types.Unauthorized: return(Unauthorized(context)); case General.Error.Types.NotFound: return(NotFound(context)); case General.Error.Types.HasNotPermission: return(Forbidden(context)); default: return(new ApiResponse(500, data?.Any() == true ? Displays.Get( context: context, id: errorData.Type.ToString()).Params(data) : Displays.Get( context: context, id: errorData.Type.ToString()))); } }
public MainPage() { InitializeComponent(); config = Config.Instance; recentListData = new RecentPodcastListData(); podcastListItems.DataContext = recentListData; recentPlayedListData = new RecentPlayedListData(); podcastRecentPlayedItems.DataContext = recentPlayedListData; searchData = new SearchPodcastData(); searchPodcastList.DataContext = searchData; errorData = new ErrorData(); errorGrid.DataContext = errorData; errorData.Error = "Loading..."; sliderData = new TimeSliderData(); timeSlider.DataContext = sliderData; otherPageData = new OtherMainPageData(); AlbumArt.DataContext = otherPageData; PodcastFunctions.UpdateLatestListEvent += OnLatestListUpdate; PodcastFunctions.UpdateLatestPlayedListEvent += OnRecentPlayListUpdate; PodcastFunctions.AlbumArtUpdated += OnAlbumArtUpdated; ItemsControlTemplates.OnDownloadRecentEvent += DownloadRecentClicked; ItemsControlTemplates.OnSelectEpisodeEvent += SelectEpisodeClicked; ItemsControlTemplates.OnPlayEpisodeEvent += PlayRecentClicked; MainWindow.OnMainWindowSizeChanged += OnMainWindowSizeChanged; Task.Run(() => InitializePodcasts()); }
public static void registerToUnity(OnError onError, bool logWarnings) { Application.logMessageReceivedThreaded += (message, backtrace, type) => { if ( type == LogType.Assert || type == LogType.Error || type == LogType.Exception || (logWarnings && type == LogType.Warning) ) { ASync.OnMainThread( () => { try { var parsedBacktrace = // backtrace may be empty in release mode. string.IsNullOrEmpty(backtrace) ? BacktraceElem.generateFromHere() : BacktraceElem.parseUnityBacktrace(backtrace); var data = new ErrorData(type, message, parsedBacktrace); onError(data); } catch (Exception e) { // Log at info level so that we wouldn't trigger this handler again. Log.info( $"[{nameof(ErrorReporter)}] Exception in " + $"{nameof(Application)}.{nameof(Application.logMessageReceivedThreaded)}" + $" handler!\n\n{e}" ); } }, // https://fogbugz.unity3d.com/default.asp?832198_48nbh0a3a8cjpr12 runNowIfOnMainThread: false ); } }; }
public void Convert() { var random = new Random(); var data = new ErrorData(Guid.NewGuid()) { ClassName = StringHelper.ValidString(), DeploymentId = StringHelper.ValidString(), ErrorCode = random.Next(), EventTypeValue = 2, MachineName = StringHelper.ValidString(), Message = StringHelper.ValidString(), OccurredOn = DateTime.UtcNow, ParentId = Guid.NewGuid(), Source = StringHelper.ValidString(), StackTrace = StringHelper.ValidString(), SessionIdentifier = Guid.NewGuid(), }; var converted = data.Convert(); Assert.AreEqual <string>(data.ClassName, converted.ClassName); Assert.AreEqual <string>(data.DeploymentId, converted.DeploymentId); Assert.AreEqual <int>(data.ErrorCode, converted.ErrorCode); Assert.AreEqual <int>(data.EventTypeValue, (int)converted.EventType); Assert.AreEqual <string>(data.MachineName, converted.MachineName); Assert.AreEqual <string>(data.Message, converted.Message); Assert.AreEqual <DateTime>(data.OccurredOn, converted.OccurredOn); Assert.AreEqual <string>(data.Source, converted.Source); Assert.AreEqual <string>(data.StackTrace, converted.StackTrace); Assert.AreEqual <Guid>(data.ApplicationId, converted.Token.ApplicationId); Assert.AreEqual <Guid>(data.ParentId, converted.ParentIdentifier); Assert.AreEqual <Guid>(Guid.Parse(data.RowKey), converted.Identifier); Assert.AreEqual <Guid?>(data.SessionIdentifier, converted.SessionIdentifier); }
public void ManagedSignature() { int n = 0; Errors = 0; ErrorData.Clear(); foreach (Type t in Assembly.GetTypes()) { if (!NSObjectType.IsAssignableFrom(t)) { continue; } CurrentType = t; foreach (MethodInfo m in t.GetMethods(Flags)) { CheckManagedMemberSignatures(m, t, ref n); } foreach (MethodBase m in t.GetConstructors(Flags)) { CheckManagedMemberSignatures(m, t, ref n); } } AssertIfErrors("{0} errors found in {1} signatures validated{2}", Errors, n, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString() + "\n"); }
public void CanHideStacksFromStats() { _dataHelper.ResetProjectData(TestConstants.ProjectId); TimeSpan timeOffset = _projectRepository.GetDefaultTimeOffset(TestConstants.ProjectId); DateTime startDate = DateTime.UtcNow.Add(timeOffset).Date.AddDays(-120); DateTime endDate = DateTime.UtcNow.Add(timeOffset).Date; const int count = 50; List <Error> errors = ErrorData.GenerateErrors(count, organizationId: TestConstants.OrganizationId, startDate: startDate, endDate: endDate, projectId: TestConstants.ProjectId, timeZoneOffset: timeOffset).ToList(); _errorPipeline.Run(errors); var firstStack = _errorStackRepository.Where(es => es.ProjectId == TestConstants.ProjectId).OrderBy(es => es.FirstOccurrence).First(); firstStack.IsHidden = true; _errorStackRepository.Update(firstStack); var biggestStack = _errorStackRepository.Where(es => es.ProjectId == TestConstants.ProjectId && !es.IsHidden).OrderByDescending(es => es.TotalOccurrences).First(); biggestStack.IsHidden = true; _errorStackRepository.Update(biggestStack); _errorStackRepository.InvalidateHiddenIdsCache(TestConstants.ProjectId); long stackCount = _errorStackRepository.Where(s => !s.IsHidden).Count(); int countWithoutHidden = count - firstStack.TotalOccurrences - biggestStack.TotalOccurrences; var info = _errorStatsHelper.GetProjectErrorStats(TestConstants.ProjectId, timeOffset, startDate, endDate); Assert.Equal(countWithoutHidden, info.Total); Assert.InRange(info.UniqueTotal, 1, count); Assert.Equal(stackCount, info.NewTotal); Assert.True(info.Stats.Count > 40); Assert.Equal(countWithoutHidden, info.Stats.Sum(ds => ds.Total)); Assert.Equal(stackCount, info.Stats.Sum(ds => ds.NewTotal)); }
public void Transform(ErrorData errorData, float priority) { if (!_configurationService.Configuration.ErrorCollectorEnabled) { return; } var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorEvent, AttributeDestinations.ErrorTrace); if (errorData.CustomAttributes != null && _configurationService.Configuration.CaptureCustomParameters) { foreach (var customAttrib in errorData.CustomAttributes) { _attribDefs.GetCustomAttributeForError(customAttrib.Key).TrySetValue(attribValues, customAttrib.Value); } } // For Custom Errors (occurring outside a transaction), UI Error Analytics page co-opts the // 'transactionName' attribute to find the corresponding Error Trace (matching it to 'Path') // so it can display the stack trace. _attribDefs.TransactionNameForError.TrySetValue(attribValues, errorData.Path); //We have to do the filtering here b/c these methods further update var errorTrace = _errorTraceMaker.GetErrorTrace(new AttributeValueCollection(attribValues, AttributeDestinations.ErrorTrace), errorData); var errorEvent = _errorEventMaker.GetErrorEvent(errorData, new AttributeValueCollection(attribValues, AttributeDestinations.ErrorEvent), priority); _errorTraceAggregator.Collect(errorTrace); _errorEventAggregator.Collect(errorEvent); }
public void CanAggregateStatsOverSeveralMonthsForMultipleProjects() { _dataHelper.ResetProjectData(TestConstants.ProjectId); TimeSpan timeOffset = _projectRepository.GetDefaultTimeOffset(TestConstants.ProjectId); DateTime startDate = DateTime.UtcNow.Add(timeOffset).Date.AddDays(-120); DateTime endDate = DateTime.UtcNow.Add(timeOffset).Date; const int count1 = 50; const int count2 = 50; List <Error> errors1 = ErrorData.GenerateErrors(count1, organizationId: TestConstants.OrganizationId, startDate: startDate, endDate: endDate, errorStackId: TestConstants.ErrorStackId, projectId: TestConstants.ProjectId, timeZoneOffset: timeOffset).ToList(); _errorPipeline.Run(errors1); List <Error> errors2 = ErrorData.GenerateErrors(count2, organizationId: TestConstants.OrganizationId, startDate: startDate, endDate: endDate, errorStackId: TestConstants.ErrorStackId2, projectId: TestConstants.ProjectIdWithNoRoles, timeZoneOffset: timeOffset).ToList(); _errorPipeline.Run(errors2); var info1 = _errorStatsHelper.GetProjectErrorStats(TestConstants.ProjectId, timeOffset, startDate, endDate); Assert.Equal(count1, info1.Total); Assert.InRange(info1.UniqueTotal, 1, count1); Assert.Equal(0, info1.NewTotal); Assert.True(info1.Stats.Count > 40); Assert.Equal(count1, info1.Stats.Sum(ds => ds.Total)); Assert.Equal(0, info1.Stats.Sum(ds => ds.NewTotal)); var info2 = _errorStatsHelper.GetProjectErrorStats(TestConstants.ProjectIdWithNoRoles, timeOffset, startDate, endDate); Assert.Equal(count2, info2.Total); Assert.InRange(info2.UniqueTotal, 1, count2); Assert.Equal(0, info2.NewTotal); Assert.True(info2.Stats.Count > 40); Assert.Equal(count2, info2.Stats.Sum(ds => ds.Total)); Assert.Equal(0, info2.Stats.Sum(ds => ds.NewTotal)); }
public void CanStackErrorsForMultipleProjects() { _dataHelper.ResetProjectData(TestConstants.ProjectId); TimeSpan timeOffset = _projectRepository.GetDefaultTimeOffset(TestConstants.ProjectId); DateTime startDate = DateTime.UtcNow.Add(timeOffset).Date.AddDays(-120); DateTime endDate = DateTime.UtcNow.Add(timeOffset).Date; const int count = 25; List <Error> errors1 = ErrorData.GenerateErrors(count, organizationId: TestConstants.OrganizationId, startDate: startDate, endDate: endDate, projectId: TestConstants.ProjectId, timeZoneOffset: timeOffset).ToList(); _errorPipeline.Run(errors1); List <Error> errors2 = ErrorData.GenerateErrors(count, organizationId: TestConstants.OrganizationId, startDate: startDate, endDate: endDate, projectId: TestConstants.ProjectIdWithNoRoles, timeZoneOffset: timeOffset).ToList(); _errorPipeline.Run(errors2); long stackCount = _errorStackRepository.Where(es => es.ProjectId == TestConstants.ProjectId).Count(); var info = _errorStatsHelper.GetProjectErrorStats(TestConstants.ProjectId, timeOffset, startDate, endDate); Assert.Equal(count, info.Total); Assert.InRange(info.UniqueTotal, 1, count); Assert.Equal(stackCount, info.NewTotal); Assert.True(info.Stats.Count > 40); Assert.Equal(count, info.Stats.Sum(ds => ds.Total)); Assert.Equal(stackCount, info.Stats.Sum(ds => ds.NewTotal)); }
private void ReportErrorToUser(ApplicationUnhandledExceptionEventArgs e, string errorMessage) { if (e.ExceptionObject != null) { errorDisplay = new ErrorDisplay(); // Attempt to get the stack trace with IL offsets string stackTraceIL = e.ExceptionObject.StackTraceIL(); ErrorData data = new ErrorData() { Message = errorMessage ?? e.ExceptionObject.Message, StackTrace = !string.IsNullOrEmpty(stackTraceIL) ? stackTraceIL : e.ExceptionObject.StackTrace }; errorDisplay.DataContext = data; if (Application.Current.RootVisual != null) { // Size the error UI double width = Application.Current.RootVisual.RenderSize.Width * 0.67; errorDisplay.Width = width > errorDisplay.MaxWidth ? errorDisplay.MaxWidth : width; errorDisplay.Completed += new EventHandler <EventArgs>(errorDisplay_Completed); // Show the error BuilderApplication.Instance.ShowWindow(Strings.ErrorOccured, errorDisplay, false, null, null); } else { MessageBox.Show(data.Message + "\n" + data.StackTrace, Strings.ErrorOccured, MessageBoxButton.OK); } } }
private FaultException GetFaultException(Exception error) { CheckHelper.ArgumentNotNull(error, "error"); var faultException = error as FaultException; if (faultException != null) { return(faultException); } const string REASON = "Server error."; if (IsUserLoggedIn()) { var exceptionData = new ErrorData { Message = error.Message, UtcTime = DateTime.UtcNow, StackTrace = error.StackTrace, ExceptionType = error.GetType().ToString() }; return(new FaultException <ErrorData>(exceptionData, REASON)); } return(new FaultException(REASON)); }
private string SendRequest(string requestParams) { HttpClient client = new HttpClient(); string requestUrl = string.Format("{0}{1}", explorerServerUrl, requestParams); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); var task = Task.Run(async() => { var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); return(responseString); }); task.Wait(); string responseStr = task.Result; ErrorData errorData = JsonConvert.DeserializeObject <ErrorData>(responseStr); if (!string.IsNullOrEmpty(errorData.ErrorCode)) { throw new XDagExplorerException(errorData); } return(responseStr); }
private void OnRegisterCallback(long statusCode, string json) { switch (statusCode) { case 200: // Ok { onRegistrationFinishedListener.OnRegistrationSucceed(); break; } case 400: // Bad Request { var errorMessage = ErrorData.FromJsonToErrorMessage(json); if (errorMessage == string.Empty) { errorMessage = NoticeMessages.AuthView.UnknownError; } onRegistrationFinishedListener.OnRegistrationFailed(errorMessage); break; } default: { var errorMessage = NoticeMessages.AuthView.UnknownError; onRegistrationFinishedListener.OnRegistrationFailed(errorMessage); break; } } }
public void CanGetMinuteStats() { TimeSpan timeOffset = _projectRepository.GetDefaultTimeOffset(TestConstants.ProjectId); DateTime startDate = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Unspecified).Add(timeOffset); DateTime utcStartDate = new DateTimeOffset(startDate, timeOffset).UtcDateTime; DateTime endDate = startDate.AddDays(2); DateTime utcEndDate = new DateTimeOffset(endDate, timeOffset).UtcDateTime; const int count = 100; List <Error> errors = ErrorData.GenerateErrors(count, startDate: startDate, endDate: endDate, errorStackId: TestConstants.ErrorStackId, projectId: TestConstants.ProjectId, timeZoneOffset: timeOffset).ToList(); DateTimeOffset first = errors.Min(e => e.OccurrenceDate); Assert.True(first >= utcStartDate); DateTimeOffset last = errors.Max(e => e.OccurrenceDate); Assert.True(last <= utcEndDate); _errorPipeline.Run(errors); var info = _errorStatsHelper.GetProjectErrorStatsByMinuteBlock(TestConstants.ProjectId, timeOffset, startDate, endDate); Assert.Equal(count, info.Total); Assert.Equal(1, info.UniqueTotal); Assert.Equal(0, info.NewTotal); //Assert.Equal(1, info.Stats.Count); Assert.Equal(count, info.Stats.Sum(ds => ds.Total)); Assert.True(info.Stats.All(ds => ds.UniqueTotal <= 1)); Assert.Equal(0, info.Stats.Sum(ds => ds.NewTotal)); }
public override ErrorData Simulate(Transform vesselTransform, Vector3d targetDirection, Vector3d targetDirectionYaw, Vector3 targetPosition, Vector3 upDirection, float upWeighting, Vessel vessel) { float pitchError; float rollError; float yawError; float sideslip; sideslip = (float)Math.Asin(Vector3.Dot(vesselTransform.right, vessel.srf_velocity.normalized)) * Mathf.Rad2Deg; pitchError = (float)Math.Asin(Vector3d.Dot(Vector3d.back, VectorUtils.Vector3dProjectOnPlane(targetDirection, Vector3d.right))) * Mathf.Rad2Deg; yawError = (float)Math.Asin(Vector3d.Dot(Vector3d.right, VectorUtils.Vector3dProjectOnPlane(targetDirectionYaw, Vector3d.forward))) * Mathf.Rad2Deg; //roll Vector3 currentRoll = -vesselTransform.forward; Vector3 rollTarget; rollTarget = (targetPosition + Mathf.Clamp(upWeighting * (100f - Math.Abs(yawError * 1.6f) - (pitchError * 2.8f)), 0, float.PositiveInfinity) * upDirection) - vessel.CoM; rollTarget = Vector3.ProjectOnPlane(rollTarget, vesselTransform.up); rollError = VectorUtils.SignedAngle(currentRoll, rollTarget, vesselTransform.right) - sideslip * (float)Math.Sqrt(vessel.srf_velocity.magnitude) / 5; float pitchDownFactor = pitchError * (10 / ((float)Math.Pow(yawError, 2) + 10f) - 0.1f); rollError -= Mathf.Clamp(pitchDownFactor, -15, 0); ErrorData behavior = new ErrorData(pitchError, rollError, yawError); return behavior; }
public ErrorResponse(HttpStatusCode code, string message, ErrorData data = null) { StatusCode = (int)code; StatusDescription = HttpWorkerRequest.GetStatusDescription(StatusCode); Details = message; Data = data; }
/// <summary> /// 报单错误回报 /// </summary> /// <param name="pInputOrder"></param> /// <param name="pRspInfo"></param> /// <param name="nRequestID"></param> /// <param name="bIsLast"></param> public void HandleErrRtnOrderInsert(ThostFtdcInputOrderField pInputOrder, ThostFtdcRspInfoField pRspInfo) { var order = new OrderData(); order.gatewayName = this.Gateway.gatewayName; order.symbol = pInputOrder.InstrumentID; order.vtSymbol = pInputOrder.InstrumentID; order.exchange = pInputOrder.ExchangeID; order.orderID = pInputOrder.OrderRef; order.vtOrderID = order.vtSymbol + '.' + order.orderID; order.direction = (string)TradeConstantDicSetting.DirectionTypeDic[pInputOrder.Direction]; order.offset = (string)TradeConstantDicSetting.OffsetTypeDic[pInputOrder.CombOffsetFlag_0]; order.status = TradeCanstant.statusReject; order.price = pInputOrder.LimitPrice; order.totalVolume = pInputOrder.VolumeTotalOriginal; ///推送委托信息 this.Gateway.MainController.MainEvent._OnOrder.Invoke(order); ///错误推送 var errorData = new ErrorData(); errorData.gatewayName = this.Gateway.gatewayName; errorData.errorID = Convert.ToString(pRspInfo.ErrorID); errorData.errorMsg = pRspInfo.ErrorMsg; this.Gateway.MainController.MainEvent._OnError.Invoke(errorData); }
public void GetSpanEvent_Generates_ExpecedErrorAttribute(bool hasExpectedError) { // ARRANGE var testError = new ErrorData("error message", "ErrorType", "stack trace", DateTime.UtcNow, null, hasExpectedError); var segments = new List <Segment>() { _baseGenericSegment.CreateSimilar(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(5), new List <KeyValuePair <string, object> >()) }; segments[0].ErrorData = testError; var immutableTransaction = BuildTestTransaction(segments, sampled: true, hasIncomingPayload: true); var transactionMetricName = _transactionMetricNameMaker.GetTransactionMetricName(immutableTransaction.TransactionName); var metricStatsCollection = new TransactionMetricStatsCollection(transactionMetricName); var transactionAttributes = _transactionAttribMaker.GetAttributes(immutableTransaction, transactionMetricName, TimeSpan.FromSeconds(1), immutableTransaction.Duration, metricStatsCollection); // ACT var spanEvents = _spanEventMaker.GetSpanEvents(immutableTransaction, TransactionName, transactionAttributes).ToList(); var rootSpanEvent = spanEvents[0]; var spanEvent = spanEvents[1]; // ASSERT if (hasExpectedError) { CollectionAssert.Contains(rootSpanEvent.AgentAttributes().Keys, "error.expected"); Assert.AreEqual(true, rootSpanEvent.AgentAttributes()["error.expected"]); CollectionAssert.Contains(spanEvent.AgentAttributes().Keys, "error.expected"); Assert.AreEqual(true, spanEvent.AgentAttributes()["error.expected"]); } else { CollectionAssert.DoesNotContain(rootSpanEvent.AgentAttributes().Keys, "error.expected"); CollectionAssert.DoesNotContain(spanEvent.AgentAttributes().Keys, "error.expected"); } }
public static ContentResult Error(Context context, ErrorData errorData, params string[] data) { return(Get(ApiResponses.Error( context: context, errorData: errorData, data: data))); }
/// <summary> /// Checks if the request returned an error or not. If not, returns the content of the reponse. /// </summary> /// <param name="response">Response to the http request</param> /// <returns>The content of the request if it was successful</returns> /// <exception cref="ChallongeException">Throws this exception if the request was unsuccessful</exception> /// <exception cref="ChallongeValidationException">Throws this exception if the request was successful, but not the api validation</exception> async static public Task <string> ParseResponseAsync(HttpResponseMessage response) { string responseString = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { return(responseString); } ErrorData errorData = JsonSerializer.Deserialize <ErrorData>(responseString); string errors = string.Concat(errorData.Errors); switch (response.StatusCode) { case HttpStatusCode.Unauthorized: // Unauthorized (Invalid API key or insufficient permissions) throw new ChallongeException("Challonge api request returned 401: Unauthorized. (Invalid API key or insufficient permissions). " + errors); case HttpStatusCode.NotFound: // Not found throw new ChallongeException("Challonge api request returned 404: Object not found. " + errors); case HttpStatusCode.NotAcceptable: // Request format not supported throw new ChallongeException("Challonge api request returned 406: Requested format is not supported - request JSON or XML only. " + errors); case HttpStatusCode.InternalServerError: // Server-side error throw new ChallongeException("Challonge api request returned 500: Something went wrong the server side. If you continually receive this, please contact the challonge team. " + errors); case HttpStatusCode.UnprocessableEntity: // Validation error string errorMessage = "The following errors happend while trying to reach the Challonge API:\n" + errors; throw new ChallongeException(errorMessage); default: // We assume that by default, the request was successful return(await response.Content.ReadAsStringAsync()); } }
/// <summary> /// Called when the current plugin or the ones previous in the list /// threw an exception. /// </summary> /// <param name="sender">The real time stylus</param> /// <param name="data">Error data</param> void IStylusAsyncPlugin.Error(RealTimeStylus sender, ErrorData data) { Debug.Assert(false, null, "An error occurred while collecting ink. Details:\n" + "DataId=" + data.DataId + "\n" + "Exception=" + data.InnerException + "\n" + "StackTrace=" + data.InnerException.StackTrace); }
private static void setActionResult(ActionExecutedContext filterContext, ErrorData viewModel, UrlHelper helper) { if (helper.RouteCollection["Error"] == null) { string url = helper.Action("Index", "Error", viewModel); filterContext.Result = new RedirectResult(url); } else { string url = helper.RouteUrl("Error", viewModel); filterContext.Result = new RedirectResult(url); } }
public ErrorData Collect(Exception e) { if (ErrorditeScope.Data == null) return null; var ret = new ErrorData(); foreach (var dataItem in ErrorditeScope.Data) { ret.Add(dataItem.Key, dataItem.Value); } return ret; }
public ErrorData Collect(Exception exception, IErrorditeConfiguration configuration) { if (exception == null) return new ErrorData(); var data = new ErrorData(); foreach (var key in exception.Data.Keys) { AddIfNotEmpty(string.Format("Exception.{0}", key), Sanitise(configuration, key.ToString(), exception.Data[key].ToString()), data); } return data; }
/// <summary> /// Redirects the user to an error screen if an exception is thrown. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.Exception != null && !filterContext.ExceptionHandled) { ErrorData viewModel = new ErrorData(); setErrorMessage(filterContext, viewModel); UrlHelper helper = new UrlHelper(filterContext.RequestContext); setReturnUrl(filterContext, viewModel, helper); setActionResult(filterContext, viewModel, helper); filterContext.ExceptionHandled = true; } base.OnActionExecuted(filterContext); }
public ErrorData ValidateProducerName(RegisteredProducer producer, string producerRegistrationNumber, string producerName) { ErrorData error = null; if (!string.Equals(producer.CurrentSubmission.OrganisationName, producerName, StringComparison.InvariantCultureIgnoreCase)) { var errorMessage = string.Format( "The producer name {0} registered with producer registration number {1} for {2} does not match the registered producer name of {3}. Ensure the registration number and producer name match the registered details.", producerName, producerRegistrationNumber, quarter.Year, producer.CurrentSubmission.OrganisationName); error = new ErrorData(errorMessage, ErrorLevel.Error); } return error; }
protected void AddIfNotEmpty(string key, string value, ErrorData data) { if (!string.IsNullOrEmpty(value)) { //make sure we dont get duplicate keys if (data.ContainsKey(key)) { int index = 1; while (data.ContainsKey(key)) { key = string.Format("{0}-{1}", key, index); index++; } } data.Add(key, value); } }
private void setErrorMessage(ActionExecutedContext filterContext, ErrorData viewModel) { if (String.IsNullOrWhiteSpace(ErrorMessage)) { CodedException exception = filterContext.Exception as CodedException; if (exception == null) { viewModel.ErrorMessage = "An error occurred while processing your request."; } else { viewModel.ErrorMessage = filterContext.Exception.Message; } } else { viewModel.ErrorMessage = ErrorMessage; } }
public ErrorData Collect(Exception e, IErrorditeConfiguration configuration) { var context = HttpContext.Current; if (context == null) return null; var data = new ErrorData(); AddIfNotEmpty("HttpMethod", context.Request.HttpMethod, data); if(context.Request.UrlReferrer != null) AddIfNotEmpty("Referrer", context.Request.UrlReferrer.AbsoluteUri, data); if (context.Request.Form.Count > 0) { foreach(var key in context.Request.Form.Keys) { AddIfNotEmpty(string.Format("Form.{0}", key), Sanitise(configuration, key.ToString(), context.Request.Form[key.ToString()]), data); } } if (context.Request.Headers.Count > 0) { foreach (string key in context.Request.Headers.Keys) { switch (key) { case "User-Agent": continue; } AddIfNotEmpty(string.Format("Header.{0}", key), Sanitise(configuration, key, context.Request.Headers[key]), data); } } return data; }
private void setReturnUrl(ActionExecutedContext filterContext, ErrorData viewModel, UrlHelper helper) { string returnController = ReturnController; if (String.IsNullOrWhiteSpace(returnController)) { returnController = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; } string returnAction = ReturnAction; if (String.IsNullOrWhiteSpace(returnAction)) { returnAction = "Index"; } viewModel.ReturnUrl = helper.Action(returnAction, returnController); }
public ErrorData ValidateProducerObligationType(RegisteredProducer producer, string producerRegistrationNumber, string producerName, ObligationType obligationType) { ErrorData error = null; if (!producer.CurrentSubmission.ObligationType.HasFlag(obligationType)) { var errorMessage = string.Format( "Producer registration number {0} {1} has submitted a {2} return for one or more categories but is only registered for {3}. Amend the return or submit an update for the producer's details.", producerRegistrationNumber, producerName, obligationType, producer.CurrentSubmission.ObligationType); error = new ErrorData(errorMessage, ErrorLevel.Error); } return error; }
public void DisplaysSourceCodeLines_PreAndPostErrorLine(ErrorData errorData) { // Arrange var middleware = GetErrorPageMiddleware(); var stackFrame = new StackFrame(); // Act middleware.ReadFrameContent( stackFrame, errorData.AllLines, errorData.ErrorStartLine, errorData.ErrorEndLine); // Assert Assert.Equal(errorData.ExpectedPreContextLine, stackFrame.PreContextLine); Assert.Equal(errorData.ExpectedPreErrorCode, stackFrame.PreContextCode); Assert.Equal(errorData.ExpectedErrorCode, stackFrame.ContextCode); Assert.Equal(errorData.ExpectedPostErrorCode, stackFrame.PostContextCode); }
static ErrorData() { instance = new ErrorData(); }
public void SetErrorCode(QCARUnity.InitError errorCode) { mCurrentError = new ErrorData(); mCurrentError.Title = "QCAR Initialization Error"; mCurrentError.Text = ""; Debug.LogError("QCAR initialization failed: " + errorCode); mErrorcode = errorCode; switch (errorCode) { case QCARUnity.InitError.INIT_LICENSE_ERROR_MISSING_KEY: mCurrentError.Text = "Vuforia App key is missing. Please get a valid key, by logging into your account at developer.vuforia.com and creating a new project "; break; #if UNITY_IPHONE case QCARUnity.InitError.INIT_NO_CAMERA_ACCESS: mCurrentError.Text = "Camera Access was denied to this App. \n" + "When running on iOS8 devices, \n" + "users must explictly allow the App to access the camera.\n" + "To restore camera access on your device, go to: \n" + "Settings > Privacy > Camera > [This App Name] and switch it ON."; break; #endif case QCARUnity.InitError.INIT_LICENSE_ERROR_INVALID_KEY: mCurrentError.Text = " Invalid Key used. Please make sure you are using a valid Vuforia App Key"; break; case QCARUnity.InitError.INIT_LICENSE_ERROR_NO_NETWORK_TRANSIENT: mCurrentError.Text = "Unable to contact server. Please try again later."; break; case QCARUnity.InitError.INIT_LICENSE_ERROR_NO_NETWORK_PERMANENT: mCurrentError.Text = "No network available. Please make sure you are connected to the Internet."; break; case QCARUnity.InitError.INIT_LICENSE_ERROR_CANCELED_KEY: mCurrentError.Text = "This app license key has been canceled and may no longer be used. Please get a new license key"; break; case QCARUnity.InitError.INIT_ERROR: mCurrentError.Text = "Failed to initialize QCAR."; break; } }
private static ErrorData GetCustomData(Exception exception, IEnumerable<KeyValuePair<string, string>> customData) { var items = new ErrorData(); if (customData != null) { foreach (var item in customData) { items.Add("Custom." + item.Key, item.Value); } } var scopedItems = new ScopedDataCollector().Collect(exception); if (scopedItems != null) { foreach (var item in scopedItems) { items.Add("Scoped." + item.Key, item.Value); } } var httpItems = new HttpContextDataCollector().Collect(exception, Configuration); if (httpItems != null) { foreach (var item in httpItems) { items.Add("Request." + item.Key, item.Value); } } if (Configuration.DataCollectors == null) return items; foreach (var dataCollectorFactory in Configuration.DataCollectors) { var item = CollectData(exception, dataCollectorFactory); if (item != null) items.Add(item); } return items; }
private static ErrorData CollectData(Exception exception, IDataCollectorFactory dataCollectorFactory) { try { var dataCollector = dataCollectorFactory.Create(); if (dataCollector == null) { return null; } var exceptionData = dataCollector.Collect(exception); if (exceptionData != null) { var ret = new ErrorData(); foreach (var kvp in exceptionData) { ret.Add(string.Format("{0}.{1}", dataCollectorFactory.Prefix, kvp.Key), kvp.Value); } return ret; } } catch (Exception e) { return new ErrorData{{"Error", e.Message}}; } return null; }
/// <summary> /// Called when the current plugin or the ones previous in the list /// threw an exception. /// </summary> /// <param name="sender">The real time stylus</param> /// <param name="data">Error data</param> void IStylusSyncPlugin.Error(RealTimeStylus sender, ErrorData data) { Debug.Assert(false, null, "An error occurred while collecting ink. Details:\n" + "DataId=" + data.DataId + "\n" + "Exception=" + data.InnerException + "\n" + "StackTrace=" + data.InnerException.StackTrace); }
public void Error(RealTimeStylus sender, ErrorData data) { }
void IStylusSyncPlugin.Error(RealTimeStylus sender, ErrorData data) { }
/// <summary> /// Called when the current plugin or the ones previous in the list /// threw an exception. /// </summary> /// <param name="sender">The real time stylus</param> /// <param name="data">Error data</param> public void Error(RealTimeStylus sender, ErrorData data) { Debug.Assert(false, null, "An error occurred. DataId=" + data.DataId + ", " + "Exception=" + data.InnerException); }
public virtual ErrorData Simulate(Transform vesselTransform, Vector3d targetDirection, Vector3d targetDirectionYaw, Vector3 targetPosition, Vector3 upDirection, float upWeighting, Vessel vessel) { ErrorData behavior = new ErrorData(0, 0, 0); return behavior; }