コード例 #1
0
        /// <summary>
        /// After verifying rules are valid syntax and load; combines into a single .json file
        /// for ease in distribution including this application's defaultset which are
        /// added to the manifest as an embedded resource (see AppInspector.Commands.csproj)
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "PackRules"));
            RulesVerifier verifier = new RulesVerifier(_path);

            if (!verifier.Verify())//throws anyway
            {
                return((int)ExitCode.CriticalError);
            }

            List <Rule> list = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.Formatting = (_indent) ? Formatting.Indented : Formatting.None;

            using (FileStream fs = File.Open(_outputfile, FileMode.Create, FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(JsonConvert.SerializeObject(list, settings));
                sw.Close();
                fs.Close();
            }

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "PackRules"));
            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _outputfile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);

            return((int)ExitCode.NoIssues);
        }
コード例 #2
0
 void ConfigRules()
 {
     if (string.IsNullOrEmpty(_arg_customRulesPath))
     {
         throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
     }
 }
コード例 #3
0
        public static Writer GetWriter(string writerName, string defaultWritter, string format = null)
        {
            if (string.IsNullOrEmpty(writerName))
            {
                writerName = defaultWritter;
            }

            if (string.IsNullOrEmpty(writerName))
            {
                writerName = "text";
            }

            switch (writerName.ToLowerInvariant())
            {
            case "_dummy":
                return(new DummyWriter());

            case "json":
                return(new JsonWriter());

            case "text":
                return(new SimpleTextWriter(format));

            case "html":
                return(new LiquidWriter());

            default:
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-f")));
            }
        }
コード例 #4
0
        public void FlushAll()
        {
            if (_outputWriter != null)
            {
                _outputWriter.WriteApp(_appProfile);

                if (_outputWriter.TextWriter != null && _arg_fileFormat != "html")
                {
                    _outputWriter.FlushAndClose();//not required for html formal i.e. multiple files already closed
                    _outputWriter = null;

                    //Special case to avoid writing tmp file path to output file for TagTest,TagDiff or when called as a DLL since unnecessary
                    if (_arg_consoleVerbosityLevel.ToLower() != "none")
                    {
                        if (!String.IsNullOrEmpty(_arg_outputFile))
                        {
                            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);
                        }
                        else
                        {
                            WriteOnce.NewLine();
                        }
                    }
                }
            }
        }
コード例 #5
0
        public void ConfigureRules()
        {
            List <string> rulePaths = new List <string>();

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                rulePaths.Add(_arg_customRulesPath);
            }

            foreach (string rulePath in rulePaths)
            {
                if (Directory.Exists(rulePath))
                {
                    _rulesSet.AddDirectory(rulePath);
                }
                else if (File.Exists(rulePath))
                {
                    _rulesSet.AddFile(rulePath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rulesSet.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
コード例 #6
0
        /// <summary>
        /// Simple validation on source path provided for scanning and preparation
        /// </summary>
        void ConfigSourcetoScan()
        {
            WriteOnce.SafeLog("AnalyzeCommand::ConfigSourcetoScan", LogLevel.Trace);

            if (Directory.Exists(_arg_sourcePath))
            {
                try
                {
                    _srcfileList = Directory.EnumerateFiles(_arg_sourcePath, "*.*", SearchOption.AllDirectories);
                    if (_srcfileList.Count() == 0)
                    {
                        throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, _arg_sourcePath));
                    }
                }
                catch (Exception)
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, _arg_sourcePath));
                }
            }
            else if (File.Exists(_arg_sourcePath)) //not a directory but make one for single flow
            {
                _srcfileList = new List <string>()
                {
                    _arg_sourcePath
                }
            }
            ;
            else
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, _arg_sourcePath));
            }
        }
