private void FillRepositoryWithPreviousResults(IMetricsRepository repository)
        {
            Enumerable.Range(1, 31)
            .ToList()
            .ForEach(pastDay =>
            {
                var pastResultsEU = new Dictionary <IAnalyzer <IMetric>, IMetric>
                {
                    { Initializers.Size(), new DoubleMetric(MetricEntity.Dataset, "*", "Size", Math.Floor(pastDay / 3.0)) },
                    { Initializers.Mean("sales"), new DoubleMetric(MetricEntity.Column, "sales", "Mean", pastDay * 7) }
                };

                var pastResultsNA = new Dictionary <IAnalyzer <IMetric>, IMetric>
                {
                    { Initializers.Size(), new DoubleMetric(MetricEntity.Dataset, "*", "Size", pastDay) },
                    { Initializers.Mean("sales"), new DoubleMetric(MetricEntity.Column, "sales", "Mean", pastDay * 9) }
                };

                var analyzerContextEU = new AnalyzerContext(pastResultsEU);
                var analyzerContextNA = new AnalyzerContext(pastResultsNA);

                long dateTime = CreateDate(2018, 7, pastDay);

                repository.Save(new ResultKey(dateTime, new Dictionary <string, string> {
                    { "marketplace", "EU" }
                }),
                                analyzerContextEU);

                repository.Save(new ResultKey(dateTime, new Dictionary <string, string> {
                    { "marketplace", "NA" }
                }),
                                analyzerContextNA);
            });
        }
        private void AnalyzeField(SyntaxNodeAnalysisContext context, AnalyzerContext analyzerContext)
        {
            var node = (FieldDeclarationSyntax)context.Node;

            if (node == null)
            {
                return;
            }

            var firstVariable = node.Declaration?.Variables.FirstOrDefault();

            if (firstVariable == null)
            {
                return;
            }

            var symbol = context.SemanticModel.GetDeclaredSymbol(firstVariable, context.CancellationToken) as IFieldSymbol;

            if (!symbol.IsVisibleOutsideOfAssembly())
            {
                return;
            }

            if (IsValidType(analyzerContext, symbol.Type))
            {
                return;
            }

            context.ReportDiagnostic(s_rule, node.Declaration.Type);
        }
コード例 #3
0
        private void SaveOrAppendResultsIfNecessary(
            AnalyzerContext resultingAnalyzerContext,
            Option <IMetricsRepository> metricsRepository,
            Option <ResultKey> saveOrAppendResultsWithKey) =>
        metricsRepository.Select <object>(repository =>
        {
            saveOrAppendResultsWithKey.Select <object>(key =>
            {
                Option <AnalyzerContext> currentValueForKey = repository.LoadByKey(key);
                AnalyzerContext alreadySavedResult          =
                    currentValueForKey.GetOrElse(AnalyzerContext.Empty());         // TODO missing override

                Dictionary <string, IAnalyzer <IMetric> > alreadySavedDict =
                    alreadySavedResult.MetricMap.ToDictionary(pair => pair.Key.ToString(), pair => pair.Key);

                resultingAnalyzerContext.MetricMap.ToList().ForEach(keyValuePair =>
                {
                    if (alreadySavedDict.ContainsKey(keyValuePair.Key.ToString()) &&
                        alreadySavedResult.MetricMap.ContainsKey(alreadySavedDict[keyValuePair.Key.ToString()]))
                    {
                        alreadySavedResult.MetricMap[alreadySavedDict[keyValuePair.Key.ToString()]] = keyValuePair.Value;
                    }
                    else
                    {
                        alreadySavedResult.MetricMap.Add(keyValuePair.Key, keyValuePair.Value);
                    }
                });

                repository.Save(saveOrAppendResultsWithKey.Value, alreadySavedResult);
                return(null);
            });

            return(null);
        });
