Beispiel #1
0
 private void DisplayAllTfsVariables(TfsVariable tfsVariables)
 {
     foreach (var item in tfsVariables.RawData)
     {
         WriteDetail(item.Key + " - " + item.Value);
     }
 }
Beispiel #2
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <PartialUnitTestSetting> usrVariables)
        {
            var setting = usrVariables.Config;

            if (setting == null)
            {
                return(new TaskStatu("PUT01", "No setting found."));
            }

            var changedAll = TFSHelper.ChangedFiles();

            if (!changedAll.Any())
            {
                return(new TaskStatu("No code change found on TFS"));
            }

            var codes        = changedAll.Where(x => x.FilePath.EndsWith(".cs")).ToList();
            var codesChanged = codes.Where(x => x.State == SourceControlFileState.Changed).ToList();
            var codesAdded   = codes.Where(x => x.State == SourceControlFileState.Added).ToList();

            if (codesChanged.Count + codesAdded.Count < 1)
            {
                return(new TaskStatu("No code changes found to check for partial unit test"));
            }

            var      tmpFile   = codesChanged.Any() ? codesChanged[0] : codesAdded[0];
            Solution gSolution = GetSolutionInfo(tfsVariables, setting, tmpFile);

            if (gSolution == null)
            {
                return(new TaskStatu("PUT03", "No suitable solution found"));
            }

            var tmpMethodsforChanged = GetChangeforChangedFiles(codesChanged, tfsVariables, gSolution);

            if (tmpMethodsforChanged == null)
            {
                return(new TaskStatu("PUT04", "No suitable project document found for changed list"));
            }
            var tmpMethodsforAdded = GetChangeforChangedAdded(codesAdded, tfsVariables, gSolution);

            if (tmpMethodsforAdded == null)
            {
                return(new TaskStatu("PUT05", "No suitable project document found for added list"));
            }

            int totalMethod = tmpMethodsforAdded.MethodCount + tmpMethodsforChanged.MethodCount;

            WriteDetail(string.Format("{0} number of methods will be looked for unit test", totalMethod));
            var unitTesttoCheck = CheckforUnitTest(setting, gSolution, tfsVariables, tmpMethodsforChanged, tmpMethodsforAdded);

            if (unitTesttoCheck == null)
            {
                return(new TaskStatu("PUT06", "No unit test found for partial check"));
            }

            bool isAllSucc = RunUnitTests(tfsVariables, setting, unitTesttoCheck, usrVariables.WorkingPath);

            return(isAllSucc ? new TaskStatu("Partial Unit Test check successful") : new TaskStatu("PUT07", "Partial Unit Test  failed"));
        }
Beispiel #3
0
        public static TaskList Get(Dictionary <string, string> tfsVariables, Dictionary <string, string> usrVar)
        {
            try
            {
                var settTfs = new TfsVariable(tfsVariables);
                var settUsr = new UserVariable <RawBasicBuildSetting>(RawBasicBuildSetting.KeyBaseConfigArea, usrVar);
                Logger.Set(settUsr.WorkingPath);

                if (settUsr.Config == null)
                {
                    throw new Exception("User Setting File is missing or wrongly formatted.");
                }

                var dlls     = GetDllList(settUsr.WorkingPath);
                var allTasks = GetAllTasks(dlls, settUsr);
                allTasks = ReOrder(settUsr, allTasks);

                return(allTasks);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                throw;
            }
        }
Beispiel #4
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <RawBasicBuildSetting> usrVariables)
        {
            Stopwatch tmrWatch = Stopwatch.StartNew();
            TaskStatu tsk      = new TaskStatu("TestAsyncTask at begining.");

            folderPath = tfsVariables.AgentWorkFolder;
            var fMsg = CheckFileOp(folderPath);

            if (!string.IsNullOrEmpty(fMsg))
            {
                return(new TaskStatu("T1", "CheckFileOp failed. Ex = " + fMsg));
            }

            try
            {
                var thr = new Thread(new ThreadStart(TestPostRun));
                thr.Start();
                tsk = new TaskStatu("TestAsyncTask started.");
            }
            catch (Exception ex)
            {
                Logger.Write(ex);

                tsk = new TaskStatu("T2", "TestAsyncTask.Job's ThreadStart start throw exception. Ex = " + ex.ToString());
            }

            return(tsk);
        }
Beispiel #5
0
 public TFSClientLogic(TfsVariable tfsVar) : base(tfsVar)
 {
     idService = TeamColl.GetService(typeof(IIdentityManagementService)) as IIdentityManagementService;
     tfsId     = IdentityService.ReadIdentity(IdentitySearchFactor.DisplayName,
                                              initSetting.BuildRequestedUser,
                                              MembershipQuery.None,
                                              ReadIdentityOptions.None);
 }
        private ShellStatu RunTask(Func <string, string, string, Dictionary <string, string>, Dictionary <string, string>, ShellStatu> tsk)
        {
            var dictTfs = DummyTfsVariable();
            var dictUsr = DummyUserVariable();
            var tfs     = new TfsVariable(dictTfs);
            var usr     = new UserVariable <RawBasicBuildSetting>("", dictUsr);

            return(tsk("xFile", "xClass", "xMethod", dictTfs, dictUsr));
        }
        public void TfsHelperTest()
        {
            var dictTfs = DummyTfsVariable();
            var tfs     = new TfsVariable(dictTfs);

            TFSHelper.Initialize(tfs);
            var usrGroups = TFSHelper.GroupUserJoined();

            Assert.IsTrue(usrGroups.Count > 0);
        }
Beispiel #8
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <CodeMetricSetting> usrVariables)
        {
            var setting = usrVariables.Config;

            if (setting == null)
            {
                return(new TaskStatu("CM01", "No setting found"));
            }

            string buildPath     = tfsVariables.BuildSourceDirectory;
            var    solutionsPath = SolutionHelper.FindSolutionFiles(buildPath);

            solutionsPath = !string.IsNullOrEmpty(tfsVariables.SolutiontoBuild) ?
                            solutionsPath.Where(x => x.Contains(tfsVariables.SolutiontoBuild)).ToArray()
                : solutionsPath;

            if (!solutionsPath.Any())
            {
                return(new TaskStatu("CM02", "No solution file found"));
            }

            foreach (var slnPath in solutionsPath)
            {
                if (setting.ExcludedSolutions.Any(x => x == slnPath))
                {
                    continue;
                }

                using (var slnProvider = new SolutionProvider())
                {
                    var solution = slnProvider.Get(slnPath).Result;
                    var slnName  = Path.GetFileName(slnPath);
                    var projects = solution.Projects.ToList();
                    if (!projects.Any())
                    {
                        return(new TaskStatu("CM03", string.Format("No solution found in [{0}] solution", slnName)));
                    }
                    WriteDetail(string.Format("Calculating metrics for [{0}] solution", slnName));
                    var metricBag = GetSolutionMetric(projects, solution, setting);
                    if (metricBag == null)
                    {
                        return(new TaskStatu("CM04", "CodeMetric failed due to an project build or style error."));
                    }

                    var checkResult = CheckMetric(metricBag, setting, slnName);
                    if (!string.IsNullOrEmpty(checkResult))
                    {
                        return(new TaskStatu("CM05", checkResult));
                    }
                }
            }

            return(new TaskStatu("CodeMetrics check finished successfully."));
        }
Beispiel #9
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <RawBasicBuildSetting> usrVariables)
        {
            Stopwatch tmrWatch = Stopwatch.StartNew();
            TaskStatu tsk      = new TaskStatu("TestTask start successfully");

            DisplayAllTfsVariables(tfsVariables);

            DisplayAllChangedFiles(tfsVariables);

            WriteDetail("This how to use detail method :)", tmrWatch);
            return(tsk);
        }
Beispiel #10
0
        private static string FindRightOutputDll(string outputFilePath, TfsVariable tfsVariables)
        {
            string buildMode = string.IsNullOrEmpty(tfsVariables.BuildConfiguration)
                ? ""
                : tfsVariables.BuildConfiguration.ToLowerInvariant();

            if (buildMode == "release")
            {
                return(outputFilePath.Replace(@"\bin\Debug\", @"\bin\Release\"));
            }

            return(outputFilePath);
        }
Beispiel #11
0
        private bool RunStyleCopRules(List <string> srcFilestoCheck, TfsVariable tfsVariables, UserVariable <StyleCopSetting> usrVariables)
        {
            List <string> addInPaths = new List <string> {
                usrVariables.WorkingPath
            };
            string styleSettingFile = FindRuleFile(usrVariables);

            // Create the StyleCop console. But do not initialise the addins as this can cause modal dialogs to be shown on errors
            var console = new StyleCopConsole(styleSettingFile, false, "StyleCopXmlOutputFile.xml", null, false);

            // make sure the UI is not dispayed on error
            console.Core.DisplayUI = false;

            // declare the add-ins to load
            console.Core.Initialize(addInPaths, true);

            // Create the configuration.
            Configuration configuration = new Configuration(new string[0]);

            // Create a CodeProject object for these files. we use a time stamp for the key and the current directory for the cache location
            CodeProject project = new CodeProject(DateTime.Now.ToLongTimeString().GetHashCode(), @".\", configuration);

            foreach (var itmFile in srcFilestoCheck)
            {
                console.Core.Environment.AddSourceCode(project, itmFile, null);
            }

            try
            {
                // Subscribe to events
                console.OutputGenerated      += this.OnOutputGenerated;
                console.ViolationEncountered += this.OnViolationEncountered;

                // Analyze the source files
                CodeProject[] projects    = new[] { project };
                var           startResult = console.Start(projects, true);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                // Unsubscribe from events
                console.OutputGenerated      -= this.OnOutputGenerated;
                console.ViolationEncountered -= this.OnViolationEncountered;
            }

            return(violateError.Count <= usrVariables.Config.MaxErrorCount);
        }
Beispiel #12
0
        private bool CalculateCoverage(TfsVariable tfsVariables, PartialUnitTestSetting setting, List <VstestConsoleParser> cmdResults)
        {
            try
            {
                foreach (var itmOut in cmdResults)
                {
                    WriteDetail($"[{Path.GetFileName(itmOut.CoverageFilePath)}] file is starting to read.");
                    using (var coverInfo = CoverageInfo.CreateFromFile(itmOut.CoverageFilePath))
                    {
                        var dllName = itmOut.AssemblyName.ToLowerInvariant();
                        foreach (var module in coverInfo.Modules)
                        {
                            if (module.Name != dllName)
                            {
                                continue;
                            }

                            byte[] coverageBuffer = module.GetCoverageBuffer(null);
                            using (var reader = module.Symbols.CreateReader())
                            {
                                uint   methodId;
                                string mthdName, undecoratedMthd, className, namespaceName;

                                var lines = new List <BlockLineRange>();

                                while (reader.GetNextMethod(out methodId, out mthdName, out undecoratedMthd, out className, out namespaceName, lines))
                                {
                                    var    stats       = CoverageInfo.GetMethodStatistics(coverageBuffer, lines);
                                    string tmpUnitName = namespaceName + "." + className + "." + mthdName;

                                    string mLine = $"Covered/NotCovered => Block - Line : {stats.BlocksCovered} / {stats.BlocksNotCovered} - {stats.LinesCovered} / {stats.LinesNotCovered} => {tmpUnitName} ";
                                    WriteDetail(mLine);
                                }
                            }
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                WriteDetail($"Coverage calculation failed : {ex}");
            }

            return(false);
        }
Beispiel #13
0
        private void DisplayAllChangedFiles(TfsVariable tfsVariables)
        {
            var files = TFSHelper.ChangedFiles();

            if (files.Any())
            {
                WriteDetail("Changed files are : ");
                foreach (var itm in files)
                {
                    WriteDetail(itm.State + " : " + itm.FilePath);
                }
            }
            else
            {
                WriteDetail("No changed files found");
            }
        }
Beispiel #14
0
        /// <summary>
        /// This is where shell script trigger. A cocoon ;)
        /// </summary>
        /// <param name="dllName"></param>
        /// <param name="className"></param>
        /// <param name="methodName"></param>
        /// <param name="tfsVarRaw"></param>
        /// <param name="usrVarRaw"></param>
        /// <returns></returns>
        public ShellStatu Initializer(string dllName, string className, string methodName, Dictionary <string, string> tfsVarRaw, Dictionary <string, string> usrVarRaw)
        {
            Stopwatch watchGeneral = Stopwatch.StartNew();
            string    taskLongName = string.Empty;

            try
            {
                taskLongName = Path.GetFileNameWithoutExtension(dllName) + " -> " + className;
                var tfsVar = new TfsVariable(tfsVarRaw);
                var usrVar = new UserVariable <Tsetting>(this.GetType().Name, usrVarRaw);
                Logger.Set(usrVar.WorkingPath);

                var bsSetting = usrVar.Config;
                if (bsSetting == null)
                {
                    return(new ShellStatu(false, string.Format("{0}.{1} tasks setting could not deserialized.", className, methodName)));
                }

                TFSHelper.Initialize(tfsVar);

                Stopwatch watchTask = Stopwatch.StartNew();
                var       tmpResult = Job(tfsVar, usrVar);
                watchTask.Stop();

                if (intrDetailContainer.Any() && !tmpResult.Detail.Any())
                {
                    tmpResult.Detail = intrDetailContainer;
                }

                var rtnData = tmpResult == null ? new ShellStatu() : tmpResult.ToShellStatu(taskLongName);
                watchGeneral.Stop();
                rtnData.Msgs.Add(string.Format("*** FINISH > [{0}] task runned/total (ms) : {1}/{2}",
                                               className, watchTask.Elapsed.TotalMilliseconds, watchGeneral.Elapsed.TotalMilliseconds));

                rtnData.Msgs.Add("---------------------------------------");

                return(rtnData);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return(new ShellStatu(false, string.Format("!!! BaseTask.Initializer failed. TaskName = [{0}]. ExDetail = [{1}].", taskLongName, ex)));
            }
        }
Beispiel #15
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <FileControlSetting> usrVariables)
        {
            var setting = usrVariables.Config;

            if (setting == null)
            {
                return(new TaskStatu("No setting found."));
            }

            var allFiles = TFSHelper.ChangedFiles();

            if (!allFiles.Any())
            {
                return(new TaskStatu("No changed file found."));
            }

            string adName    = TFSHelper.UserDomainName;
            var    usrGroups = TFSHelper.GroupUserJoined();

            foreach (var sourceData in allFiles)
            {
                var sourceFile = sourceData.FilePath;
                var rule       = setting.Files.FirstOrDefault(x => x.FileNames.Any(y => sourceFile.EndsWith(y)));

                if (rule == null)
                {
                    continue;
                }

                if (rule.AllowedUser.Any(x => x == adName))
                {
                    continue;
                }

                if (rule.AllowedGroup.Any(x => (usrGroups.Any(y => y.EndsWith(x)))))
                {
                    continue;
                }

                return(new TaskStatu("FC01", string.Format("[{0}] file is restirected for [{1}] user.", sourceFile, adName)));
            }

            return(new TaskStatu(string.Format("All changes controlled successfully. FileCount/TotalRule = {0}/{1}.", allFiles.Count, setting.Files.Count)));
        }
Beispiel #16
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <StyleCopSetting> usrVariables)
        {
            GlobalSetting    = usrVariables?.Config;
            SourceBaseFolder = tfsVariables.BuildSourceDirectory;
            if (GlobalSetting == null)
            {
                return(new TaskStatu("SCT02", "No setting loaded."));
            }

            bool isExcFilesExist    = GlobalSetting.ExcludedFiles.Any();
            bool isExcProjectsExist = GlobalSetting.ExcludedProjects.Any();

            SourceBaseFolder = tfsVariables.BuildSourceDirectory;
            WriteDetail("Source Folder : " + SourceBaseFolder);
            WriteDetail("Exclusion files : " +
                        (isExcFilesExist ? string.Join(", ", GlobalSetting.ExcludedFiles) : "None"));
            WriteDetail("Exclusion projects : " +
                        (isExcFilesExist ? string.Join(", ", GlobalSetting.ExcludedProjects) : "None"));

            var           srcFilesAll = Directory.GetFiles(SourceBaseFolder, "*.cs", SearchOption.AllDirectories).ToList();
            List <string> srcFilestoCheck;

            if (isExcFilesExist || isExcProjectsExist)
            {
                srcFilestoCheck = FilterFiles(srcFilesAll, GlobalSetting.ExcludedFiles, GlobalSetting.ExcludedProjects);
            }
            else
            {
                srcFilestoCheck = srcFilesAll;
            }

            WriteDetail(string.Format("File Count (Check/All) : {0}/{1}", srcFilestoCheck.Count, srcFilesAll.Count));

            bool isResultOk = RunStyleCopRules(srcFilestoCheck, tfsVariables, usrVariables);

            if (!IsRunned)
            {
                return(new TaskStatu("SCT03", "StyleCop engine did not runned."));
            }

            return(isResultOk ? new TaskStatu("StyleCopTask finished successfully") : new TaskStatu("SCT04", "There is too much error."));
        }
Beispiel #17
0
        private bool RunUnitTests(TfsVariable tfsVariables, PartialUnitTestSetting setting, List <UnitTestDetail> unitTesttoCheck, string workingPath)
        {
            Stopwatch watch           = Stopwatch.StartNew();
            string    cmdRaw          = string.IsNullOrEmpty(setting.RunSettingFile) ? cmdParams : cmdParams + " /Settings:{2}";
            var       groupedUnitTest = unitTesttoCheck.GroupBy(x => x.AssemblyPath);
            bool      isSucc          = false;
            var       cmdResults      = new List <VstestConsoleParser>();

            foreach (var itmGrp in groupedUnitTest)
            {
                var sb = new StringBuilder();
                foreach (var itmUnitTest in itmGrp)
                {
                    sb.Append(itmUnitTest.MethodName + ",");
                }

                string tstMethodLine = sb.ToString().TrimEnd(',');
                string settFile      = Path.Combine(workingPath, setting.RunSettingFile);
                WriteDetail($"Unit Test Setting file found : {File.Exists(settFile)}. Path = [{settFile}]");
                string prms = string.Format(cmdRaw, itmGrp.Key, tstMethodLine, settFile);

                var runResult = RunMsUnitTestExe(prms, itmGrp.Key);
                cmdResults.Add(runResult);

                DisplayResult(runResult, itmGrp.Key, tstMethodLine);
                isSucc = runResult.IsAllSucceeded;

                if (!isSucc)
                {
                    break;
                }
            }
            if (isSucc && cmdResults.Any())
            {
                isSucc &= CalculateCoverage(tfsVariables, setting, cmdResults);
            }

            WriteDetail("All test methods runned", watch);
            return(isSucc);
        }
Beispiel #18
0
        private Solution GetSolutionInfo(TfsVariable tfsVariables, PartialUnitTestSetting setting, TFSFileState itmChanged)
        {
            bool   isSolutionSelected = !string.IsNullOrEmpty(tfsVariables.SolutiontoBuild);
            string slnPath            = null;

            string[] slnFiles = isSolutionSelected
                ? SolutionHelper.FindSolutionFiles(tfsVariables.BuildSourceDirectory, tfsVariables.SolutiontoBuild)
                : SolutionHelper.FindSolutionFiles(tfsVariables.BuildSourceDirectory);

            if (isSolutionSelected)
            {
                slnPath = slnFiles.FirstOrDefault();
            }
            else
            {
                foreach (var slnFullPath in slnFiles)
                {
                    string mainFolderName = Path.GetDirectoryName(slnFullPath);
                    var    mainFolder     = new DirectoryInfo(mainFolderName);
                    var    repoFolder     = mainFolder.Parent.FullName;
                    string tmpFile        = repoFolder + itmChanged.FilePath;
                    if (File.Exists(tmpFile))
                    {
                        slnPath = slnFullPath;
                        break;
                    }
                }

                if (string.IsNullOrEmpty(slnPath))
                {
                    return(null);
                }
            }
            MSBuildWorkspace workSpace = MSBuildWorkspace.Create();
            var solution = workSpace.OpenSolutionAsync(slnPath).Result;

            return(solution);
        }
Beispiel #19
0
 /// <summary>
 /// This is where developed real job
 /// </summary>
 /// <param name="tfsVariables"></param>
 /// <param name="usrVariables"></param>
 /// <returns></returns>
 public abstract TaskStatu Job(TfsVariable tfsVariables, UserVariable <Tsetting> usrVariables);
Beispiel #20
0
        private static List <UnitTestDetail> FindUnitTestReferences(Solution solution, IMethodSymbol method, TfsVariable tfsVariables)
        {
            var methodReferences = SymbolFinder.FindReferencesAsync(method, solution).Result.ToList();

            if (!methodReferences.Any())
            {
                return(null);
            }

            var depo = new List <UnitTestDetail>();

            foreach (ReferencedSymbol methodReference in methodReferences)
            {
                IEnumerable <ReferenceLocation> locations = methodReference.Locations;
                foreach (ReferenceLocation location in locations)
                {
                    MethodDeclarationSyntax referenceMds = GetMethodFromLine(location.Document.GetSemanticModelAsync().Result.SyntaxTree, location.Location.GetMappedLineSpan().StartLinePosition.Line);

                    if (referenceMds != null)
                    {
                        ClassDeclarationSyntax referenceCds = referenceMds.Parent as ClassDeclarationSyntax;
                        bool isTestClass = HasAttibute(referenceCds.AttributeLists, "TestClass");
                        if (isTestClass)
                        {
                            bool isTestMethod = HasAttibute(referenceMds.AttributeLists, "TestMethod");
                            if (isTestMethod)
                            {
                                string rightDll = FindRightOutputDll(location.Document.Project.OutputFilePath, tfsVariables);
                                depo.Add(
                                    new UnitTestDetail(referenceMds.Identifier.Text, rightDll)
                                    );
                            }
                        }
                    }
                }
            }

            return(depo);
        }
Beispiel #21
0
        private MethodUnitTestCollection GetChangeforChangedFiles(List <TFSFileState> changedFiles, TfsVariable tfsVariables, Solution solution)
        {
            var depo = new MethodUnitTestCollection();

            if (!changedFiles.Any())
            {
                return(depo);
            }

            foreach (var itmChanged in changedFiles)
            {
                var webPath       = itmChanged.FilePath.Substring(1).Replace("/", "\\");
                var serverVersion = TFSHelper.DownloadFile(webPath);
                serverVersion = string.IsNullOrEmpty(serverVersion) ? serverVersion : serverVersion.Replace("\r\n", "\n");
                var      localVersionFullPath = Path.Combine(tfsVariables.BuildSourceDirectory, webPath);
                var      report = GetFileChanges(serverVersion, localVersionFullPath);
                Document doc    = null;
                foreach (var tmp in solution.Projects)
                {
                    doc = tmp.Documents.FirstOrDefault(x => x.FilePath == localVersionFullPath);
                    if (doc != null)
                    {
                        break;
                    }
                }
                if (doc == null)
                {
                    WriteDetail(string.Format("(Changed) No project document found for : {0}", localVersionFullPath));
                    return(null);
                }

                var tmpMethods = GetChangedPublicMethods(doc, report);
                if (tmpMethods != null)
                {
                    depo.Add(doc, tmpMethods);
                }
            }

            return(depo);
        }
Beispiel #22
0
        private List <UnitTestDetail> CheckforUnitTest(PartialUnitTestSetting setting, Solution solution, TfsVariable tfsVariables, params MethodUnitTestCollection[] bags)
        {
            int totalFailCount        = 0;
            List <UnitTestDetail> lst = new List <UnitTestDetail>();

            foreach (var queuDepo in bags)
            {
                foreach (var itmDoc in queuDepo)
                {
                    int tmpFail = 0;
                    foreach (var itmMethod in itmDoc.Methods)
                    {
                        IMethodSymbol method   = itmDoc.Doc.GetSemanticModelAsync().Result.GetDeclaredSymbol(itmMethod);
                        var           unitTest = FindUnitTestReferences(solution, method, tfsVariables);
                        if ((unitTest == null) || !unitTest.Any())
                        {
                            WriteDetail(string.Format("[{0}] method test is not found!!!", method.Name));
                            ++tmpFail;
                            if (totalFailCount > setting.MaxLogCount)
                            {
                                return(null);
                            }
                        }
                        else
                        {
                            lst.AddRange(unitTest);
                        }
                    }
                    totalFailCount += tmpFail;
                    if (tmpFail == 0)
                    {
                        WriteDetail(string.Format("[{0}] project's all test are found", itmDoc.Doc.Project.Name));
                    }
                }
            }

            return(totalFailCount == 0 ? lst : null);
        }
Beispiel #23
0
        private MethodUnitTestCollection GetChangeforChangedAdded(List <TFSFileState> codesAdded, TfsVariable tfsVariables, Solution solution)
        {
            var depo = new MethodUnitTestCollection();

            if (!codesAdded.Any())
            {
                return(depo);
            }

            foreach (var itmChanged in codesAdded)
            {
                var      webPath = itmChanged.FilePath.Replace("/", "\\").TrimStart('\\');
                var      localVersionFullPath = Path.Combine(tfsVariables.BuildSourceDirectory, webPath);
                Document doc = null;
                foreach (var tmp in solution.Projects)
                {
                    doc = tmp.Documents.FirstOrDefault(x => x.FilePath == localVersionFullPath);
                    if (doc != null)
                    {
                        break;
                    }
                }
                if (doc == null)
                {
                    WriteDetail(string.Format("(Added) No project document found for : {0}", localVersionFullPath));
                    return(null);
                }

                var tmpMethods = GetAllPublicMethods(doc);
                if (tmpMethods != null)
                {
                    depo.Add(doc, tmpMethods);
                }
            }

            return(depo);
        }
Beispiel #24
0
 public TFSBaseLogic(TfsVariable tfsVar)
 {
     initSetting = tfsVar;
     teamColl    = new TfsTeamProjectCollection(new Uri(initSetting.CollectionUri));
 }
Beispiel #25
0
 public static bool Initialize(TfsVariable tfsVar)
 {
     initSetting = tfsVar;
     return(true);
 }
Beispiel #26
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <AnalyzerEnforcerSetting> usrVariables)
        {
            string settingOkMsg = CheckSetting(usrVariables);
            var    setting      = usrVariables.Config;

            if (!string.IsNullOrEmpty(settingOkMsg))
            {
                return(new TaskStatu("RET01", settingOkMsg));
            }
            string buildPath = tfsVariables.BuildSourceDirectory;

            string[] slnFiles = SolutionHelper.FindSolutionFiles(buildPath);
            slnFiles = !string.IsNullOrEmpty(tfsVariables.SolutiontoBuild) ?
                       slnFiles.Where(x => x.Contains(tfsVariables.SolutiontoBuild)).ToArray()
                : slnFiles;

            if ((slnFiles == null) || (!slnFiles.Any()))
            {
                return(new TaskStatu("RET02", "No solution file found."));
            }

            var workspace = MSBuildWorkspace.Create();

            foreach (var slnItem in slnFiles)
            {
                var slnName = Path.GetFileNameWithoutExtension(slnItem);
                if (IsSolutionExcluded(setting, slnName))
                {
                    continue;
                }

                var solution = workspace.OpenSolutionAsync(slnItem).Result;


                foreach (var libItem in setting.References)
                {
                    var analyzer = new AnalyzerFileReference(libItem.DLLPath, FromFileLoader.Instance);

                    foreach (var project in solution.Projects)
                    {
                        if (IsProjectExcluded(setting, project.Name))
                        {
                            continue;
                        }

                        bool analyzerExists = false;
                        foreach (var analyzerReference in project.AnalyzerReferences)
                        {
                            if (analyzerReference.FullPath.EndsWith(libItem.DLLName))
                            {
                                analyzerExists = true;
                                break;
                            }
                        }

                        if (!analyzerExists)
                        {
                            WriteDetail(string.Format("{0} project is missing {1} library. Adding...", project.Name, libItem.DLLName));
                            solution = solution.AddAnalyzerReference(project.Id, analyzer);
                        }
                    }
                }

                workspace.TryApplyChanges(solution);
            }

            return(new TaskStatu("Enforce finished successfully."));
        }
Beispiel #27
0
 public TFSApiLogic(TfsVariable tfsVar) : base(tfsVar)
 {
     SettingTFS = tfsVar;
 }
Beispiel #28
0
        public override TaskStatu Job(TfsVariable tfsVariables, UserVariable <AutoDeploySetting> usrVariables)
        {
            var sourceFolder = tfsVariables.BuildDirectory;
            var setting      = usrVariables?.Config;

            if (setting == null)
            {
                return(new TaskStatu("ADT01", "No setting loaded."));
            }

            var inptControl = setting.CheckRules();

            if (!string.IsNullOrEmpty(inptControl))
            {
                return(new TaskStatu("ADT02", inptControl));
            }

            if (setting.TakeBackup)
            {
                WriteDetail("Backup started.");
                var bckMsg = FileOperationHelper.TakeBackup(setting, sourceFolder, setting.BackupFolder);
                if (!string.IsNullOrEmpty(bckMsg))
                {
                    return(new TaskStatu("ADT03", bckMsg));
                }
                WriteDetail("Backup finished.");
            }

            List <HashItem> fileHashInfo;
            List <string>   srcFiles = PrepareFileList(sourceFolder, setting, out fileHashInfo);

            WriteDetail($"For deploy; {srcFiles.Count} files found.");

            bool willImpersonate  = !string.IsNullOrEmpty(setting.ImpersonateName);
            bool willIISStopStart = !string.IsNullOrEmpty(setting.AppPoolName) && !string.IsNullOrEmpty(setting.IISServerName);

            var appMsg = StopIIS(willImpersonate, setting, willIISStopStart);

            if (!string.IsNullOrEmpty(appMsg))
            {
                return(new TaskStatu("ADT04", appMsg));
            }

            string deplMsg = StartDeploy(srcFiles, sourceFolder, setting);

            if (!string.IsNullOrEmpty(deplMsg))
            {
                string rllMsg = StartRollBack(srcFiles, sourceFolder, setting);
                return(new TaskStatu("ADT05", deplMsg));
            }
            string msgWrtHash = WriteNewHashFile(setting, fileHashInfo);

            var startMsg = StartIIS(willImpersonate, setting, willIISStopStart);

            if (!string.IsNullOrEmpty(startMsg))
            {
                return(new TaskStatu("ADT06", startMsg));
            }

            return(new TaskStatu("AutoDeploy finished successfully."));
        }