示例#1
0
        public void Run(EventPluginContext context)
        {
            if (!context.Event.IsError())
            {
                return;
            }

            InnerError current      = context.Event.GetError(context.Client.Configuration.Resolver.GetJsonSerializer());
            DateTime   repeatWindow = DateTime.Now.AddSeconds(-2);

            while (current != null)
            {
                int hashCode = current.GetHashCode();

                // make sure that we don't process the same error multiple times within 2 seconds.
                if (_recentlyProcessedErrors.Any(s => s.Item1 == hashCode && s.Item2 >= repeatWindow))
                {
                    context.Log.FormattedInfo(typeof(ExceptionlessClient), "Ignoring duplicate error event: hash={0}", hashCode);
                    context.Cancel = true;
                    return;
                }

                // add this exception to our list of recent errors that we have processed.
                _recentlyProcessedErrors.Enqueue(Tuple.Create(hashCode, DateTime.Now));

                // only keep the last 10 recent errors
                Tuple <int, DateTime> temp;
                while (_recentlyProcessedErrors.Count > 10)
                {
                    _recentlyProcessedErrors.TryDequeue(out temp);
                }

                current = current.Inner;
            }
        }
示例#2
0
 public Error(string message, ErrorCodes code, string target = default, InnerError inner = default)
 {
     Message    = message;
     Code       = code;
     Target     = target;
     InnerError = inner;
 }
示例#3
0
        public static StackingTarget GetStackingTarget(this Error error) {
            if (error == null)
                return null;

            InnerError targetError = error;
            while (targetError != null) {
                StackFrame m = targetError.StackTrace.FirstOrDefault(st => st.IsSignatureTarget);
                if (m != null)
                    return new StackingTarget {
                        Error = targetError,
                        Method = m
                    };

                if (targetError.TargetMethod != null && targetError.TargetMethod.IsSignatureTarget)
                    return new StackingTarget {
                        Error = targetError,
                        Method = targetError.TargetMethod
                    };

                targetError = targetError.Inner;
            }

            // fallback to default
            InnerError defaultError = error.GetInnermostError();
            Method defaultMethod = defaultError.StackTrace != null ? defaultError.StackTrace.FirstOrDefault() : null;
            if (defaultMethod == null && error.StackTrace != null) {
                defaultMethod = error.StackTrace.FirstOrDefault();
                defaultError = error;
            }

            return new StackingTarget {
                Error = defaultError,
                Method = defaultMethod
            };
        }
示例#4
0
        private void AddSpecialCaseDetails(InnerError error)
        {
            if (!error.Data.ContainsKey(Error.KnownDataKeys.ExtraProperties))
            {
                return;
            }

            var extraProperties = error.Data.GetValue <Dictionary <string, object> >(Error.KnownDataKeys.ExtraProperties);

            if (extraProperties == null)
            {
                return;
            }

            object value;

            if (extraProperties.TryGetValue("Number", out value))
            {
                SignatureInfo.Add("Number", value.ToString());
            }

            if (extraProperties.TryGetValue("ErrorCode", out value))
            {
                SignatureInfo.Add("ErrorCode", value.ToString());
            }
        }
示例#5
0
        /// <summary>
        /// Returns the expected ATOM payload for an inner error payload.
        /// </summary>
        /// <param name="innerError">The inner error to create the ATOM payload for.</param>
        /// <param name="depth">The depth of the inner error (starting with 0).</param>
        /// <returns>The expected ATOM payload for the <paramref name="innerError"/> payload.</returns>
        private static string ExpectedAtomInnerErrorPayload(InnerError innerError, int depth)
        {
            if (innerError == null)
            {
                return(string.Empty);
            }

            return(string.Format(
                       string.Join(
                           "$(NL)",
                           "  <{0}:{1}>",
                           "    <{0}:{2}>{5}</{0}:{2}>",
                           "    <{0}:{3}>{6}</{0}:{3}>",
                           "    <{0}:{4}>{7}</{0}:{4}>",
                           innerError.NestedError == null ? string.Empty : "    {8}",
                           "  </{0}:{1}>"
                           ),
                       TestAtomConstants.ODataMetadataNamespacePrefix,
                       depth == 0 ? TestAtomConstants.ODataInnerErrorElementName : TestAtomConstants.ODataInnerErrorInnerErrorElementName,
                       TestAtomConstants.ODataInnerErrorMessageElementName,
                       TestAtomConstants.ODataInnerErrorTypeElementName,
                       TestAtomConstants.ODataInnerErrorStackTraceElementName,
                       innerError.Message ?? string.Empty,
                       innerError.TypeName ?? string.Empty,
                       innerError.StackTrace ?? string.Empty,
                       ExpectedAtomInnerErrorPayload(innerError.NestedError, depth + 1)));
        }
