예제 #1
0
        /// <summary>
        /// Finds the node processes whose executables are in the specified directory.
        /// <para>Bolj tocna metoda kot pa <see cref="GetNodeProcessesByTime"/>, ampak pocasnejsa.</para>
        /// </summary>
        /// <param name="executablesDirectory">The directory of the NodeJs executables.</param>
        private static List <Process> GetNodeProcessesByExecutablePath(string executablesDirectory)
        {
            var allNodeProcesses = Process.GetProcessesByName("node");

            string nodeExecutablePath = Path.Combine(executablesDirectory, "node.exe").ToLower();

            List <Process> result = allNodeProcesses.Where(p => ProcessUtility.GetProcessPath(p).ToLower() == nodeExecutablePath).ToList();

            return(result);
        }
예제 #2
0
        public static List <string> GetFeatureClassNamesFromFileGdb(FileInfo ogrInfoFileInfo, FileInfo gdbFileInfo, double totalMilliseconds)
        {
            // ReSharper disable once AssignNullToNotNullAttribute
            var gdalDataDirectory    = new DirectoryInfo(Path.Combine(ogrInfoFileInfo.DirectoryName, "gdal-data"));
            var commandLineArguments = BuildOgrInfoCommandLineArgumentsToListFeatureClasses(gdbFileInfo, gdalDataDirectory);
            var processUtilityResult = ProcessUtility.ShellAndWaitImpl(ogrInfoFileInfo.DirectoryName, ogrInfoFileInfo.FullName, commandLineArguments, true, Convert.ToInt32(totalMilliseconds));

            var featureClassesFromFileGdb = processUtilityResult.StdOut.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();

            return(featureClassesFromFileGdb.Select(x => x.Split(' ').Skip(1).First()).ToList());
        }
예제 #3
0
        /// <summary>
        /// Kills all processes (if any exist) that use the same executables as this instance of <see cref="NodeJsServer"/>.
        /// </summary>
        private void KillAllProcesssesOfThisNodeExecutables()
        {
            // look for any running node processes in that directory
            List <Process> nodeProcessesAlreadyRunning = GetNodeProcessesByExecutablePath(ExecutablesDirectory);

            // ... and kill them if they exist
            if (!nodeProcessesAlreadyRunning.IsNullOrEmpty())
            {
                ProcessUtility.KillAllProcesses(nodeProcessesAlreadyRunning);
            }
        }
예제 #4
0
        private static void RunDiskPart(string action, string vdiskPath)
        {
            var scriptPath = Path.GetTempFileName();

            using (var scriptStream = File.CreateText(scriptPath))
            {
                scriptStream.WriteLine($"select vdisk file=\"{vdiskPath}\"");
                scriptStream.WriteLine($"{action} vdisk");
            }
            ProcessUtility.Run("diskpart", $"/s {scriptPath}");
            File.Delete(scriptPath);
        }
예제 #5
0
        public static void Verify(string assemblyName)
        {
            var log = new List <string>();
            var rc  = ProcessUtility.ExecuteCommandLine(ExePath, new[] { "/nologo", assemblyName }, null, log, log);

            // TODO: not great to just throw like this vs. returning an error structure
            // TODO: will it return 0 even if there are warnings?
            if (rc != 0)
            {
                throw new PeVerifyException(assemblyName, rc, log);
            }
        }
예제 #6
0
        private static void ConfigureLogging(HostBuilderContext context, ILoggingBuilder logging)
        {
            var path = ProcessUtility.GetExecutionPath();
            var file = Path.Join(path, Constants.LogFileName);

            logging.ClearProviders();

            logging.AddFile(file, LogLevel.Information, new Dictionary <string, LogLevel>
            {
                { "System", LogLevel.None },
                { "Microsoft", LogLevel.None }
            });
        }
예제 #7
0
        public TwitterService()
        {
            // WebAPI認証用データ取得
            Dictionary <string, string> apiKeyConfig = ProcessUtility.ReadAppConfig("twitter");

            // AWSのlambda関数使用時はApp.configの値がnullとなるためnullチェックを入れる
            _consumerKey    = ProcessUtility.GetEnvVarByKey(apiKeyConfig, "consumerKey", "CONSUMER_KEY");
            _consumerSecret = ProcessUtility.GetEnvVarByKey(apiKeyConfig, "consumerSecret", "CONSUMER_SECRET");
            _accessKey      = ProcessUtility.GetEnvVarByKey(apiKeyConfig, "accessKey", "ACCESS_KEY");
            _accessSecret   = ProcessUtility.GetEnvVarByKey(apiKeyConfig, "accessSecret", "ACCESS_SECRET");
            // Twitter認証
            _tokens = Tokens.Create(_consumerKey, _consumerSecret, _accessKey, _accessSecret);
        }
예제 #8
0
        static bool FormatUncrustify(FormatItem formatItem, List <string> lines)
        {
            var packageRoot    = formatItem.Context.ThisPackageRoot;
            var uncrustifyPath = packageRoot.Combine(UncrustifyRelativePathForCurrentPlatform());
            var settingsPath   = packageRoot.Combine($"Coding~/Configs/Uncrustify/{formatItem.Path.ExtensionWithoutDot.ToLower()}.ini");

            var tempFormatPath = formatItem.Path.ChangeExtension(".tmp" + formatItem.Path.ExtensionWithDot);

            try
            {
                using (var file = File.Create(tempFormatPath))
                    WriteLines(file, lines, Charset.UTF8, EndOfLine.LF);

                var args = new[]
                {
                    "-L1,2",                // only want warnings and errors, and no status
                    "-c", settingsPath,     // config file to use
                    "-f", tempFormatPath,   // file to process
                    "-o", tempFormatPath,   // overwrite the thing
                };

                var stderr   = new List <string>();
                var exitCode = ProcessUtility.ExecuteCommandLine(uncrustifyPath, args, null, null, stderr);

                // we should be able to use `--no-backup` but uncrustify complains that this can't be used with -f/-o. we're already working with a tmp
                // file to get atomic rewrite as well as avoid updating a file that doesn't change (so timestamp not affected).
                // https://gitlab.cds.internal.unity3d.com/upm-packages/core/com.unity.coding/issues/3
                tempFormatPath.Parent.Combine(tempFormatPath.FileName + ".unc-backup.md5~").DeleteIfExists();
                tempFormatPath.Parent.Combine(tempFormatPath.FileName + ".unc-backup~").DeleteIfExists();

                if (stderr.Any())
                {
                    formatItem.Context.LogError($"Errors encountered while formatting '{formatItem.Path}':\n  {stderr.StringJoin("\n  ")}");
                    return(false);
                }

                if (exitCode != 0)
                {
                    formatItem.Context.LogError($"Fatal encountered while formatting '{formatItem.Path}'\n(Uncrustify gave an exit code of 0x{exitCode:X})");
                    return(false);
                }

                lines.SetRange(ReadLines(tempFormatPath).lines);
            }
            finally
            {
                tempFormatPath.DeleteIfExists();
            }

            return(true);
        }
예제 #9
0
        /// <summary>
        /// 音声ファイルを再生する。
        /// 再生用プログラムが見つからない場合はFileNotFoundExceptionを投げる。
        /// </summary>
        /// <param name="filePath">音声ファイルのパス</param>
        public static void PlayStreaming(string filePath)
        {
            // 再生用メディアプレイヤーが見つからない場合には例外を投げる
            if (File.Exists(UserSetting.MediaPlayerPath) == false)
            {
                throw new FileNotFoundException("Not found media player.");
            }
            if (filePath == string.Empty)
            {
                return;
            }

            ProcessUtility.CreateProcess(UserSetting.MediaPlayerPath, "\"" + filePath + "\"");
        }
예제 #10
0
        /// <summary>
        /// Webサイトにアクセスする。
        /// ブラウザが見つからない場合はFileNotFoundExceptionを投げる。
        /// </summary>
        /// <param name="url">WebサイトのURL</param>
        public static void AccessWebsite(Uri websiteUrl)
        {
            // ブラウザが見つからない場合には例外を投げる
            if (File.Exists(UserSetting.BrowserPath) == false)
            {
                throw new FileNotFoundException("Not found web browser.");
            }
            if (websiteUrl == null)
            {
                return;
            }

            ProcessUtility.CreateProcess(UserSetting.BrowserPath, websiteUrl.ToString());
        }
 private string GetForPid(int pid)
 {
     if (globalCache.GetValue().TryGetValue(pid, out var instanceId))
     {
         return(instanceId);
     }
     ProcessUtility.EnsureProcessIsRunning(pid);
     globalCache.Evict();
     if (!globalCache.GetValue().TryGetValue(pid, out instanceId))
     {
         throw new InvalidOperationException($"Process with pid {pid} exists, but not found in cache");
     }
     return(instanceId);
 }
예제 #12
0
        /// <summary>
        /// ストリーミングを再生する。
        /// 再生用プログラムが見つからない場合はFileNotFoundExceptionを投げる。
        /// </summary>
        /// <param name="streamingUrl">ストリーミングのURL</param>
        public static void PlayStreaming(Uri streamingUrl)
        {
            // 再生用メディアプレイヤーが見つからない場合には例外を投げる
            if (File.Exists(UserSetting.MediaPlayerPath) == false)
            {
                throw new FileNotFoundException("Not found media player.");
            }
            if (streamingUrl == null)
            {
                return;
            }

            ProcessUtility.CreateProcess(UserSetting.MediaPlayerPath, streamingUrl.ToString());
        }
예제 #13
0
        private IEnumerable <string> BuildX86()
        {
            clearTargetBuildFlags();
            var output = new List <string>();
            var setEnv = ProgramFinder.ProgramFiles.ScanForFile("setenv.cmd");

            if (string.IsNullOrEmpty(setEnv))
            {
                throw new Exception("Cannot locate SDK SetEnv command. Please install the Windows SDK");
            }

            var se = new ProcessUtility("cmd.exe");

            se.Exec(@"/c ""{0}"" /{1} & set ", setEnv, "x86");


            foreach (var x in se.StandardOut.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                if (x.Contains("="))
                {
                    var v = x.Split('=');
                    Environment.SetEnvironmentVariable(v[0], v[1]);
                }
            }

            var target_cpu = Environment.GetEnvironmentVariable("TARGET_CPU");

            if (string.IsNullOrEmpty(target_cpu) || (target_cpu == "x64"))
            {
                throw new Exception(
                          "Cannot set the SDK environment. Please install the Windows SDK and use the setenv.cmd command to set your environment");
            }



            foreach (var dll in sharedLibraryTargets)
            {
                CreateDLL(dll, "x86", output);
            }

            foreach (var exe in applicationTargets)
            {
                CreateEXE(exe, "x86", output);
            }



            return(null);
        }
예제 #14
0
        public bool IsPortListening(int port)
        {
            if (_runtime.IsWindowsLinux || _ipGlobalProperties == null) // IPGlobalProperties is not implemented for WSL at this time
            {
                string netstat = _runtime.IsWindows || _runtime.IsWindowsLinux ? "netstat.exe" : "netstat";

                ProcessUtility.RunProcessAndWaitForExit(netstat, "-tna", _fileSystem, out string output, out string _, 5_000);

                return(ContainsNetstatPort(output, port));
            }

            var activeTcpPorts = _ipGlobalProperties.GetActiveTcpListeners();

            return(activeTcpPorts.Any(p => p.Port == port));
        }
