public void SimpleCommandLineParser_Parse_Arguments()
        {
            // Assign
            _parser.Parse(new[] { "--test1", "one", "--test2", "two", "--test3", "three" });

            // Act
            string value1 = _parser.GetStringValue("test1");
            string value2 = _parser.GetStringValue("test2");
            string value3 = _parser.GetStringValue("test3");

            // Assert
            Check.That(value1).IsEqualTo("one");
            Check.That(value2).IsEqualTo("two");
            Check.That(value3).IsEqualTo("three");
        }
Exemplo n.º 2
0
        public static bool LoadConfig(string[] args)
        {
            try
            {
                var parser = new SimpleCommandLineParser();
                parser.Parse(args);

                bool exists = File.Exists(GGMCFile);

                if (!exists)
                {
                    GenerateConfig();
                }
                else
                {
                    GGMC = DeSerializeString <GGMConfig>(File.ReadAllText(GGMCFile));
                }

                return(true);
            }
            catch (Exception ex)
            {
                Logger.Log(LogType.FatalError, "Error while loading config.", ex);
                return(false);
            }
        }
Exemplo n.º 3
0
        public void Run(string[] args)
        {
            RebooterProperties = new AppProperties();

            // Parse the command line arguments
            var oParser = new SimpleCommandLineParser();

            oParser.Parse(args);

            RebooterProperties.CurrentModem = GetModemClass();

            // Show startup text
            ShowIntro(RebooterProperties);

            // Read the command line parameters
            RebooterProperties.ReadParameters(oParser, RebooterProperties);

            // One minute timer
            Timer oTimer = new Timer {
                Interval = 60000
            };

            oTimer.Elapsed += (sender, e) => { HandleTimerElapsed(RebooterProperties); };
            oTimer.Enabled  = !String.IsNullOrEmpty(RebooterProperties.ModemIP);

            if (oTimer.Enabled)
            {
                DoTimedEvents(RebooterProperties);
            }

            DoConsoleRead();
            oTimer.Dispose();
        }
Exemplo n.º 4
0
        static int Main(string[] args)
        {
            SimpleCommandLineParser parser = new SimpleCommandLineParser(args);

            parser.addOption("v", ARGUMENT_TYPE.MUST, "verb");
            parser.addOption("a", ARGUMENT_TYPE.MUST, "arguments");
            parser.addOption("type", ARGUMENT_TYPE.MUST, "type");
            parser.addOption("name", ARGUMENT_TYPE.MUST, "name");
            parser.Parse();

            string verb      = parser["v"].ToString(); // getString("v");
            string arguments = parser["a"].ToString(); //.getString("a");
            string folder    = parser.getMainargs(0);

            if (string.IsNullOrEmpty(verb))
            {
                MessageBox.Show("No Verb", Application.ProductName);
                return(-1);
            }
            if (string.IsNullOrEmpty(arguments))
            {
                MessageBox.Show("No Arguments", Application.ProductName);
                return(-1);
            }
            if (string.IsNullOrEmpty(folder))
            {
                MessageBox.Show("No Folder", Application.ProductName);
                return(-1);
            }
            if (!Directory.Exists(folder))
            {
                MessageBox.Show(folder + " does not exist.", Application.ProductName);
                return(-1);
            }


            string type = parser["type"].ToString();

            if (type != null)
            {
                if (type != "f" || type != "d")
                {
                    MessageBox.Show("wrong type", Application.ProductName);
                    return(-1);
                }
            }

            string name = parser["name"].ToString();


            return(0);
        }
Exemplo n.º 5
0
        public void ParseTest()
        {
            var parser = new SimpleCommandLineParser();

            String[] args = { "-help" };
            parser.Parse(args);

            bool shouldContainHelp = false;

            if (parser.Arguments.ContainsKey("help"))
            {
                shouldContainHelp = true;
            }
            Assert.IsTrue(shouldContainHelp);


            String[] realArgs = new String[] { "C:\\temp\\Video_Sync_2\\MediaPlayer\\MyMediaPlayer\\bin\\Debug\\MyMediaPlayer.vshost.exe", "-file", "c:\\\\temp\\\\testcase objects\\\\0) Unreal 2004 patching instructions.PNG", "-time", "1" };
            parser.Parse(realArgs);

            bool shouldContainFile = false;

            if (parser.Arguments.ContainsKey("file"))
            {
                shouldContainFile = true;
            }
            Assert.IsTrue(shouldContainFile);


            bool shouldContainTime = false;

            if (parser.Arguments.ContainsKey("time"))
            {
                shouldContainTime = true;
            }
            Assert.IsTrue(shouldContainTime);
        }
Exemplo n.º 6
0
        public VideoSyncServer(string[] args)
        {
            InitializeComponent();

            cmdParser.Parse(args);
            ProcessCmdArgs();

            textBoxIP.Text = m_Globals.m_library.GetLocalName();

            // React to the command line arguments that perform automation.
            if (isAutoConnectCmd)
            {
                BeginListening();
            }
        }
Exemplo n.º 7
0
        public static string[] Parse(string input)
        {
            if (string.IsNullOrWhiteSpace(input) || input.Length == 0)
            {
                throw new ArgumentException("Cannot parse an empty embedded command-line string");
            }

#if !SYS_SUB_CMDLINE
            var parser = new SimpleCommandLineParser(input);
            return(parser.Parse());
#endif

#if SYS_SUB_CMDLINE
            var allowance = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode);
            allowance.Assert();
            IntPtr argv = IntPtr.Zero;
            try
            {
                int argc;
                argv = CommandLineToArgvW(input, out argc);
                if (argv == IntPtr.Zero)
                {
                    throw new ArgumentException("Unable to parse arguments", input, new System.ComponentModel.Win32Exception());
                }
                string[] args = new string[argc];
                for (int k = 0; k < argc; ++k)
                {
                    args[k] = System.Runtime.InteropServices.Marshal.PtrToStringUni
                              (
                        System.Runtime.InteropServices.Marshal.ReadIntPtr(argv, k * IntPtr.Size)
                              );
                }
                return(args);
            }
            finally
            {
                LocalFree(argv);
                System.Security.CodeAccessPermission.RevertAssert();
            }