示例#6
0
        /// <summary>
        /// Returns the expected JSON Lite payload for an inner error payload.
        /// </summary>
        /// <param name="innerError">The inner error to create the JSON Lite payload for.</param>
        /// <param name="depth">The depth of the inner error (starting with 0).</param>
        /// <returns>The expected JSON Lite payload for the <paramref name="innerError"/> payload.</returns>
        private static string ExpectedJsonLightInnerErrorPayload(InnerError innerError, int depth)
        {
            if (innerError == null)
            {
                return(string.Empty);
            }

            string prefix = string.Empty;

            for (int i = 0; i < depth; ++i)
            {
                prefix += "$(Indent)";
            }

            string propertyName = depth == 0
                ? JsonConstants.ODataErrorInnerErrorName
                : JsonConstants.ODataErrorInnerErrorInnerErrorName;

            string innerErrorString = string.Join(
                "$(NL)",
                ",\"" + propertyName + "\":{",
                "$(Indent)$(Indent)$(Indent)" + prefix + "\"" +
                JsonConstants.ODataErrorInnerErrorMessageName + "\":\"" + (innerError.Message ?? string.Empty) + "\",\"" +
                JsonConstants.ODataErrorInnerErrorTypeNameName + "\":\"" + (innerError.TypeName ?? string.Empty) + "\",\"" +
                JsonConstants.ODataErrorInnerErrorStackTraceName + "\":\"" + (innerError.StackTrace ?? string.Empty) + "\"" +
                ExpectedJsonLightInnerErrorPayload(innerError.NestedError, depth + 1),
                "$(Indent)$(Indent)" + prefix + "}");

            return(innerErrorString);
        }
示例#7
0
        private void Compare(Exception ex, InnerError err, int level = 1)
        {
            Console.WriteLine("Level " + level);
            Assert.Equal(ex.GetType().FullName, err.Type);
            if (String.IsNullOrEmpty(ex.StackTrace))
            {
                Assert.Equal(0, err.StackTrace.Count);
            }
            else
            {
                string[] lines = Regex.Split(ex.StackTrace, "\r\n|\r|\n");
                Assert.Equal(lines.Length, err.StackTrace.Count);
                Assert.Equal(ex.StackTrace, err.StackTrace.ToString());
            }

            // TODO: Fix formatting bugs with inner exception tostring
            if (level == 1)
            {
                Assert.Equal(ex.ToString(), err.ToString());
            }

            if (ex.InnerException != null)
            {
                Compare(ex.InnerException, err.Inner, level + 1);
            }
        }
        /// <summary>Actions the error.</summary>
        /// <param name="statusCode">The status code.</param>
        /// <param name="error">The error.</param>
        /// <returns></returns>
        private IActionResult ActionError(int statusCode, InnerError error)
        {
            var errorResponse = new Error(statusCode.ToString());

            errorResponse.Errors.Add(error);

            return(StatusCode(statusCode, errorResponse));
        }
示例#9
0
        public override int GetHashCode()
        {
            var hash = 17;

            hash += 31 * Exception.GetHashCode();
            hash += 31 * InnerError.GetHashCode();

            return(hash);
        }
示例#10
0
        protected override void ExecuteDeleteStoredProcedure()
        {
            if (InnerError != null)
            {
                InnerError.Delete();
            }

            Data.Error.DeleteError(Id);
        }
示例#11
0
        public static InnerError GetInnermostError(this InnerError error) {
            if (error == null)
                throw new ArgumentNullException(nameof(error));

            InnerError current = error;
            while (current.Inner != null)
                current = current.Inner;

            return current;
        }
        internal static TextAnalyticsError ConvertToError(TextAnalyticsErrorInternal error)
        {
            string     errorCode  = error.Code;
            string     message    = error.Message;
            string     target     = error.Target;
            InnerError innerError = error.Innererror;

            if (innerError != null)
            {
                // Return the innermost error, which should be only one level down.
                return(new TextAnalyticsError(innerError.Code, innerError.Message, innerError.Target));
            }

            return(new TextAnalyticsError(errorCode, message, target));
        }
示例#13
0
        public IEnumerable <TraceFrame> GetAllFrames()
        {
            foreach (var item in this.StackTrace)
            {
                yield return(item);
            }

            if (InnerError != null)
            {
                foreach (var item in InnerError.GetAllFrames())
                {
                    yield return(item);
                }
            }
        }