コード例 #7
0
        void ConfigRules()
        {
            if (!_arg_ignoreDefaultRules)
            {
                _rules = Utils.GetDefaultRuleSet(_arg_logger);
            }

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                if (_rules == null)
                {
                    _rules = new RuleSet(_arg_logger);
                }

                if (Directory.Exists(_arg_customRulesPath))
                {
                    _rules.AddDirectory(_arg_customRulesPath);
                }
                else if (File.Exists(_arg_customRulesPath))
                {
                    _rules.AddFile(_arg_customRulesPath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, _arg_customRulesPath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rules == null || _rules.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
コード例 #8
0
        /// Compares a set of rules against a source path...
        /// Used for both RulesPresent and RulesNotePresent options
        /// Focus is pass/fail not detailed comparison output -see Tagdiff for more
        public TagTestCommand(TagTestCommandOptions opt)
        {
            _arg_srcPath               = opt.SourcePath;
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            opt.TestType ??= "RulesPresent";
            _arg_logger = opt.Log;

            WriteOnce.ConsoleVerbosity verbosity = WriteOnce.ConsoleVerbosity.Medium;
            if (!Enum.TryParse(_arg_consoleVerbosityLevel, true, out verbosity))
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
            }
            WriteOnce.Verbosity = verbosity;

            if (!Enum.TryParse(opt.TestType, true, out _arg_tagTestType))
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, opt.TestType));
            }

            _arg_ignoreDefaultRules = opt.IgnoreDefaultRules;
            _rulesSet = new RuleSet(_arg_logger);

            if (string.IsNullOrEmpty(opt.CustomRulesPath) && _arg_ignoreDefaultRules)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }

            ConfigureRules();
            ConfigureOutput();
        }
コード例 #9
0
 /// <summary>
 /// Expects user to supply all that apply
 /// </summary>
 void ConfigConfidenceFilters()
 {
     WriteOnce.SafeLog("AnalyzeCommand::ConfigConfidenceFilters", LogLevel.Trace);
     //parse and verify confidence values
     if (String.IsNullOrEmpty(_arg_confidenceFilters))
     {
         _arg_confidence = Confidence.High | Confidence.Medium; //excludes low by default
     }
     else
     {
         string[] confidences = _arg_confidenceFilters.Split(',');
         foreach (string confidence in confidences)
         {
             Confidence single;
             if (Enum.TryParse(confidence, true, out single))
             {
                 _arg_confidence |= single;
             }
             else
             {
                 throw new Exception(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "x"));
             }
         }
     }
 }
コード例 #10
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            bool issues = false;

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Verify Rules"));

            RulesVerifier verifier = new RulesVerifier(_arg_customRulesPath);

            if (!verifier.Verify())
            {
                return((int)ExitCode.NotVerified);
            }

            RuleSet rules = verifier.CompiledRuleset;

            //report each add
            foreach (Rule rule in rules)
            {
                WriteOnce.Result(string.Format("Rule {0}-{1} verified", rule.Id, rule.Name), true, WriteOnce.ConsoleVerbosity.High);
            }

            WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Verify Rules"));

            WriteOnce.FlushAll();
            if (!String.IsNullOrEmpty(_arg_outputFile))
            {
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
            }

            return(issues ? (int)ExitCode.NotVerified : (int)ExitCode.Verified);
        }
コード例 #11
0
        public TagDiffCommand(TagDiffCommandOptions opt)
        {
            _arg_src1                  = opt.SourcePath1;
            _arg_src2                  = opt.SourcePath2;
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";

            _arg_ignoreDefault = opt.IgnoreDefaultRules;
            opt.TestType ??= "equality";
            _arg_outputFile = opt.OutputFilePath;
            _arg_logger     = opt.Log;


            WriteOnce.ConsoleVerbosity verbosity = WriteOnce.ConsoleVerbosity.Medium;
            if (!Enum.TryParse(_arg_consoleVerbosityLevel, true, out verbosity))
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
            }
            WriteOnce.Verbosity = verbosity;

            if (!Enum.TryParse(opt.TestType, true, out _arg_tagTestType))
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, opt.TestType));
            }
        }
コード例 #12
0
 void ConfigureCompareType()
 {
     if (!Enum.TryParse(_arg_test_type_raw, true, out _arg_tagTestType))
     {
         WriteOnce.Error((ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, _arg_test_type_raw)));
         throw new Exception(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, _arg_test_type_raw));
     }
 }
コード例 #13
0
        void ConfigFileOutput()
        {
            WriteOnce.SafeLog("PackRulesCommand::ConfigOutput", LogLevel.Trace);

            if (string.IsNullOrEmpty(_arg_outputfile))
            {
                throw new Exception(ErrMsg.FormatString(ErrMsg.ID.PACK_MISSING_OUTPUT_ARG));
            }
        }