#endif
        }
Exemplo n.º 8
0
        public PlaylistGenerator(string[] args)
        {
            InitializeComponent();

            cmdParser.Parse(args);
            ProcessCmdArgs();

            m_Globals.m_communications.m_serverName = m_library.GetLocalName();
            textBoxIP.Text = m_Globals.m_communications.m_serverName;

            // React to the command line arguments that perform automation.
            if (isAutoConnectCmd)
            {
                bool wasConnectionGood = m_Globals.m_communications.ConnectToServer();
                UpdateControls(wasConnectionGood);

                if (wasConnectionGood)
                {
                    SendPlaylist("publisher_connect", "publisher");
                }

                if (IsFilePathGiven)
                {
                    SendPlaylist("publisher_playlist", richText_Playlist.Text);
                    if (isImmediateExitCmd)
                    {
                        try
                        {
                            System.Threading.Thread.Sleep(1000);
                            System.Environment.Exit(0);
                        }
                        catch (SystemException se)
                        {
                            String se_string = se.ToString();
                        }
                    }
                }
            }
        }
Exemplo n.º 9
0
        public VideoSyncClient(string[] args)
        {
            InitializeComponent();

            cmdParser.Parse(args);
            ProcessCmdArgs();

            m_Globals.m_library.SetStateFile(Library1.State.not_busy);

            m_Globals.m_communications.m_serverName = m_Globals.m_library.GetLocalName();
            m_Globals.m_communications.m_portNumber = m_Globals.m_communications.GetPortNumber();

            m_LastSettingsFile = m_Globals.m_ApplicationDirectory + @"\lastSettings.xml";
            if (m_Globals.m_library.TestFilePathExistance(m_LastSettingsFile) == true)
            {
                m_Globals.AssignVariablesFromXML(m_LastSettingsFile);
                m_UsersChosenSettingsFile = m_LastSettingsFile;
                String tempPath = m_Globals.Get_tempPath();
                if (m_Globals.m_library.TestFilePathExistance(tempPath))
                {
                    m_Globals.isTempPathSet = true;
                }
            }

            textBoxIP.Text = m_Globals.m_communications.m_serverName;

            // React to the command line arguments that perform automation.
            if (isAutoConnectCmd)
            {
                m_Globals.AssignVariablesFromXML(m_LastSettingsFile);

                bool wasConnectionGood = m_Globals.m_communications.ConnectToServer();
                UpdateControls(wasConnectionGood);
                {
                    First_WaitForData();
                    SendConnectMessageToServer();
                }
            }
        }
Exemplo n.º 10
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Start Electron Desktop Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                string aspCoreProjectPath = "";

                if (parser.Arguments.ContainsKey(_aspCoreProjectPath))
                {
                    string projectPath = parser.Arguments[_aspCoreProjectPath].First();
                    if (Directory.Exists(projectPath))
                    {
                        aspCoreProjectPath = projectPath;
                    }
                }
                else
                {
                    aspCoreProjectPath = Directory.GetCurrentDirectory();
                }

                string tempPath = Path.Combine(aspCoreProjectPath, "obj", "Host");
                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }

                var platformInfo = GetTargetPlatformInformation.Do(string.Empty, string.Empty);

                string tempBinPath = Path.Combine(tempPath, "bin");
                var resultCode = ProcessHelper.CmdExecute($"dotnet publish -r {platformInfo.NetCorePublishRid} --output \"{tempBinPath}\"", aspCoreProjectPath);

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);

                var nodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                Console.WriteLine("node_modules missing in: " + nodeModulesDirPath);

                Console.WriteLine("Start npm install...");
                ProcessHelper.CmdExecute("npm install", tempPath);

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for typescript & hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p ../../ElectronHostHook", tempPath);
                }

                string arguments = "";

                if (parser.Arguments.ContainsKey(_arguments))
                {
                    arguments = string.Join(' ', parser.Arguments[_arguments]);
                }

                if (parser.Arguments.ContainsKey(_manifest))
                {
                    arguments += " --manifest=" + parser.Arguments[_manifest].First();
                }

                string path = Path.Combine(tempPath, "node_modules", ".bin");
                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                if (isWindows)
                {
                    Console.WriteLine("Invoke electron.cmd - in dir: " + path);
                    ProcessHelper.CmdExecute(@"electron.cmd ""..\..\main.js"" " + arguments, path);
                }
                else
                {
                    Console.WriteLine("Invoke electron - in dir: " + path);
                    ProcessHelper.CmdExecute(@"./electron ""../../main.js"" " + arguments, path);
                }

                return true;
            }));
        }
 public InitCommand(string[] args)
 {
     _parser.Parse(args);
 }