示例#14
0
        public static StackingTarget GetStackingTarget(this Error error)
        {
            if (error == null)
            {
                return(null);
            }

            InnerError targetError = error;

            while (targetError != null)
            {
                var frame = targetError.StackTrace?.FirstOrDefault(st => st.IsSignatureTarget);
                if (frame != null)
                {
                    return new StackingTarget {
                               Error  = targetError,
                               Method = frame
                    }
                }
                ;

                if (targetError.TargetMethod != null && targetError.TargetMethod.IsSignatureTarget)
                {
                    return new StackingTarget {
                               Error  = targetError,
                               Method = targetError.TargetMethod
                    }
                }
                ;

                targetError = targetError.Inner;
            }

            // fallback to default
            var defaultError  = error.GetInnermostError();
            var defaultMethod = defaultError.StackTrace?.FirstOrDefault();

            if (defaultMethod == null && error.StackTrace != null)
            {
                defaultMethod = error.StackTrace.FirstOrDefault();
                defaultError  = error;
            }

            return(new StackingTarget {
                Error = defaultError,
                Method = defaultMethod
            });
        }
示例#15
0
        public static InnerError GetInnermostError(this InnerError error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            InnerError current = error;

            while (current.Inner != null)
            {
                current = current.Inner;
            }

            return(current);
        }
示例#16
0
        internal static void AppendError(Error error, StringBuilder sb, bool html = false, string traceIndentValue = "   ") {
            var exList = new List<InnerError>();
            InnerError currentEx = error;
            if (html)
                sb.Append("<span class=\"ex-header\">");
            while (currentEx != null) {
                if (html)
                    sb.Append("<span class=\"ex-type\">");
                sb.Append(html ? currentEx.Type.HtmlEntityEncode() : currentEx.Type);
                if (html)
                    sb.Append("</span>");

                if (!String.IsNullOrEmpty(currentEx.Message)) {
                    if (html)
                        sb.Append("<span class=\"ex-message\">");
                    sb.Append(": ").Append(html ? currentEx.Message.HtmlEntityEncode() : currentEx.Message);
                    if (html)
                        sb.Append("</span>");
                }

                if (currentEx.Inner != null) {
                    if (html)
                        sb.Append("</span><span class=\"ex-header\"><span class=\"ex-innersep\">");
                    sb.Append(" ---> ");
                    if (html)
                        sb.Append("</span>");
                }

                exList.Add(currentEx);
                currentEx = currentEx.Inner;
            }
            if (html)
                sb.Append("</span>");
            else
                sb.AppendLine();

            exList.Reverse();
            foreach (InnerError ex in exList) {
                if (ex.StackTrace != null && ex.StackTrace.Count > 0) {
                    StackFrameCollectionExtensions.AppendStackFrames(ex.StackTrace, sb, true, linkFilePath: html, traceIndentValue: traceIndentValue);

                    if (exList.Count > 1)
                        sb.Append(traceIndentValue).AppendLine("--- End of inner exception stack trace ---");
                }
            }
        }
示例#17
0
        public string FramesToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in this.StackTrace)
            {
                sb.AppendFormat("  at {0}\r\n", item.Method);
            }

            if (InnerError != null)
            {
                sb.Append("--- End of inner exception stack trace ---\r\n");
                sb.Append(InnerError.FramesToString());
            }

            return(sb.ToString());
        }
示例#18
0
        public bool IsDuplicate(Event ev)
        {
            if (!ev.IsError)
            {
                return(false);
            }

            InnerError current      = ev.GetError();
            DateTime   repeatWindow = DateTime.Now.AddSeconds(-2);

            while (current != null)
            {
                int hashCode = current.GetHashCode();
                _log.FormattedTrace(typeof(ExceptionlessClient), "Checking for duplicate error: hash={0} type={1}", hashCode, current.Type);
                _log.FormattedTrace(typeof(ExceptionlessClient), "Error contents: {0}", current.ToString());

                // make sure that we don't process the same error multiple times within 2 seconds.
                if (_recentlyProcessedErrors.Any(s => s.Item1 == hashCode && s.Item2 >= repeatWindow))
                {
                    _log.FormattedInfo(typeof(ExceptionlessClient), "Ignoring duplicate exception: type={0}", current.Type);
                    return(true);
                }

                // add this exception to our list of recent errors that we have processed.
                _recentlyProcessedErrors.Enqueue(Tuple.Create(hashCode, DateTime.Now));

                // only keep the last 10 recent errors
                Tuple <int, DateTime> temp;
                while (_recentlyProcessedErrors.Count > 10)
                {
                    _recentlyProcessedErrors.TryDequeue(out temp);
                }

                current = current.Inner;
            }

            return(false);
        }