コード例 #14
0
        void UnZipAndProcess(string filename, ArchiveFileType archiveFileType)
        {
            // zip itself may be in excluded list i.e. sample, test or similar unless ignore filter requested
            if (_fileExclusionList != null && _fileExclusionList.Any(v => filename.ToLower().Contains(v)))
            {
                WriteOnce.SafeLog(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_EXCLUDED_TYPE_SKIPPED, filename), LogLevel.Warn);
                _appProfile.MetaData.FilesSkipped++;
                return;
            }

            //zip itself may be too huge for timely processing
            if (new FileInfo(filename).Length > WARN_ZIP_FILE_SIZE)
            {
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_FILESIZE_WARN));
            }
            else
            {
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_PROCESSING));
            }

            LastUpdated = File.GetLastWriteTime(filename);
            _appProfile.MetaData.PackageTypes.Add(ErrMsg.GetString(ErrMsg.ID.ANALYZE_COMPRESSED_FILETYPE));

            try
            {
                IEnumerable <FileEntry> files = Extractor.ExtractFile(filename);

                if (files.Count() > 0)
                {
                    _appProfile.MetaData.TotalFiles += files.Count();//additive in case additional child zip files processed

                    foreach (FileEntry file in files)
                    {
                        //check uncompressed file passes standard checks
                        LanguageInfo languageInfo = new LanguageInfo();
                        if (FileChecksPassed(file.FullPath, ref languageInfo, file.Content.Length))
                        {
                            byte[] streamByteArray = file.Content.ToArray();
                            ProcessInMemory(file.FullPath, Encoding.UTF8.GetString(streamByteArray, 0, streamByteArray.Length), languageInfo);
                        }
                    }
                }
                else
                {
                    WriteOnce.SafeLog(string.Format("Decompression found no files in {0}", filename), LogLevel.Warn);//zero results can be valid
                }
            }
            catch (Exception)
            {
                string errmsg = ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_ERROR, filename);
                WriteOnce.Error(errmsg);
                throw;
            }
        }
コード例 #15
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("VerifyRulesCommand::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "verifyrules"));

            ExitCode exitCode = ExitCode.CriticalError;

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path);
                verifier.Verify();
                exitCode = ExitCode.Verified;

                RuleSet rules = verifier.CompiledRuleset;

                //report each add to console if desired
                foreach (Rule rule in rules)
                {
                    WriteOnce.Result(string.Format("Rule {0}-{1} verified", rule.Id, rule.Name), true, WriteOnce.ConsoleVerbosity.High);
                }

                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "verifyrules"));
                if (!String.IsNullOrEmpty(_arg_outputFile) && Utils.CLIExecutionContext)
                {
                    WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
                }
                WriteOnce.FlushAll();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)exitCode);
        }
コード例 #16
0
        void ConfigSourceToScan()
        {
            WriteOnce.SafeLog("TagDiff::ConfigRules", LogLevel.Trace);

            if (_arg_src1 == _arg_src2)
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.TAGDIFF_SAME_FILE_ARG));
            }
            else if (string.IsNullOrEmpty(_arg_src1) || string.IsNullOrEmpty(_arg_src2))
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.CMD_INVALID_ARG_VALUE));
            }
        }
コード例 #17
0
        public static Logger SetupLogging(AllCommandOptions opts)
        {
            var config = new NLog.Config.LoggingConfiguration();

            if (String.IsNullOrEmpty(opts.LogFilePath))
            {
                opts.LogFilePath = Utils.GetPath(Utils.AppPath.defaultLog);
                //if using default app log path clean up previous for convenience in reading
                if (File.Exists(opts.LogFilePath))
                {
                    File.Delete(opts.LogFilePath);
                }
            }

            LogLevel log_level = LogLevel.Error;//default

            if (String.IsNullOrEmpty(opts.LogFileLevel))
            {
                opts.LogFileLevel = "Error";
            }

            try
            {
                log_level = LogLevel.FromString(opts.LogFileLevel);
            }
            catch (Exception)
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-v")));
            }

            using (var fileTarget = new FileTarget()
            {
                Name = "LogFile",
                FileName = opts.LogFilePath,
                Layout = @"${date:universalTime=true:format=s} ${threadid} ${level:uppercase=true} - ${message}",
                ForceMutexConcurrentWrites = true
            })
            {
                config.AddTarget(fileTarget);
                config.LoggingRules.Add(new LoggingRule("CST.ApplicationInspector", log_level, fileTarget));
            }

            LogFilePath = opts.LogFilePath;//preserve for console path msg

            LogManager.Configuration = config;
            Logger logger = LogManager.GetLogger("CST.ApplicationInspector");

            logger.Info("[" + DateTime.Now.ToLocalTime() + "] //////////////////////////////////////////////////////////");

            return(logger);
        }
コード例 #18
0
        /// <summary>
        /// After verifying rules are valid syntax and load; combines into a single .json file
        /// for ease in distribution including this application's defaultset which are
        /// added to the manifest as an embedded resource (see AppInspector.Commands.csproj)
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "packrules"));

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path);
                verifier.Verify();

                List <Rule> list = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.Formatting = (_arg_indent) ? Formatting.Indented : Formatting.None;

                using (FileStream fs = File.Open(_arg_outputfile, FileMode.Create, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(JsonConvert.SerializeObject(list, settings));
                    sw.Close();
                    fs.Close();
                }

                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "packrules"));
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputfile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);
                WriteOnce.FlushAll();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)ExitCode.NoIssues);
        }
コード例 #19
0
        void ConfigRules()
        {
            WriteOnce.SafeLog("PackRulesCommand::ConfigRules", LogLevel.Trace);

            if (_arg_repack_default_rules && !Utils.CLIExecutionContext)
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_NO_CLI_DEFAULT));
            }

            if (!_arg_repack_default_rules && string.IsNullOrEmpty(_arg_custom_rules_path))
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
コード例 #20
0
        /// <summary>
        /// Wrapper for files that are on disk and ready to read vs unzipped files which are not to allow separation of core
        /// scan evaluation for use by decompression methods as well
        /// </summary>
        /// <param name="filename"></param>
        void ProcessAsFile(string filename)
        {
            //check for supported language
            LanguageInfo languageInfo = new LanguageInfo();

            if (FileChecksPassed(filename, ref languageInfo))
            {
                LastUpdated = File.GetLastWriteTime(filename);
                _appProfile.MetaData.PackageTypes.Add(ErrMsg.GetString(ErrMsg.ID.ANALYZE_UNCOMPRESSED_FILETYPE));

                string fileText = File.ReadAllText(filename);
                ProcessInMemory(filename, fileText, languageInfo);
            }
        }
コード例 #21
0
 public void Verify()
 {
     if (Directory.Exists(_rulesPath))
     {
         LoadDirectory(_rulesPath);
     }
     else if (File.Exists(_rulesPath))
     {
         LoadFile(_rulesPath);
     }
     else
     {
         throw new Exception(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, _rulesPath));
     }
 }
コード例 #22
0
        public VerifyRulesCommand(VerifyRulesCommandOptions opt)
        {
            _arg_customRulesPath    = opt.CustomRulesPath;
            _arg_ignoreDefaultRules = opt.IgnoreDefaultRules;
            _arg_outputFile         = opt.OutputFilePath;
            _arg_logger             = opt.Log;

            if (!Enum.TryParse(opt.ConsoleVerbosityLevel, true, out _arg_consoleVerbosityLevel))
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
            }
            WriteOnce.Verbosity = _arg_consoleVerbosityLevel;
            ConfigureOutput();
            ConfigRules();
        }
コード例 #23
0
        void ConfigRules()
        {
            _rulePaths = new List <string>();

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                _rulePaths.Add(_arg_customRulesPath);
            }

            if (_rulePaths.Count == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }

            //validation of paths is delayed for Run in this cmd
        }
コード例 #24
0
        public VerifyRulesCommand(VerifyRulesCommandOptions opt)
        {
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_logger = opt.Log;

            WriteOnce.ConsoleVerbosity verbosity = WriteOnce.ConsoleVerbosity.Medium;
            if (!Enum.TryParse(_arg_consoleVerbosityLevel, true, out verbosity))
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
            }
            WriteOnce.Verbosity = verbosity;

            ConfigOutput();
            ConfigRules();
        }
コード例 #25
0
 public static void OpenBrowser(string url)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         try
         {
             Process.Start(new ProcessStartInfo("cmd", $"/c start {url}"));
             WriteOnce.General(ErrMsg.GetString(ErrMsg.ID.BROWSER_START_SUCCESS));
         }
         catch (Exception)
         {
             WriteOnce.General(ErrMsg.GetString(ErrMsg.ID.BROWSER_START_FAIL));
         }
     }
     else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
     {
         if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BROWSER")))
         {
             try
             {
                 Process.Start("xdg-open", "\"" + url + "\"");
                 WriteOnce.General(ErrMsg.GetString(ErrMsg.ID.BROWSER_START_SUCCESS));
             }
             catch (Exception)
             {
                 WriteOnce.SafeLog("Unable to open browser using BROWSER environment var", NLog.LogLevel.Error);
             }
         }
         else
         {
             WriteOnce.General(ErrMsg.GetString(ErrMsg.ID.BROWSER_ENVIRONMENT_VAR));
         }
     }
     else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
     {
         try
         {
             Process.Start("open", "\"" + url + "\"");
             WriteOnce.General(ErrMsg.GetString(ErrMsg.ID.BROWSER_START_SUCCESS));
         }
         catch (Exception)
         {
             WriteOnce.General(ErrMsg.GetString(ErrMsg.ID.BROWSER_START_FAIL));
         }
     }
 }