Exemplo n.º 12
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Build Electron Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                var desiredPlatform = parser.Arguments[_paramTarget][0];
                string specifiedFromCustom = string.Empty;
                if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                {
                    specifiedFromCustom = parser.Arguments[_paramTarget][1];
                }

                string configuration = "Release";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                var platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid}...");


                string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "obj", "desktop", desiredPlatform);
                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }

                Console.WriteLine("Executing dotnet publish in this directory: " + tempPath);

                string tempBinPath = Path.Combine(tempPath, "bin");

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid} under {configuration}-Configuration...");

                var resultCode = ProcessHelper.CmdExecute($"dotnet publish -r {platformInfo.NetCorePublishRid} -c {configuration} --output \"{tempBinPath}\"", Directory.GetCurrentDirectory());

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);

                var checkForNodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (Directory.Exists(checkForNodeModulesDirPath) == false)
                {
                    Console.WriteLine("node_modules missing in: " + checkForNodeModulesDirPath);

                    Console.WriteLine("Start npm install...");
                    ProcessHelper.CmdExecute("npm install", tempPath);

                    Console.WriteLine("Start npm install electron-packager...");

                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        // Works proper on Windows...
                        ProcessHelper.CmdExecute("npm install electron-packager --global", tempPath);
                    }
                    else
                    {
                        // ToDo: find another solution or document it proper
                        // GH Issue https://github.com/electron-userland/electron-prebuilt/issues/48
                        Console.WriteLine("Electron Packager - make sure you invoke 'sudo npm install electron-packager --global' at " + tempPath + " manually. Sry.");
                    }
                }
                else
                {
                    Console.WriteLine("Skip npm install, because node_modules directory exists in: " + checkForNodeModulesDirPath);
                }

                Console.WriteLine("Build Electron Desktop Application...");
                string buildPath = Path.Combine(Directory.GetCurrentDirectory(), "bin", "desktop");

                Console.WriteLine("Executing electron magic in this directory: " + buildPath);

                // ToDo: Need a solution for --asar support

                string electronArch = "x64";
                if (parser.Arguments.ContainsKey(_paramElectronArch))
                {
                    electronArch = parser.Arguments[_paramElectronArch][0];
                }

                string electronParams = "";
                if (parser.Arguments.ContainsKey(_paramElectronParams))
                {
                    electronParams = parser.Arguments[_paramElectronParams][0];
                }

                Console.WriteLine($"Package Electron App for Platform {platformInfo.ElectronPackerPlatform}...");
                ProcessHelper.CmdExecute($"electron-packager . --platform={platformInfo.ElectronPackerPlatform} --arch={electronArch} {electronParams} --out=\"{buildPath}\" --overwrite", tempPath);

                Console.WriteLine("... done");

                return true;
            }));
        }
Exemplo n.º 13
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Build Electron Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                var desiredPlatform = parser.Arguments[_paramTarget][0];
                string specifiedFromCustom = string.Empty;
                if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                {
                    specifiedFromCustom = parser.Arguments[_paramTarget][1];
                }

                string configuration = "Release";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                var platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid}...");

                string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "obj", "desktop", desiredPlatform);

                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }

                Console.WriteLine("Executing dotnet publish in this directory: " + tempPath);

                string tempBinPath = Path.Combine(tempPath, "bin");

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid} under {configuration}-Configuration...");

                var resultCode = ProcessHelper.CmdExecute($"dotnet publish -r {platformInfo.NetCorePublishRid} -c {configuration} --output \"{tempBinPath}\"", Directory.GetCurrentDirectory());

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);
                var nodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (parser.Arguments.ContainsKey(_paramPackageJson))
                {
                    Console.WriteLine("Copying custom package.json.");

                    File.Copy(parser.Arguments[_paramPackageJson][0], Path.Combine(tempPath, "package.json"), true);
                }

                var checkForNodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (Directory.Exists(checkForNodeModulesDirPath) == false || parser.Contains(_paramForceNodeInstall) || parser.Contains(_paramPackageJson))
                {
                    Console.WriteLine("Start npm install...");
                }
                ProcessHelper.CmdExecute("npm install --production", tempPath);

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p . --sourceMap false", hosthookDir);
                }

                Console.WriteLine("Build Electron Desktop Application...");

                // Specifying an absolute path supercedes a relative path
                string buildPath = Path.Combine(Directory.GetCurrentDirectory(), "bin", "desktop");
                if (parser.Arguments.ContainsKey(_paramAbsoluteOutput))
                {
                    buildPath = parser.Arguments[_paramAbsoluteOutput][0];
                }
                else if (parser.Arguments.ContainsKey(_paramOutputDirectory))
                {
                    buildPath = Path.Combine(Directory.GetCurrentDirectory(), parser.Arguments[_paramOutputDirectory][0]);
                }

                Console.WriteLine("Executing electron magic in this directory: " + buildPath);

                string electronArch = "x64";
                if (parser.Arguments.ContainsKey(_paramElectronArch))
                {
                    electronArch = parser.Arguments[_paramElectronArch][0];
                }

                string electronParams = "";
                if (parser.Arguments.ContainsKey(_paramElectronParams))
                {
                    electronParams = parser.Arguments[_paramElectronParams][0];
                }

                // ToDo: Make the same thing easer with native c# - we can save a tmp file in production code :)
                Console.WriteLine("Create electron-builder configuration file...");
                ProcessHelper.CmdExecute($"node build-helper.js", tempPath);

                Console.WriteLine($"Package Electron App for Platform {platformInfo.ElectronPackerPlatform}...");
                ProcessHelper.CmdExecute($"npx electron-builder . --config=./bin/electron-builder.json --{platformInfo.ElectronPackerPlatform} --{electronArch} -c.electronVersion=5.0.8 {electronParams}", tempPath);

                Console.WriteLine("... done");

                return true;
            }));
        }
