コード例 #1
0
ファイル: EFSyntaxWalker.cs プロジェクト: mirsaeedi/Codelyn
        private void AnalyzeLoop(BlockSyntax blockSyntax)
        {
            var context = new AnalyzeContext(_efAnalyzer.Project,
                                             _efAnalyzer.Document);

            _efAnalyzer.AnalyzedContexts.Add(context);

            var methodInvocations = blockSyntax.DescendantNodes()
                                    .Where(q => q.Kind() == SyntaxKind.InvocationExpression)
                                    .OfType <InvocationExpressionSyntax>()
                                    .ToArray();

            foreach (var methodInvocation in methodInvocations)
            {
                var detectAddRemoveInsideLoopAnalyzer = new DetectAddRemoveInsideLoopAnalyzer(_efAnalyzer.DocumentSemanticModel);
                context.RuleViolations.AddRange(detectAddRemoveInsideLoopAnalyzer.AnalyzeSyntaxNode(methodInvocation));

                var detectSaveInsideLoopAnalyzer = new DetectSaveInsideLoopAnalyzer(_efAnalyzer.DocumentSemanticModel);
                context.RuleViolations.AddRange(detectSaveInsideLoopAnalyzer.AnalyzeSyntaxNode(methodInvocation));
            }

            var objectCreations = blockSyntax.DescendantNodes()
                                  .Where(q => q.Kind() == SyntaxKind.ObjectCreationExpression)
                                  .OfType <ObjectCreationExpressionSyntax>()
                                  .ToArray();

            foreach (var objectCreation in objectCreations)
            {
                var detectDbContextCreationInsideLoopAnalyzer = new DetectDbContextCreationInsideLoopAnalyzer(_efAnalyzer.DocumentSemanticModel);
                context.RuleViolations.AddRange(detectDbContextCreationInsideLoopAnalyzer.AnalyzeSyntaxNode(objectCreation));
            }
        }
コード例 #2
0
ファイル: EFSyntaxWalker.cs プロジェクト: mirsaeedi/Codelyn
        public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var context = new AnalyzeContext(_efAnalyzer.Project,
                                             _efAnalyzer.Document);

            _efAnalyzer.AnalyzedContexts.Add(context);

            var fieldDeclarationSyntaxes = node.DescendantNodes()
                                           .Where(n => n.Kind() == SyntaxKind.FieldDeclaration)
                                           .OfType <FieldDeclarationSyntax>()
                                           .ToArray();

            foreach (var fieldDeclarationSyntax in fieldDeclarationSyntaxes)
            {
                var detectDbContextInitializationAsClassFieldAnalyzer =
                    new DetectDbContextInitializationAsClassFieldAnalyzer(_efAnalyzer.DocumentSemanticModel);
                context.RuleViolations.AddRange(detectDbContextInitializationAsClassFieldAnalyzer.AnalyzeSyntaxNode(fieldDeclarationSyntax));

                var detectStaticDbContextFieldAnalyzer =
                    new DetectStaticDbContextFieldAnalyzer(_efAnalyzer.DocumentSemanticModel);
                context.RuleViolations.AddRange(detectStaticDbContextFieldAnalyzer.AnalyzeSyntaxNode(fieldDeclarationSyntax));
            }

            base.VisitClassDeclaration(node);
        }
コード例 #3
0
ファイル: StadAnalyzer.cs プロジェクト: penspanic/Stad
        private static StadRegistry MakeRegistry(TypeCollectorResult result)
        {
            AnalyzeContext      context       = new AnalyzeContext(result);
            List <DataSetModel> dataSetModels = new List <DataSetModel>();

            foreach (ObjectSerializationInfo info in result.CollectedObjectInfo)
            {
                if (info.Attributes.IsDefaultOrEmpty == true)
                {
                    continue;
                }

                var dataSetDefinitionAttribute = info.Attributes.FirstOrDefault(a =>
                                                                                a.Type.Contains(nameof(Stad.Annotation.DataSetDefinition)));
                if (dataSetDefinitionAttribute != null)
                {
                    var dataSetModel = MakeDataSetModel(context, info);
                    if (dataSetModel != null)
                    {
                        dataSetModels.Add(dataSetModel);
                    }
                }
            }

            return(StadRegistry.Create(new ReadOnlyCollection <DataSetModel>(dataSetModels)));
        }
コード例 #4
0
 public IEnumerable <string> Execute(IEnumerable <string> tokens, AnalyzeContext context)
 {
     foreach (var token in tokens)
     {
         var matches = _regex.Matches(token);
         foreach (Match match in matches)
         {
             if (match.Success)
             {
                 foreach (Group group in match.Groups)
                 {
                     if (!group.Success || group is Match)
                     {
                         continue;
                     }
                     yield return(group.Value);
                 }
             }
         }
         if (_preserveOriginal)
         {
             yield return(token);
         }
     }
 }
コード例 #5
0
        public string ParseStatement(AnalyzeContext context)
        {
            var queryPropertyName = context.QueryProperty.Name;
            var modelPropertyName = context.ModelProperty.Name;
            var navigation        = new List <string>(context.Navigations)
            {
                modelPropertyName
            };
            var builder           = new StringBuilder();
            var modelPropertyType = context.ModelProperty.PropertyType;

            builder.AppendLineFormat("if({0}.{1} != null)", context.QueryParamName, queryPropertyName)
            .AppendLine("{");
            if (modelPropertyType.IsGenericType)
            {
                builder.AppendLineFormat("{0} = {0}.Where(o=>{3}.{1}.Contains(o.{2}.Value));", context.SourceParamName, queryPropertyName,
                                         string.Join(".", navigation), context.QueryParamName);
            }
            else
            {
                builder.AppendLineFormat("{0} = {0}.Where(o=>{3}.{1}.Contains(o.{2}));", context.SourceParamName, queryPropertyName,
                                         string.Join(".", navigation), context.QueryParamName);
            }

            builder.AppendLine("}");
            return(builder.ToString());
        }
コード例 #6
0
ファイル: Runner.cs プロジェクト: ztz2018/Trady
        public Result Run(decimal principal, DateTime?startTime = null, DateTime?endTime = null)
        {
            if (_weightings == null || !_weightings.Any())
            {
                throw new ArgumentException("You should have at least one candle set for calculation");
            }

            // Distribute principal to each candle set
            decimal totalWeight = _weightings.Sum(w => w.Value);
            IReadOnlyDictionary <IEnumerable <IOhlcv>, decimal> preAssetCashMap = _weightings.ToDictionary(w => w.Key, w => principal * w.Value / totalWeight);
            var assetCashMap = preAssetCashMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            // Init transaction history
            var transactions = new List <Transaction>();

            // Loop with each asset
            for (int i = 0; i < _weightings.Count; i++)
            {
                var asset      = assetCashMap.ElementAt(i).Key;
                var startIndex = asset.FindIndexOrDefault(c => c.DateTime >= (startTime ?? DateTimeOffset.MinValue), 0).Value;
                var endIndex   = asset.FindLastIndexOrDefault(c => c.DateTime <= (endTime ?? DateTimeOffset.MaxValue), asset.Count() - 1).Value;
                using (var context = new AnalyzeContext(asset))
                {
                    var executor = CreateBuySellRuleExecutor(context, _calculator, assetCashMap, transactions);
                    executor.Execute(startIndex, endIndex);
                }
            }

            return(new Result(preAssetCashMap, assetCashMap, transactions));
        }
コード例 #7
0
        public async Task TestRuleExecutorWithVerifyAsync()
        {
            var candles = await ImportIOhlcvDatasAsync();

            void Verify(Predicate <IIndexedOhlcv> rule)
            {
                IReadOnlyList <IIndexedOhlcv> list;

                // Get all indexed candle who fulfill the rule
                using (var ctx = new AnalyzeContext(candles))
                {
                    var executor = new SimpleRuleExecutor(ctx, rule);
                    list = executor.Execute();
                }

                var indexList = list.Select(l => l.Index);

                //var indexString = string.Join(",", indexList);

                // Verify if fulfilled indexed candle is true or not
                foreach (var index in indexList)
                {
                    var ic = new IndexedCandle(candles, index);
                    Assert.IsTrue(rule(ic));
                }
            }

            bool buyRule(IIndexedOhlcv ic) => ic.IsEmaBullishCross(21, 55);

            Verify(buyRule);

            bool sellRule(IIndexedOhlcv ic) => ic.IsEmaBearishCross(21, 55);

            Verify(sellRule);
        }
コード例 #8
0
        private void AnalyzeCommand(IRegex engine)
        {
            var disabledSkimmers = new HashSet <string>();
            var testLogger       = new TestLogger();

            // Acquire skimmers for searchers
            ISet <Skimmer <AnalyzeContext> > skimmers =
                PatternMatcher.AnalyzeCommand.CreateSkimmersFromDefinitionsFiles(
                    fileSystemMock.Object,
                    new string[] { searchDefinitionsPath },
                    engine);

            string     scanTargetFileName = Path.Combine(@"C:\", Guid.NewGuid().ToString() + ".test");
            FlexString fileContents       = "bar foo foo";

            var context = new AnalyzeContext()
            {
                TargetUri    = new Uri(scanTargetFileName, UriKind.RelativeOrAbsolute),
                FileContents = fileContents,
                Logger       = testLogger
            };

            IEnumerable <Skimmer <AnalyzeContext> > applicableSkimmers = PatternMatcher.AnalyzeCommand.DetermineApplicabilityForTargetHelper(context, skimmers, disabledSkimmers);

            PatternMatcher.AnalyzeCommand.AnalyzeTargetHelper(context, applicableSkimmers, disabledSkimmers);
        }
コード例 #9
0
 public IEnumerable <string> Execute(IEnumerable <string> tokens, AnalyzeContext context)
 {
     foreach (var token in tokens)
     {
         yield return(token.ToUpperInvariant());
     }
 }
コード例 #10
0
        private static void GenerateCallGraph(AnalyzeContext ctx, Compilation comp)
        {
            foreach (MethodNode method in ctx.Methods.Values.ToList())
            {
                SemanticModel model = comp.GetSemanticModel(method.Declaration.SyntaxTree);

                IEnumerable <InvocationExpressionSyntax> invocations =
                    method.Declaration.Body.DescendantNodes(
                        sn => !(sn is LambdaExpressionSyntax))
                    .OfType <InvocationExpressionSyntax>();

                foreach (InvocationExpressionSyntax invoc in invocations)
                {
                    IMethodSymbol calledSym = model.GetSymbolInfo(invoc).Symbol as IMethodSymbol;
                    if (calledSym == null)
                    {
                        continue;
                    }

                    if (!ctx.IsAsyncCompatible(calledSym))
                    {
                        continue;
                    }

                    MethodNode called = ctx.AddOrGetNode(calledSym, null);

                    bool isAwaited  = IsAwaited(invoc);
                    bool isReturned = IsReturned(invoc);
                    called.Callers.Add(new Call(method, isAwaited, isReturned));
                    method.Callees.Add(new Call(called, isAwaited, isReturned));
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Gets the <see cref="SemanticModel"/> for the current <paramref name="tree"/> by resolving it through the provided <paramref name="context"/>.
        /// </summary>
        /// <param name="tree">A <see cref="SyntaxTree"/> for which to get the semantic model.</param>
        /// <param name="context">An <see cref="AnalyzeContext"/> tracking information about the analysis.</param>
        /// <returns>Returns the <see cref="SemanticModel"/> for the provided <paramref name="tree"/>.</returns>
        public static SemanticModel GetSemanticModel(this SyntaxTree tree, AnalyzeContext context)
        {
            var project     = context.Projects.Keys.FirstOrDefault(p => p.Documents.Any(d => d.FilePath == tree.FilePath));
            var compilation = context.Projects[project].Value;

            return(compilation.GetSemanticModel(tree));
        }
コード例 #12
0
ファイル: SOSHost.cs プロジェクト: nissims/diagnostics
        /// <summary>
        /// Create an instance of the hosting class
        /// </summary>
        /// <param name="serviceProvider">Service provider</param>
        public SOSHost(IServiceProvider serviceProvider)
        {
            DataTarget dataTarget = serviceProvider.GetService <DataTarget>();

            DataReader       = dataTarget.DataReader;
            _console         = serviceProvider.GetService <IConsoleService>();
            AnalyzeContext   = serviceProvider.GetService <AnalyzeContext>();
            _memoryService   = serviceProvider.GetService <MemoryService>();
            _registerService = serviceProvider.GetService <RegisterService>();
            _versionCache    = new ReadVirtualCache(_memoryService);

            string rid = InstallHelper.GetRid();

            SOSPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), rid);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var debugClient = new DebugClient(this);
                _ccw       = debugClient;
                _interface = debugClient.IDebugClient;
            }
            else
            {
                var lldbServices = new LLDBServices(this);
                _ccw       = lldbServices;
                _interface = lldbServices.ILLDBServices;
            }
        }
コード例 #13
0
        protected override bool AnalyzeCore(Uri uri, string text, string solutionDirectory, SarifLogger sarifLogger, CancellationToken cancellationToken)
        {
            if (!SariferOption.Instance.ShouldAnalyzeSarifFile && uri.GetFilePath().EndsWith(".sarif", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (string.IsNullOrEmpty(solutionDirectory) ||
                (this.currentSolutionDirectory?.Equals(solutionDirectory, StringComparison.OrdinalIgnoreCase) != true))
            {
                // clear older rules
                this.rules?.Clear();
                this.currentSolutionDirectory = solutionDirectory;

                if (this.currentSolutionDirectory != null)
                {
                    this.rules = LoadSearchDefinitionsFiles(this.fileSystem, this.currentSolutionDirectory);
                    Trace.WriteLine($"Rules loaded: {this.rules.Count}");
                }
            }

            if (this.rules == null || this.rules.Count == 0)
            {
                return(false);
            }

            Trace.WriteLine($"Analyzing {uri}...");

            var disabledSkimmers = new HashSet <string>();

            var context = new AnalyzeContext
            {
                TargetUri         = uri,
                FileContents      = text,
                Logger            = sarifLogger,
                DynamicValidation = true, // Enable dynamic validations.
            };

            using (context)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // clear region cache make sure latest text is cached
                FileRegionsCache.Instance.ClearCache();

                // Filtering file before analyzing.
                IEnumerable <Skimmer <AnalyzeContext> > applicableSkimmers = AnalyzeCommand.DetermineApplicabilityForTargetHelper(context, this.rules, disabledSkimmers);

                Trace.WriteLine($"Applicable rules count: {applicableSkimmers.Count()}");

                AnalyzeCommand.AnalyzeTargetHelper(context, applicableSkimmers, disabledSkimmers);
            }

            Trace.WriteLine($"Analyzing {uri} completed.");

            return(true);
        }
コード例 #14
0
		public string ParseStatement(AnalyzeContext context)
		{
			Init();
			/**
             *      ***Navigation
             *      if(concreteQuery.UserQuery != null)
             *     {
             *          {
             *              var naviQuery = concreteQuery.UserQuery;
             *              if(naviQuery.Id != null){
             *                  source = source.Where(t=>t.User.Id == naviQuery.Id);
             *              }
			 *              if(naviQuery.RoleQuery != null){
			 *					var naviQuery_2 = naviQuery.RoleQuery;
			 *					
			 *              }
             *          }
             *      }
             */
			if (context.Depth >= MaxDepth) return "";
			var queryPropertyName = context.QueryProperty.Name;
			var modelPropertyName = context.ModelProperty.Name;
			var naviQueryParam = "naviQuery_" + (context.Depth + 1);
			var builder = new StringBuilder();
			builder.AppendLineFormat("if({0} != null)", context.QueryParamName+"."+queryPropertyName);
			builder.AppendLine("{");
			builder.AppendLineFormat("var {0}={1}.{2};", naviQueryParam, context.QueryParamName, queryPropertyName);
			var naviQueryProperties = context.QueryProperty.PropertyType.GetProperties();
			var naviModelProperties = context.ModelProperty.PropertyType.GetProperties();
			foreach (var naviQueryProperty in naviQueryProperties)
			{
				var naviContext = new AnalyzeContext()
					{
						Depth = context.Depth + 1,
						QueryProperty = naviQueryProperty,
						SourceParamName = context.SourceParamName,
						QueryParamName = naviQueryParam,
						Navigations = context.Navigations.Concat(new[] {context.ModelProperty.Name}).ToArray()
					};
				for (var index = 0; index < Analyzers.Length; index++)
				{
					var naviAnalyzer = Analyzers[index];
					var naviModelProperty = naviAnalyzer.FindAttachedModelProperty(naviQueryProperty, naviModelProperties);
					if (naviModelProperty == null) continue;
					naviContext.ModelProperty = naviModelProperty;
					var naviStatement = naviAnalyzer.ParseStatement(naviContext);
					queues[index].Add(naviStatement);
				}
				
			}
			for (var index = 0; index < Analyzers.Length; index++)
			{
				builder.Append(string.Join("", queues[index]));
			}
			builder.AppendLine("}");
			return builder.ToString();
		}
コード例 #15
0
        private IEnumerable <string> Analyze(string text, AnalyzeContext analyzeContext)
        {
            var tokens = Tokenizer.Tokenize(text);

            foreach (var tokenFilter in TokenFilters)
            {
                tokens = tokenFilter.Execute(tokens, analyzeContext);
            }
            return(tokens);
        }
コード例 #16
0
        public async Task TestRuleExecutorAsync()
        {
            var candles = await ImportIOhlcvDatasAsync();

            var rule = Rule.Create(ic => ic.IsAboveSma(30));
            IReadOnlyList <IOhlcv> validObjects;

            using (var ctx = new AnalyzeContext(candles))
                validObjects = new SimpleRuleExecutor(ctx, rule).Execute();
            Assert.IsTrue(validObjects.Count() == 882);
        }
コード例 #17
0
		public string ParseStatement(AnalyzeContext context)
		{
			var queryPropertyName = context.QueryProperty.Name;
			var modelPropertyName = context.ModelProperty.Name;
			var navigation = new List<string>(context.Navigations) { modelPropertyName };
			var builder = new StringBuilder();
			builder.AppendLineFormat("if({0} != null)", context.QueryParamName + "." + queryPropertyName)
			       .AppendLine("{")
				   .AppendLineFormat("{0}={0}.Where(o=>o.{1}.Contains({2}));", context.SourceParamName, string.Join(".", navigation), context.QueryParamName + "." + queryPropertyName)
			       .AppendLine("}");
			return builder.ToString();
		}
コード例 #18
0
        public static SarifLog Analyze(string filePath, string text, string rulePath)
        {
            if (Skimmers == null)
            {
                IEnumerable <string> regexDefinitions = FileSystem.DirectoryGetFiles(Path.Combine(rulePath, @"..\bin\"), "*.json");

                // Load all rules from JSON. This also automatically loads any validations file that
                // lives alongside the JSON. For a JSON file named PlaintextSecrets.json, the
                // corresponding validations assembly is named PlaintextSecrets.dll (i.e., only the
                // extension name changes from .json to .dll).
                Skimmers = AnalyzeCommand.CreateSkimmersFromDefinitionsFiles(FileSystem, regexDefinitions);
            }

            var sb = new StringBuilder();

            // We should clear every time to prevent colision.
            FileRegionsCache.Instance.ClearCache();

            using (var outputTextWriter = new StringWriter(sb))
                using (var logger = new SarifLogger(
                           outputTextWriter,
                           LogFilePersistenceOptions.PrettyPrint,
                           dataToInsert: OptionallyEmittedData.Hashes | OptionallyEmittedData.RegionSnippets | OptionallyEmittedData.ContextRegionSnippets | OptionallyEmittedData.ComprehensiveRegionProperties,
                           levels: new List <FailureLevel> {
                    FailureLevel.Error, FailureLevel.Warning, FailureLevel.Note, FailureLevel.None
                },
                           kinds: new List <ResultKind> {
                    ResultKind.Fail
                }))
                {
                    // The analysis will disable skimmers that raise an exception. This
                    // hash set stores the disabled skimmers. When a skimmer is disabled,
                    // that catastrophic event is logged as a SARIF notification.
                    var disabledSkimmers = new HashSet <string>();

                    var context = new AnalyzeContext
                    {
                        TargetUri         = new Uri(filePath, UriKind.RelativeOrAbsolute),
                        FileContents      = text,
                        Logger            = logger,
                        DynamicValidation = true,
                    };

                    using (context)
                    {
                        IEnumerable <Skimmer <AnalyzeContext> > applicableSkimmers = AnalyzeCommand.DetermineApplicabilityForTargetHelper(context, Skimmers, disabledSkimmers);
                        AnalyzeCommand.AnalyzeTargetHelper(context, applicableSkimmers, disabledSkimmers);
                    }
                }

            return(JsonConvert.DeserializeObject <SarifLog>(sb.ToString()));
        }
コード例 #19
0
        public async Task TestBullishCrossAlwaysFalseAsync()
        {
            var candles = await ImportIOhlcvDatasAsync();

            var rule = Rule.Create(ic => ic.IsEmaBullishCross(10, 30));
            IReadOnlyList <IOhlcv> validObjects;

            using (var ctx = new AnalyzeContext(candles))
            {
                validObjects = new SimpleRuleExecutor(ctx, rule).Execute();
            }

            Assert.IsTrue(validObjects.Count == 21);
        }
コード例 #20
0
        public IEnumerable <string> Execute(IEnumerable <string> tokens, AnalyzeContext context)
        {
            switch (context)
            {
            case AnalyzeContext.Entity:
                return(tokens.SelectMany(GenerateEdgeNGram));

            case AnalyzeContext.Query:
                return(tokens);

            default:
                throw new ArgumentOutOfRangeException(nameof(context));
            }
        }
コード例 #21
0
        public string ParseStatement(AnalyzeContext context)
        {
            var queryPropertyName = context.QueryProperty.Name;
            var modelPropertyName = context.ModelProperty.Name;
            var navigation        = new List <string>(context.Navigations)
            {
                modelPropertyName
            };
            var builder = new StringBuilder();

            builder.AppendLineFormat("if({0} != null)", context.QueryParamName + "." + queryPropertyName)
            .AppendLine("{")
            .AppendLineFormat("{0}={0}.Where(o=>o.{1}.Contains({2}));", context.SourceParamName, string.Join(".", navigation), context.QueryParamName + "." + queryPropertyName)
            .AppendLine("}");
            return(builder.ToString());
        }
コード例 #22
0
        private static void ClassifyTasks(AnalyzeContext ctx)
        {
            // Pass 1: Mark our assumptions.
            string[] bosslandPrefixes =
            {
                "Buddy.Coroutines.",
                "Styx.CommonBot.Coroutines."
            };

            foreach (
                MethodNode method in ctx.GetByName(name => bosslandPrefixes.Any(name.StartsWith)))
            {
                method.Kind = AsyncMethodKind.Coroutine;
            }

            foreach (MethodNode method in ctx.GetByName(name => name.EndsWith("Coroutine")))
            {
                method.Kind = AsyncMethodKind.Coroutine;
            }

            foreach (MethodNode method in ctx.GetByName(name => name.StartsWith("System.")))
            {
                method.Kind = AsyncMethodKind.ExternalTask;
            }

            foreach (MethodNode method in ctx.GetByName(name => name.EndsWith("Async")))
            {
                method.Kind = AsyncMethodKind.ExternalTask;
            }

            string[] bothKindPrefixes =
            {
                "System.Threading.Tasks.Task.CompletedTask",
                "System.Threading.Tasks.Task.FromResult",
                "System.Func"
            };

            foreach (
                MethodNode method in ctx.GetByName(name => bothKindPrefixes.Any(name.StartsWith)))
            {
                method.Kind = AsyncMethodKind.Both;
            }

            // Pass 2: Classify recursively.
            ctx.FloodClassify(AsyncMethodKind.Coroutine);
            ctx.FloodClassify(AsyncMethodKind.ExternalTask);
        }
コード例 #23
0
ファイル: EqualAnalyzer.cs プロジェクト: tianzhiyuan/agile
		public string ParseStatement(AnalyzeContext context)
		{
			var propertyName = context.QueryProperty.Name;
			//if(Id != null)
			//{
			//	  source = source.Where(o=>o.Id == Id);
			//}
			var navigation = new List<string>(context.Navigations) {propertyName};
			var builder = new StringBuilder();
			builder.AppendLineFormat("if({0}.{1} != null)", context.QueryParamName, propertyName)
			       .AppendLine("{")
			       .AppendLineFormat("{0} = {0}.Where(o=>o.{1} == {2}.{3});", context.SourceParamName,
			                         string.Join(".", navigation),
			                         context.QueryParamName, propertyName)
			       .AppendLine("}");
			return builder.ToString();
		}
コード例 #24
0
ファイル: StadAnalyzer.cs プロジェクト: penspanic/Stad
        private static DataSetModel MakeDataSetModel(AnalyzeContext context, ObjectSerializationInfo info)
        {
            List <StadModel> listModels   = new List <StadModel>();
            List <StadModel> singleModels = new List <StadModel>();

            foreach (MemberSerializationInfo member in info.Members)
            {
                var memberObjectInfo = GetObjectInfo(context.CollectResult, member.Type);
                if (memberObjectInfo == null)
                {
                    throw new Exception($"Member not found, {member.Type}");
                }

                if (memberObjectInfo.Attributes.FirstOrDefault(a =>
                                                               a.Type.Contains(nameof(Stad.Annotation.IgnoreMemberAttribute))) != null)
                {
                    continue;
                }

                StadModel memberModel = MakeStadModel(context, memberObjectInfo);
                if (memberModel == null)
                {
                    throw new Exception($"Member create failed, {memberObjectInfo}");
                }

                if (memberModel.Type.Contains("StadKeyValueCollection") == true)
                {
                    listModels.Add(memberModel);
                }
                else
                {
                    singleModels.Add(memberModel);
                }
            }

            foreach (StadModel model in context.AllModels)
            {
                foreach (MemberDefinition memberDefinition in model.Members)
                {
                    var memberModel = context.AllModels.Find(m => m.Type == memberDefinition.Type);
                    memberDefinition.SetModel(memberModel);
                }
            }

            return(new DataSetModel(info.FullName, new ReadOnlyCollection <StadModel>(listModels), new ReadOnlyCollection <StadModel>(singleModels)));
        }
コード例 #25
0
        public async Task TestGetRuleAsync()
        {
            var candles = await ImportIOhlcvDatasAsync();

            RuleRegistry.Register("isbelowsma30_2", "ic.Get<SimpleMovingAverage>(30)[ic.Index].Tick.IsTrue(t => t > ic.Close)");
            RuleRegistry.Register("isbelowsma30", (ic, p) => ic.Get <SimpleMovingAverage>(p[0])[ic.Index].Tick.IsTrue(t => t > ic.Close));

            using (var ctx = new AnalyzeContext(candles))
            {
                var result  = new SimpleRuleExecutor(ctx, ctx.GetRule("isbelowsma30_2")).Execute();
                var result2 = new SimpleRuleExecutor(ctx, ctx.GetRule("isbelowsma30", 30)).Execute();
                var result3 = new SimpleRuleExecutor(ctx, ic => ic.IsBelowSma(30)).Execute();

                Assert.AreEqual(result.Count(), result3.Count());
                Assert.AreEqual(result2.Count(), result3.Count());
            }
        }
コード例 #26
0
        private static async Task Rules()
        {
            var data = await GetData();

            var rule = Trady.Analysis.Rule.Create(c => c.IsBullish()).And(k => k.IsMacdOscBearish());

            // Use context here for caching indicator results
            using (var ctx = new AnalyzeContext(data))
            {
                var validObjects = new SimpleRuleExecutor(ctx, rule).Execute();

                foreach (var item in validObjects)
                {
                    Console.WriteLine(item.GetPersianDate() + " - " + item.IsBullish());
                }
            }
        }
コード例 #27
0
        private static void FindDeclaredTasks(AnalyzeContext ctx, Compilation comp)
        {
            IEnumerable <MethodDeclarationSyntax> methods =
                comp.SyntaxTrees.SelectMany(
                    st => st.GetRoot().DescendantNodes().OfType <MethodDeclarationSyntax>());

            foreach (MethodDeclarationSyntax method in methods)
            {
                SemanticModel semanticModel = comp.GetSemanticModel(method.SyntaxTree);
                IMethodSymbol sym           = semanticModel.GetDeclaredSymbol(method);
                if (method.Body == null ||
                    !ctx.IsAsyncCompatible(sym))
                {
                    continue;
                }

                ctx.AddOrGetNode(sym, method);
            }
        }
コード例 #28
0
ファイル: TryAnalyzer.cs プロジェクト: mirsaeedi/Codelyn
        public AnalyzeContext AnalyzeTryStatements(TryStatementSyntax tryStatementSyntax)
        {
            var tryContext = new AnalyzeContext(Project, Document);

            var tryStatement = new TryStatement();

            tryContext.Node         = tryStatementSyntax;
            tryContext.TryStatement = tryStatement;

            var(@class, declaration) = GetPlaceOfTryStatement(tryStatementSyntax, tryContext);
            tryContext.Class         = @class;
            tryContext.Declaration   = declaration;

            tryStatement.CatchClauses  = AnalyzeCatchClauses(tryStatementSyntax, tryContext);
            tryStatement.FinallyClause = AnalyzeFinallyClause(tryStatementSyntax, tryContext);

            RuleViolations.AddRange(tryContext.TryStatement.CatchClauses.SelectMany(c => c.RuleViolations));
            AnalyzedContexts.Add(tryContext);

            return(tryContext);
        }
コード例 #29
0
        public string ParseStatement(AnalyzeContext context)
        {
            var propertyName = context.QueryProperty.Name;
            //if(Id != null)
            //{
            //	  source = source.Where(o=>o.Id == Id);
            //}
            var navigation = new List <string>(context.Navigations)
            {
                propertyName
            };
            var builder = new StringBuilder();

            builder.AppendLineFormat("if({0}.{1} != null)", context.QueryParamName, propertyName)
            .AppendLine("{")
            .AppendLineFormat("{0} = {0}.Where(o=>o.{1} == {2}.{3});", context.SourceParamName,
                              string.Join(".", navigation),
                              context.QueryParamName, propertyName)
            .AppendLine("}");
            return(builder.ToString());
        }
コード例 #30
0
        private void OnNodeEnd(StrategyTree tree, AnalyzeContext[] stack, int depth)
        {
            AnalyzeContext context = stack[depth];
            Int64          n       = context.NodeIdx;

            if (context.ChildrenCount == 0)
            {
                LeavesCount++;
                if (tree.Nodes[n].IsPlayerAction(HeroPosition))
                {
                    if (tree.Nodes[n].Probab == 0)
                    {
                        ZaspLeavesCount++;
                    }
                }
            }
            if (context.IsHeroActingWithNonZeroProbab)
            {
                _stats[context.Round].NZaspMovesCount++;
            }
        }
コード例 #31
0
ファイル: EFSyntaxWalker.cs プロジェクト: mirsaeedi/Codelyn
        public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            var context = new AnalyzeContext(_efAnalyzer.Project,
                                             _efAnalyzer.Document);

            _efAnalyzer.AnalyzedContexts.Add(context);

            var detectDbContextUsageInsideMvcControllerAnalyzer =
                new DetectDbContextUsageInsideMvcControllerAnalyzer(_efAnalyzer.DocumentSemanticModel);

            context.RuleViolations.AddRange(detectDbContextUsageInsideMvcControllerAnalyzer.AnalyzeSyntaxNode(node));

            var methodInvocations = node.DescendantNodes()
                                    .Where(n => n.Kind() == SyntaxKind.InvocationExpression)
                                    .OfType <InvocationExpressionSyntax>()
                                    .ToArray();

            foreach (var methodInvocation in methodInvocations)
            {
                var detectSyncronousMethodCalls = new DetectSyncronousMethodCalls(_efAnalyzer
                                                                                  .DocumentSemanticModel);
                context.RuleViolations.AddRange(detectSyncronousMethodCalls.AnalyzeSyntaxNode(methodInvocation));
            }

            var objectCreations = node.DescendantNodes()
                                  .Where(q => q.Kind() == SyntaxKind.ObjectCreationExpression)
                                  .OfType <ObjectCreationExpressionSyntax>()
                                  .ToArray();

            foreach (var objectCreation in objectCreations)
            {
                var detectDbContextCreationWithoutUsingAnalyzer =
                    new DetectDbContextCreationWithoutUsingAnalyzer(_efAnalyzer.DocumentSemanticModel);

                context.RuleViolations.AddRange(detectDbContextCreationWithoutUsingAnalyzer.AnalyzeSyntaxNode(objectCreation));
            }

            base.VisitMethodDeclaration(node);
        }
コード例 #32
0
        public async Task RunAsync(CancellationToken token)
        {
            using var context = await _contextFactory.CreateContext(token);

            await _stateManager.LoadStateAsync(context, token);

            var analzyerContext  = new AnalyzeContext(context);
            var analyzeResultMap = new List <AnalyzeResultDefinition>();

            await foreach (var provider in _providers.ToAsyncEnumerable().WhereAwait(async i => await i.IsApplicableAsync(analzyerContext, token)))
            {
                analyzeResultMap.Add(new()
                {
                    Version         = GetProviderVersion(provider),
                    Name            = provider.Name,
                    InformationUri  = provider.InformationUri,
                    AnalysisResults = provider.AnalyzeAsync(analzyerContext, token),
                });
            }

            await _writer.WriteAsync(analyzeResultMap.ToAsyncEnumerable(), _options.Value.Format, token).ConfigureAwait(false);
        }
コード例 #33
0
        public async Task RunAsync(CancellationToken token)
        {
            using var context = await _contextFactory.CreateContext(token);

            await _stateManager.LoadStateAsync(context, token);

            var analzyerContext  = new AnalyzeContext(context);
            var analyzeResultMap = new List <AnalyzeResultDefinition>();

            await foreach (var provider in _providers.ToAsyncEnumerable().WhereAwait(async i => await i.IsApplicableAsync(analzyerContext, token)))
            {
                analyzeResultMap.Add(new()
                {
                    Version         = GetProviderVersion(provider),
                    Name            = provider.Name,
                    InformationUri  = provider.InformationUri,
                    AnalysisResults = provider.AnalyzeAsync(analzyerContext, token),
                });
            }

            if (_writerProvider.TryGetWriter(_options.Value.Format, out var writer))
            {
                var output = Path.Combine(Directory.GetCurrentDirectory(), $"AnalysisReport.{_options.Value.Format}");

                _logger.LogInformation(LocalizedStrings.WritingOutputMessage, output);

                using var stream = File.Create(output);
                await writer.WriteAsync(analyzeResultMap.ToAsyncEnumerable(), stream, token).ConfigureAwait(false);

                _logger.LogInformation(LocalizedStrings.AnalysisCompleteMessage, output);
            }
            else
            {
                _logger.LogError(LocalizedStrings.RequestedFormatUnavailableMessage, _options.Value.Format);
            }
        }
コード例 #34
0
		public string ParseStatement(AnalyzeContext context)
		{
			var queryPropertyName = context.QueryProperty.Name;
			var modelPropertyName = context.ModelProperty.Name;
			var navigation = new List<string>(context.Navigations) { modelPropertyName };
			var builder = new StringBuilder();
			var modelPropertyType = context.ModelProperty.PropertyType;

			builder.AppendLineFormat("if({0}.{1} != null)", context.QueryParamName, queryPropertyName)
			       .AppendLine("{");
			if (modelPropertyType.IsGenericType)
			{
				builder.AppendLineFormat("{0} = {0}.Where(o=>{3}.{1}.Contains(o.{2}.Value));", context.SourceParamName, queryPropertyName,
				                         string.Join(".", navigation), context.QueryParamName);
			}
			else
			{
				builder.AppendLineFormat("{0} = {0}.Where(o=>{3}.{1}.Contains(o.{2}));", context.SourceParamName, queryPropertyName,
										 string.Join(".", navigation), context.QueryParamName);
			}
			       
			builder.AppendLine("}");
			return builder.ToString();
		}