コード例 #4
0
 public DataBindingBackgroundHelper(AnalyzerBase analyzer, TreeItem treeItem, AnalyzerContext context, Action doneAction)
 {
     _context    = context;
     _analyzer   = analyzer;
     _treeItem   = treeItem;
     _doneAction = doneAction;
 }
        private bool IsValidType(AnalyzerContext analyzerContext, ITypeSymbol symbol)
        {
            if (symbol == null)
            {
                return(true);
            }

            var originalDefinition = symbol.OriginalDefinition;

            if (analyzerContext.ConcreteCollectionSymbols.Any(t => t.IsEqualTo(originalDefinition)))
            {
                return(false);
            }

            var namedTypeSymbol = symbol as INamedTypeSymbol;

            if (namedTypeSymbol != null)
            {
                if (analyzerContext.TaskSymbols.Any(t => t.IsEqualTo(symbol.OriginalDefinition)))
                {
                    return(IsValidType(analyzerContext, namedTypeSymbol.TypeArguments[0]));
                }
            }

            return(true);
        }
        private void AnalyzeIndexer(SyntaxNodeAnalysisContext context, AnalyzerContext analyzerContext)
        {
            var node = (IndexerDeclarationSyntax)context.Node;

            if (node == null)
            {
                return;
            }

            var symbol = context.SemanticModel.GetDeclaredSymbol(node, context.CancellationToken);

            if (!symbol.IsVisibleOutsideOfAssembly() || symbol.IsOverrideOrInterfaceImplementation())
            {
                return;
            }

            var type = node.Type;

            if (type != null && !IsValidType(analyzerContext, context.SemanticModel.GetTypeInfo(type, context.CancellationToken).Type))
            {
                context.ReportDiagnostic(s_rule, type);
            }

            AnalyzeParameters(context, analyzerContext, node.ParameterList?.Parameters);
        }
コード例 #7
0
 private List <Cartridge> LoadCartridgesDetails()
 {
     using (AnalyzerContext db = new AnalyzerContext())
     {
         db.Cartridges.Load();
         return(db.Cartridges.Local.ToList());
     }
 }
コード例 #8
0
 private ObservableCollection <Cartridge> LoadCartridgesDetails()
 {
     using (AnalyzerContext db = new AnalyzerContext())
     {
         db.Cartridges.Load();
         return(db.Cartridges.Local.ToObservableCollection());
     }
 }
コード例 #9
0
        public void should_execute_incremental_metrics_example()
        {
            DataFrame dataSetDE = LoadIncrementalMetricsData(
                new[] { new object[] { 1, "ManufacturerA", "DE" }, new object[] { 2, "ManufacturerB", "DE" },
                        new object[] { 2, "ManufacturerC", "DE" } });

            DataFrame dataSetUS = LoadIncrementalMetricsData(
                new[]
            {
                new object[] { 3, "ManufacturerD", "US" }, new object[] { 4, "ManufacturerE", "US" },
                new object[] { 5, "ManufacturerF", "US" }
            });

            DataFrame dataSetCN = LoadIncrementalMetricsData(
                new[] { new object[] { 6, "ManufacturerG", "CN" }, new object[] { 7, "ManufacturerH", "CN" }, });

            // We initialize a new check for the following data fields
            var check = new Check(CheckLevel.Warning, "generic check")
                        .IsComplete("manufacturerName")
                        .ContainsURL("manufacturerName", val => val == 0.0)
                        .IsContainedIn("countryCode", new[] { "DE", "US", "CN" });


            // We create a new Analysis instance with the corresponding RequiredAnalyzers defined in the check
            Analysis analysis = new Analysis(check.RequiredAnalyzers());

            // We create a new in-memory state provider for each countryCode defined in the dataset
            InMemoryStateProvider deStates = new InMemoryStateProvider();
            InMemoryStateProvider usStates = new InMemoryStateProvider();
            InMemoryStateProvider cnStates = new InMemoryStateProvider();

            // These call will store the resulting metrics in the separate states providers for each dataSet
            AnalysisRunner.Run(dataSetDE, analysis, saveStatesWith: deStates);
            AnalysisRunner.Run(dataSetUS, analysis, saveStatesWith: usStates);
            AnalysisRunner.Run(dataSetCN, analysis, saveStatesWith: cnStates);

            // Next, we are able to compute the metrics for the whole table from the partition states
            // This just aggregates the previously calculated metrics, it doesn't performs computation on the data
            AnalyzerContext tableMetrics = AnalysisRunner.RunOnAggregatedStates(dataSetDE.Schema(), analysis,
                                                                                new[] { deStates, usStates, cnStates });

            // Lets now assume that a single partition changes. We only need to recompute the state of this
            // partition in order to update the metrics for the whole table.
            DataFrame updatedUsManufacturers = LoadIncrementalMetricsData(new[]
            {
                new object[] { 3, "ManufacturerDNew", "US" }, new object[] { 4, null, "US" },
                new object[] { 5, "ManufacturerFNew http://clickme.com", "US" },
            });

            // Recompute state of partition
            InMemoryStateProvider updatedUsStates = new InMemoryStateProvider();

            AnalysisRunner.Run(updatedUsManufacturers, analysis, updatedUsStates);

            // Recompute metrics for whole tables from states. We do not need to touch old data!
            AnalyzerContext updatedTableMetrics = AnalysisRunner.RunOnAggregatedStates(dataSetDE.Schema(), analysis,
                                                                                       new[] { deStates, usStates, cnStates });
        }
        private void AnalyzeParameter(SyntaxNodeAnalysisContext context, AnalyzerContext analyzerContext, ParameterSyntax parameter)
        {
            var type = parameter.Type;

            if (type != null && !IsValidType(analyzerContext, context.SemanticModel.GetTypeInfo(type, context.CancellationToken).Type))
            {
                context.ReportDiagnostic(s_rule, parameter);
            }
        }