Exemplo n.º 14
0
        static int Main(string[] args)
        {
            SimpleCommandLineParser parser = new SimpleCommandLineParser(args);

            parser.addOption("rf", ARGUMENT_TYPE.MUST);
            parser.addOption("rt", ARGUMENT_TYPE.MUST);
            parser.addOption("ie", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("ic", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("cf", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("ca", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("blob", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("h", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("?", ARGUMENT_TYPE.MUSTNOT);
            parser.Parse();
            if (parser["h"] != null || parser["?"] != null)
            {
                return(0);
            }
            if (parser["ca"] != null)
            {
                // check argument
                StringBuilder sb = new StringBuilder();
                if (parser["rf"] != null)
                {
                    sb.Append("rf:");
                    sb.AppendLine(parser["rf"].ToString());
                }

                if (parser["rt"] != null)
                {
                    sb.Append("rt:");
                    sb.AppendLine(parser["rt"].ToString());
                }

                if (parser["ie"] != null)
                {
                    sb.AppendLine("ie");
                }
                if (parser["ic"] != null)
                {
                    sb.AppendLine("ic");
                }
                if (parser["ca"] != null)
                {
                    sb.AppendLine("ca");
                }
                if (parser["cf"] != null)
                {
                    sb.AppendLine("cf");
                }
                if (parser["blob"] != null)
                {
                    sb.AppendLine("blob");
                }
                if (parser["h"] != null)
                {
                    sb.AppendLine("h");
                }
                if (parser["?"] != null)
                {
                    sb.AppendLine("?");
                }

                sb.AppendLine("--------------");

                for (int i = 0; i < parser.MainargLength; ++i)
                {
                    sb.AppendLine(parser.getMainargs(i));
                }

                CppUtils.CenteredMessageBox(sb.ToString());
            }

            return(0);
        }
Exemplo n.º 15
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                string port = "8000";
                if (parser.Arguments.ContainsKey(_paramPort))
                {
                    port = parser.Arguments[_paramPort][0];
                }

                string staticPort = "false";
                if (parser.Arguments.ContainsKey(_paramStaticPort))
                {
                    staticPort = parser.Arguments[_paramStaticPort][0];
                }

                string aspCoreProjectPath = "";
                if (parser.Arguments.ContainsKey(_paramPath))
                {
                    if (Directory.Exists(parser.Arguments[_paramPath][0]))
                    {
                        aspCoreProjectPath = parser.Arguments[_paramPath][0];
                    }
                    else
                    {
                        Console.WriteLine("Supplied path doesn't exist. Creating in current working directory.");
                    }
                }
                else
                {
                    aspCoreProjectPath = Directory.GetCurrentDirectory();
                }

                var currentDirectory = aspCoreProjectPath;

                Console.WriteLine("Adding our config file to your project...");

                var targetFilePath = Path.Combine(currentDirectory, ConfigName);

                if (File.Exists(targetFilePath))
                {
                    Console.WriteLine("Config file already in your project.");
                    return false;
                }

                // Deploy config file
                EmbeddedFileHelper.DeployEmbeddedFile(currentDirectory, ConfigName);

                // search .csproj
                Console.WriteLine($"Search your .csproj to add the needed {ConfigName}...");
                var projectFile = Directory.EnumerateFiles(currentDirectory, "*.csproj", SearchOption.TopDirectoryOnly).FirstOrDefault();

                string executable = GetAssemblyName(projectFile);

                string text = File.ReadAllText(targetFilePath);
                text = text.Replace("{{executable}}", executable);
                text = text.Replace("\"{{port}}\"", port);
                text = text.Replace("\"{{static}}\"", staticPort);
                File.WriteAllText(targetFilePath, text);

                Console.WriteLine($"Found your .csproj: {projectFile} - check for existing config or update it.");

                if (!EditCsProj(projectFile))
                {
                    return false;
                }

                // search launchSettings.json
                Console.WriteLine($"Search your .launchSettings to add our electron debug profile...");

                EditLaunchSettings(currentDirectory);

                Console.WriteLine($"Everything done - happy electronizing!");

                return true;
            }));
        }
Exemplo n.º 16
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Build Electron Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                //This version will be shared between the dotnet publish and electron-builder commands
                string version = null;
                if (parser.Arguments.ContainsKey(_paramVersion))
                {
                    version = parser.Arguments[_paramVersion][0];
                }

                if (!parser.Arguments.ContainsKey(_paramTarget) || parser.Arguments[_paramTarget].Length == 0)
                {
                    Console.WriteLine($"Error: missing '{_paramTarget}' argument.");
                    Console.WriteLine(COMMAND_ARGUMENTS);
                    return false;
                }

                var desiredPlatform = parser.Arguments[_paramTarget][0];
                string specifiedFromCustom = string.Empty;
                if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                {
                    specifiedFromCustom = parser.Arguments[_paramTarget][1];
                }

                string configuration = "Release";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                var platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid}...");

                string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "obj", "desktop", desiredPlatform);

                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }
                else
                {
                    Directory.Delete(tempPath, true);
                    Directory.CreateDirectory(tempPath);
                }


                Console.WriteLine("Executing dotnet publish in this directory: " + tempPath);

                string tempBinPath = Path.Combine(tempPath, "bin");

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid} under {configuration}-Configuration...");

                var dotNetPublishFlags = GetDotNetPublishFlags(parser, "false", "false");

                var project = string.Empty;
                if (parser.Arguments.ContainsKey(_paramDotNetProject))
                {
                    project = parser.Arguments[_paramDotNetProject][0];
                }

                var command =
                    $"dotnet publish {project} -r {platformInfo.NetCorePublishRid} -c \"{configuration}\" --output \"{tempBinPath}\" {string.Join(' ', dotNetPublishFlags.Select(kvp => $"{kvp.Key}={kvp.Value}"))}";

                // add any additional dotnet flags
                var dotnetFlags = GetDotNetArgs(parser);
                if (dotnetFlags.Any())
                {
                    command += " " + string.Join(" ", dotnetFlags);
                }

                // output the command
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(command);
                Console.ResetColor();

                var resultCode = ProcessHelper.CmdExecute(command, Directory.GetCurrentDirectory());

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);

                if (parser.Arguments.ContainsKey(_paramPackageJson))
                {
                    Console.WriteLine("Copying custom package.json.");

                    File.Copy(parser.Arguments[_paramPackageJson][0], Path.Combine(tempPath, "package.json"), true);
                }

                var checkForNodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (!Directory.Exists(checkForNodeModulesDirPath) || parser.Contains(_paramForceNodeInstall) || parser.Contains(_paramPackageJson))
                {
                    Console.WriteLine("Start npm install...");
                    ProcessHelper.CmdExecute("npm install --production", tempPath);
                }

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p . --sourceMap false", hosthookDir);
                }

                Console.WriteLine("Build Electron Desktop Application...");

                // Specifying an absolute path supercedes a relative path
                string buildPath = Path.Combine(Directory.GetCurrentDirectory(), "bin", "desktop");
                if (parser.Arguments.ContainsKey(_paramAbsoluteOutput))
                {
                    buildPath = parser.Arguments[_paramAbsoluteOutput][0];
                }
                else if (parser.Arguments.ContainsKey(_paramOutputDirectory))
                {
                    buildPath = Path.Combine(Directory.GetCurrentDirectory(), parser.Arguments[_paramOutputDirectory][0]);
                }

                Console.WriteLine("Executing electron magic in this directory: " + buildPath);


                string electronArch = "x64";

                if (platformInfo.NetCorePublishRid == "osx-arm64") //Apple Silicon Mac
                {
                    electronArch = "arm64";
                }

                if (parser.Arguments.ContainsKey(_paramElectronArch))
                {
                    electronArch = parser.Arguments[_paramElectronArch][0];
                }

                var electronVersion = "";
                if (parser.Arguments.ContainsKey(_paramElectronVersion))
                {
                    electronVersion = parser.Arguments[_paramElectronVersion][0];
                }
                else
                {
                    //try getting version from project
                    foreach (var projectFile in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.csproj"))
                    {
                        var projectXML = File.ReadAllText(projectFile);
                        var match = Regex.Match(projectXML, @"<PackageReference\s+Include=""h5\.ElectronNET\.API""\s+Version=""([0-9\.]+)""\s+\/>");
                        if (match.Success)
                        {
                            var candidate = match.Groups[1].Value;
                            var majorMinorRevision = string.Join(".", candidate.Split(new char[] { '.' }).Take(3));
                            electronVersion = majorMinorRevision;
                            Console.WriteLine($"Found electron version {majorMinorRevision} in project file {projectFile}");
                            break;
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(electronVersion))
                {
                    electronVersion = _defaultElectronVersion;
                }


                string electronParams = "";
                if (parser.Arguments.ContainsKey(_paramElectronParams))
                {
                    electronParams = parser.Arguments[_paramElectronParams][0];
                }

                // ToDo: Make the same thing easer with native c# - we can save a tmp file in production code :)
                Console.WriteLine("Create electron-builder configuration file...");

                string manifestFileName = "electron.manifest.json";

                if (parser.Arguments.ContainsKey(_manifest))
                {
                    manifestFileName = parser.Arguments[_manifest].First();
                }

                ProcessHelper.CmdExecute(
                    string.IsNullOrWhiteSpace(version)
                        ? $"node build-helper.js {manifestFileName}"
                        : $"node build-helper.js {manifestFileName} {version}", tempPath);

                Console.WriteLine($"Package Electron App for Platform {platformInfo.ElectronPackerPlatform}...");
                ProcessHelper.CmdExecute($"npx electron-builder --config=./bin/electron-builder.json --{platformInfo.ElectronPackerPlatform} --{electronArch} -c.electronVersion={electronVersion} {electronParams}", tempPath);

                Console.WriteLine("... done");

                return true;
            }));
        }