예제 #15
0
 private void StartLocalDbButton_Click(object sender, RoutedEventArgs e)
 {
     if (MessageBox.Show("Are you sure you want to restart the SQL local DB instance?", "Restart local DB", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
     {
         var result = ProcessUtility.RunCommand("Start SQL LocalDB", @"sqllocaldb start MSSQLLocalDB", TextBoxLogger.Get());
         if (result.IsSuccess)
         {
             MessageBox.Show("SQL LocalDB started successfully.", "Success");
         }
         else
         {
             MessageBox.Show("Could not successfully start SQL Local DB.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
 }
예제 #16
0
        // The FileGDB driver for Ogr2Ogr prints an empty line to standard error and returns a code even when successful, so we have to trap that case explicitly
        // ReSharper disable once UnusedMethodReturnValue.Local
        private ProcessUtilityResult ExecuteOgr2OgrCommandForFileGdbWrite(List <string> commandLineArguments)
        {
            var processUtilityResult = ProcessUtility.ShellAndWaitImpl(_ogr2OgrExecutable.DirectoryName, _ogr2OgrExecutable.FullName, commandLineArguments, true, Convert.ToInt32(_totalMilliseconds));

            if (processUtilityResult.ReturnCode != 0 && !(processUtilityResult.StdOutAndStdErr.Equals("[stdout] \r\n[stderr] \r\n") || processUtilityResult.StdOutAndStdErr.Equals("[stderr] \r\n[stdout] \r\n")))
            {
                var argumentsAsString       = String.Join(" ", commandLineArguments.Select(ProcessUtility.EncodeArgumentForCommandLine).ToList());
                var fullProcessAndArguments =
                    $"{ProcessUtility.EncodeArgumentForCommandLine(_ogr2OgrExecutable.FullName)} {argumentsAsString}";
                var errorMessage =
                    $"Process \"{_ogr2OgrExecutable.Name}\" returned with exit code {processUtilityResult.ReturnCode}, expected exit code 0.\r\n\r\nStdErr and StdOut:\r\n{processUtilityResult.StdOutAndStdErr}\r\n\r\nProcess Command Line:\r\n{fullProcessAndArguments}\r\n\r\nProcess Working Directory: {_ogr2OgrExecutable.DirectoryName}";
                throw new Ogr2OgrCommandLineException(errorMessage);
            }
            return(processUtilityResult);
        }
예제 #17
0
        private IEnumerable <string> BuildMSIL()
        {
            clearTargetBuildFlags();
            var setEnv = ProgramFinder.ProgramFiles.ScanForFile("VSVARS32.bat");

            if (string.IsNullOrEmpty(setEnv))
            {
                throw new Exception("Cannot locate VCVARS32.bat command. Please install something?");
            }

            var se = new ProcessUtility(setEnv);

            se.Exec("");

            return(null);
        }
예제 #18
0
        /// <summary>
        /// Estimates memory consumption
        /// </summary>
        /// <exception cref="InvalidOperationException">Process has exited</exception>
        /// <returns></returns>
        public ProcessMemoryInfo GetMemoryInfo()
        {
            ProcessUtility.EnsureProcessIsRunning(handle, pid);

            if (!PsApi.GetProcessMemoryInfo(handle, out var counters))
            {
                Win32ExceptionUtility.Throw();
            }

            return(new ProcessMemoryInfo
            {
                // use PrivateUsage instead of PagefileUsage because PagefileUsage is always zero on Windows 7, Windows Server 2008 R2 and earlier systems
                PrivateBytes = (long)counters.PrivateUsage,
                WorkingSetBytes = (long)counters.WorkingSetSize,
            });
        }
예제 #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ogrInfoExecutableFileInfo">Path to the ogrinfo.exe executable</param>
        /// <param name="kmlFileInfo"></param>
        /// <param name="originalFilename">This is the original name of the file as it appeared on the users file system. It is provided just for error messaging purposes.</param>
        /// <param name="totalMilliseconds"></param>
        /// <returns></returns>
        public static List <string> GetFeatureClassNamesFromFileKml(FileInfo ogrInfoExecutableFileInfo, FileInfo kmlFileInfo, string originalFilename, double totalMilliseconds)
        {
            // ReSharper disable once AssignNullToNotNullAttribute
            var gdalDataDirectory    = new DirectoryInfo(Path.Combine(ogrInfoExecutableFileInfo.DirectoryName, "gdal-data"));
            var commandLineArguments = BuildOgrInfoCommandLineArgumentsToListFeatureClassesKml(kmlFileInfo, gdalDataDirectory);
            var processUtilityResult = ProcessUtility.ShellAndWaitImpl(ogrInfoExecutableFileInfo.DirectoryName, ogrInfoExecutableFileInfo.FullName, commandLineArguments, true, Convert.ToInt32(totalMilliseconds));

            if (processUtilityResult.ReturnCode != 0)
            {
                throw new SitkaGeometryDisplayErrorException($"{ogrInfoExecutableFileInfo.FullName} unable to open KML file {kmlFileInfo.FullName} - original filename {originalFilename}.");
            }

            var featureClassesFromFileKml = processUtilityResult.StdOut.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();

            return(featureClassesFromFileKml.Select(x => x.Split(new[] { ' ' }, 2).Skip(1).First()).ToList());
        }
예제 #20
0
        public static ProcessUtilityResult ExecutePyqgisScript(string pathToPyqgisScript, string workingDirectory)
        {
            var commandLineArguments = new List <string>
            {
                "/q",
                "/c",
                NeptuneWebConfiguration.PathToPyqgisLauncher,
                pathToPyqgisScript,
                NeptuneWebConfiguration.DatabaseConnectionString
            };

            var processUtilityResult = ProcessUtility.ShellAndWaitImpl(workingDirectory,
                                                                       "cmd.exe", commandLineArguments, true, null);

            return(processUtilityResult);
        }
예제 #21
0
        public void CreateProcess_returns_process_with_fileName_and_arguments_in_target_directory()
        {
            string targetDirectory = PathHelper.GetSampleProjectPath("ConfigurationGood");

            _fileSystem.WorkingDirectory = targetDirectory;

            var process = ProcessUtility.CreateProcess("wumbo", "--foo bar", _fileSystem);

            Assert.Equal("wumbo", process.StartInfo.FileName);
            Assert.Equal("--foo bar", process.StartInfo.Arguments);
            Assert.Equal(targetDirectory, process.StartInfo.WorkingDirectory);
            Assert.True(process.StartInfo.RedirectStandardOutput);
            Assert.True(process.StartInfo.RedirectStandardError);
            Assert.True(process.StartInfo.RedirectStandardInput);
            Assert.False(process.StartInfo.UseShellExecute);
        }
예제 #22
0
            public int GetThreadsCount(int pid)
            {
                if (TryGetThreadsCount(pid, out var count))
                {
                    return(count);
                }

                ProcessUtility.EnsureProcessIsRunning(pid);
                threadsCountCache.Evict();

                if (TryGetThreadsCount(pid, out count))
                {
                    return(count);
                }

                throw new InvalidOperationException($"Unable to retrieve process metrics for process with id {pid}");
            }
예제 #23
0
        public static void RenderGraphViz(NPath png, string dot, params string[] extraArgs)
        {
            var dotPath    = NPath.SystemTemp.Combine(Guid.NewGuid() + ".dot");
            var renderPath = dotPath.ChangeExtension(".png");

            try
            {
                dotPath.WriteAllText(dot);
                ProcessUtility.ExecuteCommandLine("dot", $"-Gdpi=175 -Nfontname=Roboto -Efontname=Roboto -Tpng {dotPath} -o {renderPath}".Split(' ').Concat(extraArgs), null, null, null);
                ProcessUtility.ExecuteCommandLine("magick", $"{renderPath} -channel RGB -negate {png}".Split(' '), null, null, null);
            }
            finally
            {
                dotPath.DeleteIfExists();
                renderPath.DeleteIfExists();
            }
        }
예제 #24
0
        public Process GetKillProcess(string processName, CommandOptions options)
        {
            var startInfo = new ProcessStartInfo
            {
                CreateNoWindow         = false,
                WindowStyle            = ProcessWindowStyle.Normal,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            if (RuntimeInfo.IsWindows)
            {
                startInfo.FileName  = "taskkill";
                startInfo.Arguments = $"/F /IM {ProcessUtility.AddExtension(processName)}";
            }
            else
            {
                startInfo.FileName  = "killall";
                startInfo.Arguments = processName;
            }

            var process = new Process
            {
                StartInfo           = startInfo,
                EnableRaisingEvents = true,
            };

            process.OutputDataReceived += (o, e) =>
            {
                if (options.Verbose && !string.IsNullOrWhiteSpace(e.Data))
                {
                    _console.WriteLine(e.Data);
                }
            };
            process.ErrorDataReceived += (o, e) =>
            {
                if (!string.IsNullOrWhiteSpace(e.Data))
                {
                    _console.WriteWarningLine(e.Data);
                }
            };

            return(process);
        }
예제 #25
0
        public static void Verify(string assemblyName)
        {
            // TODO: find a better way to avoid assemblies that don't peverify out of the box
            if (new[] { "mscorlib", "System.Runtime", "netstandard" }.Contains(new NPath(assemblyName).FileNameWithoutExtension))
            {
                return;
            }

            var log = new List <string>();
            var rc  = ProcessUtility.ExecuteCommandLine(ExePath, new[] { "/nologo", assemblyName }, null, log, log);

            // TODO: not great to just throw like this vs. returning an error structure
            // TODO: will it return 0 even if there are warnings?
            if (rc != 0)
            {
                throw new PeVerifyException(assemblyName, rc, log);
            }
        }
예제 #26
0
        private static Settings GetSettings()
        {
            var path = ProcessUtility.GetExecutionPath();
            var file = Path.Join(path, Constants.SettingsFileName);

            if (File.Exists(file))
            {
                return(JsonSerializer.Deserialize <Settings>(File.ReadAllText(file)));
            }

            var settings = new Settings();
            var options  = new JsonSerializerOptions {
                WriteIndented = true
            };

            File.WriteAllText(file, JsonSerializer.Serialize(settings, options));

            return(settings);
        }
예제 #27
0
 private void PollRemote()
 {
     Logger.Debug("Checking Remote");
     foreach (SaveFileHandler handler in SaveFiles)
     {
         if (ProcessUtility.IsProcessActive(handler.ExecutableName))
         {
             Logger.Debug($"Holding off sync (Remote) for {handler.LocalSaveFile.GameTitle} because game is active");
             continue;
         }
         if (m_syncQueue.Contains(handler))
         {
             Logger.Debug($"Holding off sync (Remote) for {handler.LocalSaveFile.GameTitle} because the game is already in local syncing queue");
             continue;
         }
         this.ExecuteSyncAction(handler, this.DetermineSyncAction(handler));
         Thread.Sleep(1000);
     }
 }
예제 #28
0
        private Tuple <bool, string> CheckDisk()
        {
            var previousDrives = DriveInfo.GetDrives();

            RunDiskPart("attach", VhdxPath);
            var    newDrives    = DriveInfo.GetDrives();
            var    mountedDrive = newDrives.FirstOrDefault(d => previousDrives.All(p => p.Name != d.Name));
            bool   success      = true;
            string checkResult  = null;

            if (mountedDrive != null)
            {
                var result = ProcessUtility.Run("chkdsk", mountedDrive.Name.TrimEnd('\\'));
                success     = result.Item1 == 0;
                checkResult = result.Item2;
            }
            RunDiskPart("detach", VhdxPath);
            return(Tuple.Create(success, checkResult));
        }
예제 #29
0
        public static string OcrSmallText(Int2 size, Func <Int2, bool> isSet)
        {
            var imagePath = Path.GetTempFileName().ToNPath();

            try
            {
                // to detect small text, tesseract needs black on white with a border and scaled up 400%
                using (var image = new MagickImage(MagickColors.White, size.X, size.Y))
                {
                    image.Density = new Density(100, DensityUnit.PixelsPerInch);

                    using (var outPixels = image.GetPixels())
                    {
                        for (var y = 0; y < image.Height; ++y)
                        {
                            for (var x = 0; x < image.Width; ++x)
                            {
                                if (isSet(new Int2(x, y)))
                                {
                                    outPixels[x, y].Set(k_On);
                                }
                            }
                        }
                    }

                    image.Scale(new Percentage(400));

                    image.BorderColor = image.BackgroundColor;
                    image.Border(10);

                    image.Write(imagePath, MagickFormat.Png);
                }

                var(stdout, stderr) = (new List <string>(), new List <string>());
                ProcessUtility.ExecuteCommandLine("tesseract", Arr(imagePath.ToString(), "stdout"), null, stdout, stderr);
                return(stdout[0]);
            }
            finally
            {
                imagePath.DeleteIfExists();
            }
        }
예제 #30
0
파일: Tools.cs 프로젝트: virmitio/devtools
        internal static void LocateCommandlineTools()
        {
            try {
                WixCompiler = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("candle.exe", minimumVersion: "3.6", executableType: ExecutableInfo.managed));
            } catch {
                throw new ConsoleException(
                    "Unable to find 'candle.exe' from WiX 3.5 installation. \r\n\r\n ****************\r\n Autopackage Requires Wix 3.6 to be installed\r\n Get it from (http://wix.codeplex.com/releases/view/75656)\r\n ****************\r\n");
            }

            try {
                WixLinker = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("light.exe", minimumVersion: "3.6", executableType: ExecutableInfo.managed));
            } catch {
                throw new ConsoleException("Unable to find 'light.exe' from WiX 3.5 installation. \r\n\r\n ****************\r\n Autopackage Requires Wix 3.6 to be installed\r\n Get it from (http://wix.codeplex.com/releases/view/75656)\r\n ****************\r\n");
            }

            try {
                ManifestTool = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("mt.exe"));
            } catch {
                throw new ConsoleException("Unable to find 'mt.exe' from Windows SDK.");
            }

            try {
                MakeCatalog = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("makecat.exe"));
            } catch {
                throw new ConsoleException("Unable to find 'makecat.exe' from Windows SDK.");
            }

            try {
                AssemblyLinker = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("al.exe"));
            } catch {
                throw new ConsoleException("Unable to find 'al.exe' from Windows SDK.");
            }

            if (ShowTools) {
                Console.WriteLine("Tools:");
                Console.WriteLine("Wix/Candle.exe : {0}", WixCompiler.Executable);
                Console.WriteLine("Wix/Light.exe : {0}", WixLinker.Executable);
                Console.WriteLine("SDK/mt.exe : {0}", ManifestTool.Executable);
                Console.WriteLine("SDK/makecat.exe : {0}", MakeCatalog.Executable);
                Console.WriteLine("SDK/al.exe : {0}", AssemblyLinker.Executable);
            }
        }
        public static Tuple <double, double, double, double> GetExtentFromGeoJson(FileInfo ogrInfoFileInfo, string geoJson, double totalMilliseconds)
        {
            using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
            {
                File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);

                var gdalDataDirectory    = new DirectoryInfo(Path.Combine(ogrInfoFileInfo.DirectoryName, "gdal-data"));
                var commandLineArguments = BuildOgrInfoCommandLineArgumentsGetExtent(geoJsonFile.FileInfo, gdalDataDirectory);
                var processUtilityResult = ProcessUtility.ShellAndWaitImpl(ogrInfoFileInfo.DirectoryName, ogrInfoFileInfo.FullName, commandLineArguments, true, Convert.ToInt32(totalMilliseconds));

                var lines = processUtilityResult.StdOut.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (lines.Any(x => x.Contains("Feature Count: 0")))
                {
                    return(null);
                }

                var extentTokens = lines.First(x => x.StartsWith("Extent:")).Split(new[] { ' ', '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                return(new Tuple <double, double, double, double>(double.Parse(extentTokens[1]), double.Parse(extentTokens[2]), double.Parse(extentTokens[4]), double.Parse(extentTokens[5])));
            }
        }
        internal static void LocateCommandlineTools()
        {
            WixCompiler = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("candle.exe"));
            WixLinker = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("light.exe"));
            ManifestTool = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("mt.exe"));
            MakeCatalog = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("makecat.exe"));
            AssemblyLinker = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("al.exe"));

            if (WixCompiler.Executable == null) {
                throw new ConsoleException("Unable to find 'candle.exe' from WiX 3.5 installation.");
            }

            if (WixLinker.Executable == null) {
                throw new ConsoleException("Unable to find 'light.exe' from WiX 3.5 installation.");
            }

            if (ManifestTool.Executable == null) {
                throw new ConsoleException("Unable to find 'mt.exe' from Windows SDK.");
            }

            if (MakeCatalog.Executable == null) {
                throw new ConsoleException("Unable to find 'makecat.exe' from Windows SDK.");
            }

            if (AssemblyLinker.Executable == null) {
                throw new ConsoleException("Unable to find 'al.exe' from Windows SDK.");
            }

            if (ShowTools) {
                Console.WriteLine("Tools:");
                Console.WriteLine("Wix/Candle.exe : {0}", WixCompiler.Executable);
                Console.WriteLine("Wix/Light.exe : {0}", WixLinker.Executable);
                Console.WriteLine("SDK/mt.exe : {0}", ManifestTool.Executable);
                Console.WriteLine("SDK/makecat.exe : {0}", MakeCatalog.Executable);
                Console.WriteLine("SDK/al.exe : {0}", AssemblyLinker.Executable);
            }
        }