示例#19
0
 /// <summary>
 /// Returns the expected ATOM payload for an error.
 /// </summary>
 /// <param name="code">The code of the error.</param>
 /// <param name="message">The error message.</param>
 /// <param name="innerError">The inner error (if null, don't write anything).</param>
 /// <returns>The expected ATOM payload for an error.</returns>
 private static string ExpectedAtomErrorPayload(string code, string message, InnerError innerError)
 {
     return(string.Format(
                string.Join(
                    "$(NL)",
                    "<{0}:{2} xmlns:{0}=\"{1}\">",
                    "  {3}",
                    "  <{0}:{4}>{5}</{0}:{4}>{6}",
                    "</{0}:{2}>"
                    ),
                TestAtomConstants.ODataMetadataNamespacePrefix,
                TestAtomConstants.ODataMetadataNamespace,
                TestAtomConstants.ODataErrorElementName,
                string.Format(code == string.Empty ?
                              "<{0}:{1} />" :
                              "<{0}:{1}>{2}</{0}:{1}>",
                              TestAtomConstants.ODataMetadataNamespacePrefix,
                              TestAtomConstants.ODataErrorCodeElementName,
                              code),
                TestAtomConstants.ODataErrorMessageElementName,
                message,
                ExpectedAtomInnerErrorPayload(innerError, 0)));
 }