Exemplo n.º 17
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Build Electron Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                //This version will be shared between the dotnet publish and electron-builder commands
                string version = null;
                if (parser.Arguments.ContainsKey(_paramVersion))
                {
                    version = parser.Arguments[_paramVersion][0];
                }

                if (!parser.Arguments.ContainsKey(_paramTarget) || parser.Arguments[_paramTarget].Length == 0)
                {
                    Console.WriteLine($"Error: missing '{_paramTarget}' argument.");
                    Console.WriteLine(COMMAND_ARGUMENTS);
                    return false;
                }

                var desiredPlatform = parser.Arguments[_paramTarget][0];
                string specifiedFromCustom = string.Empty;
                if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                {
                    specifiedFromCustom = parser.Arguments[_paramTarget][1];
                }

                string configuration = "Release";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                var platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid}...");

                string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "obj", "desktop", desiredPlatform);

                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }
                else
                {
                    Directory.Delete(tempPath, true);
                    Directory.CreateDirectory(tempPath);
                }


                Console.WriteLine("Executing dotnet publish in this directory: " + tempPath);

                string tempBinPath = Path.Combine(tempPath, "bin");

                Console.WriteLine($"Build ASP.NET Core App for {platformInfo.NetCorePublishRid} under {configuration}-Configuration...");

                var dotNetPublishFlags = GetDotNetPublishFlags(parser);

                var command =
                    $"dotnet publish -r {platformInfo.NetCorePublishRid} -c \"{configuration}\" --output \"{tempBinPath}\" {string.Join(' ', dotNetPublishFlags.Select(kvp => $"{kvp.Key}={kvp.Value}"))} --self-contained";

                // output the command
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(command);
                Console.ResetColor();

                var resultCode = ProcessHelper.CmdExecute(command, Directory.GetCurrentDirectory());

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);
                var nodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (parser.Arguments.ContainsKey(_paramPackageJson))
                {
                    Console.WriteLine("Copying custom package.json.");

                    File.Copy(parser.Arguments[_paramPackageJson][0], Path.Combine(tempPath, "package.json"), true);
                }

                var checkForNodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                if (Directory.Exists(checkForNodeModulesDirPath) == false || parser.Contains(_paramForceNodeInstall) || parser.Contains(_paramPackageJson))
                {
                    Console.WriteLine("Start npm install...");
                }
                ProcessHelper.CmdExecute("npm install --production", tempPath);

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p . --sourceMap false", hosthookDir);
                }

                Console.WriteLine("Build Electron Desktop Application...");

                // Specifying an absolute path supercedes a relative path
                string buildPath = Path.Combine(Directory.GetCurrentDirectory(), "bin", "desktop");
                if (parser.Arguments.ContainsKey(_paramAbsoluteOutput))
                {
                    buildPath = parser.Arguments[_paramAbsoluteOutput][0];
                }
                else if (parser.Arguments.ContainsKey(_paramOutputDirectory))
                {
                    buildPath = Path.Combine(Directory.GetCurrentDirectory(), parser.Arguments[_paramOutputDirectory][0]);
                }

                Console.WriteLine("Executing electron magic in this directory: " + buildPath);

                string electronArch = "x64";
                if (parser.Arguments.ContainsKey(_paramElectronArch))
                {
                    electronArch = parser.Arguments[_paramElectronArch][0];
                }

                string electronParams = "";
                if (parser.Arguments.ContainsKey(_paramElectronParams))
                {
                    electronParams = parser.Arguments[_paramElectronParams][0];
                }

                // ToDo: Make the same thing easer with native c# - we can save a tmp file in production code :)
                Console.WriteLine("Create electron-builder configuration file...");

                string manifestFileName = "electron.manifest.json";

                if (parser.Arguments.ContainsKey(_manifest))
                {
                    manifestFileName = parser.Arguments[_manifest].First();
                }

                ProcessHelper.CmdExecute(
                    string.IsNullOrWhiteSpace(version)
                        ? $"node build-helper.js {manifestFileName}"
                        : $"node build-helper.js {manifestFileName} {version}", tempPath);

                Console.WriteLine($"Package Electron App for Platform {platformInfo.ElectronPackerPlatform}...");
                ProcessHelper.CmdExecute($"npx electron-builder --config=./bin/electron-builder.json --{platformInfo.ElectronPackerPlatform} --{electronArch} -c.electronVersion=13.1.5 {electronParams}", tempPath);

                Console.WriteLine("... done");

                return true;
            }));
        }
Exemplo n.º 18
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Start Electron Desktop Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                string aspCoreProjectPath = "";

                if (parser.Arguments.ContainsKey(_aspCoreProjectPath))
                {
                    string projectPath = parser.Arguments[_aspCoreProjectPath].First();
                    if (Directory.Exists(projectPath))
                    {
                        aspCoreProjectPath = projectPath;
                    }
                }
                else
                {
                    aspCoreProjectPath = Directory.GetCurrentDirectory();
                }

                string tempPath = Path.Combine(aspCoreProjectPath, "obj", "Host");
                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }

                string tempBinPath = Path.GetFullPath(Path.Combine(tempPath, "bin"));

                var dotNetPublishFlags = BuildCommand.GetDotNetPublishFlags(parser, "false", "false");

                var resultCode = 0;


                // If target is specified as a command line argument, use it.
                // Format is the same as the build command.
                // If target is not specified, autodetect it.
                var platformInfo = GetTargetPlatformInformation.Do(string.Empty, string.Empty);
                if (parser.Arguments.ContainsKey(_paramTarget))
                {
                    var desiredPlatform = parser.Arguments[_paramTarget][0];
                    string specifiedFromCustom = string.Empty;
                    if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                    {
                        specifiedFromCustom = parser.Arguments[_paramTarget][1];
                    }
                    platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);
                }

                string configuration = "Debug";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                var project = string.Empty;
                if (parser.Arguments.ContainsKey(_paramDotNetProject))
                {
                    project = parser.Arguments[_paramDotNetProject][0];
                }

                if (!parser.Arguments.ContainsKey("watch"))
                {
                    resultCode = ProcessHelper.CmdExecute($"dotnet publish {project} -r {platformInfo.NetCorePublishRid} -c \"{configuration}\" --output \"{tempBinPath}\" {string.Join(' ', dotNetPublishFlags.Select(kvp => $"{kvp.Key}={kvp.Value}"))} /p:DisabledWarnings=true", aspCoreProjectPath);
                }

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);

                var nodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                bool runNpmInstall = false;

                Console.WriteLine("node_modules in: " + nodeModulesDirPath);

                if (!Directory.Exists(nodeModulesDirPath))
                {
                    runNpmInstall = true;
                }

                var packagesJson = Path.Combine(tempPath, "package.json");
                var packagesPrevious = Path.Combine(tempPath, "package.json.previous");

                if (!runNpmInstall)
                {
                    if (File.Exists(packagesPrevious))
                    {
                        if (File.ReadAllText(packagesPrevious) != File.ReadAllText(packagesJson))
                        {
                            runNpmInstall = true;
                        }
                    }
                    else
                    {
                        runNpmInstall = true;
                    }
                }

                if (runNpmInstall)
                {
                    Console.WriteLine("Start npm install...");
                    ProcessHelper.CmdExecute("npm install", tempPath);
                    File.Copy(packagesJson, packagesPrevious, true);
                }

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for typescript & hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p ../../ElectronHostHook", tempPath);
                }

                string arguments = "";

                if (parser.Arguments.ContainsKey(_arguments))
                {
                    arguments = string.Join(' ', parser.Arguments[_arguments]);
                }

                if (parser.Arguments.ContainsKey(_manifest))
                {
                    arguments += " --manifest=" + parser.Arguments[_manifest].First();
                }

                if (parser.Arguments.ContainsKey(_clearCache))
                {
                    arguments += " --clear-cache=true";
                }

                if (parser.Arguments.ContainsKey("watch"))
                {
                    arguments += " --watch=true";
                }

                string path = Path.Combine(tempPath, "node_modules", ".bin");
                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                if (isWindows)
                {
                    Console.WriteLine("Invoke electron.cmd - in dir: " + path);
                    Console.WriteLine("\n\n---------------------------------------------------\n\n\n");
                    ProcessHelper.CmdExecute(@"electron.cmd ""..\..\main.js"" " + arguments, path);
                }
                else
                {
                    Console.WriteLine("Invoke electron - in dir: " + path);
                    Console.WriteLine("\n\n---------------------------------------------------\n\n\n");
                    ProcessHelper.CmdExecute(@"./electron ""../../main.js"" " + arguments, path);
                }

                return true;
            }));
        }
Exemplo n.º 19
0
        private static void Main(string[] args)
        {
            var parser = new SimpleCommandLineParser();
            parser.Parse(args);

            if (parser.Arguments.ContainsKey("server"))
            {
                var server = new LoadTestServer
                {
                    MessagesPerAck = parser.GetValue("MessagesPerAck", 0, 0)
                };
                server.Start(parser.GetValue("server", 0, 8334));
                Console.WriteLine("Server started");
                if (parser.Arguments.ContainsKey("quit"))
                {
                    Console.WriteLine("Waiting for completion");
                    server.WaitForExit();
                    Console.WriteLine("Exiting");
                }
                else
                {
                    Console.WriteLine("Press ENTER to quit");
                    Console.ReadLine();
                }
            }
            else if (parser.Arguments.ContainsKey("client"))
            {
                Process serverProcess = null;
                if (parser.Arguments.ContainsKey("SpawnServer"))
                {
                    var hostAndPort = parser.Arguments["client"][0];
                    var port = hostAndPort.Split(':')[1];
                    var psi = new ProcessStartInfo(Assembly.GetExecutingAssembly().Location);
                    psi.Arguments = " -server " + port + " -quit";
                    serverProcess = Process.Start(psi);
                }
                var client = new LoadTestClient
                {
                    MessageCount = parser.GetValue("MessageCount", 0, 10000),
                    MessageSize = parser.GetValue("MessageSize", 0, 1000),
                    MessagesPerAck = parser.GetValue("MessagesPerAck", 0, 0),
                    RemoteHost = parser.Arguments["client"][0]
                };

                var mbits = (client.MessageCount * client.MessageSize * 8) / 1000000;
                Console.WriteLine("Sending " + client.MessageCount + " messages of size " + client.MessageSize + " bytes. Total of " + mbits.ToString("N3") + "Mbits.");
                if (client.MessagesPerAck > 0)
                    Console.WriteLine("Using ACKs every " + client.MessagesPerAck + " message.");

                client.Start();
                Console.WriteLine("Waiting for exit");
                client.WaitForExit();
                if (serverProcess != null)
                {
                    client.Close();
                    Console.WriteLine("Waiting for server exit");
                    serverProcess.WaitForExit();
                }
            }
            else
            {
                Console.WriteLine("SharpMessaging.BenchmarkApp");
                Console.WriteLine();
                Console.WriteLine("SharpMessaging.BenchmarkApp -server [port]");
                Console.WriteLine("SharpMessaging.BenchmarkApp -client [host:port]");
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Options (for client and server)");
                Console.WriteLine("   Name             Default    Description");
                Console.WriteLine("   ==============================================");
                Console.WriteLine("   MessagesPerAck   0          0 = disable acks");
                Console.WriteLine();
                Console.WriteLine("Options (for client)");
                Console.WriteLine("   Name             Default    Description");
                Console.WriteLine("   ==============================================");
                Console.WriteLine("   MessageCount     10000      Number of messages to send");
                Console.WriteLine("   MessageSize      1000       Message size");
                Console.WriteLine();
                Console.WriteLine("Example:");
                Console.WriteLine("SharpMessaging.BenchmarkApp -client localhost:8334 -MessageCount 100000");
                return;
            }
        }
Exemplo n.º 20
0
        public Task <bool> ExecuteAsync()
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("Start Electron Desktop Application...");

                SimpleCommandLineParser parser = new SimpleCommandLineParser();
                parser.Parse(_args);

                string aspCoreProjectPath = "";

                if (parser.Arguments.ContainsKey(_aspCoreProjectPath))
                {
                    string projectPath = parser.Arguments[_aspCoreProjectPath].First();
                    if (Directory.Exists(projectPath))
                    {
                        aspCoreProjectPath = projectPath;
                    }
                }
                else
                {
                    aspCoreProjectPath = Directory.GetCurrentDirectory();
                }

                string tempPath = Path.Combine(aspCoreProjectPath, "obj", "Host");
                if (Directory.Exists(tempPath) == false)
                {
                    Directory.CreateDirectory(tempPath);
                }

                string tempBinPath = Path.Combine(tempPath, "bin");
                var resultCode = 0;

                string publishReadyToRun = "/p:PublishReadyToRun=";
                if (parser.Arguments.ContainsKey(_paramPublishReadyToRun))
                {
                    publishReadyToRun += parser.Arguments[_paramPublishReadyToRun][0];
                }
                else
                {
                    publishReadyToRun += "true";
                }

                string publishSingleFile = "/p:PublishSingleFile=";
                if (parser.Arguments.ContainsKey(_paramPublishSingleFile))
                {
                    publishSingleFile += parser.Arguments[_paramPublishSingleFile][0];
                }
                else
                {
                    publishSingleFile += "true";
                }

                // If target is specified as a command line argument, use it.
                // Format is the same as the build command.
                // If target is not specified, autodetect it.
                var platformInfo = GetTargetPlatformInformation.Do(string.Empty, string.Empty);
                if (parser.Arguments.ContainsKey(_paramTarget))
                {
                    var desiredPlatform = parser.Arguments[_paramTarget][0];
                    string specifiedFromCustom = string.Empty;
                    if (desiredPlatform == "custom" && parser.Arguments[_paramTarget].Length > 1)
                    {
                        specifiedFromCustom = parser.Arguments[_paramTarget][1];
                    }
                    platformInfo = GetTargetPlatformInformation.Do(desiredPlatform, specifiedFromCustom);
                }

                string configuration = "Debug";
                if (parser.Arguments.ContainsKey(_paramDotNetConfig))
                {
                    configuration = parser.Arguments[_paramDotNetConfig][0];
                }

                if (parser != null && !parser.Arguments.ContainsKey("watch"))
                {
                    resultCode = ProcessHelper.CmdExecute($"dotnet publish -r {platformInfo.NetCorePublishRid} -c \"{configuration}\" --output \"{tempBinPath}\" {publishReadyToRun} {publishSingleFile} --no-self-contained", aspCoreProjectPath);
                }

                if (resultCode != 0)
                {
                    Console.WriteLine("Error occurred during dotnet publish: " + resultCode);
                    return false;
                }

                DeployEmbeddedElectronFiles.Do(tempPath);

                var nodeModulesDirPath = Path.Combine(tempPath, "node_modules");

                Console.WriteLine("node_modules missing in: " + nodeModulesDirPath);

                Console.WriteLine("Start npm install...");
                ProcessHelper.CmdExecute("npm install", tempPath);

                Console.WriteLine("ElectronHostHook handling started...");

                string electronhosthookDir = Path.Combine(Directory.GetCurrentDirectory(), "ElectronHostHook");

                if (Directory.Exists(electronhosthookDir))
                {
                    string hosthookDir = Path.Combine(tempPath, "ElectronHostHook");
                    DirectoryCopy.Do(electronhosthookDir, hosthookDir, true, new List <string>()
                    {
                        "node_modules"
                    });

                    Console.WriteLine("Start npm install for typescript & hosthooks...");
                    ProcessHelper.CmdExecute("npm install", hosthookDir);

                    // ToDo: Not sure if this runs under linux/macos
                    ProcessHelper.CmdExecute(@"npx tsc -p ../../ElectronHostHook", tempPath);
                }

                string arguments = "";

                if (parser.Arguments.ContainsKey(_arguments))
                {
                    arguments = string.Join(' ', parser.Arguments[_arguments]);
                }

                if (parser.Arguments.ContainsKey(_manifest))
                {
                    arguments += " --manifest=" + parser.Arguments[_manifest].First();
                }

                if (parser.Arguments.ContainsKey(_clearCache))
                {
                    arguments += " --clear-cache=true";
                }

                if (parser.Arguments.ContainsKey("watch"))
                {
                    arguments += " --watch=true";
                }

                string path = Path.Combine(tempPath, "node_modules", ".bin");
                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                if (isWindows)
                {
                    Console.WriteLine("Invoke electron.cmd - in dir: " + path);
                    ProcessHelper.CmdExecute(@"electron.cmd ""..\..\main.js"" " + arguments, path);
                }
                else
                {
                    Console.WriteLine("Invoke electron - in dir: " + path);
                    ProcessHelper.CmdExecute(@"./electron ""../../main.js"" " + arguments, path);
                }

                return true;
            }));
        }
