Esempio n. 1
0
        protected override void Execute(CodeActivityContext context)
        {
            bool   leaveXppIL        = LeaveXppIL.Get(context);
            string configurationFile = ConfigurationFile.Get(context);
            var    serverConfig      = Helper.GetServerConfig(configurationFile);

            context.TrackBuildMessage("Cleaning server label artifacts");
            CleanFolder(string.Format(@"{0}\Application\Appl\Standard", serverConfig.AlternateBinDirectory), "ax*.al?");

            if (!leaveXppIL)
            {
                context.TrackBuildMessage("Cleaning server XppIL artifacts");
                CleanFolder(string.Format(@"{0}\XppIL", serverConfig.AlternateBinDirectory), "*");
            }

            context.TrackBuildMessage("Cleaning server VSAssemblies artifacts");
            CleanFolder(string.Format(@"{0}\VSAssemblies", serverConfig.AlternateBinDirectory), "*");

            context.TrackBuildMessage("Cleaning client cache artifacts");
            CleanFolder(System.Environment.GetEnvironmentVariable("localappdata"), "ax_*.auc");
            CleanFolder(System.Environment.GetEnvironmentVariable("localappdata"), "ax*.kti");

            context.TrackBuildMessage("Cleaning client VSAssemblies artifacts");
            CleanFolders(string.Format(@"{0}\{1}", System.Environment.GetEnvironmentVariable("localappdata"), @"Microsoft\Dynamics Ax"), "VSAssemblies*", "*");
        }