示例#20
0
        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call GetLongRunningOperationStatus to determine whether the
        /// operation has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operationStatusLink'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Compute service response for long-running operations.
        /// </returns>
        public async Task <ComputeLongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
        {
            // Validate
            if (operationStatusLink == null)
            {
                throw new ArgumentNullException("operationStatusLink");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("operationStatusLink", operationStatusLink);
                TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + operationStatusLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ComputeLongRunningOperationResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ComputeLongRunningOperationResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken operationIdValue = responseDoc["operationId"];
                            if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
                            {
                                string operationIdInstance = ((string)operationIdValue);
                                result.TrackingOperationId = operationIdInstance;
                            }

                            JToken statusValue = responseDoc["status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                ComputeOperationStatus statusInstance = ((ComputeOperationStatus)Enum.Parse(typeof(ComputeOperationStatus), ((string)statusValue), true));
                                result.Status = statusInstance;
                            }

                            JToken startTimeValue = responseDoc["startTime"];
                            if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                result.StartTime = startTimeInstance;
                            }

                            JToken endTimeValue = responseDoc["endTime"];
                            if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                result.EndTime = endTimeInstance;
                            }

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                JToken outputValue = propertiesValue["output"];
                                if (outputValue != null && outputValue.Type != JTokenType.Null)
                                {
                                    string outputInstance = outputValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    result.Output = outputInstance;
                                }
                            }

                            JToken errorValue = responseDoc["error"];
                            if (errorValue != null && errorValue.Type != JTokenType.Null)
                            {
                                ApiError errorInstance = new ApiError();
                                result.Error = errorInstance;

                                JToken detailsArray = errorValue["details"];
                                if (detailsArray != null && detailsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken detailsValue in ((JArray)detailsArray))
                                    {
                                        ApiErrorBase apiErrorBaseInstance = new ApiErrorBase();
                                        errorInstance.Details.Add(apiErrorBaseInstance);

                                        JToken codeValue = detailsValue["code"];
                                        if (codeValue != null && codeValue.Type != JTokenType.Null)
                                        {
                                            string codeInstance = ((string)codeValue);
                                            apiErrorBaseInstance.Code = codeInstance;
                                        }

                                        JToken targetValue = detailsValue["target"];
                                        if (targetValue != null && targetValue.Type != JTokenType.Null)
                                        {
                                            string targetInstance = ((string)targetValue);
                                            apiErrorBaseInstance.Target = targetInstance;
                                        }

                                        JToken messageValue = detailsValue["message"];
                                        if (messageValue != null && messageValue.Type != JTokenType.Null)
                                        {
                                            string messageInstance = ((string)messageValue);
                                            apiErrorBaseInstance.Message = messageInstance;
                                        }
                                    }
                                }

                                JToken innererrorValue = errorValue["innererror"];
                                if (innererrorValue != null && innererrorValue.Type != JTokenType.Null)
                                {
                                    InnerError innererrorInstance = new InnerError();
                                    errorInstance.InnerError = innererrorInstance;

                                    JToken exceptiontypeValue = innererrorValue["exceptiontype"];
                                    if (exceptiontypeValue != null && exceptiontypeValue.Type != JTokenType.Null)
                                    {
                                        string exceptiontypeInstance = ((string)exceptiontypeValue);
                                        innererrorInstance.ExceptionType = exceptiontypeInstance;
                                    }

                                    JToken errordetailValue = innererrorValue["errordetail"];
                                    if (errordetailValue != null && errordetailValue.Type != JTokenType.Null)
                                    {
                                        string errordetailInstance = ((string)errordetailValue);
                                        innererrorInstance.ErrorDetail = errordetailInstance;
                                    }
                                }

                                JToken codeValue2 = errorValue["code"];
                                if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
                                {
                                    string codeInstance2 = ((string)codeValue2);
                                    errorInstance.Code = codeInstance2;
                                }

                                JToken targetValue2 = errorValue["target"];
                                if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
                                {
                                    string targetInstance2 = ((string)targetValue2);
                                    errorInstance.Target = targetInstance2;
                                }

                                JToken messageValue2 = errorValue["message"];
                                if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
                                {
                                    string messageInstance2 = ((string)messageValue2);
                                    errorInstance.Message = messageInstance2;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        public async Task GeneratePerformanceData()
        {
            var currentBatchCount   = 0;
            var parserPluginManager = IoC.GetInstance <EventParserPluginManager>();
            var dataDirectory       = Path.GetFullPath(@"..\..\Pipeline\Data\");

            foreach (var file in Directory.GetFiles(dataDirectory))
            {
                File.Delete(file);
            }

            Dictionary <string, UserInfo> _mappedUsers = new Dictionary <string, UserInfo>();
            Dictionary <string, string>   _mappedIPs   = new Dictionary <string, string>();

            var storage = new FolderFileStorage(Path.GetFullPath(@"..\..\..\"));

            foreach (var file in await storage.GetFileListAsync(@"Api\App_Data\storage\q\*"))
            {
                var eventPostInfo = await storage.GetObjectAsync <EventPostInfo>(file.Path);

                byte[] data = eventPostInfo.Data;
                if (!String.IsNullOrEmpty(eventPostInfo.ContentEncoding))
                {
                    data = data.Decompress(eventPostInfo.ContentEncoding);
                }

                var encoding = Encoding.UTF8;
                if (!String.IsNullOrEmpty(eventPostInfo.CharSet))
                {
                    encoding = Encoding.GetEncoding(eventPostInfo.CharSet);
                }

                string input  = encoding.GetString(data);
                var    events = parserPluginManager.ParseEvents(input, eventPostInfo.ApiVersion, eventPostInfo.UserAgent);

                foreach (var ev in events)
                {
                    ev.Date           = new DateTimeOffset(new DateTime(2020, 1, 1));
                    ev.ProjectId      = null;
                    ev.OrganizationId = null;
                    ev.StackId        = null;

                    if (ev.Message != null)
                    {
                        ev.Message = RandomData.GetSentence();
                    }

                    var keysToRemove = ev.Data.Keys.Where(k => !k.StartsWith("@") && k != "MachineName" && k != "job" && k != "host" && k != "process").ToList();
                    foreach (var key in keysToRemove)
                    {
                        ev.Data.Remove(key);
                    }

                    ev.Data.Remove(Event.KnownDataKeys.UserDescription);
                    var identity = ev.GetUserIdentity();
                    if (identity != null)
                    {
                        if (!_mappedUsers.ContainsKey(identity.Identity))
                        {
                            _mappedUsers.Add(identity.Identity, new UserInfo(Guid.NewGuid().ToString(), currentBatchCount.ToString()));
                        }

                        ev.SetUserIdentity(_mappedUsers[identity.Identity]);
                    }

                    var request = ev.GetRequestInfo();
                    if (request != null)
                    {
                        request.Cookies?.Clear();
                        request.PostData = null;
                        request.QueryString?.Clear();
                        request.Referrer = null;
                        request.Host     = RandomData.GetIp4Address();
                        request.Path     = $"/{RandomData.GetWord(false)}/{RandomData.GetWord(false)}";
                        request.Data.Clear();

                        if (request.ClientIpAddress != null)
                        {
                            if (!_mappedIPs.ContainsKey(request.ClientIpAddress))
                            {
                                _mappedIPs.Add(request.ClientIpAddress, RandomData.GetIp4Address());
                            }

                            request.ClientIpAddress = _mappedIPs[request.ClientIpAddress];
                        }
                    }

                    InnerError error = ev.GetError();
                    while (error != null)
                    {
                        error.Message = RandomData.GetSentence();
                        error.Data.Clear();
                        (error as Error)?.Modules.Clear();

                        error = error.Inner;
                    }

                    var environment = ev.GetEnvironmentInfo();
                    environment?.Data.Clear();
                }

                // inject random session start events.
                if (currentBatchCount % 10 == 0)
                {
                    events.Insert(0, events[0].ToSessionStartEvent());
                }

                await storage.SaveObjectAsync($"{dataDirectory}\\{currentBatchCount++}.json", events);
            }
        }
示例#22
0
 /// <summary>
 /// Returns the expected JSON Lite payload for an error.
 /// </summary>
 /// <param name="code">The code of the error.</param>
 /// <param name="message">The error message.</param>
 /// <param name="innerError">The inner error (if null, don't write anything).</param>
 /// <returns>The expected JSON Lite payload for an error.</returns>
 private static string ExpectedJsonLightErrorPayload(string code, string message, InnerError innerError)
 {
     return string.Join(
         "$(NL)",
         "{",
         "$(Indent)\"" + JsonLightConstants.ODataErrorPropertyName + "\":{",
         "$(Indent)$(Indent)\"" + JsonConstants.ODataErrorCodeName + "\":\"" + code + "\",\"" ,
         JsonConstants.ODataErrorMessageName + "\":\"" + message + "\"",
         ExpectedJsonLightInnerErrorPayload(innerError, 0),
         "$(Indent)}",
         "}");
 }
 public static InnerError InnerError(string code = default, string message = default, string errorDetail = default, InnerError innerErrorValue = default)
 {
     return(new InnerError(code, message, errorDetail, innerErrorValue));
 }
示例#24
0
 internal InnerError(string code, InnerError innererror)
 {
     Code       = code;
     Innererror = innererror;
 }
示例#25
0
 /// <summary>
 /// Returns the expected ATOM payload for an error.
 /// </summary>
 /// <param name="code">The code of the error.</param>
 /// <param name="message">The error message.</param>
 /// <param name="innerError">The inner error (if null, don't write anything).</param>
 /// <returns>The expected ATOM payload for an error.</returns>
 private static string ExpectedAtomErrorPayload(string code, string message, InnerError innerError)
 {
     return string.Format(
         string.Join(
             "$(NL)",
             "<{0}:{2} xmlns:{0}=\"{1}\">",
             "  {3}",
             "  <{0}:{4}>{5}</{0}:{4}>{6}",
             "</{0}:{2}>"
         ),
         TestAtomConstants.ODataMetadataNamespacePrefix,
         TestAtomConstants.ODataMetadataNamespace,
         TestAtomConstants.ODataErrorElementName,
         string.Format(code == string.Empty ?
             "<{0}:{1} />" :
             "<{0}:{1}>{2}</{0}:{1}>",
             TestAtomConstants.ODataMetadataNamespacePrefix,
             TestAtomConstants.ODataErrorCodeElementName,
             code),
         TestAtomConstants.ODataErrorMessageElementName,
         message,
         ExpectedAtomInnerErrorPayload(innerError, 0));
 }
示例#26
0
 public static Result ValidationError(InnerError errors)
 => ValidationError(new[] { errors });
示例#27
0
 public static Result Failure(InnerError errors)
 => Failure(new[] { errors });
示例#28
0
        /// <summary>
        /// Returns the expected JSON Lite payload for an inner error payload.
        /// </summary>
        /// <param name="innerError">The inner error to create the JSON Lite payload for.</param>
        /// <param name="depth">The depth of the inner error (starting with 0).</param>
        /// <returns>The expected JSON Lite payload for the <paramref name="innerError"/> payload.</returns>
        private static string ExpectedJsonLightInnerErrorPayload(InnerError innerError, int depth)
        {
            if (innerError == null)
            {
                return string.Empty;
            }

            string prefix = string.Empty;
            for (int i = 0; i < depth; ++i)
            {
                prefix += "$(Indent)";
            }

            string propertyName = depth == 0
                ? JsonConstants.ODataErrorInnerErrorName
                : JsonConstants.ODataErrorInnerErrorInnerErrorName;

            string innerErrorString = string.Join(
                "$(NL)",
                ",\"" + propertyName + "\":{",
                "$(Indent)$(Indent)$(Indent)" + prefix + "\"" +
                    JsonConstants.ODataErrorInnerErrorMessageName + "\":\"" + (innerError.Message ?? string.Empty) + "\",\"" +
                    JsonConstants.ODataErrorInnerErrorTypeNameName + "\":\"" + (innerError.TypeName ?? string.Empty) + "\",\"" +
                    JsonConstants.ODataErrorInnerErrorStackTraceName + "\":\"" + (innerError.StackTrace ?? string.Empty) + "\"" +
                    ExpectedJsonLightInnerErrorPayload(innerError.NestedError, depth + 1),
                "$(Indent)$(Indent)" + prefix + "}");
            return innerErrorString;
        }
示例#29
0
 /// <summary>
 /// Returns the expected JSON Lite payload for an error.
 /// </summary>
 /// <param name="code">The code of the error.</param>
 /// <param name="message">The error message.</param>
 /// <param name="innerError">The inner error (if null, don't write anything).</param>
 /// <returns>The expected JSON Lite payload for an error.</returns>
 private static string ExpectedJsonLightErrorPayload(string code, string message, InnerError innerError)
 {
     return(string.Join(
                "$(NL)",
                "{",
                "$(Indent)\"" + JsonLightConstants.ODataErrorPropertyName + "\":{",
                "$(Indent)$(Indent)\"" + JsonConstants.ODataErrorCodeName + "\":\"" + code + "\",\"",
                JsonConstants.ODataErrorMessageName + "\":\"" + message + "\"",
                ExpectedJsonLightInnerErrorPayload(innerError, 0),
                "$(Indent)}",
                "}"));
 }
 public static Error Error(string code = default, string message = default, string target = default, IReadOnlyList <Error> details = default, InnerError innererror = default, DateTimeOffset?occurredDateTime = default)
 {
     details ??= new List <Error>();
     return(new Error(code, message, target, details, innererror, occurredDateTime));
 }
示例#31
0
        /// <summary>
        /// Returns the expected ATOM payload for an inner error payload.
        /// </summary>
        /// <param name="innerError">The inner error to create the ATOM payload for.</param>
        /// <param name="depth">The depth of the inner error (starting with 0).</param>
        /// <returns>The expected ATOM payload for the <paramref name="innerError"/> payload.</returns>
        private static string ExpectedAtomInnerErrorPayload(InnerError innerError, int depth)
        {
            if (innerError == null)
            {
                return string.Empty;
            }

            return string.Format(
                string.Join(
                    "$(NL)",
                    "  <{0}:{1}>",
                    "    <{0}:{2}>{5}</{0}:{2}>",
                    "    <{0}:{3}>{6}</{0}:{3}>",
                    "    <{0}:{4}>{7}</{0}:{4}>",
                    innerError.NestedError == null ? string.Empty : "    {8}",
                    "  </{0}:{1}>"
                ),
                TestAtomConstants.ODataMetadataNamespacePrefix,
                depth == 0 ? TestAtomConstants.ODataInnerErrorElementName : TestAtomConstants.ODataInnerErrorInnerErrorElementName,
                TestAtomConstants.ODataInnerErrorMessageElementName,
                TestAtomConstants.ODataInnerErrorTypeElementName,
                TestAtomConstants.ODataInnerErrorStackTraceElementName,
                innerError.Message ?? string.Empty,
                innerError.TypeName ?? string.Empty,
                innerError.StackTrace ?? string.Empty,
                ExpectedAtomInnerErrorPayload(innerError.NestedError, depth + 1));
        }
示例#32
0
        private void Parse()
        {
            SignatureInfo.Clear();

            // start at the inner most exception and work our way out until we find a user method
            InnerError current    = Error;
            var        errorStack = new List <InnerError> {
                current
            };

            while (current.Inner != null)
            {
                current = current.Inner;
                errorStack.Add(current);
            }

            errorStack.Reverse();

            // reset all flags before we figure out which method to tag as the new target.
            if (ShouldFlagSignatureTarget)
            {
                errorStack.ForEach(es => es.StackTrace.ForEach(st => st.IsSignatureTarget = false));
            }

            foreach (InnerError e in errorStack)
            {
                StackFrameCollection stackTrace = e.StackTrace;
                if (stackTrace == null)
                {
                    continue;
                }

                foreach (StackFrame stackFrame in stackTrace.Where(IsUserFrame))
                {
                    SignatureInfo.AddItemIfNotEmpty("ExceptionType", e.Type);
                    SignatureInfo.AddItemIfNotEmpty("Method", GetStackFrameSignature(stackFrame));
                    if (ShouldFlagSignatureTarget)
                    {
                        stackFrame.IsSignatureTarget = true;
                    }
                    AddSpecialCaseDetails(e);
                    UpdateInfo(true);
                    return;
                }
            }

            // We haven't found a user method yet, try some alternatives with the inner most error.
            InnerError innerMostError = errorStack[0];

            if (innerMostError.TargetMethod != null)
            {
                // Use the target method if it exists.
                SignatureInfo.AddItemIfNotEmpty("ExceptionType", innerMostError.Type);
                SignatureInfo.AddItemIfNotEmpty("Method", GetStackFrameSignature(innerMostError.TargetMethod));
                if (ShouldFlagSignatureTarget)
                {
                    innerMostError.TargetMethod.IsSignatureTarget = true;
                }
            }
            else if (innerMostError.StackTrace != null && innerMostError.StackTrace.Count > 0)
            {
                // Use the topmost stack frame.
                SignatureInfo.AddItemIfNotEmpty("ExceptionType", innerMostError.Type);
                SignatureInfo.AddItemIfNotEmpty("Method", GetStackFrameSignature(innerMostError.StackTrace[0]));
                if (ShouldFlagSignatureTarget)
                {
                    innerMostError.StackTrace[0].IsSignatureTarget = true;
                }
            }
            else
            {
                // All else failed, use the type.
                SignatureInfo.AddItemIfNotEmpty("ExceptionType", innerMostError.Type);
            }

            AddSpecialCaseDetails(innerMostError);
            if (SignatureInfo.Count == 0)
            {
                SignatureInfo.Add("NoStackingInformation", Guid.NewGuid().ToString());
            }

            UpdateInfo(false);
        }
 public Error(string message, string code, InnerError inner)
 {
     this.Message    = message;
     this.Code       = code;
     this.InnerError = inner;
 }
示例#34
0
        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='azureAsyncOperation'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        public async Task <AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(string azureAsyncOperation, CancellationToken cancellationToken)
        {
            // Validate
            if (azureAsyncOperation == null)
            {
                throw new ArgumentNullException("azureAsyncOperation");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("azureAsyncOperation", azureAsyncOperation);
                TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + azureAsyncOperation;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AzureAsyncOperationResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new AzureAsyncOperationResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken statusValue = responseDoc["status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true));
                                result.Status = statusInstance;
                            }

                            JToken errorValue = responseDoc["error"];
                            if (errorValue != null && errorValue.Type != JTokenType.Null)
                            {
                                Error errorInstance = new Error();
                                result.Error = errorInstance;

                                JToken codeValue = errorValue["code"];
                                if (codeValue != null && codeValue.Type != JTokenType.Null)
                                {
                                    string codeInstance = ((string)codeValue);
                                    errorInstance.Code = codeInstance;
                                }

                                JToken messageValue = errorValue["message"];
                                if (messageValue != null && messageValue.Type != JTokenType.Null)
                                {
                                    string messageInstance = ((string)messageValue);
                                    errorInstance.Message = messageInstance;
                                }

                                JToken targetValue = errorValue["target"];
                                if (targetValue != null && targetValue.Type != JTokenType.Null)
                                {
                                    string targetInstance = ((string)targetValue);
                                    errorInstance.Target = targetInstance;
                                }

                                JToken detailsArray = errorValue["details"];
                                if (detailsArray != null && detailsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken detailsValue in ((JArray)detailsArray))
                                    {
                                        ErrorDetails errorDetailsInstance = new ErrorDetails();
                                        errorInstance.Details.Add(errorDetailsInstance);

                                        JToken codeValue2 = detailsValue["code"];
                                        if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
                                        {
                                            string codeInstance2 = ((string)codeValue2);
                                            errorDetailsInstance.Code = codeInstance2;
                                        }

                                        JToken messageValue2 = detailsValue["message"];
                                        if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
                                        {
                                            string messageInstance2 = ((string)messageValue2);
                                            errorDetailsInstance.Message = messageInstance2;
                                        }

                                        JToken targetValue2 = detailsValue["target"];
                                        if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
                                        {
                                            string targetInstance2 = ((string)targetValue2);
                                            errorDetailsInstance.Target = targetInstance2;
                                        }
                                    }
                                }

                                JToken innerErrorValue = errorValue["innerError"];
                                if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null)
                                {
                                    InnerError innerErrorInstance = new InnerError();
                                    errorInstance.InnerError = innerErrorInstance;

                                    JToken traceValue = innerErrorValue["trace"];
                                    if (traceValue != null && traceValue.Type != JTokenType.Null)
                                    {
                                        string traceInstance = ((string)traceValue);
                                        innerErrorInstance.Trace = traceInstance;
                                    }

                                    JToken contextValue = innerErrorValue["context"];
                                    if (contextValue != null && contextValue.Type != JTokenType.Null)
                                    {
                                        string contextInstance = ((string)contextValue);
                                        innerErrorInstance.Context = contextInstance;
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }