/// <summary> /// 读取指标与分类的关联关系 /// </summary> /// <returns></returns> private List <IndexAssocationEntity> ReadAssocation() { List <IndexAssocationEntity> data = new List <IndexAssocationEntity>(); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/关联关系.xlsx"); if (!File.Exists(path)) { WriteMsg?.Invoke("未找到“指标分类.xlsx文件”,请检查文件在不在程序根目录下"); WriteMsg?.Invoke("==用navicat执行下面sql语句导出Excel文件放到根目录下的Content/指标 里面=="); WriteMsg?.Invoke(@"select b.NATURE,a.* from base_indexassociation a inner join base_department b on a.deptid=b.DEPARTMENTID "); WriteMsg?.Invoke("===========附件名称:关联关系.xlsx============="); throw new ArgumentNullException("未找到附件"); } var book = new Workbook(path); var sheet = book.Worksheets[0]; for (int i = 1; i <= sheet.Cells.MaxDataRow; i++) { IndexAssocationEntity indexEntity = new IndexAssocationEntity() { Nature = sheet.Cells[i, 0].StringValue.Trim(), Id = sheet.Cells[i, 1].StringValue.Trim(), TitleId = sheet.Cells[i, 2].StringValue.Trim(), DataSetId = sheet.Cells[i, 3].StringValue.Trim(), DeptId = sheet.Cells[i, 4].StringValue.Trim(), }; data.Add(indexEntity); } return(data); }
/// <summary> /// Saving LIM file to the targeted path. /// </summary> /// <param name="intput">Input file with full path</param> /// <param name="output">Output file path</param> /// <param name="limName">Output LIM file name</param> public static void SaveLimASG(string intput, string output, string limName) { if (MainDeclaration.Instance.DumpLimml) { SaveLimML(intput, output, limName); } List <IHeaderData> headers = new List <IHeaderData>(); headers.Add(MainDeclaration.Instance.LimOrigin); headers.Add(MainDeclaration.Instance.OverrideRelations); WriteMsg.WriteLine("LIM saving..."); //Save LIM MainDeclaration.Instance.LimFactory.save( output + ((limName != string.Empty) ? Path.GetFileName(limName) : Path.GetFileNameWithoutExtension(intput)) + Constants.LIMEXTENSION, headers); //Save Filtered LIM MainDeclaration.Instance.LimFactory.saveFilter( output + ((limName != string.Empty) ? Path.GetFileName(limName) : Path.GetFileNameWithoutExtension(intput)) + Constants.FILTEREDLIMEXTENSION); WriteMsg.WriteLine("LIM saved"); }
public Filter(string path) { Lines = new List <FilterLine>(); StreamReader file = null; try { file = new StreamReader(path); string line; while ((line = file.ReadLine()) != null) { if (line[0] == '-' || line[0] == '+') { Lines.Add(ProcessLine(line)); } } } catch (FileNotFoundException) { WriteMsg.WriteWithBreak("Warning: filter file \"{0}\" not found!", WriteMsg.MsgLevel.Warning, 0, path); } finally { file?.Dispose(); } Lines.Reverse(); //we will check from the last line, and the first match determines if the file is needed or not }
public static void SendMsg_MSG_LOGIN(TcpHandle tcp) { WriteMsg msg = new WriteMsg((UInt16)MsgIds.MSG_LOGIN); msg.WriteString(tcp.gameState.Account); msg.WriteString(tcp.gameState.LoginKey); tcp.Send(msg); }
public static void SendMsg_MSG_CHAT(TcpHandle client, string info) { WriteMsg msg = new WriteMsg((UInt16)MsgIds.MSG_CHAT); msg.WriteUInt16(1); msg.WriteString(info); client.Send(msg); }
/// <summary> /// 开始初始化数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Btn_Begin_Click(object sender, EventArgs e) { if (_dbmodel == null && _repository == null) { WriteMsg?.Invoke("未选择目标数据库,请在主界面选择要初始化的数据库"); return; } WriteMsg?.Invoke("开始备份数据"); List <TerminalDataSetEntity> terminalDataSetEntities = _repository.GetList <TerminalDataSetEntity>("select * from base_terminaldataset").Result.ToList(); WriteMsg?.Invoke("base_terminaldataset数据读取完毕"); List <IndexManageEntity> indexManageEntities = _repository.GetList <IndexManageEntity>("select * from base_indexmanage").Result.ToList(); WriteMsg?.Invoke("base_indexmanage数据读取完毕"); List <IndexAssocationEntity> assocationEntities = _repository.GetList <IndexAssocationEntity>("select * from base_indexassociation").Result.ToList(); WriteMsg?.Invoke("base_indexassociation数据读取完毕"); if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/备份"))) { Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/备份")); } File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/备份/基础指标数据.txt"), JsonConvert.SerializeObject(terminalDataSetEntities)); WriteMsg?.Invoke("base_terminaldataset数据备份完毕"); File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/备份/标题配置.txt"), JsonConvert.SerializeObject(indexManageEntities)); WriteMsg?.Invoke("base_indexmanage数据备份完毕"); File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/备份/关联关系.txt"), JsonConvert.SerializeObject(assocationEntities)); WriteMsg?.Invoke("base_indexassociation数据备份完毕"); WriteMsg?.Invoke("开始删除目标服务器里的数据"); }
/// <summary> /// 开始读取数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_read_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txt_ConStr.Text.Trim())) { WriteMsg?.Invoke("数据库链接字符串不能为空"); } else { try { IRepository repository = new MysqlRepository(txt_ConStr.Text.Trim()); List <TerminalDataSetEntity> terminalDataSetEntities = repository.GetList <TerminalDataSetEntity>("select * from base_terminaldataset").Result.ToList(); List <IndexManageEntity> indexManageEntities = repository.GetList <IndexManageEntity>("select * from base_indexmanage").Result.ToList(); List <IndexAssocationEntity> assocationEntities = repository.GetList <IndexAssocationEntity>("select * from base_indexassociation").Result.ToList(); File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/基础指标数据.txt"), JsonConvert.SerializeObject(terminalDataSetEntities)); File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/标题配置.txt"), JsonConvert.SerializeObject(indexManageEntities)); File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/关联关系.txt"), JsonConvert.SerializeObject(assocationEntities)); WriteMsg?.Invoke("数据读取并存储完毕"); } catch (Exception ex) { WriteMsg?.Invoke(ex.Message); } } }
/// <summary> /// Building main entry point. /// </summary> /// <param name="abstractOpen"></param> /// <param name="output"></param> /// <param name="fxCopPath">FxCopCmd.exe path</param> /// <param name="fXCopOut">FxCop result directory</param> /// <param name="row">CSV file second row</param> public static void Start(AbstractOpen abstractOpen, string output, string fxCopPath, string fXCopOut, string outListFilePath) { WriteMsg.WriteLine("Starting analysis..."); MainDeclaration.Instance.CSSIExtension = (abstractOpen is FileOpen) ? Constants.CSSIEXTENSION : Constants.LCSSIEXTENSION; MainDeclaration.Instance.Solution = abstractOpen.Solution; foreach (Project project in abstractOpen.TopologicallySortedProjectDependencies) { if (Commons.Common.CheckOuterFilters(project.FilePath)) { continue; } WriteMsg.WriteWithBreak("Analyzing {0}...", WriteMsg.MsgLevel.Normal, 4, project.AssemblyName); Analyse(project, output, fxCopPath, fXCopOut); } MainDeclaration.Instance.Statistics[0].CSharpASGBuildingTime = MainDeclaration.Instance.CSSIWatch.ElapsedSeconds; MainDeclaration.Instance.Statistics[0].LIMASGBildingTime = MainDeclaration.Instance.LIMWatch.ElapsedSeconds; LineMetrics.Calculate(); WriteMsg.WriteLine("Analysis finished"); if (!string.IsNullOrEmpty(outListFilePath)) { File.WriteAllText(outListFilePath, string.Join(Environment.NewLine, outfiles)); } MainDeclaration.Instance.FxCopTasks.WaitAll(); }
/// <summary> /// 获取数据库选择窗体的数据库信息 /// </summary> /// <param name="db"></param> private void GetDbInfo(DBModel db, IRepository repository) { _dbmodel = db; _dbmodel.BuidConStr(); txt_checkDB.Text = _dbmodel.ConnStr; _repository = repository; WriteMsg?.Invoke("数据库选择完毕"); }
/// <summary> /// Write some statistics to the console and csv row. /// </summary> private static void WriteStatistics(Stopwatch stopwatch, long peakMemory) { WriteMsg.WriteLine("Statistics:"); WriteMsg.WriteLine(); WriteMsg.WriteLine(" Elapsed time: {0}", WriteMsg.MsgLevel.Normal, stopwatch.Elapsed); WriteMsg.WriteLine(" Used memory: {0} Mb", WriteMsg.MsgLevel.Normal, peakMemory / 1048576f); // 1024 * 1024 MainDeclaration.Instance.Statistics[0].AnalyzeTime = stopwatch.ElapsedSeconds; MainDeclaration.Instance.Statistics[0].PeakMemory = peakMemory / 1048576f; }
private static bool ppHelp(Option o, string[] args) { WriteMsg.WriteWithBreak("Usage:", WriteMsg.MsgLevel.Silent, 2); WriteMsg.WriteWithBreak("", WriteMsg.MsgLevel.Silent); WriteMsg.WriteWithBreak("CSAN [options] -input:(file.cs|file.csproj|file.sln) -output:folder", WriteMsg.MsgLevel.Silent, 4); WriteMsg.WriteWithBreak("", WriteMsg.MsgLevel.Silent); Arguments.WriteHelp(OPTIONS_OBJ, o.Internal); //if called from -helpi, then this property will be true, so internals will be written out as well Environment.Exit(1); return(true); }
/// <summary> /// Processes the \Q and \E anchors in regular expressions /// </summary> private static string ProcessEscapingAnchors(string regex) { if (string.IsNullOrEmpty(regex)) { return(regex); } var sb = new StringBuilder(); int i = 0, j = 0; bool open = false; for (; i < regex.Length - 1; i++) { if (!open && regex.Substring(i, 2) == "\\Q") //i a \-re mutat { open = true; if (i != 0) { sb.Append(regex.Substring(j, i - j)); } i++; //i a Q-ra mutat, majd a ciklus végén lépteti egyel a for j = i + 1; //emiatt, a j-t i+1re állítjuk } else if (regex.Substring(i, 2) == "\\E") { if (!open) { WriteMsg.WriteWithBreak("Warning: \\E anchor found without opening \\Q in one of the filter files. Ignoring it.", WriteMsg.MsgLevel.Warning); } else { open = false; sb.Append(Regex.Escape(regex.Substring(j, i - j))); i++; j = i + 1; } } } if (i != j) { if (open) { sb.Append(Regex.Escape(regex.Substring(j, i - j + 1))); } else { sb.Append(regex.Substring(j, i - j + 1)); } } return(sb.ToString()); }
/// <summary> /// Sets the Identifier's declaration /// </summary> /// <param name="node">A VariableDeclaration, Parameter, ForeachStatement, CatchDeclaration, MethodDeclaration and DelegateDeclaration</param> /// <param name="reference">The Identifier</param> public void DeclarationFiller(ROSLYNCS.CSharpSyntaxNode node, ROSLYNCS.Syntax.IdentifierNameSyntax reference) { if (reference != null) { if (node.Kind() != ROSLYNCS.SyntaxKind.VariableDeclarator && node.Kind() != ROSLYNCS.SyntaxKind.Parameter && node.Kind() != ROSLYNCS.SyntaxKind.ForEachStatement && node.Kind() != ROSLYNCS.SyntaxKind.CatchDeclaration && node.Kind() != ROSLYNCS.SyntaxKind.MethodDeclaration && node.Kind() != ROSLYNCS.SyntaxKind.DelegateDeclaration) { WriteMsg.WriteLine("Warning: Invalid node kind ({0}) given to CrossEdGeFiller.DeclarationFiller()", WriteMsg.MsgLevel.Warning, node.Kind()); return; } var declaration = GetOrCreateNode <CSHARP.Nodes.Base.Positioned>(node); GetOrCreateNode <CSHARP.Nodes.Expression.IdentifierNameSyntax>(reference).setDeclaration(declaration); } }
/// <summary> /// Checks FxCopPath and tries to find FxCop if not specified /// </summary> private static bool CheckFxCopPath() { if (string.IsNullOrEmpty(FXCOPPATH) && RUNFXCOP) { WriteMsg.WriteWithBreak("No FxCopPath specified, looking for it in installed Visual Studio directories..."); string relativePath = @"Team Tools\Static Analysis Tools\FxCop\"; string vsCommonTools = Environment.GetEnvironmentVariable("VS140COMNTOOLS"); string version = "2015"; if (string.IsNullOrEmpty(vsCommonTools)) { vsCommonTools = Environment.GetEnvironmentVariable("VS120COMNTOOLS"); version = "2013"; if (string.IsNullOrEmpty(vsCommonTools)) { vsCommonTools = Environment.GetEnvironmentVariable("VS100COMNTOOLS"); version = "2010"; } } if (!string.IsNullOrEmpty(vsCommonTools)) { FXCOPPATH = Path.GetFullPath(vsCommonTools + ".." + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + relativePath); if (File.Exists(FXCOPPATH + "FxCopCmd.exe")) { WriteMsg.WriteWithBreak("Found Visual Studio " + version); WriteMsg.WriteWithBreak("FxCop static analysis tool will be used from: " + FXCOPPATH); } else { FXCOPPATH = null; WriteMsg.WriteWithBreak("Could not find FxCop on your computer. FxCop analysis will be skipped.", WriteMsg.MsgLevel.Warning); } } else { WriteMsg.WriteWithBreak("Could not find FxCop on your computer. FxCop analysis will be skipped.", WriteMsg.MsgLevel.Warning); } } else if (RUNFXCOP && !File.Exists(FXCOPPATH.EndsWith(".exe") ? FXCOPPATH : FXCOPPATH + "FxCopCmd.exe")) { WriteMsg.WriteWithBreak("Could not find FxCop at the specified location: {0}", WriteMsg.MsgLevel.Error, 0, FXCOPPATH); return(false); } return(true); }
/// <summary> /// 读取指标分类信息 /// </summary> /// <returns></returns> private List <IndexManageEntity> ReadIndex() { List <IndexManageEntity> data = new List <IndexManageEntity>(); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/指标分类.xlsx"); if (!System.IO.File.Exists(path)) { WriteMsg?.Invoke("未找到“指标分类.xlsx文件”,请检查文件在不在程序根目录下"); WriteMsg?.Invoke("==用navicat执行下面sql语句导出Excel文件放到根目录下的Content/指标 里面=="); WriteMsg?.Invoke(@"select b.NATURE,a.* from base_indexmanage a left join base_department b on a.deptid= b.DEPARTMENTID" ); WriteMsg?.Invoke("=============附件名称:指标分类.xlsx================"); throw new ArgumentNullException("未找到附件"); } var book = new Workbook(path); var sheet = book.Worksheets[0]; for (int i = 1; i <= sheet.Cells.MaxDataRow; i++) { IndexManageEntity indexEntity = new IndexManageEntity() { Nature = sheet.Cells[i, 0].StringValue.Trim(), Id = sheet.Cells[i, 1].StringValue.Trim(), DeptId = sheet.Cells[i, 2].StringValue.Trim(), Title = sheet.Cells[i, 3].StringValue.Trim(), DeptCode = sheet.Cells[i, 4].StringValue.Trim(), DeptName = sheet.Cells[i, 5].StringValue.Trim(), Sort = sheet.Cells[i, 6].IntValue, IsShow = sheet.Cells[i, 7].IntValue, CreateUserId = sheet.Cells[i, 8].StringValue.Trim(), CreateDate = DateTime.Parse(sheet.Cells[i, 9].StringValue), CreateUserName = sheet.Cells[i, 10].StringValue.Trim(), ModifyUserId = sheet.Cells[i, 11].StringValue.Trim(), ModifyDate = DateTime.Parse(sheet.Cells[i, 12].StringValue), ModifyUserName = sheet.Cells[i, 13].StringValue.Trim(), IndexType = sheet.Cells[i, 14].IntValue, Templet = sheet.Cells[i, 15].IntValue, }; data.Add(indexEntity); } return(data); }
/// <summary> /// Check soft and hard filter matching /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool CheckOuterFilters(string filePath) { if (MainDeclaration.Instance.SoftFilter != null) { MainDeclaration.Instance.CurrentFileIsSoftFiltered = !MainDeclaration.Instance.SoftFilter.IsNecessaryToAnalyse(filePath); } if (MainDeclaration.Instance.HardFilter != null) { try { return(!MainDeclaration.Instance.HardFilter.IsNecessaryToAnalyse(filePath)); } catch (Exception) { WriteMsg.WriteLine("Warning: Wrong regular expression!", WriteMsg.MsgLevel.Warning); } } return(false); }
/// <summary> /// 检验数据模板 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnCheckData_Click(object sender, EventArgs e) { bool result = true; List <TerminalDataSetEntity> terminalDataSetEntities; List <IndexManageEntity> indexManageEntities; List <IndexAssocationEntity> assocationEntities; WriteMsg?.Invoke("开始检验"); if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/基础指标数据.txt"))) { WriteMsg?.Invoke("基础指标数据.txt文件正常"); terminalDataSetEntities = ReadIndexList().Result; if (terminalDataSetEntities != null && terminalDataSetEntities.Count > 0) { WriteMsg?.Invoke("基础指标数据.txt数据正常"); } else { WriteMsg?.Invoke("基础指标数据.txt无数据"); result = false; } } else { WriteMsg?.Invoke("基础指标数据.txt文件不存在"); } result = false; if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/标题配置.txt"))) { WriteMsg?.Invoke("标题配置.txt文件正常"); indexManageEntities = ReadIndexManageList().Result; if (indexManageEntities != null && indexManageEntities.Count > 0) { WriteMsg?.Invoke("标题配置.txt数据正常"); } else { WriteMsg?.Invoke("标题配置.txt无数据"); result = false; } } else { WriteMsg?.Invoke("标题配置.txt文件不存在"); } result = false; if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content/指标/关联关系.txt"))) { WriteMsg?.Invoke("关联关系.txt文件正常"); assocationEntities = ReadAssocationList().Result; if (assocationEntities != null && assocationEntities.Count > 0) { WriteMsg?.Invoke("关联关系.txt数据正常"); } else { WriteMsg?.Invoke("关联关系.txt无数据"); result = false; } } else { WriteMsg?.Invoke("关联关系.txt文件不存在"); } result = false; if (result == false) { WriteMsg?.Invoke("数据检验完毕,数据有问题,忽略并执行初始化请点击“开始初始化”按钮,或点击“重新读取并存储数据”"); } else { WriteMsg?.Invoke("数据检验完毕,点击“重新读取并存储数据”"); } }
private static void ppUnknownOption(string o) { WriteMsg.WriteLine("Error: Unrecognized option: {0}\n", WriteMsg.MsgLevel.Error, o); ppHelp(default(Option), null); }
/// <summary> /// The program main entry point. /// </summary> /// <param name="args">Command line arguments</param> private static void Main(string[] args) { #if !DEBUG try { #endif MainDeclaration.Instance.MainWatch.Start(); //this should be called first, before any output WriteMsg.Initialize(args); WriteMsg.WriteLine( "C# Analyzer {0} ({1}) - {2}", WriteMsg.MsgLevel.Silent, 0, System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3), //we use 3 digit versions, eg 7.0.6 Columbus.Common.Revision, Columbus.Common.CopyRightMessage); WriteMsg.WriteLine(); Process myProcess = Process.GetCurrentProcess(); if (Arguments.ProcessArguments(args, OPTIONS_OBJ, "-", ppUnknownOption) && !string.IsNullOrEmpty(INPUT) && !string.IsNullOrEmpty(OUTPUT)) { WriteMsg.WriteLine("Input: " + INPUT); WriteMsg.WriteLine("Output: " + OUTPUT); if (!string.IsNullOrEmpty(FXCOPPATH)) { WriteMsg.WriteLine("FxCopPath: " + FXCOPPATH); } } else { WriteMsg.WriteLine("Error: No input and/or output specified!", WriteMsg.MsgLevel.Error); WriteMsg.WriteLine("", WriteMsg.MsgLevel.Error); ppHelp(default(Option), null); Environment.Exit(1); } if (!CheckFxCopPath()) { Environment.Exit(1); } CheckStopwatches(); if (MainDeclaration.Instance.HardFilter != null) { WriteMsg.WriteLine("Hardfilter: " + EXTERNALHARDFILTER); } if (MainDeclaration.Instance.SoftFilter != null) { WriteMsg.WriteLine("Softfilter: " + EXTERNALSOFTFILTER); } MainDeclaration.Instance.LimFactory.Language = Lim.Asg.Types.LanguageKind.lnkCsharp; WriteMsg.WriteLine("File parsing..."); var timer = MainDeclaration.Instance.MainWatch.ElapsedSeconds; using (AbstractOpen file = AbstractOpen.CreateInstance(INPUT, CONFIGURATION, PLATFORM)) { file.Parse(); MainDeclaration.Instance.Statistics[0].FilesParsingTime = MainDeclaration.Instance.MainWatch.ElapsedSeconds - timer; WriteMsg.WriteLine("File parsing finished."); float buildTime = 0f; if (BUILDPROJECT) { WriteMsg.WriteLine("Build started"); Stopwatch watch = Stopwatch.StartNew(); MainDeclaration.Instance.BuildTask = file.BuildSoulution().ContinueWith(task => { buildTime = watch.ElapsedSeconds; WriteMsg.WriteLine(task.Result ? "Build succeeded" : "Build failed"); }); } timer = MainDeclaration.Instance.MainWatch.ElapsedSeconds; Build.Start(file, OUTPUT, RUNFXCOP ? FXCOPPATH : null, FXCOPOUT, OUTLIST); MainDeclaration.Instance.Statistics[0].ASGBuildingTime = MainDeclaration.Instance.MainWatch.ElapsedSeconds - timer; if (MainDeclaration.Instance.BuildTask != null) { MainDeclaration.Instance.BuildTask.Wait(); } MainDeclaration.Instance.Statistics[0].SolutionsBuildingTime = buildTime; MainDeclaration.Instance.Statistics[0].RoslynTime = MainDeclaration.Instance.RoslynWatch.ElapsedSeconds; timer = MainDeclaration.Instance.MainWatch.ElapsedSeconds; Build.SaveLimASG(INPUT, OUTPUT, LIMNAME); MainDeclaration.Instance.Statistics[0].SaveTime = MainDeclaration.Instance.MainWatch.ElapsedSeconds - timer; MainDeclaration.Instance.MainWatch.Stop(); WriteMsg.WriteLine(); WriteStatistics(MainDeclaration.Instance.MainWatch, myProcess.PeakWorkingSet64); if (!string.IsNullOrEmpty(STAT)) { MainDeclaration.Instance.Statistics.ToCsv(new CsvDestination(STAT), new CsvDefinition() { FieldSeparator = CSVSEPARATOR, DecimalSeparator = DECIMALSEPARATOR }); } } #if !DEBUG } /// Catch everything to prevent .NET's default "stopped working" dialog from showing up /// and blocking multiple processes waiting on this to exit catch (AggregateException e) { Console.Error.WriteLine(); Console.Error.WriteLine("EXCEPTION: {0}", e.GetType()); Console.Error.WriteLine(); if (e.InnerExceptions.Count > 1) { foreach (var error in e.InnerExceptions) { Console.Error.WriteLine("EXCEPTION: {0}", error.GetType()); Console.Error.WriteLine(error.Message); Console.Error.WriteLine(error.StackTrace); Console.Error.WriteLine(); } } else if (e.InnerException != null) { Console.Error.WriteLine("EXCEPTION: {0}", e.InnerException.GetType()); Console.Error.WriteLine(e.InnerException.Message); Console.Error.WriteLine(e.InnerException.StackTrace); } else { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } Environment.Exit(1); } catch (Exception e) { Console.Error.WriteLine(); Console.Error.WriteLine("EXCEPTION: {0}", e.GetType()); Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); Environment.Exit(1); } #endif }
/// <summary> /// 初始化指标 /// </summary> public void InitIndexData() { //先获取所有的指标 List <DepartmentEntity> deptList = _service.GetList <DepartmentEntity>("select * from base_department").Result.ToList(); List <IndexManageEntity> indexManages = this.ReadIndex(); List <IndexAssocationEntity> assocationEntities = this.ReadAssocation(); List <string> indexSqlList = new List <string>(); List <string> asscocationSqlList = new List <string>(); Dictionary <string, string> dic = new Dictionary <string, string>(); //index Key 新的ID ,value 旧的Id #region 指标 if (indexManages != null && indexManages.Count > 0) { indexManages.ForEach(index => { List <DepartmentEntity> natureList = deptList.Where(x => x.Nature == index.Nature).ToList(); if (natureList != null && natureList.Count > 0) { natureList.ForEach(dept => { string guidId = Guid.NewGuid().ToString(); string indexInsert = @"INSERT INTO BASE_INDEXMANAGE(ID, DEPTID, TITLE, DEPTCODE, DEPTNAME, SORT, ISSHOW, CREATEUSERID, CREATEDATE, CREATEUSERNAME, MODIFYUSERID, MODIFYDATE, MODIFYUSERNAME, INDEXTYPE, Templet) VALUES ('" + guidId + "', '" + dept.DepartmentId + "', '" + index.Title + "', '" + dept.EnCode + "', '" + dept.FullName + "', " + index.Sort + ", " + index.IsShow + ", 'SYSTEM',{0} , 'Software', 'SYSTEM', {0}, 'Software', " + index.IndexType + ", " + index.Templet + ")"; if (_dbmodel.DBType == "Oracle") { indexInsert = string.Format(indexInsert, $"to_date('{DateTime.Now:yyyy-MM-dd HH:mm:ss}','yyyy-mm-dd hh24:mi:ss')"); } else { indexInsert = string.Format(indexInsert, $"'{DateTime.Now:yyyy-MM-dd HH:mm-ss}'"); } indexSqlList.Add(indexInsert); dic.Add(guidId, index.Id); }); } }); } #endregion 指标 #region 指标的关联关系 assocationEntities.ForEach(ass => { string indexId = dic.FirstOrDefault(x => x.Value == ass.TitleId).Key; List <DepartmentEntity> natureList = deptList.Where(x => x.Nature == ass.Nature).ToList(); if (natureList != null && natureList.Count > 0) { natureList.ForEach(dept => { string insertSql = $"INSERT INTO base_indexassociation(Id, TitleId, DataSetId, DeptId) VALUES ('{Guid.NewGuid().ToString()}', '{indexId}', '{ass.DataSetId}', '{dept.DepartmentId}')"; asscocationSqlList.Add(insertSql); }); } }); #endregion 指标的关联关系 List <Task> taskList = new List <Task>(); WriteMsg?.Invoke($"开始执行指标配置 {indexSqlList.Count}条数据"); indexSqlList.ForEach(x => { WriteMsg?.Invoke("执行sql语句:" + x); var task = Task.Run(() => { _service.ExecuteNonQuery(x); }); taskList.Add(task); }); WriteMsg?.Invoke($"开始执行关联关系 {asscocationSqlList.Count}条数据"); asscocationSqlList.ForEach(x => { WriteMsg?.Invoke("执行sql语句:" + x); var task = Task.Run(() => { _service.ExecuteNonQuery(x); }); taskList.Add(task); }); WriteMsg?.Invoke("指标配置执行完毕"); }
/// <summary> /// Binary file will be analysed by FxCop. /// </summary> /// <param name="inputBinary">Binary file location</param> /// <param name="resultOutputPath">FxCop result directory</param> /// <param name="fxCopPath">FxCopCmd.exe path</param> private static void StartFxCopAnalysis(string inputBinary, string resultOutputPath, string fxCopPath) { if (string.IsNullOrEmpty(fxCopPath)) { return; } string output_filename = Path.GetFileNameWithoutExtension(inputBinary) + ".xml"; string output_directory = Path.GetDirectoryName(inputBinary); string result = Path.Combine(output_directory, output_filename); if (!string.IsNullOrEmpty(resultOutputPath) && resultOutputPath[resultOutputPath.Length - 1] != Path.DirectorySeparatorChar) { resultOutputPath += Path.DirectorySeparatorChar; } System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo() { CreateNoWindow = false, UseShellExecute = false, FileName = fxCopPath.EndsWith(".exe") ? fxCopPath : fxCopPath + "FxCopCmd.exe", WorkingDirectory = fxCopPath.EndsWith(".exe") ? Path.GetDirectoryName(fxCopPath) : fxCopPath, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, Arguments = string.Format("/f:\"{0}\" /d:\"{1}\" /r:\"{2}\" /o:\"{3}{4}\" /gac", inputBinary, output_directory, (fxCopPath.Contains(".exe") ? Path.GetDirectoryName(fxCopPath) : fxCopPath) + "Rules", resultOutputPath, output_filename), RedirectStandardOutput = true, RedirectStandardError = true }; if (MainDeclaration.Instance.BuildTask != null) { MainDeclaration.Instance.BuildTask.Wait(); } if (!File.Exists(inputBinary)) { WriteMsg.WriteWithBreak("[FxCopAnalysis] {0} is missing, skipped", WriteMsg.MsgLevel.Warning, 4, inputBinary); return; } WriteMsg.WriteWithBreak("[FxCopAnalysis] Starting FxCop analysis for {0}...", WriteMsg.MsgLevel.Normal, 4, inputBinary); try { string output = string.Format("{0}{1}{2}.log", resultOutputPath, Path.DirectorySeparatorChar, output_filename); using (System.Diagnostics.Process exeProcess = new System.Diagnostics.Process()) using (StreamWriter sw = new StreamWriter(output, false)) { exeProcess.OutputDataReceived += (sender, e) => { if (e.Data != null) { sw.WriteLine(e.Data); } }; exeProcess.ErrorDataReceived += (sender, e) => { if (e.Data != null) { sw.WriteLine(e.Data); } }; exeProcess.StartInfo = startInfo; exeProcess.Start(); exeProcess.BeginOutputReadLine(); exeProcess.BeginErrorReadLine(); exeProcess.WaitForExit(); } WriteMsg.WriteWithBreak("[FxCopAnalysis] FxCop for {0} terminated", WriteMsg.MsgLevel.Normal, 4, Path.GetFileName(inputBinary)); } catch (FileNotFoundException e) { if (File.Exists(result)) { File.Delete(result); } WriteMsg.WriteWithBreak("[FxCopAnalysis][FileNotFoundException] {0}: {1}", WriteMsg.MsgLevel.Warning, 4, e.Message, startInfo.FileName); } catch (System.ComponentModel.Win32Exception e) { if (File.Exists(result)) { File.Delete(result); } WriteMsg.WriteWithBreak("[FxCopAnalysis][Win32Exception] " + e.Message, WriteMsg.MsgLevel.Warning, 4); } catch (System.IO.IOException e) { if (File.Exists(result)) { File.Delete(result); } WriteMsg.WriteWithBreak("[FxCopAnalysis][IOException] " + e.Message, WriteMsg.MsgLevel.Warning, 4); } catch (Exception e) { if (File.Exists(result)) { File.Delete(result); } WriteMsg.WriteWithBreak("[FxCopAnalysis][{0}] {1}", WriteMsg.MsgLevel.Warning, 4, e.GetType().ToString(), e.Message); } }