示例#1
0
        public void Can_compute_correct_average()
        {
            var context = new DiagnosticsContext(() => new AverageAggregator());

            context.PushResult(1);
            context.PushResult(5);

            context.Enabled = false;
            context.PushResult(200);

            Assert.Equal(3, context[""]);
        }
        public void Can_compute_correct_average()
        {
            var context = new DiagnosticsContext(() => new AverageAggregator());

            context.PushResult(1);
            context.PushResult(5);

            context.Enabled = false;
            context.PushResult(200);

            Assert.Equal(3, context[""]);
        }
示例#3
0
        public async Task <IActionResult> Handle(Request request, CancellationToken cancellationToken = default)
        {
            if (request is null)
            {
                return(BadRequest());
            }

            DiagnosticsContext.Set("CartId", request.CartId);
            DiagnosticsContext.Set("ProductId", request.ProductId);
            DiagnosticsContext.Set("Increment", request.Increment);

            CartEntity cart = await Context.Carts.AsNoTracking().SingleOrDefaultAsync(c => c.Id == request.CartId, cancellationToken);

            if (cart is null)
            {
                Logger.LogTrace("Cart not found");
                string message = Localizer.GetStringSafe("CartNotFound", request.CartId);
                return(NotFoundProblem(message));
            }

            ItemEntity item = await Context.Items.AsTracking().SingleOrDefaultAsync(c => c.CartId == request.CartId && c.ProductId == request.ProductId, cancellationToken);

            if (item is null)
            {
                item            = Mapper.Map <ItemEntity>(request);
                item.CreatedOn  = Clock.UtcNow;
                item.ModifiedOn = Clock.UtcNow;

                DiagnosticsContext.Set("NewQuantity", item.Quantity);
                DiagnosticsContext.Set("PreviousQuantity", 0);

                Context.Items.Add(item);
            }
            else
            {
                int existingQuantity = item.Quantity;
                item.Quantity  += request.Increment;
                item.ModifiedOn = Clock.UtcNow;

                DiagnosticsContext.Set("NewQuantity", item.Quantity);
                DiagnosticsContext.Set("PreviousQuantity", existingQuantity);
            }

            await Context.SaveChangesAsync(cancellationToken);

            var response = Mapper.Map <Response>(item);

            return(Ok(response));
        }
示例#4
0
        internal static void WriteDiagnostics(Task task, DiagnosticsContext diagnosticsContext, bool piiRedactionEnabled)
        {
            StringBuilder stringBuilder = null;
            List <ICollection <KeyValuePair <string, object> > > data = diagnosticsContext.Data;

            if (data == null)
            {
                return;
            }
            bool flag = ServerCache.Instance.WriteToStatsLogs && ServerCache.Instance.HostId == HostId.ECPApplicationPool;

            foreach (ICollection <KeyValuePair <string, object> > collection in data)
            {
                if (flag)
                {
                    CommonDiagnosticsLog.Instance.LogEvent(CommonDiagnosticsLog.Source.DeliveryReports, collection);
                }
                else
                {
                    if (stringBuilder == null)
                    {
                        stringBuilder = new StringBuilder(256);
                    }
                    int count = collection.Count;
                    int num   = 0;
                    foreach (KeyValuePair <string, object> keyValuePair in collection)
                    {
                        string arg;
                        if (piiRedactionEnabled && Utils.DiagnosticKeysToRedact.Contains(keyValuePair.Key))
                        {
                            arg = Utils.RedactPiiString(keyValuePair.Value as string, task);
                        }
                        else
                        {
                            arg = (keyValuePair.Value as string);
                        }
                        stringBuilder.AppendFormat("{0}={1}", keyValuePair.Key, arg);
                        if (++num < count)
                        {
                            stringBuilder.Append(",");
                        }
                    }
                    string text = stringBuilder.ToString();
                    task.WriteDebug(text);
                    stringBuilder.Length = 0;
                    ExTraceGlobals.TaskTracer.TraceDebug <string>(0L, "DEBUG: {0}", text);
                }
            }
        }