コード例 #26
0
        private void LoadFile(string file)
        {
            RuleSet rules = new RuleSet();

            try
            {
                rules.AddFile(file, null);
            }
            catch (Exception e)
            {
                Debug.Write(e.Message);//Ensure console message indicates problem for Build process
                WriteOnce.SafeLog(e.Message, NLog.LogLevel.Error);
                throw new Exception(ErrMsg.FormatString(ErrMsg.ID.VERIFY_RULE_FAILED, file));
            }

            _rules.AddRange(rules.AsEnumerable());
        }
コード例 #27
0
        List <string> _fileExclusionList;//see exclusion list


        public AnalyzeCommand(AnalyzeCommandOptions opt)
        {
            _arg_sourcePath            = opt.SourcePath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_fileFormat            = opt.OutputFileFormat;
            _arg_outputTextFormat      = opt.TextOutputFormat;
            _arg_outputUniqueTagsOnly  = !opt.AllowDupTags;
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_confidenceFilters     = opt.ConfidenceFilters ?? "high,medium";
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_autoBrowserOpen       = !opt.AutoBrowserOpen;
            _arg_ignoreDefaultRules    = opt.IgnoreDefaultRules;
            _arg_simpleTagsOnly        = opt.SimpleTagsOnly;
            _arg_logger = opt.Log;

            //if not called via CLI set default
            opt.FilePathExclusions = opt.FilePathExclusions ?? "sample,example,test,docs,.vs,.git";

            if (!string.IsNullOrEmpty(opt.FilePathExclusions))
            {
                _fileExclusionList = opt.FilePathExclusions.ToLower().Split(",").ToList <string>();
                if (_fileExclusionList != null && (_fileExclusionList.Contains("none") || _fileExclusionList.Contains("None")))
                {
                    _fileExclusionList.Clear();
                }
            }

            WriteOnce.ConsoleVerbosity verbosity = WriteOnce.ConsoleVerbosity.Medium;
            if (!Enum.TryParse(_arg_consoleVerbosityLevel, true, out verbosity))
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
            }
            WriteOnce.Verbosity = verbosity;


            LastUpdated = DateTime.MinValue;
            DateScanned = DateTime.Now;

            ConfigOutput();
            ConfigSourcetoScan();
            ConfigConfidenceFilters();
            ConfigRules();

            _uniqueTagsControl = new HashSet <string>();
        }
コード例 #28
0
        public bool Verify()
        {
            bool isCompiled = true;

            if (Directory.Exists(_rulesPath))
            {
                isCompiled = LoadDirectory(_rulesPath);
            }
            else if (File.Exists(_rulesPath))
            {
                isCompiled = LoadFile(_rulesPath);
            }
            else
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, _rulesPath));
            }

            return(isCompiled);
        }
コード例 #29
0
        public ExportTagsCommand(ExportTagsCommandOptions opt)
        {
            _rules = new RuleSet(WriteOnce.Log);
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_ignoreDefaultRules    = opt.IgnoreDefaultRules;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_logger = opt.Log;

            WriteOnce.ConsoleVerbosity verbosity = WriteOnce.ConsoleVerbosity.Medium;
            if (!Enum.TryParse(_arg_consoleVerbosityLevel, true, out verbosity))
            {
                throw new OpException(String.Format(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "-x")));
            }
            WriteOnce.Verbosity = verbosity;

            ConfigureOutput();
            ConfigRules();
        }
コード例 #30
0
        void ConfigRules()
        {
            List <string> rulePaths = new List <string>();

            if (!_arg_ignoreDefaultRules)
            {
                Assembly assembly     = Assembly.GetExecutingAssembly();
                string[] resourceName = assembly.GetManifestResourceNames();
                string   filePath     = "Microsoft.ApplicationInspector.Commands.defaultRules.json";
                Stream   resource     = assembly.GetManifestResourceStream(filePath);
                using (StreamReader file = new StreamReader(resource))
                {
                    _rules.AddString(file.ReadToEnd(), filePath, null);
                }
            }

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                rulePaths.Add(_arg_customRulesPath);
            }

            foreach (string rulePath in rulePaths)
            {
                if (Directory.Exists(rulePath))
                {
                    _rules.AddDirectory(rulePath);
                }
                else if (File.Exists(rulePath))
                {
                    _rules.AddFile(rulePath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rules.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }