/// <summary>
        /// Zips the source files.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        /// <param name="sourceDirectory">The source directory.</param>
        public static void ZipSourceFiles(
            BuildControlParameters configuration,
            DailyBuildFullResults results,
            string sourceDirectory)
        {
            string archive = Path.Combine(sourceDirectory, SourceArchiveName);

            try
            {
                string heroAppSource = FindHeroAppSourceFolder(configuration);
                using (ZipFile zip = new ZipFile(archive))
                {
                    for (Int32 i = 0; i < configuration.Projects.Length; i++)
                    {
                        if (configuration.Projects[i].BuildConfiguration != BuildProjectControl.None)
                        {
                            string appFolder = Path.Combine(heroAppSource, configuration.Projects[i].ProjectPath);
                            zip.AddDirectory(appFolder, configuration.Projects[i].ProjectPath);
                        }
                    }
                    zip.Save();
                }
            }
            catch (Exception e)
            {
                ProgramExecutionLog.AddEntry(
                    "Failed to archive source files" +
                    " Error was " + e.Message);
            }
        }
        /// <summary>
        /// Reverts the build version files.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        private static void RevertBuildVersionFiles(
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            string heroAppSource = FindHeroAppSourceFolder(configuration);

            for (Int32 i = 0; i < configuration.Projects.Length; i++)
            {
                string assemblyFile = "";
                try
                {
                    string appFolder = Path.Combine(heroAppSource, configuration.Projects[i].ProjectPath);
                    assemblyFile = Path.Combine(appFolder, configuration.Projects[i].AssemblyFilePathAndNameFromProjectRoot);
                    ProcessInformation process = ProcessOperations.SDRevert(configuration, assemblyFile);
                    CheckForErrorFromSDOperation(process, results, results.BuildTargets[i].RevertVersion);
                    results.BuildTargets[i].RevertVersion.Success = true;
                }
                catch (Exception e)
                {
                    ProgramExecutionLog.AddEntry(
                        "Failed to revert  file " + assemblyFile + " Exception information was " +
                        e.ToString());
                    results.BuildTargets[i].RevertVersion.SetResults(false, e.Message);
                }
            }
        }
 /// <summary>
 /// Resets the specified configuration.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 public void Reset(BuildControlParameters configuration)
 {
     this.EnlistmentSync.Reset();
     this.UninstallWdpt.Reset();
     this.InstallWdpt.Reset();
     this.ModifyWdpt.Reset();
     this.UninstallYdr.Reset();
     this.InstallYdr.Reset();
     this.PublishToReleaseShare.Reset();
     this.EmailBuildResults.Reset();
     this.BuildTargets = null;
     this.InitializeBuildTargetResults(configuration);
     this.EnlistmentSync.RequestedToRun = configuration.SyncEnlistment;
     this.UninstallWdpt.RequestedToRun  = configuration.UpdateWpdt;
     this.InstallWdpt.RequestedToRun    = configuration.UpdateWpdt;
     this.UninstallYdr.RequestedToRun   = configuration.UpdateYdr;
     this.InstallYdr.RequestedToRun     = configuration.UpdateYdr;
     if (configuration.UpdateWpdt)
     {
         this.ModifyWdpt.RequestedToRun = configuration.InstallOnW2k8;
     }
     else
     {
         this.ModifyWdpt.RequestedToRun = false;
     }
     this.PublishToReleaseShare.RequestedToRun = true;
     this.EmailBuildResults.RequestedToRun     = configuration.EmailResults;
 }
        /// <summary>
        /// Load the measurement configuration with a supplied filename. This will
        /// normally be called as part of the command line options where the
        /// file name is supplied in the command arguments
        /// </summary>
        /// <param name="fileName">Config file name</param>
        /// <param name="showExceptionDialog">True if we want to show the user an exception dialog
        /// If false, the exception will not be caught.</param>
        /// <returns>BDC Settings</returns>
        public static BuildControlParameters LoadConfiguration(string fileName)
        {
            BuildControlParameters ret = null;

            try
            {
                XmlSerializer mySerializer = new XmlSerializer(typeof(BuildControlParameters));
                // To read the file, create a FileStream.
                FileStream myFileStream = new FileStream(fileName, FileMode.Open);
                // Call the Deserialize method and cast to the object type.
                ret = (BuildControlParameters)mySerializer.Deserialize(myFileStream);
                myFileStream.Close();
            }
            catch (FileNotFoundException e)
            {
                ProgramExecutionLog.AddEntry("Configuration file " + fileName +
                                             " was not found! Error was " + e.Message);
            }
            if (ret != null)
            {
                // For backwards compatibility, set the default to the HeroApps build
                // folder if this is not specified in the configuration file.
                if (String.IsNullOrEmpty(ret.ApplicationParentFolderName))
                {
                    ret.ApplicationParentFolderName = ApplicationParentDefaultFolderName;
                }
            }
            return(ret);
        }
 /// <summary>
 /// Sends the result via email.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 /// <param name="results">The results.</param>
 private static void SendResultViaEmail(
     BuildControlParameters configuration,
     DailyBuildFullResults results)
 {
     Console.WriteLine("Emailing results ....");
     EmailOpsOrig.SendMailtoExchange(configuration.EmailFromAlias, configuration, results);
     Console.WriteLine("Completed mailing of results");
 }