Esempio n. 2
0
        protected static void OutputLog(CodeActivityContext context, List <KeyValuePair <string, string> > log, bool outputAllAsInfo = false)
        {
            if (log != null)
            {
                foreach (var message in log)
                {
                    if (outputAllAsInfo)
                    {
                        context.TrackBuildMessage(message.Value);
                    }
                    else
                    {
                        switch (message.Key)
                        {
                        case "Info":
                            context.TrackBuildMessage(message.Value);
                            break;

                        case "Warning":
                            context.TrackBuildWarning(message.Value);
                            break;

                        case "Error":
                            context.TrackBuildError(message.Value);
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 3
0
        protected override string Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the input arguments
            string       assemblyInfoFileMask = context.GetValue(this.AssemblyInfoFileMask);
            IBuildDetail buildDetail          = context.GetValue(this.BuildDetail);

            var workspace = buildDetail.BuildDefinition.Workspace;
            var vc        = buildDetail.BuildServer.TeamProjectCollection.GetService <VersionControlServer>();

            string attribute = "AssemblyFileVersion";

            // Define the regular expression to find (which is for example 'AssemblyFileVersion("1.0.0.0")' )
            Regex regex = new Regex(attribute + @"\(""\d+\.\d+\.\d+\.\d+""\)");

            // For every workspace folder (mapping)
            foreach (var folder in workspace.Mappings)
            {
                // Get all files (recursively) that apply to the file mask
                ItemSet itemSet = vc.GetItems(folder.ServerItem + "//" + assemblyInfoFileMask, RecursionType.Full);
                foreach (Item item in itemSet.Items)
                {
                    context.TrackBuildMessage(string.Format("Download {0}", item.ServerItem));

                    // Download the file
                    string localFile = Path.GetTempFileName();
                    item.DownloadFile(localFile);

                    // Read the text from the AssemblyInfo file
                    string text = File.ReadAllText(localFile);
                    // Search for the first occurrence of the version attribute
                    Match match = regex.Match(text);
                    // When found
                    if (match.Success)
                    {
                        // Retrieve the version number
                        string  versionNumber = match.Value.Substring(attribute.Length + 2, match.Value.Length - attribute.Length - 4);
                        Version version       = new Version(versionNumber);
                        // Increase the build number -> this will be the new version number for the build
                        Version newVersion = new Version(version.Major, version.Minor, version.Build + 1, version.Revision);

                        context.TrackBuildMessage(string.Format("Version found {0}", newVersion));

                        return(newVersion.ToString());
                    }
                }
            }

            return("No version found");
        }
Esempio n. 4
0
        protected override void Execute(CodeActivityContext context)
        {
            String[]     dirty       = context.GetValue(this.TfsProjectAndBuildDefinition);
            IBuildDetail buildDetail = context.GetValue(this.BuildDetail);

            var pds = Parse(dirty);
            //var workspace = buildDetail.BuildDefinition.Workspace;
            IBuildServer buildServer = buildDetail.BuildServer;

            foreach (var pd in pds)
            {
                try
                {
                    string message = string.Format("Queue new build \"{0}\"-\"{1}\"", pd.TfsProject, pd.BuildDefinition);
                    context.TrackBuildMessage(message);

                    IBuildDefinition buildDef = buildServer.GetBuildDefinition(pd.TfsProject, pd.BuildDefinition);
                    buildServer.QueueBuild(buildDef);
                }
                catch (Exception ex)
                {
                    string message = string.Format("Queue new build error \"{0}\"-\"{1}\", Exception : \"{2}\"",
                                                   pd.TfsProject, pd.BuildDefinition, ex.Message);
                    context.TrackBuildWarning(message);
                }
            }
        }
Esempio n. 5
0
        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            var    serverConfig      = Helper.GetServerConfig(configurationFile);
            string sourcePath        = ReferencesFolder.Get(context);

            context.TrackBuildMessage("Deploying references to client and server");

            if (System.IO.Directory.Exists(sourcePath))
            {
                string clientBasePath        = string.Format(@"{0}\Microsoft\Dynamics Ax", System.Environment.GetEnvironmentVariable("localappdata"));
                IEnumerable <string> folders = System.IO.Directory.EnumerateDirectories(clientBasePath, "VSAssemblies*");
                string serverPath            = string.Format(@"{0}\VSAssemblies", serverConfig.AlternateBinDirectory);

                if (!System.IO.Directory.Exists(serverPath))
                {
                    System.IO.Directory.CreateDirectory(serverPath);
                }

                IEnumerable <string> files = System.IO.Directory.EnumerateFiles(sourcePath, "*");
                foreach (string file in files)
                {
                    foreach (string folder in folders)
                    {
                        System.IO.File.Copy(file, string.Format(@"{0}\{1}", folder, System.IO.Path.GetFileName(file)));
                    }
                    System.IO.File.Copy(file, string.Format(@"{0}\{1}", serverPath, System.IO.Path.GetFileName(file)));
                }
            }
            else
            {
                context.TrackBuildWarning(string.Format("Folder '{0}' containing reference files does not exist", sourcePath));
            }
        }
        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution environment under which the activity executes.</param>
        /// <returns>PSObject array</returns>
        protected override PSObject[] Execute(CodeActivityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var script = this.ResolveScript(
                this.BuildWorkspace.Get(context),
                this.Script.Get(context),
                this.Arguments.Get(context));

            context.TrackBuildMessage(string.Format(CultureInfo.CurrentCulture, "Script resolved to {0}", script), BuildMessageImportance.Low);

            using (var runspace = RunspaceFactory.CreateRunspace(new WorkflowPsHost(context)))
            {
                runspace.Open();

                using (var pipeline = runspace.CreatePipeline(script))
                {
                    var output = pipeline.Invoke();
                    return(output.ToArray());
                }
            }
        }
Esempio n. 7
0
        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string modelName, publisher, layer;

            CodeCrib.AX.Manage.ModelStore.ExtractModelInfo(ModelManifestFile.Get(context), out publisher, out modelName, out layer);
            var serverConfig = Helper.GetServerConfig(configurationFile);

            CodeCrib.AX.Manage.ModelStore store = null;
            if (serverConfig.AOSVersionOrigin.Substring(0, 3) == "6.0")
            {
                store = new Manage.ModelStore(serverConfig.DatabaseServer, string.Format("{0}", serverConfig.Database));
            }
            else
            {
                store = new Manage.ModelStore(serverConfig.DatabaseServer, string.Format("{0}_model", serverConfig.Database));
            }

            context.TrackBuildMessage(string.Format("Uninstalling all models from layer {0}", layer));
            store.UninstallAllLayerModels(layer);
            if (SetNoInstallMode.Get(context))
            {
                store.SetNoInstallMode();
            }
        }
Esempio n. 8
0
        public static void ReportCompileMessages(CodeActivityContext context, CodeCrib.AX.Client.CompileOutput output)
        {
            bool hasErrors = false;

            foreach (var item in output.Output)
            {
                string compileMessage = String.Format("{0}, line {1}, column {2} : {3}", item.TreeNodePath, item.LineNumber, item.ColumnNumber, item.Message);
                switch (item.Severity)
                {
                // Compile Errors
                case 0:
                    context.TrackBuildError(compileMessage);
                    hasErrors = true;
                    break;

                // Compile Warnings
                case 1:
                case 2:
                case 3:
                    context.TrackBuildWarning(compileMessage);
                    break;

                // Best practices
                case 4:
                    context.TrackBuildMessage(string.Format("BP: {0}", compileMessage), BuildMessageImportance.Low);
                    break;

                // TODOs
                case 254:
                case 255:
                    context.TrackBuildWarning(string.Format("TODO: {0}", compileMessage));
                    break;

                // "Other"
                default:
                    context.TrackBuildMessage(compileMessage);
                    break;
                }
            }
            if (hasErrors)
            {
                throw new Exception("Compile error(s) found");
            }
        }
Esempio n. 9
0
        protected override void Execute(CodeActivityContext context)
        {
            string serverName        = ServerName.Get(context);
            string databaseName      = DatabaseName.Get(context);
            string backupFilePath    = BackupFilePath.Get(context);
            string configurationFile = ConfigurationFile.Get(context);

            if (string.IsNullOrEmpty(serverName))
            {
                var serverConfig = Helper.GetServerConfig(configurationFile);
                serverName = serverConfig.DatabaseServer;
            }

            context.TrackBuildMessage(String.Format("Restoring database {0} on server {1} from file {2}", databaseName, serverName, backupFilePath));

            Sql.DbManagement.RestoreDbFromFile(serverName, databaseName, backupFilePath);

            context.TrackBuildMessage("Database restore complete");
        }
Esempio n. 10
0
        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            var    serverConfig      = CodeCrib.AX.Deploy.Configs.GetServerConfig(configurationFile);
            string serverName        = serverConfig.DatabaseServer;
            string databaseName      = serverConfig.Database;

            context.TrackBuildMessage(String.Format("Resetting admin on database {0} on server {1}", databaseName, serverName));

            Sql.DbManagement.ResetAdminUser(serverName, databaseName);
        }
Esempio n. 11
0
        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            var    serverConfig      = CodeCrib.AX.Deploy.Configs.GetServerConfig(configurationFile);
            string serverName        = serverConfig.DatabaseServer;
            string databaseName      = serverConfig.Database;

            context.TrackBuildMessage(String.Format("Disable customer experience dialog on database {0} on server {1}", databaseName, serverName));

            Sql.DbManagement.DisableCustomerExperienceDialog(serverName, databaseName);
        }