示例#5
0
        public async Task <IActionResult> Handle(CancellationToken cancellationToken = default)
        {
            CartEntity cart = new()
            {
                CreatedOn = Clock.UtcNow
            };

            Context.Add(cart);

            await Context.SaveChangesAsync(cancellationToken);

            DiagnosticsContext.Set("CartId", cart.Id);

            return(CreatedAtAction(nameof(GetCartById.Handle), nameof(GetCartById), new { cart.Id }, cart));
        }
    }
        public void Can_compute_correct_moving_average()
        {
            var context = new DiagnosticsContext(() => new MovingAverageAggregator(history: 2));

            context.PushResult(1);
            context.PushResult(5);

            Assert.Equal(3, context[""]);

            context.PushResult(5);

            Assert.Equal(5, context[""]);

            context.PushResult(1);

            Assert.Equal(3, context[""]);
        }
示例#7
0
        public void Can_compute_correct_moving_average()
        {
            var context = new DiagnosticsContext(() => new MovingAverageAggregator(history: 2));

            context.PushResult(1);
            context.PushResult(5);

            Assert.Equal(3, context[""]);

            context.PushResult(5);

            Assert.Equal(5, context[""]);

            context.PushResult(1);

            Assert.Equal(3, context[""]);
        }
示例#8
0
        /// <nodoc />
        private bool LiteralFix(INode node, DiagnosticsContext context)
        {
            var call   = node.Cast <ICallExpression>();
            var symbol = context.SemanticModel.GetSymbolAtLocation(call.Expression);

            if (symbol != null)
            {
                if (!FixCreateFunction(call, symbol, context, "a", "PathAtom"))
                {
                    return(false);
                }

                if (!FixCreateFunction(call, symbol, context, "r", "RelativePath"))
                {
                    return(false);
                }
            }

            return(true);
        }
示例#9
0
        /// <summary>
        /// Checks if the given symbol is defined in a module whose name is <see ref="moduleName"/> and has a fully expanded name of <see ref="fullName"/>.
        /// </summary>
        private static bool Matches(DiagnosticsContext context, ISymbol symbol, string moduleName, string fullName)
        {
            var decl       = symbol.DeclarationList.FirstOrDefault();
            var owningSpec = decl?.GetSourceFile()?.GetAbsolutePath(context.PathTable);

            ParsedModule parsedModule;

            if (owningSpec.HasValue && (parsedModule = context.Workspace.TryGetModuleBySpecFileName(owningSpec.Value)) != null)
            {
                var actualFullName   = context.SemanticModel.GetFullyQualifiedName(symbol);
                var actualModuleName = parsedModule.Descriptor.Name;
                if (string.Equals(moduleName, actualModuleName, StringComparison.Ordinal) &&
                    string.Equals(fullName, actualFullName, StringComparison.Ordinal))
                {
                    return(true);
                }
            }

            return(false);
        }
示例#10
0
        private bool FixCreateFunction(ICallExpression call, ISymbol symbol, DiagnosticsContext context, string formatFunction, string interfaceName)
        {
            if (Matches(context, symbol, "Sdk.Prelude", interfaceName + ".create"))
            {
                var arg = call.Arguments.FirstOrDefault();

                var fix = ComputeFix(formatFunction, arg);

                if (Fix)
                {
                    call.Replace(fix);
                }
                else
                {
                    var existingExpression = call.ToDisplayString();
                    var fixExpression      = fix.ToDisplayString();
                    Logger.LegacyLiteralFix(LoggingContext, call.LocationForLogging(context.SourceFile), fixExpression, existingExpression);
                    return(false);
                }
            }

            return(true);
        }
示例#11
0
        public async Task <IActionResult> Handle(Guid id, CancellationToken cancellationToken = default)
        {
            DiagnosticsContext.Set("CartId", id);

            CartEntity cart = await Context.Carts.AsNoTracking().SingleOrDefaultAsync(c => c.Id == id, cancellationToken);

            if (cart is null)
            {
                Logger.LogTrace("Cart not found");
                string message = Localizer.GetStringSafe("CartNotFound", id);
                return(NotFoundProblem(message));
            }

            ItemEntity[] items = await Context.Items.AsNoTracking().Where(i => i.CartId == cart.Id).ToArrayAsync(cancellationToken);

            var response = Mapper.Map <Response>(cart);

            response.Items = items;

            DiagnosticsContext.Set("CartItemCount", items.Length);

            return(Ok(response));
        }
示例#12
0
 /// <summary>
 /// Analyzes a path node
 /// </summary>
 /// <returns>true if the path has no analysis errors, false otherwise</returns>
 public bool Analyze(INode node, DiagnosticsContext context, Logger logger, LoggingContext loggingContext)
 {
     return(PathFix(node, (literalLikeNode, maintainCaseOfLastStep) => AnalyzePathFragmentLiteral(literalLikeNode, maintainCaseOfLastStep, context, logger, loggingContext)));
 }
示例#13
0
        private bool AnalyzePathFragmentLiteral(ILiteralLikeNode node, bool maintainCaseOfLast, DiagnosticsContext context, Logger logger, LoggingContext loggingContext)
        {
            Contract.Requires(context != null, "context is required when analyzing and validating.");

            var illegalIndex = node.Text.IndexOf(IllegalPathSeparator);

            if (illegalIndex >= 0)
            {
                var location = node.LocationForLogging(context.SourceFile);
                location.Position += illegalIndex;

                logger.PathFixerIllegalPathSeparator(loggingContext, location, node.Text, ExpectedPathSeparator, IllegalPathSeparator);
                return(false);
            }

            if (!LowerCaseDirectories)
            {
                return(true);
            }

            var fragments = node.Text.Split(ExpectedPathSeparator, IllegalPathSeparator);

            int charOffSetForError = 0;
            int nrOfFragmentsToFix = fragments.Length;

            if (maintainCaseOfLast)
            {
                // Don't address the case of the last fragment.
                nrOfFragmentsToFix--;
            }

            // lowercase all parts of the path when requested.
            for (int i = 0; i < nrOfFragmentsToFix; i++)
            {
                var fragment      = fragments[i];
                var lowerFragment = fragment.ToLowerInvariant();

                if (!string.Equals(lowerFragment, fragment, StringComparison.Ordinal))
                {
                    // Try to find an estimate of the exact character that is a mismatch
                    var upperBound = Math.Min(lowerFragment.Length, fragment.Length);
                    for (int posInFragment = 0; posInFragment < upperBound; posInFragment++)
                    {
                        if (lowerFragment[posInFragment] != fragment[posInFragment])
                        {
                            charOffSetForError += posInFragment;
                        }
                    }

                    var location = node.LocationForLogging(context.SourceFile);
                    location.Position += charOffSetForError;

                    logger.PathFixerIllegalCasing(loggingContext, location, node.Text, fragment, lowerFragment);
                    return(false);
                }

                charOffSetForError += fragment.Length + 1; /*1 extra for the path separator*/
            }

            return(true);
        }
示例#14
0
        /// <summary>
        /// Fix Path handler
        /// </summary>
        public bool PathFix(INode node, [CanBeNull] DiagnosticsContext context)
        {
            var taggedTemplateExpression = node.Cast <ITaggedTemplateExpression>();

            return(Fix ? PathFixer.Fix(taggedTemplateExpression) : PathFixer.Analyze(taggedTemplateExpression, context, Logger, LoggingContext));
        }
 public DiagnosticsRepository(DiagnosticsContext context)
 {
     _context = context;
 }