Esempio n. 6
0
        /// <summary>
        /// Call sd sync command for the enlistment
        /// </summary>
        /// <param name="configuration">Main program configuration</param>
        /// <param name="fileName">File name to have the sd command execute on</param>
        /// <returns>ProcessInformation, so the caller can look at the return code etc</returns>
        public static ProcessInformation SDSync(
            BuildControlParameters configuration)
        {
            string             arguments = "sync ";
            ProcessInformation procInfo  = SDCommand(configuration, ".", arguments);

            return(procInfo);
        }
Esempio n. 7
0
        /// <summary>
        /// Call sd edit command on the given input file
        /// </summary>
        /// <param name="configuration">Main program configuration</param>
        /// <param name="fileName">File name to have the sd command execute on</param>
        /// <returns>ProcessInformation, so the caller can look at the return code etc</returns>
        public static ProcessInformation SDEdit(
            BuildControlParameters configuration,
            string fileName)
        {
            string             arguments = "edit " + Path.GetFileName(fileName);
            ProcessInformation procInfo  = SDCommand(configuration, fileName, arguments);

            return(procInfo);
        }
Esempio n. 8
0
        /// <summary>
        /// Call sd Revert command on the given input file
        /// </summary>
        /// <param name="configuration">Main program configuration</param>
        /// <param name="fileName">File name to have the sd command execute on</param>
        /// <returns>ProcessInformation, so the caller can look at the return code etc</returns>
        public static ProcessInformation SDRevert(
            BuildControlParameters configuration,
            string fileName)
        {
            string             arguments = "revert " + fileName;
            ProcessInformation procInfo  = SDCommand(configuration, fileName, arguments);

            return(procInfo);
        }
        /// <summary>
        /// This function will send email messages for either a success or failed work item.
        /// The checking will be done whether we should send the mail messages, and mail
        /// will be sent for either success or fail
        /// </summary>
        public static void SendMailtoExchange(
            string senderEmailAddress,
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            if (configuration.EmailResults)
            {
                MailMessage message;
                SmtpClient  client;
                String      subject;
                try
                {
                    client                       = new SmtpClient(SmtpServer);
                    message                      = new MailMessage();
                    message.IsBodyHtml           = true;
                    client.UseDefaultCredentials = true;
                    MailAddress from = new MailAddress(senderEmailAddress + @"@microsoft.com");
                    message.From = from;
                    subject      = "Hero Apps Daily Build Status for: " + DateTime.Now.ToString("MM/dd/yyyy");
                    message.To.Add(new MailAddress(configuration.EmailAlias + @"@microsoft.com"));
                    message.Subject = subject;
                }
                catch (Exception e)
                {
                    ProgramExecutionLog.AddEntry("Email SMTP, send address or to address failure." + e.Message);
                    return;
                }

                try
                {
                    // No point sending if there are none in the email list
                    if (message.To.Count > 0)
                    {
                        message.Body += "\n\n";
                        message.Body  = results.MakeHeroAppsReport(configuration);
                        client.Send(message);
                        Debug.WriteLine("Sent WI email with subject: " + message.Subject);
                    }
                }
                catch (SmtpFailedRecipientException e)
                {
                    ProgramExecutionLog.AddEntry("Partial email send failure. " + e.Message);
                }
                catch (ArgumentException e)
                {
                    ProgramExecutionLog.AddEntry("Email send failure. " + e.Message);
                }
                catch (InvalidOperationException e)
                {
                    ProgramExecutionLog.AddEntry("Email send failure. " + e.Message);
                }
                catch (SmtpException e)
                {
                    ProgramExecutionLog.AddEntry("Email send failure. " + e.Message);
                }
            }
        }
        /// <summary>
        /// Save the program configuration to disk
        /// </summary>
        /// <param name="config">Configuration settings</param>
        /// <param name="directoryForSave">Directory where to save the file</param>
        /// <param name="fileName">File name to use for the saving of the file</param>
        public static void SaveConfiguration(
            BuildControlParameters config,
            string directoryForSave,
            string fileName)
        {
            string fullPath = Path.Combine(directoryForSave, fileName);

            WriteConfiguration(config, fullPath);
        }
 /// <summary>
 /// Initializes the build target results.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 public void InitializeBuildTargetResults(BuildControlParameters configuration)
 {
     BuildTargets = new BuildTargetResults[configuration.Projects.Length];
     for (Int32 i = 0; i < configuration.Projects.Length; i++)
     {
         BuildTargets[i] = new BuildTargetResults();
         BuildTargets[i].ProjectTargetName = configuration.Projects[i].ProjectPath;
         BuildTargets[i].Reset(configuration);
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Execute a sd command
        /// </summary>
        /// <param name="configuration">Main Program configuration</param>
        /// <param name="fileName">File name to perform the SD command on</param>
        /// <param name="arguments">Filled out argument string that will contain the sd command as
        /// well as the file to operate on.</param>
        /// <returns></returns>
        private static ProcessInformation SDCommand(
            BuildControlParameters configuration,
            string fileName,
            string arguments)
        {
            string             progName         = Path.Combine(configuration.PathForSourceDepotProgram, "sd.exe");
            string             workingDirectory = Path.GetDirectoryName(fileName);
            ProcessInformation procInfo         = RunProcess(progName, workingDirectory, arguments, true);

            return(procInfo);
        }
        /// <summary>
        /// Creates the build script and execute.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        public static void CreateBuildScriptAndExecute(
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            string heroAppSource = FindHeroAppSourceFolder(configuration);

            if (String.IsNullOrEmpty(heroAppSource))
            {
                Console.WriteLine("Could not find Application Parent Folder. Aborting ...");
                ProgramExecutionLog.AddEntry("Could not find Application Parent Folder. Aborting ...");
                return;
            }

            Console.Write("Starting Build/Sign/License Process... ");
            GeneralFileOperations.WriteProgramStatusFile(ExecutionStatus.Running);
            if (configuration.BuildType == BuildTypeEnum.Daily &&
                configuration.UpdateDailyBuildVersion)
            {
                bool allCompletedWithSuccess = ModifyBuildVersionFiles(configuration, results);
                Console.WriteLine("Completed Modifying Revision Files. Overall status was " +
                                  allCompletedWithSuccess.ToString());
            }
            else
            {
                foreach (BuildTargetResults t in results.BuildTargets)
                {
                    t.ModifyVersion.RequestedToRun = false;
                }
            }
            Console.WriteLine("Completed!");
            Console.Write("Beginning to create batch file for build/sign/license operations ... ");
            string commandFile = BuildBatchFile(configuration, results);

            Console.WriteLine("Completed. Running batch file ....");
            ProcessOperations.RunProcess(commandFile, App.StartupPath, "", true);
            Console.WriteLine("Batch File completed. Status not reported here");
            ValidateBuildResults(configuration, results);
            PublishBuildOutput(configuration, results);
            if (configuration.BuildType == BuildTypeEnum.Daily &&
                configuration.UpdateDailyBuildVersion)
            {
                RevertBuildVersionFiles(configuration, results);
            }

            if (configuration.EmailResults)
            {
                SendResultViaEmail(configuration, results);
            }
        }
 /// <summary>
 /// Write to config file
 /// </summary>
 /// <param name="config">BDC config settings</param>
 /// <param name="fileName">Config file</param>
 private static void WriteConfiguration(BuildControlParameters config, string fileName)
 {
     try
     {
         XmlSerializer mySerializer = new XmlSerializer(typeof(BuildControlParameters));
         // To write to a file, create a StreamWriter object.
         StreamWriter myWriter = new StreamWriter(fileName);
         mySerializer.Serialize(myWriter, config);
         myWriter.Close();
     }
     catch (Exception e)
     {
         ProgramExecutionLog.AddEntry("Configuration file " + fileName +
                                      " could not be written to disk! Error was " + e.Message);
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Helper function that will check to see if a file has a read only
        /// attribute set. If it does, then the attribute is removed.
        /// </summary>
        /// <param name="configuration">Main program configuration</param>
        /// <param name="fullFileName">File Name to check for read only attribute</param>
        public static void RemoveReadOnlyAttribute(
            BuildControlParameters configuration,
            string fullFileName)
        {
            FileInfo f = new FileInfo(fullFileName);

            if ((f.Attributes & FileAttributes.ReadOnly) != 0)
            {
                if (configuration.SourceDepotOnlineMode)
                {
                    ProcessOperations.SDEdit(configuration, fullFileName);
                }
                else
                {
                    f.Attributes = f.Attributes & ~FileAttributes.ReadOnly;
                }
            }
        }
Esempio n. 16
0
        public void Reset(BuildControlParameters configuration)
        {
            Build.Reset();
            ModifyVersion.Reset();
            RevertVersion.Reset();
            SignXap.Reset();
            LicenseXap.Reset();

            if (configuration.BuildType == BuildTypeEnum.None)
            {
                Build.StatusToNotRun();
                ModifyVersion.StatusToNotRun();
                RevertVersion.StatusToNotRun();
                SignXap.StatusToNotRun();
                LicenseXap.StatusToNotRun();
            }
            if (!configuration.UpdateDailyBuildVersion)
            {
                ModifyVersion.StatusToNotRun();
                RevertVersion.StatusToNotRun();
            }
        }
 /// <summary>
 /// Syncs the enlistment.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 /// <param name="results">The results.</param>
 public static void SyncEnlistment(
     BuildControlParameters configuration,
     DailyBuildFullResults results)
 {
     Console.Write("Syncing Enlistment ... ");
     GeneralFileOperations.WriteProgramStatusFile(ExecutionStatus.SynEnlistment);
     try
     {
         ProcessInformation process = ProcessOperations.SDSync(configuration);
         CheckForErrorFromSDOperation(process, results, results.EnlistmentSync);
         Console.WriteLine("Success!");
     }
     catch (Exception e)
     {
         Console.WriteLine("Fail!");
         results.EnlistmentSync.SetResults(false, e.Message);
         ProgramExecutionLog.AddEntry(
             "Failed to sync enlistment " +
             " Error was " + e.Message);
     }
     Console.WriteLine("Enlistment Sync Status = " + results.EnlistmentSync.ToString());
 }
        /// <summary>
        /// Finds the hero app source folder.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <returns></returns>
        private static string FindHeroAppSourceFolder(BuildControlParameters configuration)
        {
            try
            {
                DirectoryInfo current       = new DirectoryInfo(App.StartupPath);
                DirectoryInfo heroAppSource = current;
                do
                {
                    heroAppSource = heroAppSource.Parent;
                }while (heroAppSource.Name.ToLower() !=
                        configuration.ApplicationParentFolderName.ToLower());
                return(heroAppSource.FullName);
            }

            catch (Exception e)
            {
                ProgramExecutionLog.AddEntry(
                    "Failed to find Application parent source folder" +
                    " Error was " + e.Message);
                return(null);
            }
        }
        /// <summary>
        /// Modifies the build version files.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        private static bool ModifyBuildVersionFiles(
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            bool   allCompletedWithSuccess = true;
            string heroAppSource           = FindHeroAppSourceFolder(configuration);

            if (!String.IsNullOrEmpty(heroAppSource))
            {
                DateTime currentTime = DateTime.Now;
                for (Int32 i = 0; i < configuration.Projects.Length; i++)
                {
                    results.BuildTargets[i].BuildStartTime = currentTime;
                    string appFolder    = Path.Combine(heroAppSource, configuration.Projects[i].ProjectPath);
                    string assemblyFile = Path.Combine(appFolder, configuration.Projects[i].AssemblyFilePathAndNameFromProjectRoot);
                    if (File.Exists(assemblyFile))
                    {
                        try
                        {
                            ProcessInformation process = ProcessOperations.SDEdit(configuration, assemblyFile);
                            CheckForErrorFromSDOperation(process, results, results.BuildTargets[i].ModifyVersion);
                            string[] assemblyFileContents = File.ReadAllLines(assemblyFile);
                            for (Int32 j = 0; j < assemblyFileContents.Length; j++)
                            {
                                if (assemblyFileContents[j].ToLower().Contains(RevisionFileStringBase.ToLower()))
                                {
                                    string   v        = assemblyFileContents[j];
                                    string[] versions = v.Split('.');
                                    if (versions.Length >= 3)
                                    {
                                        versions[2] = CreateDateTimeFormatString(currentTime);
                                    }
                                    v = "";
                                    for (Int32 k = 0; k < versions.Length; k++)
                                    {
                                        v += versions[k] + ".";
                                    }

                                    assemblyFileContents[j] = v.TrimEnd('.');
                                    break;
                                }
                            }
                            File.WriteAllLines(assemblyFile, assemblyFileContents);
                            results.BuildTargets[i].ModifyVersion.Success = true;
                        }
                        catch (Exception e)
                        {
                            results.BuildTargets[i].ModifyVersion.SetResults(false, e.Message);
                            ProgramExecutionLog.AddEntry(
                                "Failed to modify  file " + assemblyFile + " Exception information was " +
                                e.ToString());
                            allCompletedWithSuccess = false;
                        }
                    }
                    else
                    {
                        string errorMessage = "Assembly File did not exist. Path was " +
                                              assemblyFile;
                        results.BuildTargets[i].ModifyVersion.SetResults(false,
                                                                         errorMessage);
                        ProgramExecutionLog.AddEntry(errorMessage);
                        allCompletedWithSuccess = false;
                    }
                }
            }
            else
            {
                return(false);
            }
            return(allCompletedWithSuccess);
        }
        /// <summary>
        /// Validates the build results.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        private static void ValidateBuildResults(
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            Console.Write("Beginning validation of Build target results... ");
            string        heroAppSource   = FindHeroAppSourceFolder(configuration);
            string        outputPath      = configuration.BuildOutputPath;
            string        licensePath     = Path.Combine(outputPath, LicenseSubDirectory);
            List <string> installScript   = new List <string>();
            List <string> uninstallScript = new List <string>();
            string        quote           = "\"";
            string        deviceList      = quote + @"%ProgramFiles%\Zune\updatewp.exe" + quote + " /list";

            installScript.Add(deviceList);
            uninstallScript.Add(deviceList);

            for (Int32 i = 0; i < configuration.Projects.Length; i++)
            {
                try
                {
                    string xapName           = Path.GetFileName(configuration.Projects[i].XapPathAndNameFromProjectRoot);
                    string xapNameNoExt      = Path.GetFileNameWithoutExtension(configuration.Projects[i].XapPathAndNameFromProjectRoot);
                    string xapNameBeforeSign = xapName + BuildControlParameters.SignedXapOrigFileExtension;
                    string licenseName       = xapNameNoExt + BuildControlParameters.LicenseNameAddition;
                    results.BuildTargets[i].Build.Success      = File.Exists(Path.Combine(configuration.BuildOutputPath, xapName));
                    results.BuildTargets[i].SignXap.Success    = File.Exists(Path.Combine(configuration.BuildOutputPath, xapNameBeforeSign));
                    results.BuildTargets[i].LicenseXap.Success = File.Exists(Path.Combine(licensePath, licenseName));
                    installScript.Add(RelativePathToWpapp + WpappProgramPathAndName
                                      + " i " + Path.Combine(configuration.BuildOutputPath, xapName));
                    uninstallScript.Add(RelativePathToWpapp + WpappProgramPathAndName
                                        + " u " + Path.Combine(configuration.BuildOutputPath, xapName));
                }
                catch (Exception e)
                {
                    ProgramExecutionLog.AddEntry(
                        "Failed to validate output files for build target " + configuration.Projects[i].ProjectPath +
                        " Error was " + e.Message);
                    Console.WriteLine("Failed!");
                    Console.WriteLine("For project " + configuration.Projects[i].ProjectPath +
                                      " Error was " + e.Message);
                }
            }
            try
            {
                File.WriteAllLines(InstallXapsOnDevice, installScript.ToArray <string>());
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write " + InstallXapsOnDevice + " File. See log");
                ProgramExecutionLog.AddEntry(
                    "Failed to write " + InstallXapsOnDevice + " File. " +
                    " Error was " + e.Message);
            }
            try
            {
                File.WriteAllLines(UninstallXapsFromDevice, uninstallScript.ToArray <string>());
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write " + UninstallXapsFromDevice + " File. See log");
                ProgramExecutionLog.AddEntry(
                    "Failed to write " + UninstallXapsFromDevice + " File. " +
                    " Error was " + e.Message);
            }
            Console.WriteLine("Completed!");
        }
        /// <summary>
        /// This function was from a previous application, but collected information
        /// related to files.
        /// This is left here for possible use going forward
        /// </summary>
        /// <param name="directoryPath">Directory to enumerate</param>
        /// <param name="recursive">True if we are to process directories recursively</param>
        /// <param name="applyExclusions">True if we are to apply exclusions</param>
        /// <param name="configuration">Main configuration settings</param>
        /// <param name="results">Results for walking the tree object</param>
        public static void FindDirFileInfo(
           string directoryPath,
           bool recursive,
           bool applyExclusions,
           BuildControlParameters configuration,
           TotalDirectoryFileStats results)
        {
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
                DirectoryInfo[] directories = directoryInfo.GetDirectories();
                results.TotalNumberOfDirectories += directories.Length;
                FileInfo[] fileSet = directoryInfo.GetFiles();
                results.TotalNumberOfFiles += fileSet.Length;
                foreach (DirectoryInfo d in directories)
                {
                    if (configuration.AbortCurrentOperation)
                    {
                        return;
                    }
                    results.AllDirectories.Add(d.FullName);
                    bool excludeDirectory = false;
                    if (applyExclusions)
                    {
                        foreach (string exclude in configuration.DirectoriesToExclude)
                        {
                            if (d.Name.ToLower(CultureInfo.CurrentCulture) == exclude.ToLower(CultureInfo.CurrentCulture))
                            {
                                results.TotalNumberOfExcludedDirectories++;
                                excludeDirectory = true;
                                break;
                            }
                        }
                    }
                    if (!excludeDirectory)
                    {
                        results.AllSelectedDirectories.Add(d.FullName);
                        results.TotalNumberOfSelectedDirectories++;
                    }

                }
                foreach (FileInfo f in fileSet)
                {
                    results.AllFiles.Add(f.FullName);
                    bool excludeFile = false;
                    if (applyExclusions)
                    {
                        foreach (string exclude in configuration.FilesToExclude)
                        {
                            if (MatchFiles(exclude, f.Name))
                            {
                                results.TotalNumberOfExcludedFiles++;
                                excludeFile = true;
                                break;
                            }
                        }
                    }
                    if (!excludeFile)
                    {
                        results.AllSelectedFiles.Add(f.FullName);
                        results.TotalNumberOfSelectedFiles++;
                    }
                }

                if (directories.Length > 0)
                {
                    foreach (DirectoryInfo info in directories)
                    {
                        if (results.AllSelectedDirectories.Contains(info.FullName))
                        {
                            FindDirFileInfo(info.FullName, recursive, applyExclusions, configuration, results);
                        }
                    }
                }
            }
            catch (IOException)
            {
                results.DirectoryFileExceptions.Add("Parent Directory Name is " + directoryPath);
            }
        }
        /// <summary>
        /// Publishes the build output.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        private static void PublishBuildOutput(
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            Console.WriteLine("Publishing results to release share ...");
            string dateFolder = CreateDateTimeFormatString(results.BuildStartTime);

            results.PublishToReleaseShare.Success = true;
            try
            {
                string publishShare       = Path.Combine(configuration.ReleaseShareRoot, dateFolder);
                string publishLogShare    = Path.Combine(publishShare, LogsFolder);
                string publishSourceShare = Path.Combine(publishShare, SourceArchiveFolder);
                string signedXapFolder    = Path.Combine(publishShare, SignedXapFolder);
                string unsignedXapFolder  = Path.Combine(publishShare, UnsignedXapFolder);
                results.PublishShare       = publishShare;
                results.PublishLogShare    = publishLogShare;
                results.PublishSourceShare = publishSourceShare;
                GeneralFileOperations.CreateDirectory(publishShare);
                GeneralFileOperations.CreateDirectory(signedXapFolder);
                GeneralFileOperations.CreateDirectory(unsignedXapFolder);
                GeneralFileOperations.CreateDirectory(publishLogShare);
                GeneralFileOperations.CreateDirectory(publishSourceShare);
                string[] files = null;
                // Copy Signed xaps and license files
                try
                {
                    files = Directory.GetFiles(configuration.BuildOutputPath);
                    foreach (string file in files)
                    {
                        try
                        {
                            string extension = Path.GetExtension(file);
                            if (extension == ".xap" ||
                                file.ToLower().Contains("license"))
                            {
                                string targetFile =
                                    Path.Combine(signedXapFolder, Path.GetFileName(file));
                                File.Copy(file, targetFile);
                            }
                        }
                        catch (Exception e)
                        {
                            ProgramExecutionLog.AddEntry(
                                "Failed to copy result file " + file + " Error message: " + e.Message);
                            results.PublishToReleaseShare.SetResults(false, e.Message);
                        }
                    }
                }
                catch (Exception e1)
                {
                    ProgramExecutionLog.AddEntry(
                        "Failed to access directory " + configuration.BuildOutputPath +
                        " Error message: " + e1.Message);
                    results.PublishToReleaseShare.SetResults(false, e1.Message);
                }

                // Copy unigned xaps
                try
                {
                    files = Directory.GetFiles(
                        Path.Combine(configuration.BuildOutputPath, UnsignedXapFolder));
                    foreach (string file in files)
                    {
                        try
                        {
                            string extension = Path.GetExtension(file);
                            if (extension == ".xap")
                            {
                                string targetFile =
                                    Path.Combine(unsignedXapFolder, Path.GetFileName(file));
                                File.Copy(file, targetFile);
                            }
                        }
                        catch (Exception e)
                        {
                            ProgramExecutionLog.AddEntry(
                                "Failed to copy result file " + file + " Error message: " + e.Message);
                            results.PublishToReleaseShare.SetResults(false, e.Message);
                        }
                    }
                }
                catch (Exception e1)
                {
                    ProgramExecutionLog.AddEntry(
                        "Failed to access directory " + configuration.BuildOutputPath +
                        " " + UnsignedXapFolder +
                        " Error message: " + e1.Message);
                    results.PublishToReleaseShare.SetResults(false, e1.Message);
                }

                // Copy License Files
                try
                {
                    files = Directory.GetFiles(
                        Path.Combine(configuration.BuildOutputPath, LicenseSubDirectory));
                    foreach (string file in files)
                    {
                        try
                        {
                            string extension = Path.GetExtension(file);
                            if (extension == ".xap" ||
                                file.ToLower().Contains("license"))
                            {
                                string targetFile =
                                    Path.Combine(signedXapFolder, Path.GetFileName(file));
                                File.Copy(file, targetFile);
                            }
                        }
                        catch (Exception e)
                        {
                            ProgramExecutionLog.AddEntry(
                                "Failed to copy result file " + file + " Error message: " + e.Message);
                            results.PublishToReleaseShare.SetResults(false, e.Message);
                        }
                    }
                }
                catch (Exception e1)
                {
                    ProgramExecutionLog.AddEntry(
                        "Failed to access directory " + configuration.BuildOutputPath +
                        " " + LicenseSubDirectory +
                        " Error message: " + e1.Message);
                    results.PublishToReleaseShare.SetResults(false, e1.Message);
                }

                // Copy Log Files
                try
                {
                    files = Directory.GetFiles(configuration.LogPath);
                    foreach (string file in files)
                    {
                        try
                        {
                            string logTargetFile =
                                Path.Combine(publishLogShare, Path.GetFileName(file));
                            File.Copy(file, logTargetFile);
                        }
                        catch (Exception e)
                        {
                            ProgramExecutionLog.AddEntry(
                                "Failed to copy result file " + file + " Error message: " + e.Message);
                            results.PublishToReleaseShare.SetResults(false, e.Message);
                        }
                    }
                }
                catch (Exception e1)
                {
                    ProgramExecutionLog.AddEntry(
                        "Failed to access directory " + configuration.LogPath +
                        " Error message: " + e1.Message);
                    results.PublishToReleaseShare.SetResults(false, e1.Message);
                }

                for (Int32 i = 0; i < results.BuildTargets.Length; i++)
                {
                    results.BuildTargets[i].BuildLogFileLink =
                        Path.Combine(publishLogShare,
                                     Path.GetFileName(results.BuildTargets[i].BuildLogFileLink));
                }
            }
            catch (Exception e)
            {
                ProgramExecutionLog.AddEntry(
                    "General fail during Publish" + "Error message: " + e.Message);
                results.PublishToReleaseShare.SetResults(false, e.Message);
            }
            if (configuration.ArchiveSource)
            {
                ZipSourceFiles(configuration, results, results.PublishSourceShare);
            }
            Console.WriteLine("Finish publish operation. Overall status was " +
                              results.PublishToReleaseShare.Success.ToString());
        }
 /// <summary>
 /// Save the config
 /// </summary>
 /// <param name="config">BDC config settings</param>
 /// <param name="fileName">Config filename</param>
 public static void SaveConfiguration(BuildControlParameters config, string fileName)
 {
     WriteConfiguration(config, fileName);
 }
 public void UpdateWpdtOpsForInstalledVersion(BuildControlParameters configuration)
 {
 }
        /// <summary>
        /// Creates the build report that gets sent out to [email protected].
        /// </summary>
        public string MakeHeroAppsReport(BuildControlParameters configuration)
        {
            string passTextColor  = "00B050";
            string failTextColor  = "C0504D";
            string blackTextColor = "190707";

            string sourceDir = configuration.ReleaseShareRoot;

            //Gets all log files in the dated directory
            string[] fileEntries = Directory.GetFiles(PublishLogShare, "*.log", SearchOption.AllDirectories);

            string WPDT        = "WPDT";
            string wpdtVersion = string.Format(FormatHtmlStatic(), WPDT, passTextColor, configuration.WpdtLkgSourcePath);

            string YDR        = "YDR Version";
            string ydrVersion = string.Format(FormatHtmlStatic(), YDR, blackTextColor, YdrVersion);

            //Set email body static header
            string emailHeader = "<html xmlns:v=\"urn:schemas-microsoft-com:vml\" " +
                                 "xmlns:o=\"urn:schemas-microsoft-com:office:office\" " +
                                 "xmlns:w=\"urn:schemas-microsoft-com:office:word\" " +
                                 "xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" " +
                                 "xmlns=\"http://www.w3.org/TR/REC-html40\"><head><META HTTP-EQUIV=\"Content-Type\" " +
                                 "CONTENT=\"text/html; charset=us-ascii\"><meta name=Generator content=\"Microsoft Word 14 (filtered medium)\"><style><!--/* Font Definitions */@font-face	{font-family:Calibri;	panose-1:2 15 5 2 2 2 4 3 2 4;}@font-face	{font-family:Tahoma;	panose-1:2 11 6 4 3 5 4 4 2 4;}/* Style Definitions */p.MsoNormal, li.MsoNormal, div.MsoNormal	{margin:0in;	margin-bottom:.0001pt;	font-size:11.0pt;	font-family:\"Calibri\",\"sans-serif\";}a:link, span.MsoHyperlink	{mso-style-priority:99;	color:blue;	text-decoration:underline;}a:visited, span.MsoHyperlinkFollowed	{mso-style-priority:99;	color:purple;	text-decoration:underline;}span.EmailStyle17	{mso-style-type:personal;	font-family:\"Calibri\",\"sans-serif\";	color:windowtext;}span.EmailStyle18	{mso-style-type:personal-reply;	font-family:\"Calibri\",\"sans-serif\";	color:#1F497D;}.MsoChpDefault	{mso-style-type:export-only;	font-size:10.0pt;}@page WordSection1	{size:8.5in 11.0in;	margin:1.0in 1.0in 1.0in 1.0in;}div.WordSection1	{page:WordSection1;}--></style><!--[if gte mso 9]><xml><o:shapedefaults v:ext=\"edit\" spidmax=\"1026\" /></xml><![endif]--><!--[if gte mso 9]><xml><o:shapelayout v:ext=\"edit\"><o:idmap v:ext=\"edit\" data=\"1\" /></o:shapelayout></xml><![endif]--></head>";

            //Build Machine name
            string dailyBuildMachine = "Build Machine";
            string machineName       = System.Environment.MachineName;
            string buildMachine      = string.Format(FormatHtmlStatic(), dailyBuildMachine, blackTextColor, machineName);

            //Set build Location in HTML
            string dailyBuildLocation = "Build Location";
            string buildLocation      = string.Format(FormatHtmlStatic(), dailyBuildLocation, blackTextColor, PublishShare);


            string enlistmentSync  = "";
            string syncdEnlistment = "Enlistment Sync";

            if (configuration.SyncEnlistment)
            {
                if (EnlistmentSync.Success)
                {
                    string enlistmentSuccess = "PASS";
                    enlistmentSync = string.Format(FormatHtmlStatic(), syncdEnlistment, passTextColor, enlistmentSuccess);
                }
                else
                {
                    string enlistmentFail = "FAIL";
                    enlistmentSync = string.Format(FormatHtmlStatic(), syncdEnlistment, failTextColor, enlistmentFail);
                }
            }

            string wpdtStatus = "";
            string wpdtTitle  = "Uninstall and Reinstall of WPDT";

            if (configuration.UpdateWpdt)
            {
                string wpdtLkgNoChange = "Machine has current LKG installed";
                wpdtStatus = string.Format(FormatHtmlStatic(), wpdtTitle, blackTextColor, wpdtLkgNoChange);
            }

            //Setup table formatting in HTML
            string tableHeader = "<body lang=EN-US link=blue vlink=purple><div class=WordSection1><table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0 width=781 style='width:468.45pt;border-collapse:collapse'><tr><td width=285 style='width:171.2pt;border:solid black 1.0pt;background:#D9D9D9;padding:0in 5.4pt 0in 5.4pt'><p class=MsoNormal><b><span style='color:#00B0F0'>Hero App<o:p></o:p></span></b></p></td><td width=117 style='width:70.05pt;border:solid black 1.0pt;border-left:none;background:#D9D9D9;padding:0in 5.4pt 0in 5.4pt'><p class=MsoNormal><b><span style='color:#00B0F0'>Result <o:p></o:p></span></b></p></td><td width=126 valign=top style='width:75.4pt;border:solid black 1.0pt;border-left:none;background:#D9D9D9;padding:0in 0in 0in 0in'><p class=MsoNormal><b><span style='color:#00B0F0'>Sign XAP<o:p></o:p></span></b></p></td><td width=126 valign=top style='width:75.4pt;border:solid black 1.0pt;border-left:none;background:#D9D9D9;padding:0in 0in 0in 0in'><p class=MsoNormal><b><span style='color:#00B0F0'>License XAP<o:p></o:p></span></b></p></td><td width=126 style='width:75.4pt;border-top:solid black 1.0pt;border-left:none;border-bottom:solid black 1.0pt;border-right:none;background:#D9D9D9;padding:0in 0in 0in 0in'><p class=MsoNormal><b><span style='color:#00B0F0'>Logs<o:p></o:p></span></b></p></td>";


            //Sets the static members of the email body
            string completeMailBody = emailHeader + buildMachine + buildLocation + enlistmentSync + wpdtStatus + wpdtVersion + ydrVersion + tableHeader;



            //This is the loop that builds the report. I generates all the information to feed to the email body in HTML
            foreach (BuildTargetResults target in BuildTargets)
            {
                string fileNameString     = target.ProjectTargetName;
                string tempFileNameString = string.Format("<tr><td width=173 style='width:103.75pt;border:solid black 1.0pt;border-top:none;background:#D9D9D9;padding:0in 5.4pt 0in 5.4pt'><p class=MsoNormal><b>{0}<o:p></o:p></b></p></td>", fileNameString);
                completeMailBody = completeMailBody + tempFileNameString;


                if (target.Build.Success)
                {
                    string pass     = "******";
                    string tempPass = string.Format(FormatHtmlInLoop(), passTextColor, pass);
                    completeMailBody = completeMailBody + tempPass;
                }
                else
                {
                    //App was NOT successfully built.
                    string fail     = "FAIL";
                    string tempFail = string.Format(FormatHtmlInLoop(), failTextColor, fail);
                    completeMailBody = completeMailBody + tempFail;
                }
                if (target.SignXap.Success)
                {
                    //App was signed
                    string xapSignTrue     = "PASS";
                    string tempXapSignTrue = string.Format(FormatHtmlInLoop(), passTextColor, xapSignTrue);
                    completeMailBody = completeMailBody + tempXapSignTrue;
                }
                else
                {
                    string xapSignFalse     = "FAIL";
                    string tempXapSignFalse = string.Format(FormatHtmlInLoop(), failTextColor, xapSignFalse);
                    completeMailBody = completeMailBody + tempXapSignFalse;
                }

                if (target.LicenseXap.Success)
                {
                    //App was signed
                    string xapLicenseTrue     = "PASS";
                    string tempXapLicenseTrue = string.Format(FormatHtmlInLoop(), passTextColor, xapLicenseTrue);
                    completeMailBody = completeMailBody + tempXapLicenseTrue;
                }
                else
                {
                    string xapLicenseFalse  = "FAIL";
                    string tempXapSignFalse = string.Format(FormatHtmlInLoop(), failTextColor, xapLicenseFalse);
                    completeMailBody = completeMailBody + tempXapSignFalse;
                }

                //Sets the log location for all the apps
                string logLocation = string.Format("<td width=76 style='width:45.7pt;border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;background:#D9D9D9;padding:0in 5.4pt 0in 5.4pt'><p class=MsoNormal><b><a href=\"{0}\">LOG</a><o:p></o:p></b></p></td></tr><tr>",
                                                   PublishLogShare);
                completeMailBody = completeMailBody + logLocation;
            }
            return(completeMailBody);
        }
        /// <summary>
        /// Builds the batch file.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        private static string BuildBatchFile(
            BuildControlParameters configuration,
            DailyBuildFullResults results)
        {
            results.BuildStartTime = DateTime.Now;
            string progFiles   = System.Environment.GetEnvironmentVariable("ProgramFiles");
            string envVarSetup = Path.Combine(progFiles, @"Microsoft Visual Studio 10.0\VC\vcvarsall.bat");

            DeleteIntermediateDirectory(configuration.BuildOutputPath);
            DeleteIntermediateDirectory(configuration.LogPath);

            List <string> buildScript = new List <string>();

            buildScript.Add("@echo off");
            buildScript.Add("call " + "\"" + envVarSetup + "\"" + " x86");
            buildScript.Add("set ScriptDir=%~d0%~p0");
            buildScript.Add("set LogDir=" + configuration.LogPath);
            buildScript.Add("set BuildDir=" + configuration.BuildOutputPath);
            buildScript.Add("set UnsignedXapDir=" + Path.Combine(configuration.BuildOutputPath, UnsignedXapFolder));
            buildScript.Add("rd %LogDir% /s /q");
            buildScript.Add("md %LogDir%");
            buildScript.Add("rd %BuildDir% /s /q");
            buildScript.Add("md %BuildDir%");
            buildScript.Add("md %UnsignedXapDir%");
            buildScript.Add("copy XapUpdater.* %BuildDir%");

            string heroAppSource = FindHeroAppSourceFolder(configuration);

            for (Int32 i = 0; i < configuration.Projects.Length; i++)
            {
                if (configuration.Projects[i].BuildConfiguration != BuildProjectControl.None)
                {
                    StringBuilder b = new StringBuilder();
                    BuildProjectControlParameters p = configuration.Projects[i];
                    string appFolder       = Path.Combine(heroAppSource, p.ProjectPath);
                    string solutionName    = Path.GetFileName(p.SolutionPathAndNameFromProjectRoot);
                    string projectName     = Path.GetFileName(p.ProjectPathAndNameFromProjectRoot);
                    string solution        = Path.Combine(appFolder, p.SolutionPathAndNameFromProjectRoot);
                    string project         = Path.Combine(appFolder, p.ProjectPathAndNameFromProjectRoot);
                    string outputDirectory = Path.Combine(appFolder,
                                                          Path.GetDirectoryName(p.XapPathAndNameFromProjectRoot));
                    string buildtarget = p.BuildConfiguration == BuildProjectControl.Solution ?
                                         solution : project;
                    string logFileName        = Path.GetFileName(buildtarget) + ".log";
                    string xapFileName        = Path.GetFileName(p.XapPathAndNameFromProjectRoot);
                    string signLogFileName    = xapFileName + "_sign" + ".log";
                    string licenseLogFileName = xapFileName + "_license" + ".log";
                    results.BuildTargets[i].BuildLogFileLink = Path.Combine(configuration.LogPath, logFileName);

                    buildScript.Add("echo Building " + solutionName);
                    buildScript.Add("del " + outputDirectory + @"\* /q");
                    buildScript.Add("msbuild " + buildtarget + @" /t:Rebuild /p:Configuration=Release >%LogDir%\" + logFileName + " 2>&1");
                    buildScript.Add(@"IF %ERRORLEVEL% NEQ 0 echo " + solutionName + " build failed");
                    buildScript.Add("copy " + outputDirectory + @"\*.xap" + " %BuildDir%");
                    buildScript.Add("copy " + outputDirectory + @"\*.xap" + " %UnsignedXapDir%");
                    buildScript.Add("cd %BuildDir%");
                    buildScript.Add("XapUpdater.exe -xap " + xapFileName + @" >%LogDir%\" + signLogFileName);
                    buildScript.Add("XapUpdater.exe -generatepreinstalllicense " + xapFileName + @" >%LogDir%\" + licenseLogFileName);
                    buildScript.Add("cd %ScriptDir%");
                }
            }
            try
            {
                File.WriteAllLines("BuildHeroApps.cmd", buildScript.ToArray <string>());
            }
            catch (Exception e)
            {
                ProgramExecutionLog.AddEntry(
                    "Failed to write build commannd file" +
                    " Error was " + e.Message);
            }
            return("BuildHeroApps.cmd");
        }