コード例 #11
0
        public IEnumerable <ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context)
        {
            Debug.Assert(analyzedSymbol is IField);
            var scope = context.GetScopeOf((IEntity)analyzedSymbol);

            foreach (var type in scope.GetTypesInScope(context.CancellationToken))
            {
                var mappingInfo = context.Language.GetCodeMappingInfo(type.ParentModule.PEFile, type.MetadataToken);
                var methods     = type.GetMembers(m => m is IMethod, Options).OfType <IMethod>();
                foreach (var method in methods)
                {
                    if (IsUsedInMethod((IField)analyzedSymbol, method, mappingInfo, context))
                    {
                        yield return(method);
                    }
                }

                foreach (var property in type.Properties)
                {
                    if (property.CanGet && IsUsedInMethod((IField)analyzedSymbol, property.Getter, mappingInfo, context))
                    {
                        yield return(property);

                        continue;
                    }
                    if (property.CanSet && IsUsedInMethod((IField)analyzedSymbol, property.Setter, mappingInfo, context))
                    {
                        yield return(property);

                        continue;
                    }
                }

                foreach (var @event in type.Events)
                {
                    if (@event.CanAdd && IsUsedInMethod((IField)analyzedSymbol, @event.AddAccessor, mappingInfo, context))
                    {
                        yield return(@event);

                        continue;
                    }
                    if (@event.CanRemove && IsUsedInMethod((IField)analyzedSymbol, @event.RemoveAccessor, mappingInfo, context))
                    {
                        yield return(@event);

                        continue;
                    }
                    if (@event.CanInvoke && IsUsedInMethod((IField)analyzedSymbol, @event.InvokeAccessor, mappingInfo, context))
                    {
                        yield return(@event);

                        continue;
                    }
                }
            }
        }
 private void AnalyzeParameters(SyntaxNodeAnalysisContext context, AnalyzerContext analyzerContext, IEnumerable <ParameterSyntax> parameters)
 {
     if (parameters != null)
     {
         foreach (var parameter in parameters)
         {
             AnalyzeParameter(context, analyzerContext, parameter);
         }
     }
 }
コード例 #13
0
        public bool TryAnalyze(string line, string[] parts, AnalyzerContext context)
        {
            if (!(context.AnalyzerState == AnalyzerState.Default &&
                  parts[0] == "initial"))
            {
                return(false);
            }

            return(true);
        }
コード例 #14
0
        private static void Evaluate(SparkSession session, Action <AnalyzerContext, IMetricsRepository> func)
        {
            DataFrame data = FixtureSupport.GetDFFull(session);

            AnalyzerContext results = CreateAnalysis().Run(data, Option <IStateLoader> .None,
                                                           Option <IStatePersister> .None);

            IMetricsRepository repository = CreateRepository();

            func(results, repository);
        }
コード例 #15
0
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(ctx =>
            {
                var analyzerContext = new AnalyzerContext(ctx.Compilation);
                ctx.RegisterOperationAction(analyzerContext.AnalyzeBinaryOperator, OperationKind.Binary);
            });
        }
コード例 #16
0
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(ctx =>
            {
                var analyzerContext = new AnalyzerContext(ctx.Compilation);
                ctx.RegisterSymbolAction(analyzerContext.AnalyzeSymbol, SymbolKind.Event);
            });
        }
コード例 #17
0
        public IEnumerable <ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context)
        {
            Debug.Assert(analyzedSymbol is IMember);
            var member = (IMember)analyzedSymbol;

            Debug.Assert(!member.IsStatic);

            var baseMembers = InheritanceHelper.GetBaseMembers(member, includeImplementedInterfaces: true);

            return(baseMembers.Where(m => m.DeclaringTypeDefinition.Kind == TypeKind.Interface));
        }
コード例 #18
0
        private VerificationResult Evaluate(IEnumerable <Check> checks, AnalyzerContext analyzerContext)
        {
            IEnumerable <KeyValuePair <Check, CheckResult> > checkResult = checks.Select(check =>
                                                                                         new KeyValuePair <Check, CheckResult>(check, check.Evaluate(analyzerContext)));

            CheckStatus verificationStatus;

            verificationStatus = !checkResult.Any() ? CheckStatus.Success : checkResult.Max(check => check.Value.Status);

            return(new VerificationResult(verificationStatus,
                                          new Dictionary <Check, CheckResult>(checkResult), analyzerContext.MetricMap));
        }
コード例 #19
0
        public bool TryAnalyze(string line, string[] parts, AnalyzerContext context)
        {
            if (!(context.AnalyzerState == AnalyzerState.Default &&
                  parts[0] == "module" &&
                  !line.Contains(";")))
            {
                return(false);
            }

            context.Module        = new Module(parts[1]);
            context.AnalyzerState = AnalyzerState.ScanningModulePorts;
            return(true);
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(ctx =>
            {
                var compilation     = ctx.Compilation;
                var analyzerContext = new AnalyzerContext(compilation);

                ctx.RegisterSyntaxNodeAction(analyzerContext.AnalyzeMethodDeclaration, SyntaxKind.MethodDeclaration);
            });
        }
コード例 #21
0
        public IEnumerable <ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context)
        {
            Debug.Assert(analyzedSymbol is ITypeDefinition);
            var scope = context.GetScopeOf((ITypeDefinition)analyzedSymbol);

            foreach (var type in scope.GetTypesInScope(context.CancellationToken))
            {
                foreach (var result in ScanType((ITypeDefinition)analyzedSymbol, type, context))
                {
                    yield return(result);
                }
            }
        }
            public static AnalyzerContext Create(Compilation compilation)
            {
                var context = new AnalyzerContext();

                context.ConcreteCollectionSymbols.AddIfNotNull(compilation.GetTypeByMetadataName("System.Collections.Generic.List`1"));
                context.ConcreteCollectionSymbols.AddIfNotNull(compilation.GetTypeByMetadataName("System.Collections.Generic.HashSet`1"));
                context.ConcreteCollectionSymbols.AddIfNotNull(compilation.GetTypeByMetadataName("System.Collections.Generic.Dictionary`2"));
                context.ConcreteCollectionSymbols.AddIfNotNull(compilation.GetTypeByMetadataName("System.Collections.ObjectModel`1"));

                context.TaskSymbols.AddIfNotNull(compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1"));
                context.TaskSymbols.AddIfNotNull(compilation.GetTypeByMetadataName("System.Threading.Tasks.ValueTask`1"));
                return(context);
            }
コード例 #23
0
        public IEnumerable <ISymbol> Analyze(ISymbol analyzedSymbol, AnalyzerContext context)
        {
            Debug.Assert(analyzedSymbol is IMethod);
            var scope = context.GetScopeOf((IEntity)analyzedSymbol);

            foreach (var type in scope.GetTypesInScope(context.CancellationToken))
            {
                foreach (var result in AnalyzeType((IMethod)analyzedSymbol, type))
                {
                    yield return(result);
                }
            }
        }
コード例 #24
0
        public override AnalysisResult Read(ref Utf8JsonReader reader, Type typeToConvert,
                                            JsonSerializerOptions options)
        {
            JsonDocument.TryParseValue(ref reader, out JsonDocument document);
            JsonElement resultKey = document.RootElement.GetProperty(SerdeExt.RESULT_KEY_FIELD);
            JsonElement analyzer  = document.RootElement.GetProperty(SerdeExt.ANALYZER_CONTEXT_FIELD);


            ResultKey       resultKeyDe       = JsonSerializer.Deserialize <ResultKey>(resultKey.GetRawText(), options);
            AnalyzerContext analyzerContextDe =
                JsonSerializer.Deserialize <AnalyzerContext>(analyzer.GetRawText(), options);

            return(new AnalysisResult(resultKeyDe, analyzerContextDe));
        }
コード例 #25
0
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.ReportDiagnostics);

            context.RegisterCompilationStartAction(ctx =>
            {
                var analyzerContext = new AnalyzerContext(ctx.Compilation);
                ctx.RegisterSyntaxNodeAction(analyzerContext.AnalyzeAwaitExpression, SyntaxKind.AwaitExpression);
                ctx.RegisterOperationAction(analyzerContext.AnalyzeForEachStatement, OperationKind.Loop);
                ctx.RegisterOperationAction(analyzerContext.AnalyzeUsingOperation, OperationKind.Using);
                ctx.RegisterOperationAction(analyzerContext.AnalyzeUsingDeclarationOperation, OperationKind.UsingDeclaration);
            });
        }