예제 #33
0
        /// <summary>
        /// This is the main procedure
        /// </summary>
        /// <param name="args">Command line parameters</param>
        /// <returns>Error codes (0 for success, non-zero on Error)</returns>
        private int main(IEnumerable<string> args)
        {
            var options = args.Where(each => each.StartsWith("--")).Switches();
            var parameters = args.Parameters().ToArray();

            var buildinfo = string.Empty;

            Console.CancelKeyPress += (x, y) => {
                Console.WriteLine("Stopping ptk.");
                if (_cmdexe != null)
                    _cmdexe.Kill();
                if (_gitexe != null)
                    _gitexe.Kill();
                if (_hgexe != null)
                    _hgexe.Kill();
                if (_ptk != null)
                    _ptk.Kill();
            //                if (_traceexe != null) {
              //                  _traceexe.Kill();
            //            }
            };

            #region Parse Options

            // set up options which were defined by the user
            foreach (string arg in options.Keys) {
                IEnumerable<string> argumentParameters = options[arg];

                switch (arg) {
                    case "nologo":
                        // disable logo (will print "\n" anyway)
                        this.Assembly().SetLogo("");
                        break;

                    case "verbose":
                        _verbose = true;
                        break;

                    case "skip-built":
                        _skipBuilt = true;
                        _originalEnvironment.AddOrSet("skip-built", "true");
                        break;

                    case "load":
                        // user specified a custom PropertySheet
                        buildinfo = argumentParameters.LastOrDefault().GetFullPath();
                        if (!File.Exists(buildinfo)) {
                            return Fail("Unable to find buildinfo file [{0}]. \r\n\r\n    Use --help for command line help.", buildinfo);
                        }

                        break;

                    case "mingw-install":
                    case "msys-install":
                        _searchPaths += argumentParameters.LastOrDefault().GetFullPath() + ";";
                        break;

                    case "rescan-tools":
                        ProgramFinder.IgnoreCache = true;
                        break;

                    case "show-tools":
                        _showTools = true;
                        break;

                    case "help":
                        return Help();

                    default:
                        var p = argumentParameters.LastOrDefault();
                        if (string.IsNullOrEmpty(p)) {
                            if( _originalEnvironment.ContainsKey(arg) ) {
                                _originalEnvironment.Remove(arg);
                            }
                        } else{
                            _originalEnvironment.AddOrSet(arg, p);
                        }
                        break;
                }
            }

            // _originalEnvironment.Add("COAPP", CoApp.Toolkit.Engine.PackageManagerSettings.CoAppRootDirectory);
            _originalEnvironment.AddOrSet("COAPP", "C:/programdata/");

            while (string.IsNullOrEmpty(buildinfo) || !File.Exists(buildinfo)) {
                // if the user didn't pass in the file, walk up the tree to find the first directory that has a COPKG\.buildinfo file
                buildinfo = (from a in @".\COPKG\".DirectoryEnumerateFilesSmarter("*.buildinfo", SearchOption.TopDirectoryOnly)
                                     orderby a.Length ascending
                                     select a.GetFullPath()).FirstOrDefault() ?? @".\COPKG\.buildinfo".GetFullPath();

                // try the parent directory.
                var p = Path.GetDirectoryName(Environment.CurrentDirectory);
                if (string.IsNullOrEmpty(p)) {
                    return Fail("Unable to find buildinfo file [COPKG\\.buildinfo]--Even walking up the current tree.\r\n\r\n    Use --help for command line help.");
                }
                Environment.CurrentDirectory = p;
            }

            // make sure that we're in the parent directory of the .buildinfo file.
            Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetDirectoryName(buildinfo));

            sessionFeeds = new[] {Environment.CurrentDirectory, Path.GetDirectoryName(buildinfo)};

            // tell the user what we are
            Logo();

            #endregion

            // connect to coapp service

            // set up several tools we need
            _cmdexe = new ProcessUtility("cmd.exe");
            //var f = new ProgramFinder("").ScanForFile("trace.exe");

            //if(!string.IsNullOrEmpty(f)) {
                //_traceexe = new ProcessUtility(new ProgramFinder("").ScanForFile("trace.exe"));
            //}

            _ptk = new ProcessUtility(Assembly.GetEntryAssembly().Location);
            // if this package is tracked by git, we can use git
            _useGit = Directory.Exists(".git".GetFullPath());            // if this package is tracked by mercurial, we can use mercurial
            _useHg = _useGit ? false : Directory.Exists(".hg".GetFullPath());

            // source control is mandatory! create a repository for this package
            if (!(_useGit || _useHg) && _verbose) {
                Console.WriteLine("WARNING: Source should be checked out using git or hg-git.");
            }

            // find git in the file system
            // - we prefer the CMD script over git.exe
            // git.exe may be located at "C:\Program Files\Git\bin"
            // git.cmd may be located at "C:\Program Files\Git\cmd"
            if (_useGit) {
                if (_verbose) {
                    Console.WriteLine("Using git for verification");
                }
                // attemt to find git.cmd
                _gitcmd = ProgramFinder.ProgramFilesAndDotNet.ScanForFile("git.cmd");
                _gitexe = null;
                if (string.IsNullOrEmpty(_gitcmd)) {
                    var f = ProgramFinder.ProgramFilesAndDotNet.ScanForFile("git.exe");
                    if (string.IsNullOrEmpty(f)) {
                        return Fail("Can not find git.cmd or git.exe (required to perform verification.)");
                    }
                    _gitexe = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("git.exe"));
                }
            }

            if (_useHg) {
                var f = ProgramFinder.ProgramFilesAndDotNet.ScanForFile("hg.exe");
                if (string.IsNullOrEmpty(f)) {
                    return Fail("Can not find hg.exe (required to perform verification.)");
                }
                _hgexe = new ProcessUtility(f);
            }

            // find sdk batch files.

            /* FIXME: URGENT.
             * C:\Program Files (x86)\Microsoft Visual Studio 8\VC\vcvarsall.bat
                C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\vcvars32.bat
                C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\amd64\vcvarsamd64.bat
                C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\x86_amd64\vcvarsx86_amd64.bat
             * VC7.0: C:\Program Files\Microsoft Visual Studio .NET\Vc7\bin\vcvars32.bat

             * */

            _setenvcmd71 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.cmd", excludeFilters: new[] { @"\Windows Azure SDK\**" , "winddk**" }, includeFilters: new [] {"sdk**", "v7.1**"}, rememberMissingFile:true, tagWithCosmeticVersion:"7.1");
            _setenvcmd7 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.cmd", excludeFilters: new[] { @"\Windows Azure SDK\**", "7.1**", "winddk**" }, includeFilters: new[] { "sdk**", "v7**" }, rememberMissingFile: true, tagWithCosmeticVersion: "7.0");
            _setenvcmd6 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.cmd", excludeFilters: new[] { @"\Windows Azure SDK\**", "winddk**" }, includeFilters: new[] { "sdk**", "6**" }, rememberMissingFile: true, tagWithCosmeticVersion: "6");

            _wdksetenvcmd7600 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.bat", excludeFilters: new[] { @"\Windows Azure SDK\**"}, includeFilters: new[] { "winddk**"  }, rememberMissingFile: true, tagWithCosmeticVersion: "7600.16385.1");

            /// SDK Setenv (sdk2003): c:\program files (x86)\Microsoft SDK\SetEnv.bat

            _vcvarsallbat10 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "10.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "10.0");
            _vcvarsallbat9 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "9.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "9.0");
            _vcvarsallbat8 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "8**" }, rememberMissingFile: true, tagWithCosmeticVersion: "8");
            _vcvarsallbat7 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "7.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "7.0");
            _vcvarsallbat71 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "7.1**" }, rememberMissingFile: true, tagWithCosmeticVersion: "7.1");
            _vcvars32bat = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvars32.bat", includeFilters: new[] { "vc98**" }, rememberMissingFile: true, tagWithCosmeticVersion: "6");

            // _originalEnvironment.AddOrSet("COAPP", "C:/programdata/");
            var sdks = new List<string>();
            if (_setenvcmd71 != null) {
                sdks.Add("sdk7.1");
            }
            if (_setenvcmd7 != null) {
                sdks.Add("sdk7");
            }
            if (_setenvcmd6 != null) {
                sdks.Add("sdk6");
            }

            _originalEnvironment.AddOrSet("installed_sdks", sdks.Aggregate((s, s1) => s + ", " + s1));

            var compilers = new List<string>();

            if( _vcvarsallbat10 != null ) {
                compilers.Add("vc10");
            }
            if( _vcvarsallbat9 != null ) {
                compilers.Add("vc9");
            }
            if( _vcvarsallbat8 != null ) {
                compilers.Add("vc8");
            }
            if( _vcvarsallbat71 != null ) {
                compilers.Add("vc7.1");
            }
            if( _vcvarsallbat7 != null ) {
                compilers.Add("vc7");
            }
            if( _vcvars32bat != null ) {
                compilers.Add("vc6");
            }

            _originalEnvironment.AddOrSet("installed_compilers", sdks.Aggregate((s, s1) => s + ", " + s1));

            if (_showTools) {
                if (_useGit) {
                    Console.WriteLine("Git: {0}", _gitcmd ??  (_gitexe != null ? _gitexe.Executable : "Not-Found"));
                }
                if (_useHg) {
                    Console.WriteLine("hg: {0}", _hgexe.Executable);
                }
                Console.WriteLine("SDK Setenv (7.1): {0}", _setenvcmd71 ?? "Not-Found");
                Console.WriteLine("SDK Setenv (7.0): {0}", _setenvcmd7 ?? "Not-Found");
                Console.WriteLine("SDK Setenv (6): {0}", _setenvcmd6 ?? "Not-Found");

                Console.WriteLine("VC vcvarsall (10.0): {0}", _vcvarsallbat10 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (9.0): {0}", _vcvarsallbat9 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (8.0): {0}", _vcvarsallbat8 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (7.0): {0}", _vcvarsallbat7 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (7.1): {0}", _vcvarsallbat71 ?? "Not-Found");
                Console.WriteLine("VC vcvars32 (6): {0}", _vcvars32bat ?? "Not-Found");

                Console.WriteLine("ptk: {0}", _ptk.Executable);
                //Console.WriteLine("trace: {0}", _traceexe.Executable);
            }

            // tell the user we can't work without instructions
            if (!parameters.Any()) {
                return Fail("Missing action . \r\n\r\n    Use --help for command line help.");
            }

            // load property sheet (that is the .buildinfo file by default)
            _propertySheet = null;
            try {
                // load and parse. propertySheet will contain everything else we need for later
                _propertySheet = PropertySheet.Load(buildinfo);

                DefineRules = _propertySheet.Rules.Where(each => each.Id == "define" && each.Name == "*").ToArray();

                _propertySheet.GetMacroValue += (valueName) => {
                    if (valueName == "DEFAULTLAMBDAVALUE") {
                        return ".";
                    }

                    string defaultValue = null;
                    if( valueName.Contains("??")) {
                        var parts = valueName.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries);
                        defaultValue = parts.Length > 1 ? parts[1].Trim() : string.Empty;
                        valueName = parts[0];
                    }

                     var property = (from rule in DefineRules where rule.HasProperty(valueName) select rule[valueName]).FirstOrDefault();

                     if (property != null && property.HasValues && property.Values.Count() > 1) {
                         // it's a collection of values.
                         // let's take the collection and return it as a comma seperated string.
                         return property.Values.Aggregate((s, s1) => s + ", " + s1);
                     }

                    return (from rule in DefineRules where rule.HasProperty(valueName) select rule[valueName].Value).FirstOrDefault() ?? Environment.GetEnvironmentVariable(valueName) ?? defaultValue;
                };

                _propertySheet.GetCollection += (collectionName) => {
                    var property = (from rule in DefineRules where rule.HasProperty(collectionName) select rule[collectionName]).FirstOrDefault();
                    if( property != null && property.HasValues && property.Values.Count() > 1 ) {
                        return property.Values;
                    }
                    var collection = _propertySheet.GetMacroValue(collectionName);
                    return collection != null ? collection.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(each => each.Trim()) : Enumerable.Empty<object>();
                };
            }
            catch (EndUserParseException pspe) {
                using (new ConsoleColors(ConsoleColor.Yellow, ConsoleColor.Black)) {
                    Console.Write(pspe.Message);
                    Console.WriteLine("--found '{0}'", pspe.Token.Data);
                }

                return Fail("Error parsing .buildinfo file");
            }

            var builds = from rule in _propertySheet.Rules where rule.Name != "*" && (rule.HasProperty("default") && rule["default"].Value.IsTrue()) select rule;
            var command = string.Empty;

            switch(parameters.FirstOrDefault().ToLower()) {
                case "build ":
                case "clean":
                case "verify":
                case "status":
                case "trace":
                case "list":
                    command = parameters.FirstOrDefault().ToLower();
                    parameters = parameters.Skip(1).ToArray();
                    break;

                default:
                    command = "build";
                    break;
            }
            if (parameters.Any()) {
                var allbuilds = from rule in _propertySheet.Rules where rule.Name != "*" select rule;
                builds = parameters.Aggregate(Enumerable.Empty<Rule>(), (current, p) => current.Union(from build in allbuilds where build.Name.NewIsWildcardMatch(p) select build));
            }

            // are there even builds present?
            if(!builds.Any() ) {
                return Fail("No valid build configurations selected.");
            }

            // do the user's bidding
            try {
                switch (command) {
                    case "build":
                        ResetEnvironment();
                        Build(builds);

                        break;
                    case "clean":
                        ResetEnvironment();
                        Clean(builds);
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Project Cleaned.");
                        }
                        break;
                    case "verify":
                        ResetEnvironment();
                        // Clean(builds); // clean up other builds in the list first.
                        Verify(builds);
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Project Verified.");
                        }
                        break;
                    case "status":
                        ResetEnvironment();
                        Status(builds);
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Project is in clean state.");
                        }
                        break;
                    //case "trace":
                      //  Trace(builds);
                        //break;
                    case "list":
                        Console.WriteLine("Buildinfo from [{0}]\r\n", buildinfo);
                        (from build in builds
                            let compiler = build["compiler"]
                            let sdk = build["sdk"]
                            let platform = build["platform"]
                            let targets = build["targets"]
                            select new {
                                Configuration = build.Name,
                                Compiler = compiler != null ? compiler.Value : "sdk7.1",
                                Sdk = sdk != null ? sdk.Value : "sdk7.1",
                                Platform = platform != null ? platform.Value.NormalizePlatform() : "x86",
                                Number_of_Outputs = targets != null ? targets.Values.Count() : 0
                            }).ToTable().ConsoleOut();
                        break;
                    default:
                        return Fail("'{0}' is not a valid command. \r\n\r\n    Use --help for assistance.", command);
                }
            }
            catch (ConsoleException e) {
                // these exceptions are expected
                return Fail("   {0}", e.Message);
            }
            catch (Exception e) {
                // it's probably okay to crash within proper commands (because something else crashed)
                Console.WriteLine(e.StackTrace);
                return Fail("   {0}", e.Message);
            }

            return 0;
        }
예제 #34
0
 public static string PublicKeyTokenAsString(this X509Certificate2 cert)
 {
     var tempfile = Path.GetTempFileName() + ".cer";
     File.WriteAllBytes(tempfile, cert.GetRawCertData());
     var _pktExtract = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("pktExtract.exe"));
     _pktExtract.Exec("-nologo -quiet {0}", tempfile);
     var publicKeyToken = _pktExtract.StandardOut.Trim();
     File.Delete(tempfile);
     return publicKeyToken;
 }
예제 #35
0
        /// <summary>
        /// This is the main procedure
        /// </summary>
        /// <param name="args">Command line parameters</param>
        /// <returns>Error codes (0 for success, non-zero on Error)</returns>
        private int main(IEnumerable<string> args)
        {
            var options = args.Switches();
            var parameters = args.Parameters();
            var tempBuildinfo = (from a in @".\COPKG\".DirectoryEnumerateFilesSmarter("*.buildinfo", SearchOption.TopDirectoryOnly)
                                 orderby a.Length ascending
                                 select a.GetFullPath()).FirstOrDefault();
            // find PropertySheet location
            //we'll just use the default even though it won't work so I don't need to change the code much :)
            var buildinfo = tempBuildinfo ?? @".\COPKG\.buildinfo".GetFullPath();

            Console.CancelKeyPress += (x, y) => {
                Console.WriteLine("Stopping ptk.");
                if (_cmdexe != null)
                    _cmdexe.Kill();
                if (_gitexe != null)
                    _gitexe.Kill();
                if (_hgexe != null)
                    _hgexe.Kill();
                if (_ptk != null)
                    _ptk.Kill();
                if (_traceexe != null) {
                    _traceexe.Kill();
                }
            };

            #region Parse Options

            // set up options which were defined by the user
            foreach (string arg in options.Keys) {
                IEnumerable<string> argumentParameters = options[arg];

                switch (arg) {
                    case "nologo":
                        // disable logo (will print "\n" anyway)
                        this.Assembly().SetLogo("");
                        break;

                    case "verbose":
                        _verbose = true;
                        break;

                    case "load":
                        // user specified a custom PropertySheet
                        buildinfo = argumentParameters.LastOrDefault().GetFullPath();
                        break;

                    case "mingw-install":
                    case "msys-install":
                        _searchPaths += argumentParameters.LastOrDefault().GetFullPath() + ";";
                        break;

                    case "rescan-tools":
                        ProgramFinder.IgnoreCache = true;
                        break;

                    case "show-tools":
                        _showTools = true;
                        break;

                    case "help":
                        return Help();
                }
            }

            if (!File.Exists(buildinfo)) {
                return Fail("Unable to find buildinfo file [{0}]. \r\n\r\n    Use --help for command line help.", buildinfo);
            }

            // make sure that we're in the parent directory of the .buildinfo file.
            Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetDirectoryName(buildinfo));

            // tell the user what we are
            Logo();

            // tell the user we can't work without instructions
            if (parameters.Count() < 1) {
                return Fail("Missing action . \r\n\r\n    Use --help for command line help.");
            }

            #endregion

            // set up several tools we need
            _cmdexe = new ProcessUtility("cmd.exe");
            var f = new ProgramFinder("").ScanForFile("trace.exe");

            if(!string.IsNullOrEmpty(f)) {
                _traceexe = new ProcessUtility(new ProgramFinder("").ScanForFile("trace.exe"));
            }

            _ptk = new ProcessUtility(Assembly.GetEntryAssembly().Location);
            // if this package is tracked by git, we can use git
            _useGit = Directory.Exists(".git".GetFullPath());            // if this package is tracked by mercurial, we can use mercurial
            _useHg = _useGit ? false : Directory.Exists(".hg".GetFullPath());

            // source control is mandatory! create a repository for this package
            if (!(_useGit || _useHg)) {
                return Fail("Source must be checked out using git or hg-git.");
            }

            // find git in the file system
            // - we prefer the CMD script over git.exe
            // git.exe may be located at "C:\Program Files\Git\bin"
            // git.cmd may be located at "C:\Program Files\Git\cmd"
            if (_useGit) {
                if (_verbose) {
                    Console.WriteLine("Using git for verification");
                }
                // attemt to find git.cmd
                _gitcmd = ProgramFinder.ProgramFilesAndDotNet.ScanForFile("git.cmd");
                _gitexe = null;
                if (string.IsNullOrEmpty(_gitcmd)) {
                    f = ProgramFinder.ProgramFilesAndDotNet.ScanForFile("git.exe");
                    if (string.IsNullOrEmpty(f)) {
                        return Fail("Can not find git.cmd or git.exe (required to perform verification.)");
                    }
                    _gitexe = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("git.exe"));
                }
            }

            if (_useHg) {
                 f = ProgramFinder.ProgramFilesAndDotNet.ScanForFile("hg.exe");
                if (string.IsNullOrEmpty(f)) {
                    return Fail("Can not find hg.exe (required to perform verification.)");
                }
                _hgexe = new ProcessUtility(f);
            }

            // find sdk batch files.

            _setenvcmd71 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.cmd", excludeFilters: new[] { @"\Windows Azure SDK\**" , "winddk**" }, includeFilters: new [] {"sdk**", "v7.1**"}, rememberMissingFile:true, tagWithCosmeticVersion:"7.1");
            _setenvcmd7 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.cmd", excludeFilters: new[] { @"\Windows Azure SDK\**", "7.1**", "winddk**" }, includeFilters: new[] { "sdk**", "v7**" }, rememberMissingFile: true, tagWithCosmeticVersion: "7.0");
            _setenvcmd6 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.cmd", excludeFilters: new[] { @"\Windows Azure SDK\**", "winddk**" }, includeFilters: new[] { "sdk**", "6**" }, rememberMissingFile: true, tagWithCosmeticVersion: "6");

            _wdksetenvcmd7600 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("setenv.bat", excludeFilters: new[] { @"\Windows Azure SDK\**"}, includeFilters: new[] { "winddk**"  }, rememberMissingFile: true, tagWithCosmeticVersion: "7600.16385.1");

            _vcvarsallbat10 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "10.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "10.0");
            _vcvarsallbat9 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "9.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "9.0");
            _vcvarsallbat8 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "8.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "8.0");
            _vcvarsallbat7 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "7.0**" }, rememberMissingFile: true, tagWithCosmeticVersion: "7.0");
            _vcvarsallbat71 = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvarsall.bat", includeFilters: new[] { "vc**", "7.1**" }, rememberMissingFile: true, tagWithCosmeticVersion: "7.1");
            _vcvars32bat = ProgramFinder.ProgramFilesAndDotNetAndSdk.ScanForFile("vcvars32.bat", includeFilters: new[] { "vc98**" }, rememberMissingFile: true, tagWithCosmeticVersion: "6");

            if (_showTools) {
                if (_useGit) {
                    Console.Write("Git: {0}", _gitcmd ?? "");
                    if (_gitexe != null) {
                        Console.WriteLine(_gitexe.Executable ?? "");
                    }
                }
                if (_useHg) {
                    Console.WriteLine("hg: {0}", _hgexe.Executable);
                }
                Console.WriteLine("SDK Setenv (7.1): {0}", _vcvarsallbat10 ?? "Not-Found");
                Console.WriteLine("SDK Setenv (7.0): {0}", _setenvcmd7 ?? "Not-Found");
                Console.WriteLine("SDK Setenv (6): {0}", _setenvcmd6 ?? "Not-Found");

                Console.WriteLine("VC vcvarsall (10.0): {0}", _vcvarsallbat10 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (9.0): {0}", _vcvarsallbat9 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (8.0): {0}", _vcvarsallbat8 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (7.0): {0}", _vcvarsallbat7 ?? "Not-Found");
                Console.WriteLine("VC vcvarsall (7.1): {0}", _vcvarsallbat71 ?? "Not-Found");
                Console.WriteLine("VC vcvars32 (6): {0}", _vcvars32bat ?? "Not-Found");

                Console.WriteLine("ptk: {0}", _ptk.Executable);
                Console.WriteLine("trace: {0}", _traceexe.Executable);
            }

            // load property sheet (that is the .buildinfo file by default)
            PropertySheet propertySheet = null;
            try {
                // load and parse. propertySheet will contain everything else we need for later
                propertySheet = PropertySheet.Load(buildinfo);
                propertySheet.GetMacroValue += (valueName) => {
                    return null;
                };
                propertySheet.GetCollection += (collectionName) => {
                    return Enumerable.Empty<object>();
                };
            }
            catch (EndUserParseException pspe) {
                using (new ConsoleColors(ConsoleColor.Yellow, ConsoleColor.Black)) {
                    Console.Write(pspe.Message);
                    Console.WriteLine("--found '{0}'", pspe.Token.Data);
                }

                return Fail("Error parsing .buildinfo file");
            }
            var builds = from rule in propertySheet.Rules where rule.Name != "*" select rule;
            if (parameters.Count() > 1) {
                var allbuilds = builds;
                builds = parameters.Skip(1).Aggregate(Enumerable.Empty<Rule>(), (current, p) => current.Union(from build in allbuilds where build.Name.IsWildcardMatch(p) select build));
            }

            // are there even builds present?
            if(builds.Count() == 0 ) {
                return Fail("No valid build configurations selected.");
            }

            // do the user's bidding
            try {
                switch (parameters.FirstOrDefault().ToLower()) {
                    case "build":
                        Build(builds);

                        break;
                    case "clean":
                        Clean(builds);
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Project Cleaned.");
                        }
                        break;
                    case "verify":
                        Clean(builds); // clean up other builds in the list first.
                        Verify(builds);
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Project Verified.");
                        }
                        break;
                    case "status":
                        Status(builds);
                        using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
                            Console.WriteLine("Project is in clean state.");
                        }
                        break;
                    case "trace":
                        Trace(builds);
                        break;
                    case "list":
                        Console.WriteLine("Buildinfo from [{0}]", buildinfo);
                        (from build in builds
                            let compiler = build["compiler"]
                            let sdk = build["sdk"]
                            let platform = build["platform"]
                            let targets = build["targets"]
                            select new {
                                Configuration = build.Name,
                                Compiler = compiler != null ? compiler.Value : "sdk7.1",
                                Sdk = sdk != null ? sdk.Value : "sdk7.1",
                                Platform = platform != null ? platform.Value : "x86",
                                Number_of_Outputs = targets != null ? targets.Values.Count() : 0
                            }).ToTable().ConsoleOut();
                        break;
                    default:
                        return Fail("'{0}' is not a valid command. \r\n\r\n    Use --help for assistance.");
                }
            }
            catch (ConsoleException e) {
                // these exceptions are expected
                return Fail("   {0}", e.Message);
            }
            catch (Exception e) {
                // it's probably okay to crash within proper commands (because something else crashed)
                Console.WriteLine(e.StackTrace);
                return Fail("   {0}", e.Message);
            }

            return 0;
        }
예제 #36
0
        private int main(string[] args)
        {
            var options = args.Switches();
            var parameters = args.Parameters();

            #region Parse Options

            try
            {
                foreach (string arg in options.Keys)
                {
                    IEnumerable<string> argumentParameters = options[arg];

                    switch (arg)
                    {
                        /* global switches */
                        case "load-config":
                            // all ready done, but don't get too picky.
                            break;
                        case "nologo":
                            this.Assembly().SetLogo("");
                            break;

                        case "verbose":
                            verbose = true;
                            break;

                        case "help":
                            return Help();

                        case "cert-file":
                            certFile = argumentParameters.First();
                            break;
                        case "cert-pass":
                            certPass = argumentParameters.First();
                            break;
                        case "msm-dir":
                            msmDir = argumentParameters.First();
                            break;
                        case "version":
                            version = argumentParameters.First();
                            break;
                    }
                }

                Logo();

            #endregion

                _candle = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("candle.exe"));
                _light = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("light.exe"));

                _signTool = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("signTool.exe"));

                var pfxStore = PfxStoreLoader.Load(certFile, certPass);
                if (pfxStore != null)
                {
                    var codeSigningCert = pfxStore.FindCodeSigningCert();
                    if (codeSigningCert == null)
                        return Fail("No code signing certificate found.");
                }
                else
                {
                    return Fail("Couldn't open the certificate file.");
                }

                var files = Directory.EnumerateFiles(msmDir, "*.msm", SearchOption.TopDirectoryOnly);
                var groups = from f in files
                             let fi = new FileInfo(f)
                             where fi.Name.StartsWith("Microsoft") && !fi.Name.Contains("Debug")
                             let version = new String(fi.Name.Split('_')[1].Substring(2).TakeAllBut(1).ToArray())
                             group f by version into versions
                             select new
                             {
                                 Version = versions.Key,
                                 ArchGroups = (from a in versions

                                               let possArch = new String(a.TakeAllBut(4).TakeFromEnd(3).ToArray())

                                               group a by possArch into archs
                                               select new
                                               {
                                                   Arch = archs.Key,
                                                   Files = archs
                                               })

                             };

                foreach (var g in groups)
                {
                    var vers = g.Version;

                    if (version == null || version.ExtendVersion() == vers.ExtendVersion())
                    {

                        foreach (var a in g.ArchGroups)
                        {
                            Console.WriteLine("Building {0} for {1}".format(vers, a.Arch));
                            var outputFile = "{0}-{1}-{2}.msi".format("VC", vers.ExtendVersion(), a.Arch);
                            XDocument wix;
                            var huid = new Huid("Visual C/C++ Runtime Library", vers.ExtendVersion(), a.Arch, "");

                            using (var reader = new StringReader(Resources.WixTemplate))
                            {
                                wix = XDocument.Load(reader);
                            }

                            var productTag = wix.Descendants("Product").First();

                            var targetDir = (from d in productTag.Descendants()
                                             where d.Name == "Directory" &&
                                                 d.Attribute("Id").Value == "TARGETDIR"
                                             select d).First();

                            productTag.SetAttributeValue("Name", "Visual C/C++ Runtime Library");
                            productTag.SetAttributeValue("Version", vers.ExtendVersion());
                            productTag.SetAttributeValue("Manufacturer", "Microsoft");
                            productTag.SetAttributeValue("Id", huid.ToString());

                            int counter = 0;
                            var ids = new List<int>();
                            foreach (var f in a.Files)
                            {
                                targetDir.Add(
                                    new XElement("Merge",
                                        new XAttribute("Id", "VC" + counter),
                                        new XAttribute("SourceFile", f),
                                        new XAttribute("DiskId", "1"),
                                        new XAttribute("Language", "0")));
                                ids.Add(counter);
                                counter++;
                            }

                            var feature = productTag.Descendants("Feature").First();
                            foreach (var i in ids)
                            {
                                feature.Add(
                                    new XElement("MergeRef",
                                        new XAttribute("Id", "VC" + i)));
                            }

                            var packageTag = productTag.Descendants("Package").First();
                            packageTag.SetAttributeValue("Platform", a.Arch);

                            //add the Wix namespace
                            XNamespace wixNS = "http://schemas.microsoft.com/wix/2006/wi";

                            foreach (var n in wix.Descendants())
                            {
                                n.Name = wixNS + n.Name.LocalName;
                            }

                            var tempPrefix = Path.GetTempFileName();
                            File.WriteAllText(tempPrefix + ".wxs", wix.ToString());

                            if (_candle.Exec("-nologo -sw1075 -out {0}.wixobj {0}.wxs", tempPrefix) != 0)
                                return Fail(_candle.StandardOut);

                            //we suppress the lack of UpgradeCode warning since we don't use them
                            if (_light.Exec("-nologo -sw1076 -out {1} {0}.wixobj", tempPrefix, outputFile) != 0)
                                return Fail(_light.StandardOut);

                            if (!signFile(outputFile))
                                return Fail("Couldn't sign file");

                        }
                    }

                }

            }
            catch (ConsoleException e)
            {
                return Fail("   {0}", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return Fail("   {0}", e.Message);
            }

            return 0;
        }
예제 #37
0
        private ProcessUtility Exec(string script, string currentDirectory)
        {
            var cmdexe = new ProcessUtility("cmd.exe");

            if (script.Contains("\r")) {
                script =
            @"@echo off
            @setlocal
            @cd ""{0}""

            ".format(currentDirectory) + script;
                var scriptpath = WriteTempScript(script);
                cmdexe.Exec("/c {0}", scriptpath);
            }
            else {
                cmdexe.Exec("/c {0}", script);
            }

            return cmdexe;
        }
예제 #38
0
        /// <summary>
        ///   The (non-static) startup method
        /// </summary>
        /// <param name = "args">
        ///   The command line arguments.
        /// </param>
        /// <returns>
        ///   Process return code.
        /// </returns>
        protected override int Main(IEnumerable<string> args)
        {
            try
            {

                pkgMgr = new PackageManager();

                #region command line parsing

                // default:
                var options = args.Switches();
                var parameters = args.Parameters();

                foreach (var arg in options.Keys)
                {
                    var argumentParameters = options[arg];

                    switch (arg)
                    {
                        /* options  */

                        /* global switches */
                        case "load-config":
                            // all ready done, but don't get too picky.
                            break;

                        case "nologo":
                            this.Assembly().SetLogo(string.Empty);
                            break;

                        case "show-tools":
                            showTools = Boolean.Parse(argumentParameters.First());
                            break;
                        case "help":
                            return Help();

                        default:
                            if (arg.StartsWith("package-"))
                            {
                                var argName = arg.Substring(8);
                                var argValue = argumentParameters.First();
                                switch (argName)
                                {
                                    case "name":
                                        package.PackageName = argValue;
                                        break;
                                    case "version":
                                        package.PackageVersion = argValue;
                                        break;
                                    case "arch":
                                        package.PackageArch = argValue;
                                        break;
                                    case "icon":
                                        package.IconPath = argValue;
                                        break;
                                    case "short-desc":
                                        package.ShortDescriptionPath = argValue;
                                        break;
                                    case "description":
                                        package.DescriptionPath = argValue;
                                        break;
                                    case "author-version":
                                        package.AuthorVersion = argValue;
                                        break;
                                    case "display-name":
                                        package.DisplayName = argValue;
                                        break;
                                    case "policy":
                                        package.BindingPolicy = argValue;
                                        break;
                                    case "license":
                                        package.LicensePath = argValue;
                                        break;
                                    case "license-url":
                                        package.LicenseUrlEntry = argValue;
                                        break;
                                    case "orig-location":
                                        package.Location = argValue;
                                        break;
                                    case "feed-location":
                                        package.Feed = argValue;
                                        break;
                                    default:
                                        throw new ConsoleException(Resources.UnknownParameter, arg);
                                }
                            }
                            else if (arg.StartsWith("identity-"))
                            {
                                var argName = arg.Substring(9);
                                var argValue = argumentParameters.First();

                                switch (argName)
                                {
                                    case "cert-file":
                                        package.CertificateFile = argValue;
                                        break;
                                    case "cert-pass":
                                        certificatePassword = argValue;
                                        break;
                                    case "email":
                                        package.PubEmail = argValue;
                                        break;
                                    case "website":
                                        package.PubWebsite = argValue;
                                        break;
                                    default:
                                        throw new ConsoleException(Resources.UnknownParameter, arg);

                                }
                            }
                            //we do
                            else if (arg.StartsWith("dependency-"))
                            {
                                var argName = arg.Substring(11);
                                var argValue = argumentParameters.First(); ;

                                switch (argName)
                                {
                                    case "add":
                                        package.DependencyNames.Add(argValue);
                                        break;
                                    default:
                                        throw new ConsoleException(Resources.UnknownParameter, arg);

                                }
                            }
                            else if (arg.StartsWith("app-"))
                            {
                                if (package.Apps == null)
                                    package.Apps = new App();

                                parseAppArgument(arg.Substring(4), argumentParameters.First());

                            }
                            else if (arg.StartsWith("sharedlib-"))
                            {
                                if (package.SharedLibs == null)
                                    package.SharedLibs = new SharedLib();

                                parseSharedLibArgument(arg.Substring(10), argumentParameters.First());

                            }
                            else
                            {
                                throw new ConsoleException(Resources.UnknownParameter, arg);
                            }
                            break;

                    }
                }

                Logo();

                /*
                if (parameters.Count() < 1)
                {
                    throw new ConsoleException(Resources.MissingCommand);
                }
                */
                #endregion

                // GS01: I'm putting this in here so that feed resoltion happens before we actually get around to doing something.
                // Look into the necessity later.
                Tasklet.WaitforCurrentChildTasks();

                #region Tool Scanning

                Console.Write(Resources.ToolLookup);

                _candle = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("candle.exe"));
                _light = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("light.exe"));
                _mt = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("mt.exe"));
                _makecat = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("makecat.exe"));
                _al = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("al.exe"));
                _signTool = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("signTool.exe"));
                _sn = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("sn.exe"));
                _pktExtract = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("pktExtract.exe"));

                if (_candle.Executable == null)
                    errors.Add(Resources.MissingCandle);

                if (_light.Executable == null)
                    errors.Add(Resources.MissingLight);

                if (_mt.Executable == null)
                    errors.Add(Resources.MissingMt);

                if (_makecat.Executable == null)
                    errors.Add(Resources.MissingMakeCat);

                if (_al.Executable == null)
                    errors.Add(Resources.MissingAl);

                if (_signTool.Executable == null)
                    errors.Add(Resources.MissingSignTool);

                if (_sn.Executable == null)
                    errors.Add(Resources.MissingSn);

                if (_pktExtract.Executable == null)
                    errors.Add(Resources.MissingPktExtract);

                if (errors.AreFatal())
                {
                    throw new ConsoleException(errors.StringOut());
                }

                Console.WriteLine(Resources.Finished);

                if (showTools)
                {
                    Console.WriteLine("Tools:");
                    Console.WriteLine(_candle.Executable);
                    Console.WriteLine(_light.Executable);
                    Console.WriteLine(_mt.Executable);
                    Console.WriteLine(_makecat.Executable);
                    Console.WriteLine(_al.Executable);
                    Console.WriteLine(_signTool.Executable);
                    Console.WriteLine(_sn.Executable);
                }

                #endregion

                Console.WriteLine(Resources.ScanningInstalledPackages);
                var installedPackages = pkgMgr.GetInstalledPackages(new PackageManagerMessages
                {
                    PackageScanning = (progress) => { Resources.Scanning.PrintProgressBar(progress); }
                });

                installedPackages.Wait();

                // the progress bar never sends in a line break
                Console.WriteLine();

                //TODO check for invalid file paths

                //TODO check for pre-signed files and whether they're properly signed

                //TODO make sure files in app roles are proper children

                //TODO this doesn't work if the packages are a superceding version of the one given
                //TODO this doesn't work if the packages are in the same directory

                //get the dependencies and Assemblies

                foreach (var dep in package.DependencyNames)
                {
                    var depPackage = (from p in installedPackages.Result
                                      where p.CosmeticName.IsWildcardMatch(dep)
                                      orderby p.Version descending
                                      select p).FirstOrDefault();
                    if (depPackage == null)
                    {
                        errors.Add(Resources.DepNotSatifiable.format(dep));
                    }
                    else
                    {
                        package.DependencyInfo.Add(depPackage);
                    }
                }
                //TODO make sure the numbers are not larger than the max a part of a version string
                var policyRegex = new Regex(@"^policy\.\d{1,5}\.\d{1,5}\.\S+$");
                var dependentAssemblies = from p in package.DependencyInfo
                                          from a in p.Assemblies
                                          where !a.Type.Contains("policy") &&
                                          !policyRegex.IsMatch(a.Name)
                                          select a;

                #region Sanity checking primarily

                //let's check for valid roles!
                if (package.SharedLibs == null && package.Apps == null)
                    errors.Add(Resources.NoRoles);

                if (package.PackageArch == null ||
                    (!ValidArchs.Contains(package.PackageArch.ToLower()) && package.PackageArch != "auto"))
                    errors.Add(Resources.MissingPackageArch);

                if (package.PackageVersion == null || !package.PackageVersion.IsValidVersion() &&
                    package.PackageVersion != "auto")
                    errors.Add(Resources.MissingPackageVersion);

                if ((package.PackageArch == "auto" || package.PackageVersion == "auto") && firstBinFile == null)
                    errors.Add(Resources.NoBinaryFileProvided);

                //get Arch and Version if it's auto
                if (package.PackageArch == "auto")
                {
                    if (firstBinFile != null)
                    {
                        var binType = ProgramFinder.GetExeType(firstBinFile);
                        if (binType.HasFlag(ExecutableInfo.any) || binType.HasFlag(ExecutableInfo.managed))
                            package.PackageArch = "any";
                        else if (binType.HasFlag(ExecutableInfo.x86))
                            package.PackageArch = "x86";
                        else if (binType.HasFlag(ExecutableInfo.x64))
                            package.PackageArch = "x64";
                        else
                            errors.Add(Resources.NoArchDiscovered.format(firstBinFile));
                    }
                }

                if (package.PackageVersion == "auto")
                {
                    if (firstBinFile != null)
                    {
                        var versionStr = ProgramFinder.GetToolVersion(firstBinFile);
                        if (versionStr == null || !versionStr.IsValidVersion())
                            errors.Add(Resources.NoVersionDiscovered.format(firstBinFile));
                        else
                            package.PackageVersion = versionStr;

                    }
                }

                //TODO  make sure the name is valid!

                //make sure the major minors given are valid
                if (package.SharedLibs != null)
                {
                    foreach (var i in package.SharedLibs.MajorMinorsToReplace)
                    {
                        if (!i.IsValidMajorMinorVersion())
                        {
                            errors.Add(Resources.InvalidMajorMinor.format(i));
                        }
                    }
                }

                //load and check pfx file

                var pfxStore = PfxStoreLoader.Load(package.CertificateFile, certificatePassword);

                if (pfxStore == null)
                    errors.Add(Resources.InvalidPfx);
                else
                {
                    var codeSigningCert = pfxStore.FindCodeSigningCert();

                    if (codeSigningCert == null)
                        errors.Add(Resources.NoCodeSigningCert);
                    else
                    {
                        if ((package.PubToken = codeSigningCert.PublicKeyTokenAsString()) == null)
                        {
                            errors.Add(Resources.FailedPktExtraction);
                        }

                        var nameParts = codeSigningCert.GetSubjectNameParts();
                        if (nameParts.ContainsKey("CN"))
                        {
                            package.PubName = nameParts["CN"];
                        }
                        else
                        {
                            errors.Add(Resources.NoNameExtracted.format(package.CertificateFile));
                        }

                        if (package.PubEmail == "auto")
                        {
                            if (nameParts.ContainsKey("E"))
                            {
                                package.PubEmail = nameParts["E"];
                            }
                            else
                            {
                                errors.Add(Resources.NoPubEmailFound.format(package.CertificateFile));
                            }
                        }

                    }
                }

                if (package.PubEmail != null && !package.PubEmail.IsEmail())
                {
                    errors.Add(Resources.InvalidEmail.format(package.PubEmail));
                }

                if (package.IconPath != null)
                {
                    try
                    {
                        var iconFile = File.ReadAllBytes(package.IconPath);
                        using (var bytes = new MemoryStream(iconFile))
                        {
                            Image image = Image.FromStream(bytes);
                            if (image.RawFormat != ImageFormat.Png ||
                                image.Height != REQUIRED_ICON_HEIGHT ||
                                image.Width != REQUIRED_ICON_WIDTH)
                            {
                                errors.Add(Resources.InvalidIconFile.
                                    format(package.IconPath, REQUIRED_ICON_WIDTH, REQUIRED_ICON_HEIGHT));
                            }
                        }

                        package.Icon = Convert.ToBase64String(iconFile);
                    }
                    catch (OutOfMemoryException)
                    {
                        errors.Add(Resources.InvalidIconFile.
                            format(package.IconPath, REQUIRED_ICON_WIDTH, REQUIRED_ICON_HEIGHT));
                    }
                    catch (IOException)
                    {

                        errors.Add(Resources.FailedIconFileOpen.format(package.IconPath));
                    }
                }
                else
                {
                    package.Icon = Convert.ToBase64String(Resources.blankicon);
                }

                if (package.ShortDescriptionPath != null)
                {
                    try
                    {
                        package.ShortDescription = File.ReadAllText(package.ShortDescriptionPath);

                        if (package.ShortDescriptionPath.Length > MAX_SUMMARY_DESCRIPTION_LENGTH)
                        {
                            errors.Add(Resources.ShortDescriptionTooLong.
                                format(package.ShortDescriptionPath, MAX_SUMMARY_DESCRIPTION_LENGTH));
                        }
                    }
                    catch (NotSupportedException)
                    {
                        errors.Add(Resources.InvalidShortDescriptionFile.format(package.ShortDescriptionPath));
                    }
                    catch (IOException)
                    {
                        errors.Add(Resources.FailedShortDescriptionFileOpen.format(package.ShortDescriptionPath));
                    }
                }

                if (package.DescriptionPath != null)
                {
                    try
                    {
                        package.Description = File.ReadAllText(package.DescriptionPath);

                    }
                    catch (NotSupportedException)
                    {
                        errors.Add(Resources.InvalidDescriptionFile.format(package.DescriptionPath));
                    }
                    catch (IOException)
                    {
                        errors.Add(Resources.FailedDescriptionFileOpen.format(package.DescriptionPath));
                    }
                }

                if (package.PublishDate != null)
                {
                    try
                    {
                        DateTime.Parse(package.PublishDate);
                    }
                    catch (FormatException)
                    {
                        errors.Add(Resources.InvalidPublishDate.format(package.PublishDate));
                    }
                }
                else
                {
                    package.PublishDate = DateTime.Now.ToShortDateString();
                }

                if (package.LicensePath != null)
                {
                    try
                    {
                        package.LicenseText = File.ReadAllText(package.LicensePath);
                        if (package.LicenseUrlEntry != null)
                        {
                            try
                            {
                                var uri = new Uri(package.LicenseUrlEntry);
                                if (!uri.IsHttpScheme())
                                    errors.Add(Resources.InvalidLicenseUrlScheme.format(package.LicenseUrlEntry));

                                package.LicenseUrl = package.CreateUrl(package.LicenseUrlEntry, "license");
                            }
                            catch (UriFormatException)
                            {
                                errors.Add(Resources.InvalidLicenseUrl.format(package.LicenseUrlEntry));
                            }
                        }
                    }
                    catch (NotSupportedException)
                    {
                        errors.Add(Resources.InvalidLicenseText.format(package.LicensePath));
                    }
                    catch (IOException)
                    {
                        errors.Add(Resources.FailedLicenseFileOpen.format(package.LicensePath));
                    }
                }
                else
                {
                    if (package.LicenseUrlEntry != null)
                    {
                        errors.Add(Resources.LicenseUrlWithoutText, false);
                    }
                }

                if (package.Feed != null)
                {
                    try
                    {
                        var uri = new Uri(package.Feed);
                        if (!uri.IsHttpScheme())
                            errors.Add(Resources.InvalidFeedUrlScheme.format(package.Feed));

                        package.FeedUrl = package.CreateUrl(package.Feed, "feed_location");
                    }
                    catch (UriFormatException)
                    {
                        errors.Add(Resources.InvalidFeedUrl.format(package.Feed));
                    }
                }

                if (package.Location != null)
                {
                    try
                    {
                        var uri = new Uri(package.Location);
                        if (!uri.IsHttpScheme())
                            errors.Add(Resources.InvalidOriginalUrlScheme.format(package.Location));
                        package.LocationUrl = package.CreateUrl(package.Location, "original_location");
                    }
                    catch (UriFormatException)
                    {
                        errors.Add(Resources.InvalidOriginalUrl.format(package.Location));
                    }
                }

                if (errors.AreFatal())
                {
                    throw new ConsoleException(errors.StringOut());
                }

                foreach (Match m in Regex.Matches(package.BindingPolicy, @"{{(\$CURRENT-\d+)}}"))
                {
                    var i = m.Groups[1].Value;
                    var two = i.Split('-');
                    package.BindingPolicy =
                        package.BindingPolicy.Replace(m.Value,
                            (package.PackageVersion.VersionStringToUInt64() - UInt64.Parse(two[1])).UInt64VersiontoString());
                }

                if (package.BindingPolicy.IsValidVersion())
                {
                    if (package.BindingPolicy.VersionStringToUInt64() >= package.PackageVersion.VersionStringToUInt64())
                    {
                        errors.Add(Resources.BindingVersionTooHigh.format(package.BindingPolicy));
                    }
                    else
                    {
                        package.BindingMin = package.BindingPolicy;
                        package.BindingMax = package.BindingPolicy;
                    }

                }

                else
                {
                    var parts = package.BindingPolicy.Split('-');
                    bool ret = parts.Length == 2;
                    for (int i = 0; ret && i < 2; i++)
                    {
                        ret &= parts[i].IsValidVersion();
                    }

                    if (!ret)
                    {
                        errors.Add(Resources.InvalidPolicy.format(package.BindingPolicy));
                    }
                    else
                    {
                        if (parts[0].VersionStringToUInt64() >= package.PackageVersion.VersionStringToUInt64())
                        {
                            errors.Add(Resources.BindingVersionTooHigh.format(parts[0]));
                        }

                        if (parts[1].VersionStringToUInt64() >= package.PackageVersion.VersionStringToUInt64())
                        {
                            errors.Add(Resources.BindingVersionTooHigh.format(parts[1]));
                        }

                        package.BindingMin = parts[0];
                        package.BindingMax = parts[1];
                    }

                }

                //find all the files that need to be found recursively

                if (package.Apps != null)
                {
                    var wildcards = (from p in package.Apps.FilePaths
                                     where p.Contains("*")
                                     select p).ToList();

                    foreach (var w in wildcards)
                    {
                        package.Apps.FilePaths.AddRange(w.FindFilesSmarter(SearchOption.AllDirectories));
                    }

                    //remove wildcards
                    package.Apps.FilePaths.RemoveAll((fp) => fp.Contains("*"));

                    //remove duplicates based on canonical path and make them relative

                    var exeFiles = package.Apps.PrimaryExes.Values.Select((e) => e.ExeFile);

                    var sharedLibFiles = package.SharedLibs.Assemblies.Values.
                        SelectMany((a) => a.PrimaryFile.SingleItemAsEnumerable().Concat(a.OtherFiles));

                    package.Apps.FilePaths = package.Apps.FilePaths.Except(exeFiles.Concat(sharedLibFiles),
                        new PathEqualityComparer()).Select((p) =>
                            Environment.CurrentDirectory.RelativePathTo(p)).ToList();

                }

                if (errors.AreFatal())
                {
                    throw new ConsoleException(errors.StringOut());
                }

                #endregion

                #region Handle Shared Libraries

                //first create the string of all the dependencies elements

                var sharedlib = package.SharedLibs;
                if (sharedlib != null)
                {
                    Console.Write(Resources.SharedLibCreation);
                    if (package.PackageArch != "any")
                    {
                        var dependencyStr = new StringBuilder();

                        foreach (var dep in dependentAssemblies)
                        {
                            dependencyStr.Append(DependencyEntry.Replace("[$LIBTYPE]", dep.Type).Replace("[$LIBNAME]", dep.Name).
                                            Replace("[$LIBVERSION]", dep.Version).Replace("[$ARCH]", dep.Arch).
                                            Replace("[$PUBLICKEYTOKEN]", dep.PublicKeyToken));
                        }

                        foreach (var a in sharedlib.Assemblies.Values)
                        {
                            var manifestFilesString = new StringBuilder();
                            var filesString = new StringBuilder();

                            filesString.Append(FileEntry.Replace("[$FILE]", Path.GetFileName(a.PrimaryFile)));
                            foreach (var f in a.OtherFiles)
                            {
                                filesString.Append(FileEntry.Replace("[$FILE]", Path.GetFileName(f)));
                            }

                            manifestFilesString.Append(SharedLibraryManifest.Replace("[$LIBNAME]", a.Name).
                                    Replace("[$LIBVERSION]", package.PackageVersion).
                                    Replace("[$DEPENDENCY]", dependencyStr.ToString()).Replace("[$PUBLICKEYTOKEN]", package.PubToken).
                                    Replace("[$ARCH]", package.PackageArch).Replace("[$FILES]", filesString.ToString()));

                            a.Manifest = Path.Combine(new FileInfo(a.PrimaryFile).DirectoryName, a.PrimaryFile + ".manifest");
                            //TODO do file checking
                            File.WriteAllText(a.Manifest, manifestFilesString.ToString());

                            // sign all the non-primary BinFiles
                            var binFiles = from f in a.OtherFiles
                                           where Path.GetExtension(f) == ".exe" ||
                                           Path.GetExtension(f) == ".dll"
                                           select f;
                            foreach (var f in binFiles)
                            {
                                signFile(f);
                            }

                            //manifest created. Let's embed it.
                            if (!createManifestAndEmbed(a.PrimaryFile))
                            {
                                throw new ConsoleException(errors.StringOut());
                            }

                            //sign the primary file

                            if (!signFile(a.PrimaryFile))
                                throw new ConsoleException(errors.StringOut());

                            a.CatFile = a.PrimaryFile + ".cat";
                            if (!createAndSignCat(a.Manifest))
                            {
                                throw new ConsoleException(errors.StringOut());
                            }

                            //we're going to create the policy assemblies
                            foreach (var p in package.SharedLibs.MajorMinorsToReplace)
                            {

                                var pa = new PolicyAssemblyDescription(p, a.Name);
                                package.SharedLibs.PolicyAssemblies.Add(pa);

                                var paManifestString = PublisherConfiguration.Replace("[$ASSMNAME]", a.Name).
                                    Replace("[$LIBMAJORMINOR]", p).Replace("[$PUBLICKEYTOKEN]", package.PubToken).
                                    Replace("[$LIBVERSION]", package.PackageVersion).Replace("[$ARCH]", package.PackageArch).
                                    Replace("[$OLDVERSION]", package.BindingPolicy);

                                pa.Manifest = Path.Combine(new FileInfo(a.PrimaryFile).DirectoryName, pa.Name + ".manifest");

                                File.WriteAllText(pa.Manifest, paManifestString);

                                pa.CatFile = pa.Manifest.Replace(".manifest", "") + ".cat";

                                if (!createAndSignCat(pa.Manifest))
                                    throw new ConsoleException(errors.StringOut());

                            }

                        }
                    }

                    else
                    {
                        // it's .NET
                        foreach (var a in sharedlib.Assemblies.Values)
                        {

                            if (!StrongName(a.PrimaryFile))
                            {
                                throw new ConsoleException(errors.StringOut());
                            }

                            if (!signFile(a.PrimaryFile))
                                throw new ConsoleException(errors.StringOut());

                            foreach (var p in package.SharedLibs.MajorMinorsToReplace)
                            {

                                var pa = new PolicyAssemblyDescription(p, a.Name);
                                package.SharedLibs.PolicyAssemblies.Add(pa);

                                pa.PrimaryFile = Path.Combine(new FileInfo(a.PrimaryFile).DirectoryName, pa.Name + ".dll");

                                var paManifestString = MSILPublisherConfiguration.Replace("[$ASSMNAME]", a.Name).
                                    Replace("[$PUBLICKEYTOKEN]", package.PubToken).
                                    Replace("[$LIBVERSION]", package.PackageVersion).
                                    Replace("[$OLDVERSION]", package.BindingPolicy);

                                pa.Manifest = pa.PrimaryFile + ".config";
                                // cleanupFiles.Add(pa.Manifest);
                                File.WriteAllText(pa.Manifest, paManifestString);

                                if (!extractPublicKey())
                                    throw new ConsoleException(errors.StringOut());

                                if (_al.Exec("/link:{0} /out:{1} /delaysign+ /keyfile:{2} /v:{3}", pa.Manifest,
                                     pa.PrimaryFile, publicKeyFile, package.PackageVersion) != 0)
                                {
                                    errors.Add(Resources.FailedPolicyAssemblyBuild.format(pa.PrimaryFile));
                                    throw new ConsoleException(errors.StringOut());
                                }

                                if (!StrongName(pa.PrimaryFile))
                                {
                                    throw new ConsoleException(errors.StringOut());
                                }

                                if (!signFile(pa.PrimaryFile))
                                {
                                    throw new ConsoleException(errors.StringOut());
                                }
                            }

                        }
                    }
                    Console.WriteLine(Resources.Finished);
                }

                #endregion

                #region Handle Apps
                var apps = package.Apps;
                if (apps != null)
                {
                    Console.Write(Resources.AppCreation);

                    if (package.PackageArch != "any")
                    {
                        //it's native
                        var dependencyStr = new StringBuilder();

                        foreach (var dep in dependentAssemblies)
                        {
                            dependencyStr.Append(DependencyEntry.Replace("[$LIBTYPE]", dep.Type).Replace("[$LIBNAME]", dep.Name).
                                            Replace("[$LIBVERSION]", dep.Version).Replace("[$ARCH]", dep.Arch).
                                            Replace("[$PUBLICKEYTOKEN]", dep.PublicKeyToken));
                        }

                        //we needs to add in the other assemblies in this package

                        if (sharedlib != null)
                        {
                            foreach (var dep in sharedlib.Assemblies.Values)
                            {
                                dependencyStr.Append(DependencyEntry.Replace("[$LIBTYPE]", "win32").
                                    Replace("[$LIBNAME]", dep.Name).Replace("[$LIBVERSION]", package.PackageVersion).
                                    Replace("[$ARCH]", package.PackageArch).Replace("[$PUBLICKEYTOKEN]", package.PubToken));
                            }
                        }

                        foreach (var e in apps.PrimaryExes.Values)
                        {
                            var configFilename = e.ExeFile + ".config";
                            File.WriteAllText(configFilename, dependencyStr.ToString());

                            if (!embedManifest(e.ExeFile, configFilename))
                                //we can't keep working on this one but we'll try the rest before failing
                                continue;

                            signFile(e.ExeFile);
                        }

                    }
                    else
                    {
                        //it's .net

                        foreach (var e in apps.PrimaryExes.Values)
                        {
                            if (!StrongName(e.ExeFile))
                            {
                                //we can't keep working on this one but we'll try the rest before failing
                                continue;
                            }

                            signFile(e.ExeFile);
                        }

                    }

                }

                if (errors.AreFatal())
                    throw new ConsoleException(errors.StringOut());

                Console.WriteLine(Resources.Finished);
                #endregion

                #region Write Msi OutToFile
                Console.Write(Resources.CreatingMSI);
                var tempPrefix = Path.GetTempFileName();
                File.WriteAllText(tempPrefix + ".wxs", package.ConvertToWix());

                var outputFile = "{0}-{1}-{2}.msi".format(package.PackageName, package.PackageVersion, package.PackageArch);
                /*
                if (!_dontCreateMsi)
                {

                */
                //we suppress the lack of UpgradeCode warning since we don't use them

                if (_candle.Exec("-nologo -sw1075 -out {0}.wixobj {0}.wxs", tempPrefix) != 0)
                    errors.Add(Resources.FailedCandleExe.format(_candle.StandardOut));

                if (errors.AreFatal())
                    throw new ConsoleException(errors.StringOut());

                //we suppress the lack of UpgradeCode warning since we don't use them
                if (_light.Exec("-nologo -sw1076 -out {1} {0}.wixobj", tempPrefix, outputFile) != 0)
                    errors.Add(Resources.FailedLightExe.format(_light.StandardOut));

                if (errors.AreFatal())
                    throw new ConsoleException(errors.StringOut());

                signFile(outputFile);

                if (errors.AreFatal())
                    throw new ConsoleException(errors.StringOut());
                Console.WriteLine(Resources.Finished);
                #endregion

                Console.WriteLine(errors.StringOut());
            }

            catch (ConsoleException failure)
            {
                CancellationTokenSource.Cancel();
                Fail("{0}\r\n\r\n    {1}", failure.Message, Resources.ForCommandLineHelp);
            }
            finally
            {
                foreach (var f in cleanupFiles)
                {
                    File.Delete(f);
                }
            }
            return 0;
        }
        /// <summary>
        ///   The (non-static) startup method
        /// </summary>
        /// <param name = "args">
        ///   The command line arguments.
        /// </param>
        /// <returns>
        ///   Process return code.
        /// </returns>
        protected override int Main(IEnumerable<string> args)
        {
            try
            {

                _package.CertificateFile = _certificateSettings["#CurrentCertificate"].EncryptedStringValue;

                PackageManager.Instance.Connect("autopackage");
                if (!PackageManager.Instance.IsReady.WaitOne(5000)) {
                    //Verbose("# not connected...");
                    throw new ConsoleException("# Unable to connect to CoApp Service.");
                }

                _pkgMgr = PackageManager.Instance;
                PropertySheet propSheet;

                _pkgMgr.AddFeed(Environment.CurrentDirectory);

                var exceptions = new List<Exception>();
                #region command line parsing
                var configLoaded = false;
                // default:
                var options = args.Switches();
                var parameters = args.Parameters();

                foreach (var arg in options.Keys)
                {
                    var argumentParameters = options[arg];

                    switch (arg)
                    {
                        /* options  */

                        /* global switches */
                        case "load-config":
                            // all ready done, but don't get too picky.
                            break;
                        case "load":
                            propSheet = PropertySheet.Load(argumentParameters.First());
                            PropSheetParser parser = new PropSheetParser(_package);
                            //parser.Parse(propSheet);
                            configLoaded = true;

                            break;
                        case "nologo":
                            this.Assembly().SetLogo(string.Empty);
                            break;

                        case "show-tools":
                            _showTools = Boolean.Parse(argumentParameters.First());
                            break;

                        case "password":
                            _package.CertificatePassword = argumentParameters.First();
                            break;

                        case "autosign":
                            _autosign = true;
                            break;

                        case "remember":
                            _remember = true;
                            break;

                        case "accept-old-bs":
                            _acceptOldBs = true;
                            break;
                        case "help":
                            return Help();

                        default:
                            throw new ConsoleException(Resources.UnknownParameter, arg);

                    }
                }

                Logo();

                if (!configLoaded)
                    throw new ConsoleException(Resources.NoConfigFileLoaded);
                #endregion

                // GS01: I'm putting this in here so that feed resoltion happens before we actually get around to doing something.
                // Look into the necessity later.
                // Tasklet.WaitforCurrentChildTasks();

                #region Tool Scanning

                Console.Write(Resources.ToolLookup);

                _candle = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("candle.exe"));
                _light = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("light.exe"));
                _mt = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("mt.exe"));
                _makecat = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("makecat.exe"));
                _al = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("al.exe"));
                _signTool = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("signTool.exe"));
                _sn = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("sn.exe"));

                if (_candle.Executable == null)
                    exceptions.Add(CreateEndUserException(144));

                if (_light.Executable == null)
                    exceptions.Add(CreateEndUserException(145));

                if (_mt.Executable == null)
                    exceptions.Add(CreateEndUserException(146));

                if (_makecat.Executable == null)
                    exceptions.Add(CreateEndUserException(147));

                if (_al.Executable == null)
                    exceptions.Add(CreateEndUserException(148));

                if (_signTool.Executable == null)
                    exceptions.Add(CreateEndUserException(149));

                if (_sn.Executable == null)
                    exceptions.Add(CreateEndUserException(150));

                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                Console.WriteLine(Resources.Finished);

                if (_showTools)
                {
                    Console.WriteLine("Tools:");
                    Console.WriteLine(_candle.Executable);
                    Console.WriteLine(_light.Executable);
                    Console.WriteLine(_mt.Executable);
                    Console.WriteLine(_makecat.Executable);
                    Console.WriteLine(_al.Executable);
                    Console.WriteLine(_sn.Executable);
                    Console.WriteLine(_signTool.Executable);
                }

                ReadPassword();

                #endregion

                Console.WriteLine(Resources.ScanningInstalledPackages);
                //TODO What will happen when we have feeds in other places????
                IEnumerable<Package> allPackages = null;

                /*
                var tsk = _pkgMgr.GetPackagesInScanLocations(new PackageManagerMessages
                {
                    PackageScanning = (progress) => Resources.Scanning.PrintProgressBar(progress)
                }).ContinueWith((antecedent) =>
                {
                    allPackages = antecedent.Result;

                    " ".PrintProgressBar(100);
                    Console.WriteLine("\r");

                },TaskContinuationOptions.AttachedToParent);

                tsk.Wait();
                */

                //find all the files that need to be found recursively

                //verify that the lefthand side of includes are valid subpaths
                foreach (var i in _package.AllIncludes.Keys)
                {
                    foreach (var include in _package.AllIncludes[i])
                    {
                        if (!include.L.IsSimpleSubPath())
                        {
                            exceptions.Add(CreateEndUserPropertyException(i.IncludeToProp[include.L], 160, include.L));
                        }
                    }
                }

                if (_package.Apps != null)
                {

                    if (_package.Apps.GlobalBinEntry != null)
                    {
                        if (!_package.Apps.GlobalBinEntry.IsBoolean())
                        {
                            exceptions.Add(CreateEndUserPropertyException(_package.Apps.GlobalBinEntryProp, 152));
                        }
                        else
                        {
                            _package.Apps.GlobalBin = Boolean.Parse(_package.Apps.GlobalBinEntry);
                        }
                    }

                    _package.Apps.EvaluateIncludes();

                    //set up the input files
                    foreach (var e in _package.Apps.PrimaryExes)
                    {
                        var input = (from a in _package.Apps.FinalInclude
                                     where a.R.Path.IsWildcardMatch(e.ExeFile)
                                     select a).FirstOrDefault();

                        if (input == null)
                        {
                            if (!File.Exists(e.ExeFile))
                                exceptions.Add(CreateEndUserException(153, e.ExeFile));
                            else
                            {
                                //Exefile wasn't found in the Includes but it really does exist
                                _package.Apps.FinalInclude = _package.Apps.FinalInclude.Concat(new OutputTup { L = new FileInfo(e.ExeFile.Original).Name, R = e.ExeFile }.SingleItemAsEnumerable());
                            }
                        }
                        else
                        {
                            e.ExeFile = input.R;
                        }

                        if (e.GlobalBinEntry != null)
                        {
                            if (!e.GlobalBinEntry.IsBoolean())
                            {
                                exceptions.Add(CreateEndUserPropertyException(e.GlobalBinEntryProp, 152));
                            }
                            else
                            {
                                e.GlobalBin = Boolean.Parse(e.GlobalBinEntry);
                            }
                        }
                    }
                }

                if (_package.SharedLibs != null)
                {
                    var shared = _package.SharedLibs;
                    var sharedEntryValid = false;
                    if (shared.GlobalEntry != null)
                    {
                        if (!shared.GlobalEntry.IsBoolean()) {
                            exceptions.Add(CreateEndUserPropertyException(shared.GlobalEntryProp, 170));
                        }
                        else {
                            shared.Global = Boolean.Parse(shared.GlobalEntry);
                            sharedEntryValid = true;
                        }
                    }

                    foreach (var a in _package.SharedLibs.Assemblies)
                    {
                        a.EvaluateIncludes(true);
                        if (a.GlobalEntry != null)
                        {
                            if (!a.GlobalEntry.IsBoolean()) {
                                exceptions.Add(CreateEndUserPropertyException(a.GlobalEntryProp, 170));
                            }
                            else {
                                a.Global = Boolean.Parse(a.GlobalEntry);
                            }
                        }
                        else if (sharedEntryValid)
                        {
                            a.Global = shared.Global;
                        }
                    }
                }

                if (_package.DeveloperLibs != null)
                {
                    BasicIncludeAndExclude[] items = { _package.DeveloperLibs.Headers, _package.DeveloperLibs.ImportLibs, _package.DeveloperLibs.StaticLibs };
                    foreach (var sec in items)
                    {
                        if (sec.GlobalLinkEntry != null)
                        {
                            if (!sec.GlobalLinkEntry.IsBoolean())
                            {
                                exceptions.Add(CreateEndUserPropertyException(sec.GlobalLinkEntryProp, 169));
                            }
                            else
                            {
                                sec.GlobalLink = Boolean.Parse(sec.GlobalLinkEntry);
                            }
                        }
                        sec.EvaluateIncludes();
                    }

                    //add the proper prefix to all the files
                    _package.DeveloperLibs.Headers.AddPrefix(HEADERS_DIR_NAME);
                    _package.DeveloperLibs.ImportLibs.AddPrefix(IMPORTLIB_DIR_NAME);
                    _package.DeveloperLibs.StaticLibs.AddPrefix(STATICLIB_DIR_NAME);

                }

                if (_package.SourceCodes != null)
                {
                    var sc = _package.SourceCodes;
                    sc.EvaluateIncludes();

                    sc.AddPrefix(SRC_DIR_NAME);
                }

                //copy all the stuff that needs to go to Temp TO Temp
                _package.Prepare();

                foreach (var dep in _package.DependencyNames)
                {
                   /*
                    var temp = new EditableTup<string, string> {L = dep.L, R = _package.ResolveVariables(dep.R)};
                    //TODO this doesn't work if a packages is a superceding version of the one given
                    var depPackage = (from p in allPackages
                                      where p.CosmeticName.IsWildcardMatch(temp.R)
                                      orderby p.Version descending
                                      select p).FirstOrDefault();
                    if (depPackage == null)
                    {
                        if (_package.DependencyNamesProp.ContainsKey(temp.R))
                        {
                            exceptions.Add(CreateEndUserPropertyException(_package.DependencyNamesProp[dep.R], 133, dep.R));
                        }
                        else
                        {
                            exceptions.Add(CreateEndUserException(133, dep.R));
                        }
                    }
                    else
                    {
                        _package.DependencyInfo.Add(depPackage);
                    }*/
                }

                //TODO make sure the numbers are not larger than the max a part of a version string
                var policyRegex = new Regex(@"^policy\.\d{1,5}\.\d{1,5}\.\S+$");
                /*
                var dependentAssemblies = from p in _package.DependencyInfo
                                          from a in p.Assemblies
                                          where !a.Type.Contains("policy") &&
                                          !policyRegex.IsMatch(a.Name)
                                          select a;

                */

                //let's check for valid roles!

                if (_package.Roles.IsNullOrEmpty())
                    exceptions.Add(CreateEndUserException(131));

                //make sure the major minors given are valid
                if (_package.SharedLibs != null)
                {
                    foreach (var i in _package.SharedLibs.MajorMinorsToReplace)
                    {
                        if (!i.IsValidMajorMinorVersion())
                        {
                            if (_package.SharedLibs.MajorMinorsToReplaceProp.ContainsKey(i))
                            {
                                exceptions.Add(CreateEndUserPropertyException(_package.SharedLibs.MajorMinorsToReplaceProp[i], 132, i));
                            }
                            else
                            {
                                exceptions.Add(CreateEndUserException(132, i));
                            }
                        }
                    }
                }

                if (_package.Apps != null)
                {
                    foreach (var e in _package.Apps.PrimaryExes)
                    {
                        if (e.StartMenu != null)
                        {
                            if (!e.StartMenu.IsSimpleSubPath())
                            {
                                exceptions.Add(CreateEndUserPropertyException(e.StartMenuProp, 168, e.StartMenu));
                                continue;
                            }

                            if (!e.StartMenu.EndsWith(".lnk"))
                            {
                                e.StartMenu += ".lnk";
                            }

                        }
                    }
                }

                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                #region Handle Shared Libraries

                //first create the string of all the dependencies elements

                var sharedlib = _package.SharedLibs;
                if (sharedlib != null)
                {

                    //set all the assembly names properly
                    foreach (var a in sharedlib.Assemblies)
                    {
                        if (a.Name == null)
                        {
                            var fi = new FileInfo(a.PrimaryFile);
                            a.Name = fi.NameWithoutExt().Replace(" ", "_");
                        }
                    }

                    Console.Write(Resources.SharedLibCreation);
                    if (_package.PackageArch != "any")
                    {
                        var dependencyStr = new StringBuilder();
                        /*
                        foreach (var dep in dependentAssemblies)
                        {
                            dependencyStr.Append(DependencyEntry.Replace("[$LIBTYPE]", dep.Type).Replace("[$LIBNAME]", dep.Name).
                                            Replace("[$LIBVERSION]", dep.Version).Replace("[$ARCH]", dep.Arch).
                                            Replace("[$PUBLICKEYTOKEN]", dep.PublicKeyToken));
                        }
                        */
                        foreach (var a in sharedlib.Assemblies)
                        {
                            /*
                            var manifestFilesString = new StringBuilder();
                            var filesString = new StringBuilder();

                            filesString.Append(FileEntry.Replace("[$FILE]", Path.GetFileName(a.PrimaryFile)));
                            foreach (var f in a.FinalInclude)
                            {
                                filesString.Append(FileEntry.Replace("[$FILE]", f.L));
                            }

                            manifestFilesString.Append(SharedLibraryManifest.Replace("[$LIBNAME]", a.Name).
                                    Replace("[$LIBVERSION]", _package.PackageVersion).
                                    Replace("[$DEPENDENCY]", dependencyStr.ToString()).Replace("[$PUBLICKEYTOKEN]", _package.PubToken).
                                    Replace("[$ARCH]", _package.PackageArch).Replace("[$FILES]", filesString.ToString()));

                            a.Manifest = Path.Combine(new FileInfo(a.PrimaryFile).DirectoryName, a.PrimaryFile + ".manifest");
                            //TODO do file checking
                            File.WriteAllText(a.Manifest, manifestFilesString.ToString());

                            */

                            // sign all the non-primary BinFiles
                            var binFiles = from f in a.FinalInclude.BinaryFiles()
                                           select f.R;
                            exceptions.AddRange(VerifySigning(binFiles, false));

                            //manifest created. Let's embed it.
                            if (!EmbedManifest(a.PrimaryFile))
                            {
                                exceptions.Add(CreateEndUserException(137, a.PrimaryFile + ".manifest", a.PrimaryFile));
                                continue;
                            }

                            //sign the primary file

                            if (!SignFile(a.PrimaryFile))
                            {
                                exceptions.Add(CreateEndUserException(136, a.PrimaryFile));
                                continue;
                            }

                            a.CatFile = a.PrimaryFile + ".cat";
                            if (!CreateAndSignCat(a.Manifest))
                            {
                                exceptions.Add(CreateEndUserException(138, a.Manifest + ".cdf"));
                                continue;
                            }

                            //we're going to create the policy assemblies
                            foreach (var p in _package.SharedLibs.MajorMinorsToReplace)
                            {

                                var pa = new PolicyAssemblyDescription(p, a.Name);
                                _package.SharedLibs.PolicyAssemblies.Add(pa);

                                var paManifestString = PublisherConfiguration.Replace("[$ASSMNAME]", a.Name).
                                    Replace("[$LIBMAJORMINOR]", p).Replace("[$PUBLICKEYTOKEN]", _package.PubToken).
                                    Replace("[$LIBVERSION]", _package.PackageVersion).Replace("[$ARCH]", _package.PackageArch).
                                    Replace("[$OLDVERSION]", _package.BindingPolicy);

                                pa.Manifest = Path.Combine(new FileInfo(a.PrimaryFile).DirectoryName, pa.Name + ".manifest");

                                File.WriteAllText(pa.Manifest, paManifestString);

                                pa.CatFile = pa.Manifest.Replace(".manifest", "") + ".cat";

                                if (!CreateAndSignCat(pa.Manifest))
                                {
                                    exceptions.Add(CreateEndUserException(138, pa.Manifest + ".cdf"));
                                    continue;
                                }

                            }

                        }
                    }

                    else
                    {
                        // it's .NET
                        foreach (var a in sharedlib.Assemblies)
                        {

                            if (!_codeSigningCert.FinishStrongNaming(a.PrimaryFile))
                            {
                                exceptions.Add(CreateEndUserException(139, a.PrimaryFile));
                                continue;
                            }

                            if (!SignFile(a.PrimaryFile))
                            {
                                exceptions.Add(CreateEndUserException(136, a.PrimaryFile));
                                continue;
                            }

                            foreach (var p in _package.SharedLibs.MajorMinorsToReplace)
                            {

                                var pa = new PolicyAssemblyDescription(p, a.Name);
                                _package.SharedLibs.PolicyAssemblies.Add(pa);

                                pa.PrimaryFile = Path.Combine(new FileInfo(a.PrimaryFile).DirectoryName, pa.Name + ".dll");

                                var paManifestString = MSILPublisherConfiguration.Replace("[$ASSMNAME]", a.Name).
                                    Replace("[$PUBLICKEYTOKEN]", _package.PubToken).
                                    Replace("[$LIBVERSION]", _package.PackageVersion).
                                    Replace("[$OLDVERSION]", _package.BindingMin + "-" + _package.BindingMax);

                                pa.Manifest = pa.PrimaryFile + ".config";
                                // cleanupFiles.Add(pa.Manifest);
                                File.WriteAllText(pa.Manifest, paManifestString);

                                if (!ExtractPublicKey())
                                {
                                    exceptions.Add(CreateEndUserPropertyException(_package.SharedLibs.MajorMinorsToReplaceProp[p],
                                            140, _package.CertificateFile));
                                    continue;
                                }

                                if (_al.Exec("/link:{0} /out:{1} /delaysign+ /keyfile:{2} /v:{3}", pa.Manifest,
                                     pa.PrimaryFile, _publicKeyFile, _package.PackageVersion) != 0)
                                {
                                    exceptions.Add(CreateEndUserPropertyException(_package.SharedLibs.MajorMinorsToReplaceProp[p],
                                        141, pa.PrimaryFile));
                                    continue;
                                }

                                if (!_codeSigningCert.FinishStrongNaming(pa.PrimaryFile))
                                {
                                    exceptions.Add(CreateEndUserPropertyException(_package.SharedLibs.MajorMinorsToReplaceProp[p],
                                        139, pa.PrimaryFile));
                                    continue;
                                }

                                if (!SignFile(pa.PrimaryFile))
                                {
                                    exceptions.Add(CreateEndUserPropertyException(_package.SharedLibs.MajorMinorsToReplaceProp[p],
                                        136, pa.PrimaryFile));
                                    continue;
                                }
                            }

                        }
                    }
                    if (exceptions.Count > 0)
                    {
                        throw new AggregateException(exceptions);
                    }

                    Console.WriteLine(Resources.Finished);
                }

                #endregion

                #region Handle Apps
                var apps = _package.Apps;
                if (apps != null)
                {
                    Console.Write(Resources.AppCreation);

                    if (_package.PackageArch != "any")
                    {
                        //it's native
                        var dependencyStr = new StringBuilder();
                        /*
                        foreach (var dep in dependentAssemblies)
                        {
                            dependencyStr.Append(DependencyEntry.Replace("[$LIBTYPE]", dep.Type).Replace("[$LIBNAME]", dep.Name).
                                            Replace("[$LIBVERSION]", dep.Version).Replace("[$ARCH]", dep.Arch).
                                            Replace("[$PUBLICKEYTOKEN]", dep.PublicKeyToken));
                        }

                        //we needs to add in the other assemblies in this package

                        if (sharedlib != null)
                        {
                            foreach (var dep in sharedlib.Assemblies)
                            {
                                dependencyStr.Append(DependencyEntry.Replace("[$LIBTYPE]", "win32").
                                    Replace("[$LIBNAME]", dep.Name).Replace("[$LIBVERSION]", _package.PackageVersion).
                                    Replace("[$ARCH]", _package.PackageArch).Replace("[$PUBLICKEYTOKEN]", _package.PubToken));
                            }
                        }*/

                        foreach (var e in apps.PrimaryExes)
                        {
                            /*
                            if (dependencyStr.Length > 0)
                            {
                                var configFilename = e.InputFile + ".config";
                                var execManifest = new StringBuilder();
                                execManifest.Append(ExecutableManifest.Replace("[$DEPENDENCY]", dependencyStr.ToString()));
                                File.WriteAllText(configFilename, execManifest.ToString());

                                if (!EmbedManifest(e.InputFile, configFilename))
                                {
                                    exceptions.Add(CreateEndUserException(137, configFilename, e.InputFile));
                                    continue;
                                }
                            }*/

                            if (!SignFile(e.InputFile))
                            {
                                exceptions.Add(CreateEndUserException(136, e.InputFile));
                                continue;
                            }
                        }

                    }
                    else
                    {
                        //it's .net

                        foreach (var e in apps.PrimaryExes)
                        {
                            if (!_codeSigningCert.FinishStrongNaming(e.InputFile))
                            {
                                exceptions.Add(CreateEndUserException(139, e.InputFile));
                                continue;
                            }

                            if (!SignFile(e.InputFile))
                            {
                                exceptions.Add(CreateEndUserException(136, e.InputFile));
                                continue;
                            }
                        }

                    }

                    if (exceptions.Count > 0)
                    {
                        throw new AggregateException(exceptions);
                    }

                    Console.WriteLine(Resources.Finished);
                }

                //check if every binary is actually signed at all
                //yes this is really messy
                var binFilesToCheck = Enumerable.Empty<TempedFile>();
                if (apps != null)
                    binFilesToCheck = binFilesToCheck.Concat(from i in apps.BinaryFilesMinusPrimaries select i.R);

                if (_package.SourceCodes != null)
                    binFilesToCheck = binFilesToCheck.Concat(from i in _package.SourceCodes.FinalInclude.BinaryFiles() select i.R);
                if (_package.DeveloperLibs != null)
                    binFilesToCheck = binFilesToCheck.Concat(from i in _package.DeveloperLibs.Headers.FinalInclude.
                                               Concat(_package.DeveloperLibs.ImportLibs.FinalInclude).
                                               Concat(_package.DeveloperLibs.StaticLibs.FinalInclude).
                                               BinaryFiles()
                                                             select i.R);

                exceptions.AddRange(VerifySigning(binFilesToCheck));

                exceptions.AddRange(DownloadBootstrapManifest());

                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                #endregion

                #region Write Msi OutToFile
                Console.Write(Resources.CreatingMSI);
                var tempPrefix = Path.GetTempFileName();
                File.WriteAllText(tempPrefix + ".wxs", _package.ConvertToWix());

                //we suppress the lack of UpgradeCode warning since we don't use them

                if (_candle.Exec("-nologo -sw1075 -out {0}.wixobj {0}.wxs", tempPrefix) != 0)
                    exceptions.Add(CreateEndUserException(142, _candle.StandardOut));

                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                //we suppress the lack of UpgradeCode warning since we don't use them
                if (_light.Exec("-nologo -sw1076 -out {1} {0}.wixobj", tempPrefix, _package.DefaultOutputFile) != 0)
                    exceptions.Add(CreateEndUserException(143, _light.StandardOut));

                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                if (!SignFile(_package.DefaultOutputFile))
                {
                    exceptions.Add(CreateEndUserException(136, _package.DefaultOutputFile));
                }

                if (exceptions.Count > 0)
                {
                    throw new AggregateException(exceptions);
                }

                if (_remember)
                {
                    //Verbose("Storing certificate details in the registry.");
                    _certificateSettings["#CurrentCertificate"].EncryptedStringValue = _package.CertificateFile;
                    _certificateSettings[Path.GetFileName(_package.CertificateFile), "Password"].EncryptedStringValue = _package.CertificatePassword;
                }

                Console.WriteLine(Resources.Finished);

                #endregion

            }
            catch (AggregateException failures)
            {
                CancellationTokenSource.Cancel();
                Fail("{0}\r\n\r\n    {1}", failures.InnerExceptions, Resources.ForCommandLineHelp);
            }
            catch (Exception failure)
            {
                CancellationTokenSource.Cancel();
                Fail("{0}\r\n\r\n    {1}", "{0} - stacktrace: {1}".format(failure.Message, failure.StackTrace)
                    , Resources.ForCommandLineHelp);
            }
            finally
            {
                foreach (var f in _cleanupFiles)
                {
                    File.Delete(f);
                }
            }
            return 0;
        }
예제 #40
0
        private int main(string[] args) {
            bool mergeAssemblies = false;

            Dictionary<string, IEnumerable<string>> options = args.Switches();
            IEnumerable<string> parameters = args.Parameters();

            foreach (string arg in options.Keys) {
                IEnumerable<string> argumentParameters = options[arg];

                switch (arg) {
                    case "nologo":
                        this.Assembly().SetLogo("");
                        quiet = true;
                        break;

                    case "merge":
                        mergeAssemblies = true;
                        break;

                    case "keep-temp-files":
                        keepTempFiles = true;
                        break;

                    case "rescan-tools":
                        ProgramFinder.IgnoreCache = true;
                        break;

                    case "debug":
                        debug = true;
                        break;

                    case "sampleusage":
                        SampleUsage();
                        return 0;

                    case "sampleclass":
                        SampleClass();
                        return 0;

                    case "output-filename":
                        finalOuputFilename = argumentParameters.FirstOrDefault();
                        break;

                    case "create-header":
                        headerFilename = argumentParameters.FirstOrDefault();
                        break;

                    case "platform":
                        platform = (argumentParameters.FirstOrDefault() ?? "x86").Equals("x64", StringComparison.CurrentCultureIgnoreCase)
                            ? "x64"
                            : "x86";
                        break;

                    case "create-lib":
                        createLib = true;
                        break;

                    case "help":
                        Help();
                        return 0;

                    default:
                        Logo();
                        return Fail("Error: unrecognized switch:{0}", arg);
                }
            }


            if (parameters.Count() != 1) {
                Help();
                return 0;
            }

            if (!quiet) {
                Logo();
            }

            var ILDasm = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("ildasm.exe", "4.0.30319.1"));
            var ILAsm = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("ilasm.exe", "4.0.30319.1"));
            var Lib = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("lib.exe"));

            string originalAssemblyPath = parameters.First().GetFullPath();

            if (!File.Exists(originalAssemblyPath)) {
                return Fail("Error: the specified original assembly \r\n   [{0}]\r\ndoes not exist.", originalAssemblyPath);
            }

            string shimAssemblyPath = GenerateShimAssembly(originalAssemblyPath);
            finalOuputFilename = string.IsNullOrEmpty(finalOuputFilename)
                ? (mergeAssemblies ? originalAssemblyPath : shimAssemblyPath)
                : finalOuputFilename;

            string temporaryIlFilename = shimAssemblyPath + ".il";
            int rc = ILDasm.Exec(@"/text /nobar /typelist ""{0}""", shimAssemblyPath);
            if (0 != rc) {
                return Fail("Error: unable to disassemble the temporary assembly\r\n   [{0}]\r\nMore Information:\r\n{1}", shimAssemblyPath,
                    ILDasm.StandardOut);
            }
            Delete(shimAssemblyPath); // eliminate it regardless of result.
            string ilSource = Regex.Replace(ILDasm.StandardOut, @"IL_0000:.*ldstr.*\""(?<x>.*)\""", "${x}");

            if (mergeAssemblies) {
                int start = ilSource.IndexOf("\r\n.method");
                int end = ilSource.LastIndexOf("// end of global method");
                ilSource = ilSource.Substring(start, end - start);

                // arg! needed this to make sure the resources came out. grrr
                rc = ILDasm.Exec(@"/nobar /typelist ""{0}"" /out=""{1}""", originalAssemblyPath, temporaryIlFilename);
                rc = ILDasm.Exec(@"/nobar /text /typelist ""{0}""", originalAssemblyPath);
                if (0 != rc) {
                    return Fail("Error: unable to disassemble the target assembly\r\n   [{0}]\r\nMore Information:\r\n{1}", shimAssemblyPath,
                        ILDasm.StandardOut);
                }
                string ilTargetSource = ILDasm.StandardOut;

                start = Math.Min(ilTargetSource.IndexOf(".method"), ilTargetSource.IndexOf(".class"));
                ilSource = ilTargetSource.Substring(0, start) + ilSource + ilTargetSource.Substring(start);
            }

            File.WriteAllText(temporaryIlFilename, ilSource);
            rc = ILAsm.Exec(@"{3} /dll {2} /output={0} ""{1}""", shimAssemblyPath, temporaryIlFilename, debug ? "/debug" : "",
                platform == "x64" ? "/X64" : "");

            if (!debug) {
                Delete(temporaryIlFilename); // delete temp file regardless of result.
            }

            if (0 != rc) {
                return Fail("Error: unable to assemble the merged assembly\r\n   [{0}]\r\n   [{1}]\r\nMore Information:\r\n{2}",
                    shimAssemblyPath, temporaryIlFilename, ILAsm.StandardError);
            }

            if (originalAssemblyPath.Equals(finalOuputFilename, StringComparison.CurrentCultureIgnoreCase)) {
                File.Delete(originalAssemblyPath + ".orig");
                File.Move(originalAssemblyPath, originalAssemblyPath + ".orig");
            }
            File.Delete(finalOuputFilename);
            File.Move(shimAssemblyPath, finalOuputFilename);

            if (!quiet) {
                Console.WriteLine("Created Exported functions in Assembly: {0}", finalOuputFilename);
            }

            if (createLib) {
                string defFile = Path.GetFileNameWithoutExtension(finalOuputFilename) + ".def";
                string libFile = Path.GetFileNameWithoutExtension(finalOuputFilename) + ".lib";

                File.WriteAllLines(defFile, exports);
                Lib.ExecNoRedirections("/NOLOGO /machine:{0} /def:{1} /OUT:{2}", platform, defFile, libFile);
            }

            if (headerFilename != null) {
                foreach (var e in enumTypeDefs) {
                    functions.Insert(1, e.Value);
                }
                File.WriteAllLines(headerFilename, functions);
            }

            return 0;
        }