Exemplo n.º 21
0
        static int Main(string[] args)
        {
            SimpleCommandLineParser parser = new SimpleCommandLineParser(args);

            parser.addOption("rf", ARGUMENT_TYPE.MUST);
            parser.addOption("rt", ARGUMENT_TYPE.MUST);
            parser.addOption("ie", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("ic", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("cf", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("ca", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("blob", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("h", ARGUMENT_TYPE.MUSTNOT);
            parser.addOption("?", ARGUMENT_TYPE.MUSTNOT);
            parser.Parse();
            if (parser["h"] != null || parser["?"] != null)
            {
                ShowHelp();
                return(0);
            }
            if (parser["ca"] != null)
            {
                // check argument
                StringBuilder sb = new StringBuilder();
                if (parser["rf"] != null)
                {
                    sb.Append("rf:");
                    sb.AppendLine(parser["rf"].ToString());
                }

                if (parser["rt"] != null)
                {
                    sb.Append("rt:");
                    sb.AppendLine(parser["rt"].ToString());
                }

                if (parser["ie"] != null)
                {
                    sb.AppendLine("ie");
                }
                if (parser["ic"] != null)
                {
                    sb.AppendLine("ic");
                }
                if (parser["ca"] != null)
                {
                    sb.AppendLine("ca");
                }
                if (parser["cf"] != null)
                {
                    sb.AppendLine("cf");
                }
                if (parser["blob"] != null)
                {
                    sb.AppendLine("blob");
                }
                if (parser["h"] != null)
                {
                    sb.AppendLine("h");
                }
                if (parser["?"] != null)
                {
                    sb.AppendLine("?");
                }

                MessageBox.Show(sb.ToString(),
                                Application.ProductName + " " + "check arg",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(0);
            }
            if (parser["rf"] == null || parser["rt"] == null)
            {
                ShowAlert(Properties.Resources.MUST_SPECIFY_RF_RT);
                return(1);
            }

            string f = parser["rf"].ToString();
            string t = parser["rt"].ToString();

            if (parser.MainargLength == 0)
            {
                ShowAlert(Properties.Resources.NO_FILE);
                return(1);
            }

            Regex regf = null;

            try
            {
                if (parser["ic"] != null)
                {
                    regf = new Regex(f, RegexOptions.IgnoreCase);
                }
                else
                {
                    regf = new Regex(f);
                }
            }
            catch (Exception ex)
            {
                CppUtils.CenteredMessageBox(ex.Message);
                return(1);
            }
            bool isAlsoExt = null != parser["ie"];
            bool dryrun    = parser["cf"] != null;
            Dictionary <string, string> targets = new Dictionary <string, string>();

            string[] mainArgs = ConstructMainArgs(parser);
            try
            {
                foreach (string orgFullorRelativeFileName in mainArgs)// (int i = 0; i < parser.MainargLength; ++i)
                {
                    FileInfo fiorig      = new FileInfo(orgFullorRelativeFileName);
                    string   orgFileName = getProperName(fiorig, isAlsoExt);
                    string   orgFolder   = fiorig.DirectoryName;

                    string newFileName = regf.Replace(orgFileName, t);
                    if (!isAlsoExt)
                    {
                        newFileName += fiorig.Extension;
                    }

                    //if (dryrun)
                    //{
                    //    sbDry.AppendLine(string.Format("\"{0}\" -> \"{1}\"",
                    //        fiorig.FullName, orgFolder + @"\" + newFileName));
                    //}
                    //else
                    //{
                    //    fiorig.MoveTo(orgFolder + @"\" + newFileName);
                    //}
                    targets.Add(fiorig.FullName, orgFolder + @"\" + newFileName);
                }

                if (dryrun)
                {
                    StringBuilder sbDry = new StringBuilder();
                    foreach (string org in targets.Keys)
                    {
                        sbDry.AppendFormat("\"{0}\" -> \"{1}\"", org, targets[org]);
                        sbDry.AppendLine();
                        sbDry.AppendLine();
                    }
                    sbDry.AppendLine();
                    sbDry.AppendLine(Properties.Resources.DO_YOU_WANT_TO_PERFORM);

                    if (DialogResult.Yes != MessageBox.Show(
                            sbDry.ToString(),
                            Application.ProductName + " " + Properties.Resources.CONFIRM,
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question,
                            MessageBoxDefaultButton.Button2))
                    {
                        return(0);
                    }
                }

                foreach (string org in targets.Keys)
                {
                    if (Directory.Exists(org))
                    {
                        Directory.Move(org, targets[org]);
                    }
                    else
                    {
                        File.Move(org, targets[org]);
                    }
                }
                return(0);
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    e.Message, Application.ProductName,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return(-1);
            }
        }