コード例 #26
0
 private ObservableCollection <AnalysisType> LoadAnalysisTypesDetails()
 {
     using (AnalyzerContext db = new AnalyzerContext())
     {
         db.AnalysisTypes
         .Include(a => a.Cartridge)
         .Include(a => a.SamplingStage)
         .Include(a => a.ConjugateStage)
         .Include(a => a.EnzymeComplexStage)
         .Include(a => a.SubstrateStage)
         .Load();
         return(db.AnalysisTypes.Local.ToObservableCollection());
     }
 }
コード例 #27
0
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(ctx =>
            {
                var analyzerContext = new AnalyzerContext(ctx.Compilation);
                if (analyzerContext.CancellationTokenSymbol == null)
                    return;

                ctx.RegisterOperationAction(analyzerContext.Analyze, OperationKind.Invocation);
            });
        }
コード例 #28
0
        public void SystemInt32UsedByMainAssembly()
        {
            var context = new AnalyzerContext {
                AssemblyList = assemblyList, Language = language
            };
            var symbol = testAssemblyTypeSystem.FindType(typeof(int)).GetDefinition();

            var results = new TypeUsedByAnalyzer().Analyze(symbol, context).ToList();

            Assert.IsNotEmpty(results);
            var method = results.OfType <IMethod>().SingleOrDefault(m => m.FullName == "ICSharpCode.ILSpy.Tests.Analyzers.TestCases.Main.MainAssembly.UsesInt32");

            Assert.IsNotNull(method);
            Assert.IsFalse(method.MetadataToken.IsNil);
        }
コード例 #29
0
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);

            context.RegisterCompilationStartAction(ctx =>
            {
                var analyzerContext = new AnalyzerContext();

                ctx.RegisterSyntaxNodeAction(analyzerContext.AnalyzeMethod, SyntaxKind.MethodDeclaration);
                ctx.RegisterSyntaxNodeAction(analyzerContext.AnalyzeProperty, SyntaxKind.PropertyDeclaration);
                ctx.RegisterOperationAction(analyzerContext.AnalyzeEventAssignment, OperationKind.EventAssignment);
                ctx.RegisterCompilationEndAction(analyzerContext.CompilationEnd);
            });
        }
コード例 #30
0
        public bool TryAnalyze(string line, string[] parts, AnalyzerContext context)
        {
            if (!(context.AnalyzerState == AnalyzerState.Default &&
                  (parts[0] == "input" || parts[0] == "output")))
            {
                return(false);
            }

            var portId = parts[1].RemoveAll(";");

            Enum.TryParse(parts[0], true, out NetType portType);
            context.Module.Nets.First(p => p.Identifier == portId).NetType = portType;

            return(true);
        }
コード例 #31
0
ファイル: TreeItem.cs プロジェクト: bdurrani/WPF-Inspector
        public void Analyze(AnalyzerContext context)
        {
            _analyzercontext = context;
            if (_analyzercontext != null)
            {
                _analyzercontext.Analyze(this);
                List<TreeItem> cloneList;
                lock (this)
                {
                    cloneList = new List<TreeItem>(Children);
                }

                foreach (var child in cloneList)
                {
                    //child.Analyze(context);
                    TreeItem item = child;
                    Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => item.Analyze(context)),
                                                             DispatcherPriority.Background);
                }
            }
        }
コード例 #32
0
 /// <summary>
 /// Analyzes the specified element for issues.
 /// </summary>
 public virtual void Analyze(TreeItem treeItem, AnalyzerContext analyzerContext)
 {
     analyzerContext.UpdateIssues(this,treeItem, AnalyzeInternal(treeItem));
 }