Esempio n. 12
0
        protected override void Execute(CodeActivityContext context)
        {
            string serverName          = ServerName.Get(context);
            string databaseName        = DatabaseName.Get(context);
            string backupFilePath      = BackupFilePath.Get(context);
            bool   overwriteBackupSets = OverwriteBackupSets.Get(context);
            bool   forceCompressionOn  = ForceCompressionOn.Get(context);
            string configurationFile   = ConfigurationFile.Get(context);

            if (string.IsNullOrEmpty(serverName))
            {
                var serverConfig = Helper.GetServerConfig(configurationFile);
                serverName = serverConfig.DatabaseServer;
            }

            context.TrackBuildMessage(String.Format("Backing up database {0} from server {1} to file {2}", databaseName, serverName, backupFilePath));

            Sql.DbManagement.BackupDbToFile(serverName, databaseName, backupFilePath, true, overwriteBackupSets, forceCompressionOn);

            context.TrackBuildMessage("Database backup complete");
        }
        private int RunProcess(CodeActivityContext context, string fullPath, string workingDirectory, string arguments)
        {
            context.TrackBuildMessage("fullPath: " + fullPath, BuildMessageImportance.Low);
            context.TrackBuildMessage("workingDir: " + workingDirectory, BuildMessageImportance.Low);
            context.TrackBuildMessage("arguments: " + arguments, BuildMessageImportance.Low);
            using (Process proc = new Process())
            {
                proc.StartInfo.FileName = fullPath;

                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.Arguments = arguments;
                context.TrackBuildMessage("Running " + proc.StartInfo.FileName + " " + proc.StartInfo.Arguments, BuildMessageImportance.High);

                if (!string.IsNullOrEmpty(workingDirectory))
                {
                    proc.StartInfo.WorkingDirectory = workingDirectory;
                }

                proc.Start();

                string outputStream = proc.StandardOutput.ReadToEnd();
                if (outputStream.Length > 0)
                {
                    context.TrackBuildMessage(outputStream, BuildMessageImportance.Normal);
                }

                string errorStream = proc.StandardError.ReadToEnd();
                if (errorStream.Length > 0)
                {
                    context.TrackBuildError(errorStream);
                }

                proc.WaitForExit();
                context.TrackBuildMessage("Exit Code: " + proc.ExitCode, BuildMessageImportance.Low);
                return proc.ExitCode;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Execute Activity
        /// </summary>
        /// <param name="context">code activity context </param>
        protected override void Execute(CodeActivityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var directoryInfo = context.GetValue(this.BaseDirectory);

            if (!directoryInfo.Exists)
            {
                return;
            }

            var searchDescription = context.GetValue(this.SearchDescription);
            var fileExtensions    = context.GetValue(this.FileExtensions);

            var searchStrings = context.GetValue(this.SearchStrings);

            if (searchStrings == null || searchStrings.Length == 0)
            {
                return;
            }

            var matches = directoryInfo.Search(fileExtensions, searchStrings);

            // Write to build outputs log
            context.TrackBuildMessage(string.Format("{0}: {1} items found.", searchDescription, matches.Count), BuildMessageImportance.High);
            foreach (var match in matches)
            {
                var fileAndLine = string.Format("{0} ({1})", match.File.Name, match.LineNumber);
                context.TrackBuildMessage(string.Format("{0,-50} {1}", fileAndLine, match.LineText.Trim()), BuildMessageImportance.High);
            }

            // Set output
            this.MatchCount.Set(context, matches.Count);
        }
Esempio n. 15
0
        protected override void Execute(CodeActivityContext context)
        {
            // Mapeamento dos parametros para variaveis:
            string tfsServer          = context.GetValue(this.TFSServer);
            string tfsCollection      = context.GetValue(this.TFSCollection);
            string tfsProject         = context.GetValue(this.TFSProject);
            string tfsUser            = context.GetValue(this.TFSUser);
            string tfsPassword        = context.GetValue(this.TFSPassword);
            string tfsDomain          = context.GetValue(this.TFSDomain);
            string envEnvironmentName = context.GetValue(this.EnvEnvironmentName);

            try
            {
                #region Client do TFS e Lab Service

                System.Net.NetworkCredential administratorCredentials =
                    new System.Net.NetworkCredential(tfsUser, tfsPassword, tfsDomain);

                string tfsName = tfsServer + "/" + tfsCollection;
                Uri    uri     = new Uri(tfsName);
                TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(uri, administratorCredentials);

                LabService lab = tfs.GetService <LabService>();

                if (lab == null)
                {
                    throw new System.ArgumentOutOfRangeException("Lab Service não encontrado.");
                }

                #endregion

                #region Obtém o ambiente

                var env = lab.GetLabEnvironments(tfsProject).FirstOrDefault(c => c.Name == envEnvironmentName);

                if (env != null)
                {
                    context.TrackBuildMessage("Ambiente encontrado sob URI: '" + env.Uri.ToString() + "'.", BuildMessageImportance.High);
                    context.SetValue(this.Result, env);
                    context.SetValue(this.ResultUri, env.Uri.ToString());
                }

                #endregion
            }
            catch (Exception ex)
            {
                context.TrackBuildError("Ambiente não pode ser obtido:  " + ex.ToString() + ".");
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Extension method to help writing messages to the build context
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <param name="messageImportance"></param>
        public static void WriteBuildMessage(this CodeActivityContext context, string message, BuildMessageImportance messageImportance)
        {
            if (context != null)
            {
                context.TrackBuildMessage(message, messageImportance);
                //{
                //    Value = new BuildMessage
                //                {
                //                    Importance = messageImportance,

                //                    Message = message,
                //                },
                //});
            }
        }
        /// <summary>
        /// Executes the activity
        /// </summary>
        /// <param name="context">The activity's context</param>
        protected override void Execute(CodeActivityContext context)
        {
            //context.Track(new CustomTrackingRecord("olalá", TraceLevel.Info));
            context.TrackBuildMessage("Starting", BuildMessageImportance.High);
            //context.TrackBuildError("Starting");
            WorkingFolder workingFolder =
                Workspace.Get(context).GetWorkingFolderForServerItem(SourcesDirectory.Get(context));

            var sourcesDirectory = workingFolder.LocalItem;

            context.TrackBuildWarning(string.Format("Getting js files from {0}", sourcesDirectory), BuildMessageImportance.High);
            var jsFiles = Directory.GetFiles(sourcesDirectory, "*.js");

            foreach (var jsFile in jsFiles)
            {
                context.TrackBuildWarning(string.Format("Passing tests from {0}", jsFile), BuildMessageImportance.High);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Execute
        /// </summary>
        /// <param name="context">context</param>
        /// <returns>string</returns>
        protected override string Execute(CodeActivityContext context)
        {
            // Get the message
            string myMessage = "Hello " + this.Message.Get(context);

            // Get the second message
            myMessage += this.Message2.Get(context);

            // Get the current BuildNumber using the GetExtension method
            string tfsBuildNumber = context.GetExtension <IBuildDetail>().BuildNumber;

            // add the build number to the message
            myMessage += " from " + tfsBuildNumber;

            // log it to the build output
            context.TrackBuildMessage(myMessage, BuildMessageImportance.High);

            // return the message
            return(myMessage);
        }
Esempio n. 19
0
        public static void Output(CodeActivityContext context, Client.AutoRun.AxaptaAutoRun autoRun, bool outputAllAsInfo = false, bool skipInfoLog = false)
        {
            autoRun.ParseLog();

            //OutputLog(context, autoRun.Log, outputAllAsInfo);

            foreach (var step in autoRun.Steps)
            {
                OutputLog(context, step.Log, outputAllAsInfo);
            }

            if (!skipInfoLog && !string.IsNullOrEmpty(autoRun.InfoLog))
            {
                var lines = autoRun.InfoLog.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                foreach (string line in lines)
                {
                    context.TrackBuildMessage(line.Trim());
                }
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            string resultFileToPublish = this.ResultFileToPublish.Get(context);

            string resultTrxFile = Path.Combine(Path.GetDirectoryName(resultFileToPublish), Path.GetFileNameWithoutExtension(resultFileToPublish) + ".trx");

            if (!File.Exists(resultFileToPublish))
            {
                //this could be normal if there were no tests in the file
                context.TrackBuildMessage("Could not find results file: " +  resultFileToPublish  +", skipping publish activity", BuildMessageImportance.Low);
                return;
            }

            this.TransformNUnitToMSTest(context, resultFileToPublish, resultTrxFile);

            var buildDetail = context.GetExtension<IBuildDetail>();
            string collectionUrl = buildDetail.BuildServer.TeamProjectCollection.Uri.ToString();
            string buildNumber = buildDetail.BuildNumber;
            string teamProject = buildDetail.TeamProject;
            string platform = BuildSettings.Get(context).PlatformConfigurations[0].Platform;
            string flavor = BuildSettings.Get(context).PlatformConfigurations[0].Configuration;
            this.PublishMSTestResults(context, resultTrxFile, collectionUrl, buildNumber, teamProject, platform, flavor);
        }
Esempio n. 21
0
        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string modelFile = ModelFile.Get(context);
            string axutilFolder = AxUtilBinaryFolder.Get(context);
            string modelName, publisher, layer;

            CodeCrib.AX.Manage.ModelStore.ExtractModelInfo(ModelManifestFile.Get(context), out publisher, out modelName, out layer);
            string keyFile      = StrongNameKeyFile.Get(context);
            var    serverConfig = Helper.GetServerConfig(configurationFile);

            CodeCrib.AX.Manage.ModelStore store = null;
            if (serverConfig.AOSVersionOrigin.Substring(0, 3) == "6.0")
            {
                store = new Manage.ModelStore(serverConfig.DatabaseServer, string.Format("{0}", serverConfig.Database), axutilFolder);
            }
            else
            {
                store = new Manage.ModelStore(serverConfig.DatabaseServer, string.Format("{0}_model", serverConfig.Database), axutilFolder);
            }

            context.TrackBuildMessage(string.Format("Exporting model {0} ({1})", modelName, publisher));
            store.ExportModel(modelName, publisher, modelFile, keyFile);
        }
Esempio n. 22
0
        protected override void Execute(CodeActivityContext context)
        {
            bool   updateXRef     = UpdateCrossReference.Get(context);
            int    timeOutMinutes = TimeOutMinutes.Get(context);
            string clientExePath  = ClientExecutablePath.Get(context);

            StringList aotCompilePaths = AOTCompilePaths.Get(context);

            if (aotCompilePaths == null ||
                aotCompilePaths.Count == 0)
            {
                // Nothing to do.
                return;
            }

            string configurationFile = ConfigurationFile.Get(context);

            Client.Commands.AutoRun command = new Client.Commands.AutoRun
            {
                LazyClassLoading = true,
                LazyTableLoading = true,
                Minimize         = true
            };

            if (!string.IsNullOrEmpty(configurationFile))
            {
                command.ConfigurationFile = configurationFile;
            }

            StringList layerCodes = LayerCodes.Get(context);

            if (layerCodes != null)
            {
                string modelManifest = ModelManifestFile.Get(context);
                if (!string.IsNullOrEmpty(modelManifest))
                {
                    string model;
                    string publisher;
                    string layer;
                    string layerCode;

                    Helper.ExtractClientLayerModelInfo(configurationFile, layerCodes, modelManifest, out model, out publisher, out layer, out layerCode);

                    command.Model          = model;
                    command.ModelPublisher = publisher;
                    command.Layer          = layer;
                    command.LayerCode      = layerCode;
                }
            }

            Client.AutoRun.AxaptaAutoRun axaptaAutoRun = new Client.AutoRun.AxaptaAutoRun()
            {
                ExitWhenDone = true
            };

            foreach (string path in aotCompilePaths)
            {
                axaptaAutoRun.Steps.Add(new Client.AutoRun.CompileApplication()
                {
                    UpdateCrossReference = false,
                    Node = path
                });
            }

            string autorunFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Client.AutoRun.AxaptaAutoRun.SerializeAutoRun(axaptaAutoRun, autorunFilename);
            command.Filename = autorunFilename;

            context.TrackBuildMessage("Compiling individual AOT nodes");

            if (string.IsNullOrEmpty(clientExePath))
            {
                Client.Client.ExecuteCommand(command, timeOutMinutes);
            }
            else
            {
                Client.Client.ExecuteCommand(clientExePath, command, timeOutMinutes);
            }

            // Compile log is not parsed at this point.  We expect to
            // run a full compile at a later step to get the compile results.
        }
 /// <summary>
 /// Logs the specified informational message.
 /// </summary>
 /// <param name="message">The message.</param>
 public void Message(string message)
 {
     _context.TrackBuildMessage(message);
 }
        private void TransformNUnitToMSTest(CodeActivityContext context, string nunitResultFile, string mstestResultFile)
        {
            context.TrackBuildMessage("input file: " + nunitResultFile);
            context.TrackBuildMessage("output file: " + mstestResultFile);
            Stream s = this.GetType().Assembly.GetManifestResourceStream("CustomBuildActivities.NUnitToMSTest.xslt");
            if (s == null)
            {
                context.TrackBuildError("Could not load NUnitToMSTest.xslt from embedded resources");
                return;
            }

            using (var reader = new XmlTextReader(s))
            {
                XslCompiledTransform transform = new XslCompiledTransform();
                transform.Load(reader);
                transform.Transform(nunitResultFile, mstestResultFile);
            }
        }
        /// <summary>
        /// Execute Activity
        /// </summary>
        /// <param name="context">code activity context </param>
        protected override void Execute(CodeActivityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var directoryInfo = context.GetValue(this.BaseDirectory);
            if (!directoryInfo.Exists)
            {
                return;
            }

            var searchDescription = context.GetValue(this.SearchDescription);
            var fileExtensions = context.GetValue(this.FileExtensions);

            var searchStrings = context.GetValue(this.SearchStrings);
            if (searchStrings == null || searchStrings.Length == 0)
            {
                return;
            }

            var matches = directoryInfo.Search(fileExtensions, searchStrings);

            // Write to build outputs log
            context.TrackBuildMessage(string.Format("{0}: {1} items found.", searchDescription, matches.Count), BuildMessageImportance.High);
            foreach (var match in matches)
            {
                var fileAndLine = string.Format("{0} ({1})", match.File.Name, match.LineNumber);
                context.TrackBuildMessage(string.Format("{0,-50} {1}", fileAndLine, match.LineText.Trim()), BuildMessageImportance.High);
            }

            // Set output
            this.MatchCount.Set(context, matches.Count);
        }
        /// <summary>
        /// Override Execute method for custom build activity.
        /// </summary>
        /// <param name="context">CodeActivityContext context contains arguments including the InstallShieldProjectFullPath.</param>
        protected override void Execute(CodeActivityContext context)
        {
            Workspace workspace          = context.GetValue(this.Workspace);
            string    deliverablesFolder = context.GetValue <string>(this.DeliverablesFolder);
            string    binariesFolder     = context.GetValue(this.BinariesFolder);
            bool      isVersionedBuild   = context.GetValue <bool>(this.IsVersionedBuild);

            if (!String.IsNullOrEmpty(deliverablesFolder.Trim()))
            {
                if (context.GetValue <bool>(this.IsVersionedBuild))
                {
                    int majorVersion   = context.GetValue <int>(this.MajorVersion);
                    int minorVersion   = context.GetValue <int>(this.MinorVersion);
                    int ternaryVersion = context.GetValue <int>(this.TernaryVersion);

                    deliverablesFolder = Path.Combine(deliverablesFolder, String.Join(".", majorVersion, minorVersion, ternaryVersion));
                }

                workspace.Map(deliverablesFolder, binariesFolder);

                // if the deliverablesFolder does not exist, PendAdd it so we can add individual files to that folder
                if (!workspace.VersionControlServer.ServerItemExists(deliverablesFolder, ItemType.Folder))
                {
                    workspace.PendAdd(binariesFolder, false);
                    context.TrackBuildMessage(String.Format("Created pending DIRECTORY ADD change for {0} to {1}", binariesFolder, deliverablesFolder), BuildMessageImportance.Low);
                }

                // loop through each file to PendAdd to source control
                foreach (string localFile in Directory.GetFiles(binariesFolder, "*.*", SearchOption.AllDirectories))
                {
                    string fileSubPath = localFile.Remove(0, binariesFolder.Length + 1);
                    string serverFile  = Path.Combine(deliverablesFolder, fileSubPath).Replace(@"\", "/");

                    try
                    {
                        // If the RegExpr is an empty string, all files will Match successfully
                        Match match = Regex.Match(
                            fileSubPath, context.GetValue <string>(this.Regexpr), RegexOptions.IgnoreCase);

                        // Move onto next file if the file is not a match
                        if (match.Success != true)
                        {
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        context.TrackBuildMessage(String.Format("Invalid Regular Expression: {0} exception: {1} Aborting Check-In", context.GetValue <string>(this.Regexpr), ex.Message), BuildMessageImportance.Normal);
                        return;
                    }

                    if (workspace.VersionControlServer.ServerItemExists(serverFile, ItemType.File))
                    {
                        byte[] updatedFileContents = File.ReadAllBytes(localFile);

                        workspace.Get(new GetRequest(serverFile, RecursionType.None, VersionSpec.Latest), GetOptions.Overwrite);
                        workspace.PendEdit(serverFile, RecursionType.None);

                        byte[] sourceControlFileContents = File.ReadAllBytes(localFile);
                        if (!updatedFileContents.SequenceEqual(sourceControlFileContents))
                        {
                            File.WriteAllBytes(localFile, updatedFileContents);
                        }

                        context.TrackBuildMessage(String.Format("Created pending FILE EDIT change for {0} to {1}", localFile, serverFile), BuildMessageImportance.Low);
                    }
                    else
                    {
                        workspace.PendAdd(localFile);
                        context.TrackBuildMessage(String.Format("Created pending FILE ADD change for {0} to {1}", localFile, serverFile), BuildMessageImportance.Low);
                    }
                }

                // Check in pending changes if they exist
                PendingChange[] pendingChanges = workspace.GetPendingChanges();
                if (pendingChanges != null)
                {
                    context.TrackBuildMessage(String.Format("Checking in {0} binaries into source control", pendingChanges.Length));

                    // Checks all files in in the workspace that have pending changes
                    // The ***NO_CI*** comment ensures that the CI build is not triggered (and that
                    // you end in an endless loop).
                    bool   isNoCidBuild = context.GetValue <bool>(this.IsNoCiBuild);
                    string comment      = "***NO_CI***";

                    if (!isNoCidBuild)
                    {
                        comment = "";
                    }

                    workspace.CheckIn(pendingChanges, "Build Agent", comment, null, null, new PolicyOverrideInfo("Auto checkin", null), CheckinOptions.SuppressEvent);
                }
            }
        }