Ejemplo n.º 1
0
    static void GenerateFile(List <Tuple <string, string, string> > txtStrings, CmdOptions options)
    {
//		var outputFile = options.OutputFile ?? "SR.cs";

        using (var str = options.OutputFile == null ? Console.Out : new StreamWriter(options.OutputFile)) {
            str.WriteLine("//");
            str.WriteLine("// This file was generated by resx2sr tool");
            str.WriteLine("//");
            str.WriteLine();

            str.WriteLine("partial class SR");
            str.WriteLine("{");
            foreach (var entry in txtStrings)
            {
                str.Write($"\tpublic const string {entry.Item1} = \"{ToCSharpString (entry.Item2)}\";");

                if (!string.IsNullOrEmpty(entry.Item3))
                {
                    str.Write(" // {entry.Item3}");
                }

                str.WriteLine();
            }
            str.WriteLine("}");
        }
    }
Ejemplo n.º 2
0
        static async Task MainAsync(string [] args)
        {
            CmdOptions options         = new CmdOptions();
            bool       didParseOptions = CommandLine.Parser.Default.ParseArguments(args, options);

            if (!didParseOptions)
            {
                Console.WriteLine("Error: failed to parse command line options");
                return;
            }

            IPaymentProviderBackend      apiProvider    = PaymentProviderBackendFactory.GetProvider(options.Provider, new ConsoleLoggerAdapter());
            PaymentProviderConfiguration providerConfig = new PaymentProviderConfiguration()
            {
                AccountIdentifer = options.MerchantId,
                SharedSecret     = options.SecretKey
            };
            ConsoleApiCaller apiCaller = new ConsoleApiCaller(apiProvider, providerConfig);

            switch (options.CommandName)
            {
            case "checkAuth":
                await apiCaller.DoCheckAuth(options.RecordId /* , options.SubAccount */);

                break;

            default:
                Console.WriteLine($"Error: command \"{options.CommandName}\" not supporter");
                break;
            }
        }
Ejemplo n.º 3
0
        private static Task ProcessInputDataAsync(
            Process process, CmdOptions options, CancellationToken ct)
        {
            if (options.InputText == null)
            {
                return(Task.CompletedTask);
            }

            return(Task.Run(() =>
            {
                using (process.StandardInput)
                {
                    while (!ct.IsCancellationRequested)
                    {
                        string text = options.InputText(ct);
                        if (string.IsNullOrEmpty(text))
                        {
                            break;
                        }

                        process.StandardInput.WriteLine(text);
                    }
                }
            },
                            ct));
        }
Ejemplo n.º 4
0
        private static CmdOptions ParseCommandArgs(string[] args)
        {
            CmdOptions cmdOptions = new CmdOptions();

            try
            {
                var parsedArguments = CommandLine.Parser.Default.ParseArguments <CmdOptions>(args).WithParsed <CmdOptions>(opts =>
                {
                    cmdOptions = opts;
                });

                if (parsedArguments.Tag == ParserResultType.Parsed)
                {
                    return(cmdOptions);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Err");
                return(null);
            }
        }
Ejemplo n.º 5
0
        private static async Task <OutData> ProcessOutDataAsync(
            Process process, CmdOptions options, CancellationToken ct)
        {
            StringBuilder outputText = options.IsOutputDisabled ? null : new StringBuilder();
            StringBuilder errorText  = options.IsErrortDisabled ? null : new StringBuilder();

            Task outputStreamTask = ReadStreamAsync(
                process.StandardOutput, outputText, options.OutputProgress, options.OutputLines, ct);

            Task errorStreamTask = ReadStreamAsync(
                process.StandardError, errorText, options.ErrorProgress, options.ErrorLines, ct);

            Task streamsTask = Task.WhenAll(outputStreamTask, errorStreamTask);

            // Ensure cancel will abandons stream reading
            TaskCompletionSource <bool> canceledTcs = new TaskCompletionSource <bool>();

            ct.Register(() => canceledTcs.TrySetResult(true));
            await Task.WhenAny(streamsTask, canceledTcs.Task);

            string error = (errorText?.ToString() ?? "") +
                           (ct.IsCancellationRequested ? "... Canceled" : "");

            return(new OutData
            {
                Outout = outputText?.ToString() ?? "", Error = error
            });
        }
Ejemplo n.º 6
0
        static void RunArgs(CmdOptions opt, string[] args)
        {
            int port = opt.Port;
            var cts  = new CancellationTokenSource();


            Console.CancelKeyPress += delegate
            {
                Console.WriteLine("[INFO] Exiting server..");
                cts.Cancel();
            };

            // parse IP option
            if (!IPAddress.TryParse(opt.Address, out var ip))
            {
                Console.WriteLine("[ERROR] Invalid IP address provided.");
                return;
            }

            Console.WriteLine($"SLP Listening on {ip.ToString()}:{port}...");

            _slpServer = new SLPServer(port, cts);
            _slpServer.Run();

            CreateWebHostBuilder(ip, port, args).Build().Run();
        }
Ejemplo n.º 7
0
        private async Task <CmdResult2> RunGitCmsAsync(
            string gitArgs, GitOptions options, string sessionId, CancellationToken ct)
        {
            AdjustOptions(options, sessionId);

            // Log.Debug($"Running: {GitCmdPath} {gitArgs}");
            CmdOptions cmdOptions = ToCmdOptions(options);
            string     gitCmdPath = GitCmdPath;
            CmdResult2 result     = await cmd.RunAsync(gitCmdPath, gitArgs, cmdOptions, ct);

            if (result.IsFaulted &&
                !result.IsCanceled &&
                !(result.ExitCode == 1 && string.IsNullOrEmpty(result.Error)))
            {
                Track.Event("Git-error", $"{result.ElapsedMs}ms: Exit {result.ExitCode}: {result.Command} {result.Arguments}\nError:\n{result.ErrorMessage}");
            }
            else
            {
                Track.Event("Git", $"{result.ElapsedMs}ms: {result.Command} {result.Arguments}");
                var replace = result.ToString().Replace($"\"{gitCmdPath}\"", "git");
                Log.Debug($"{result.ElapsedMs}ms: {replace}");
            }

            return(result);
        }
Ejemplo n.º 8
0
        private static string GetDescription(CmdOptions o, int shift)
        {
            var sb = new StringBuilder();
            var ss = o.Description?.Split(' ') ?? Array.Empty <string>();
            var l  = shift;

            foreach (var s in ss)
            {
                if (l + s.Length <= MAX_LEN)
                {
                    sb.Append(s); sb.Append(" ");
                    l += s.Length + 1;
                }
                else
                {
                    sb.Append("\n");
                    for (int i = 0; i < shift; i++)
                    {
                        sb.Append(" ");
                    }
                    sb.Append(s); sb.Append(" ");
                    l = shift + s.Length + 1;
                }
            }
            return(sb.ToString());
        }
Ejemplo n.º 9
0
    static bool LoadGetResourceStrings(Dictionary <string, string> resourcesStrings, CmdOptions options)
    {
        foreach (var fileName in options.ResourcesStrings)
        {
            if (!File.Exists(fileName))
            {
                Console.Error.WriteLine($"Error reading resource file '{fileName}'");
                return(false);
            }

            foreach (var l in File.ReadLines(fileName))
            {
                var line = l.Trim();
                if (line.Length == 0 || line [0] == '#' || line [0] == ';')
                {
                    continue;
                }

                var epos = line.IndexOf('=');
                if (epos < 0)
                {
                    continue;
                }

                var key   = line.Substring(0, epos).Trim();
                var value = line.Substring(epos + 1).Trim();

                resourcesStrings [key] = value;
            }
        }

        return(true);
    }
Ejemplo n.º 10
0
    static bool LoadStrings(List <Tuple <string, string> > resourcesStrings, CmdOptions options)
    {
        var keys = new Dictionary <string, string> ();

        foreach (var fileName in options.ResourcesStrings)
        {
            if (!File.Exists(fileName))
            {
                Console.Error.WriteLine($"Error reading resource file '{fileName}'");
                return(false);
            }

            foreach (var l in File.ReadLines(fileName))
            {
                var line = l.Trim();
                if (line.Length == 0 || line [0] == '#')
                {
                    continue;
                }

                int start = 0;
                if (line [0] == ';')
                {
                    if (!options.IgnoreSemicolon)
                    {
                        continue;
                    }

                    start = 1;
                }

                var epos = line.IndexOf('=');
                if (epos < 0)
                {
                    continue;
                }

                var key = line.Substring(start, epos - start).Trim();
                if (key.Contains(" "))
                {
                    continue;
                }

                var value = line.Substring(epos + 1).Trim();

                string existing;
                if (keys.TryGetValue(key, out existing))
                {
                    continue;
                }

                keys.Add(key, value);
                resourcesStrings.Add(Tuple.Create(key, value));
            }
        }

        return(true);
    }
Ejemplo n.º 11
0
    public static int Main(string[] args)
    {
        var options = new CmdOptions();

        InputFiles   = new List <string> ();
        ExistingKeys = new Dictionary <string, object> ();

        var p = new OptionSet()
        {
            { "o|out=", "Specifies output file name",
              v => options.OutputFile = v },
            { "i|in=", "Specifies input file name",
              v => InputFiles.Add(v) },
            { "h|help", "Display available options",
              v => options.ShowHelp = v != null },
        };

        List <string> extra;

        try {
            extra = p.Parse(args);
        } catch (OptionException e) {
            Console.WriteLine(e.Message);
            Console.WriteLine("Try 'resx2sr -help' for more information.");
            return(1);
        }

        if (options.ShowHelp)
        {
            ShowHelp(p);
            return(0);
        }

        if (extra.Count < 1)
        {
            ShowHelp(p);
            return(2);
        }

        if (!LoadInputFiles())
        {
            return(4);
        }

        var resxStrings = new List <Tuple <string, string, string> > ();

        if (!LoadStrings(resxStrings, extra))
        {
            return(3);
        }

        GenerateFile(resxStrings, options);

        return(0);
    }
Ejemplo n.º 12
0
        public void Run(CmdOptions options)
        {
            // Drop off the rover in the specified location
            var controller = _dispatcher.SetPosition(options.InitialXPos, options.InitialYPos, options.Direction);

            // Move the rover as per instructions
            controller.Move(options.Command);

            // Write the final location of the rover
            Console.WriteLine(controller.Rover);
        }
Ejemplo n.º 13
0
    public static int Main(string[] args)
    {
        var options = new CmdOptions();

        var p = new OptionSet()
        {
            { "r|resourcestrings=", "File with string resource in key=value format",
              v => options.ResourcesStrings.Add(v) },
            { "h|help", "Display available options",
              v => options.ShowHelp = v != null },
            { "v|verbose", "Use verbose output",
              v => options.Verbose = v != null },
            { "ilreplace=", "File with IL code to be used instead",
              v => options.ILFile = v },
            { "mscorlib-debug", "IL customizations for Mono's mscorlib",
              v => options.MonoMscorlib = v != null },
        };

        List <string> extra;

        try {
            extra = p.Parse(args);
        }
        catch (OptionException e) {
            Console.WriteLine(e.Message);
            Console.WriteLine("Try 'cil-stringreplacer -help' for more information.");
            return(1);
        }

        if (options.ShowHelp)
        {
            ShowHelp(p);
            return(0);
        }

        if (extra.Count != 1)
        {
            ShowHelp(p);
            return(2);
        }

        var resourcesStrings = new Dictionary <string, string> ();

        if (!LoadGetResourceStrings(resourcesStrings, options))
        {
            return(3);
        }

        RewriteAssembly(extra [0], resourcesStrings, options);

        return(0);
    }
Ejemplo n.º 14
0
    public static int Main(string[] args)
    {
        var options = new CmdOptions();

        var p = new OptionSet()
        {
            { "t|txt=", "File with string resource in key=value format",
              v => options.ResourcesStrings.Add(v) },
            { "h|help", "Display available options",
              v => options.ShowHelp = v != null },
            { "v|verbose", "Use verbose output",
              v => options.Verbose = v != null },
            { "ignore-semicolon", "Reads lines starting with semicolon",
              v => options.IgnoreSemicolon = v != null },
        };

        List <string> extra;

        try {
            extra = p.Parse(args);
        }
        catch (OptionException e) {
            Console.WriteLine(e.Message);
            Console.WriteLine("Try 'txt2sr -help' for more information.");
            return(1);
        }

        if (options.ShowHelp)
        {
            ShowHelp(p);
            return(0);
        }

        if (extra.Count != 1)
        {
            ShowHelp(p);
            return(2);
        }

        var txtStrings = new List <Tuple <string, string> > ();

        if (!LoadStrings(txtStrings, options))
        {
            return(3);
        }

        GenerateFile(extra [0], txtStrings, options);

        return(0);
    }
Ejemplo n.º 15
0
        private static string GetDefaultValue(CmdOptions o, int shift)
        {
            var sb = new StringBuilder();

            if (o.DefaultValue != null)
            {
                sb.Append("\n");
                for (int i = 0; i < shift; i++)
                {
                    sb.Append(" ");
                }
                sb.AppendFormat(CultureInfo.InvariantCulture, "DEFAULT: {0}", o.DefaultValue);
            }
            return(sb.ToString());
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            if (args.Contains("--display-languages"))
            {
                Console.WriteLine($"Available languages:\n\t{_languagesDelimitedByComma.Replace(",", "\n\t")}");

                return;
            }

            if (args.Contains("--display-usage"))
            {
                Console.WriteLine("Usage: moss [-x] [-l language] [-d] [-b basefile1] ... [-b basefilen] [-m #] [-c \"string\"] file1 file2 file3 ...");

                return;
            }

            var options = new CmdOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                return;
            }

            var socket = new MossSocket(options.UserId);
            var result = socket.SendRequest(new MossRequest
            {
                BaseFileNames      = options.BaseFileNames,
                Comments           = options.Comments,
                FileNames          = options.FileNames,
                IsDirectoryMode    = options.IsDirectoryMode,
                IsExperimental     = options.IsExperimental,
                Language           = options.Language,
                MaximumFilesToShow = options.MaximumFilesToShow,
                MaximumMatches     = options.MaximumMatches
            });

            if (!result.IsValid)
            {
                Console.WriteLine("Something went wrong");

                return;
            }

            Console.WriteLine($"URL: {result.ResultUrl}");

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Ejemplo n.º 17
0
        private static async Task <CmdResult2> RunProcessAsync(
            string command,
            string arguments,
            CmdOptions options,
            CancellationToken ct)
        {
            // Log.Debug($"Runing: {command} {arguments}");
            Stopwatch stopwatch = Stopwatch.StartNew();

            // The task async exit code
            TaskCompletionSource <int> tcs = new TaskCompletionSource <int>();

            Process process = new Process();

            process.StartInfo.FileName  = command;
            process.StartInfo.Arguments = arguments;

            SetProcessOptions(process, options);

            process.Start();
            process.Exited += (s, e) => SetExitCode(tcs, process);

            ct.Register(() => Cancel(process, tcs));

            Task           inputTask          = ProcessInputDataAsync(process, options, ct);
            Task <OutData> outputAndErrorTask = ProcessOutDataAsync(process, options, ct);

            await inputTask.ConfigureAwait(false);

            int exitCode = await tcs.Task.ConfigureAwait(false);

            OutData outData = await outputAndErrorTask.ConfigureAwait(false);

            process?.Dispose();
            stopwatch.Start();
            return(new CmdResult2(
                       command,
                       arguments,
                       options.WorkingDirectory,
                       exitCode,
                       outData.Outout,
                       outData.Error,
                       stopwatch.Elapsed,
                       ct));
        }
Ejemplo n.º 18
0
    static void GenerateFile(List <Tuple <string, string, string> > txtStrings, CmdOptions options)
    {
//		var outputFile = options.OutputFile ?? "SR.cs";

        using (var str = options.OutputFile == null ? Console.Out : new StreamWriter(options.OutputFile)) {
            str.WriteLine("//");
            str.WriteLine("// This file was generated by resx2sr tool");
            str.WriteLine("//");
            str.WriteLine();

            str.WriteLine("partial class SR");
            str.WriteLine("{");

            var dict = new Dictionary <string, string> ();

            foreach (var entry in txtStrings)
            {
                var    value = ToCSharpString(entry.Item2);
                string found;
                if (dict.TryGetValue(entry.Item1, out found))
                {
                    if (found == value)
                    {
                        continue;
                    }

                    str.WriteLine($"\t// Constant value mismatch");
                }
                else
                {
                    dict.Add(entry.Item1, value);
                }

                str.Write($"\tpublic const string {entry.Item1} = \"{value}\";");

                if (!string.IsNullOrEmpty(entry.Item3))
                {
                    str.Write(" // {entry.Item3}");
                }

                str.WriteLine();
            }
            str.WriteLine("}");
        }
    }
Ejemplo n.º 19
0
        private static string GetOptionValue(CmdOptions o, bool IsLongName = false)
        {
            var sb = new StringBuilder();

            if (o.Pi != null && o.Pi.PropertyType != typeof(bool))
            {
                char c = IsLongName ? '=' : ' ';
                if (o.IsValueOptional)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, $"[{c}<value>]");
                }
                else
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, $"{c}<value>");
                }
            }
            return(sb.ToString());
        }
Ejemplo n.º 20
0
        private static void SetProcessOptions(Process process, CmdOptions options)
        {
            process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.RedirectStandardInput  = options.InputText != null;
            process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            process.StartInfo.StandardErrorEncoding  = Encoding.UTF8;
            process.EnableRaisingEvents = true;
            options.EnvironmentVariables?.Invoke(process.StartInfo.Environment);


            if (!string.IsNullOrWhiteSpace(options.WorkingDirectory))
            {
                process.StartInfo.WorkingDirectory = options.WorkingDirectory;
            }
        }
Ejemplo n.º 21
0
	public static int Main (string[] args)
	{
		var options = new CmdOptions ();

		var p = new OptionSet () {
			{ "t|txt=", "File with string resource in key=value format",
				v => options.ResourcesStrings.Add (v) },
			{ "h|help",  "Display available options", 
				v => options.ShowHelp = v != null },
			{ "v|verbose",  "Use verbose output", 
				v => options.Verbose = v != null },
			{ "ignore-semicolon", "Reads lines starting with semicolon",
				v => options.IgnoreSemicolon = v != null },
		};

		List<string> extra;
		try {
			extra = p.Parse (args);
		}
		catch (OptionException e) {
			Console.WriteLine (e.Message);
			Console.WriteLine ("Try 'txt2sr -help' for more information.");
			return 1;
		}

		if (options.ShowHelp) {
			ShowHelp (p);
			return 0;
		}

		if (extra.Count != 1) {
			ShowHelp (p);
			return 2;
		}

		var txtStrings = new List<Tuple<string, string>> ();
		if (!LoadStrings (txtStrings, options))
			return 3;

		GenerateFile (extra [0], txtStrings, options);

		return 0;
	}
Ejemplo n.º 22
0
        private static void ParsedMain(CmdOptions options)
        {
            string img = options.Dockerimage;
            var    rdt = Get_Repo_Dist_Tag(img);

            string repo       = rdt[0];
            string distroname = rdt[1];
            string tag        = rdt[2];

            if (options.InstallDir != null)
            {
                UserConfig.install_dir = options.InstallDir;
            }


            string install_tar_path = Docker.DownloadAndGenerateImage(repo, distroname, tag, options.Distroname);

            Wsl.InstallImage(install_tar_path, Path.Combine(UserConfig.install_dir, options.Distroname), options.Distroname, options.Version);
        }
Ejemplo n.º 23
0
        public static void Main(string[] args)
        {
            //Waboxapp asd = new Waboxapp(new WabCon("e707b32d1ea8caab83838e45c1a6f6cb5ad71bf8287de", "79169557171"));
            //var asdd = asd.SendMessage(1234, "79055728225", "(.)(.)");


            //MqXmlConverter mqXmlConverter = new MqXmlConverter();

            // return;



            CmdOptions cmdOptions = ParseCommandArgs(args);

            if (cmdOptions != null)
            {
                StartMessageGun(cmdOptions);
            }
        }
Ejemplo n.º 24
0
        private static string GetOptionName(CmdOptions o)
        {
            var sb = new StringBuilder();
            var shortNameExists = false;

            if (!string.IsNullOrEmpty(o.ShortName))
            {
                shortNameExists = true;
                sb.AppendFormat(CultureInfo.InvariantCulture, $" -{o.ShortName}{GetOptionValue(o)}");
            }
            if (!string.IsNullOrEmpty(o.LongName))
            {
                if (shortNameExists)
                {
                    sb.Append(" or");
                }
                sb.AppendFormat(CultureInfo.InvariantCulture, $" --{o.LongName}{GetOptionValue(o, true)}");
            }
            return(sb.ToString());
        }
Ejemplo n.º 25
0
	public static int Main (string[] args)
	{
		var options = new CmdOptions ();

		var p = new OptionSet () {
			{ "r|resourcestrings=", "File with string resource in key=value format",
				v => options.ResourcesStrings.Add (v) },
			{ "h|help",  "Display available options", 
				v => options.ShowHelp = v != null },
			{ "v|verbose",  "Use verbose output", 
				v => options.Verbose = v != null },			
		};

		List<string> extra;
		try {
			extra = p.Parse (args);
		}
		catch (OptionException e) {
			Console.WriteLine (e.Message);
			Console.WriteLine ("Try 'cil-stringreplacer -help' for more information.");
			return 1;
		}

		if (options.ShowHelp) {
			ShowHelp (p);
			return 0;
		}

		if (extra.Count != 1) {
			ShowHelp (p);
			return 2;
		}

		var resourcesStrings = new Dictionary<string, string> ();
		if (!LoadGetResourceStrings (resourcesStrings, options))
			return 3;

		RewriteAssembly (extra [0], resourcesStrings, options);

		return 0;
	}
Ejemplo n.º 26
0
	public static int Main (string[] args)
	{
		var options = new CmdOptions ();

		var p = new OptionSet () {
			{ "o|out=", "Specifies output file name",
				v => options.OutputFile = v },
			{ "h|help",  "Display available options", 
				v => options.ShowHelp = v != null },
		};

		List<string> extra;
		try {
			extra = p.Parse (args);
		} catch (OptionException e) {
			Console.WriteLine (e.Message);
			Console.WriteLine ("Try 'resx2sr -help' for more information.");
			return 1;
		}

		if (options.ShowHelp) {
			ShowHelp (p);
			return 0;
		}

		if (extra.Count != 1) {
			ShowHelp (p);
			return 2;
		}

		var resxStrings = new List<Tuple<string, string, string>> ();
		if (!LoadStrings (resxStrings, extra))
			return 3;

		GenerateFile (resxStrings, options);

		return 0;
	}
Ejemplo n.º 27
0
        public async Task <CmdResult2> RunAsync(
            string command, string arguments, CmdOptions options, CancellationToken ct)
        {
            // Make sure we can handle command paths with "space"
            command = Quote(command);

            try
            {
                return(await RunProcessAsync(command, arguments, options, ct));
            }
            catch (Exception e)
            {
                Log.Exception(e, $"Cmd failed: {command} {arguments}");
                return(new CmdResult2(
                           command,
                           arguments,
                           options.WorkingDirectory,
                           -1,
                           "",
                           $"{e.GetType()}, {e.Message}",
                           TimeSpan.Zero,
                           ct));
            }
        }
Ejemplo n.º 28
0
	static void GenerateFile (List<Tuple<string, string, string>> txtStrings, CmdOptions options)
	{
//		var outputFile = options.OutputFile ?? "SR.cs";

		using (var str = options.OutputFile == null ? Console.Out : new StreamWriter (options.OutputFile)) {
			str.WriteLine ("//");
			str.WriteLine ("// This file was generated by resx2sr tool");
			str.WriteLine ("//");
			str.WriteLine ();

			str.WriteLine ("partial class SR");
			str.WriteLine ("{");
			foreach (var entry in txtStrings) {
				str.Write ($"\tpublic const string {entry.Item1} = \"{ToCSharpString (entry.Item2)}\";");

				if (!string.IsNullOrEmpty (entry.Item3))
					str.Write (" // {entry.Item3}");

				str.WriteLine ();

			}
			str.WriteLine ("}");
		}
	}
Ejemplo n.º 29
0
 public MessageBusProduerService(ILogger <MessageBusProduerService> logger, IKafkaMessageBus messageBus, CmdOptions cmdOptions)
 {
     _logger     = logger;
     _messageBus = messageBus;
     _cmdOptions = cmdOptions;
 }
Ejemplo n.º 30
0
	static void RewriteAssembly (string assemblyLocation, Dictionary<string, string> resourcesStrings, CmdOptions options)
	{
		Stream pdbSymbols = null;

		var debugSymbols = Path.ChangeExtension (assemblyLocation, "pdb");
		if (File.Exists (debugSymbols))
			pdbSymbols = File.Open (debugSymbols, FileMode.Open, FileAccess.ReadWrite);

		var readerParameters = new ReaderParameters {
			ReadWrite = true,
		};

		if (pdbSymbols != null) {
			readerParameters.ReadSymbols = true;
			readerParameters.SymbolReaderProvider = new PortablePdbReaderProvider ();
			readerParameters.SymbolStream = pdbSymbols;
		}

		using (var assembly = AssemblyDefinition.ReadAssembly (assemblyLocation, readerParameters)) {
			foreach (var module in assembly.Modules) {
				foreach (var type in module.GetTypes ()) {
					foreach (var method in type.Methods) {
						if (!method.HasBody)
							continue;

						foreach (var instr in method.Body.Instructions) {
							if (instr.OpCode != OpCodes.Ldstr)
								continue;

							string value;
							if (resourcesStrings.TryGetValue ((string)instr.Operand, out value)) {
								if (options.Verbose) {
									Console.WriteLine ($"Replacing '{instr.Operand}' with '{value}'");
								}

								instr.Operand = value;
							}
						}
					}
				}
			}

			var writerParameters = new WriterParameters ();

			if (pdbSymbols != null) {
				writerParameters.WriteSymbols = true;
				writerParameters.SymbolStream = pdbSymbols;
				writerParameters.SymbolWriterProvider = new PortablePdbWriterProvider ();
				pdbSymbols.Seek (0, SeekOrigin.Begin);
			}

			assembly.Write (writerParameters);
		}

		pdbSymbols?.Dispose ();
	}
Ejemplo n.º 31
0
	static bool LoadGetResourceStrings (Dictionary<string, string> resourcesStrings, CmdOptions options)
	{
		foreach (var fileName in options.ResourcesStrings) {
			if (!File.Exists (fileName)) {
				Console.Error.WriteLine ($"Error reading resource file '{fileName}'");
				return false;
			}

			foreach (var l in File.ReadLines (fileName)) {
				var line = l.Trim ();
				if (line.Length == 0 || line [0] == '#' || line [0] == ';')
					continue;

				var epos = line.IndexOf ('=');
				if (epos < 0)
					continue;

				var key = line.Substring (0, epos).Trim ();
				var value = line.Substring (epos + 1).Trim ();

				resourcesStrings [key] = value;
			}
		}

		return true;
	}
Ejemplo n.º 32
0
    static void RewriteAssembly(string assemblyLocation, Dictionary <string, string> resourcesStrings, CmdOptions options)
    {
        var methods = new Dictionary <string, MethodBody> (StringComparer.Ordinal);

        if (options.ILFile != null)
        {
            var rp = new ReaderParameters {
                InMemory = true
            };

            using (var module = ModuleDefinition.ReadModule(options.ILFile, rp)) {
                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody)
                        {
                            continue;
                        }

                        methods.Add(method.FullName, method.Body);
                    }
                }
            }
        }

        var readerParameters = new ReaderParameters {
            ReadSymbols          = true,
            ReadWrite            = true,
            SymbolReaderProvider = new DefaultSymbolReaderProvider(false)
        };

        using (var assembly = AssemblyDefinition.ReadAssembly(assemblyLocation, readerParameters)) {
            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody)
                        {
                            continue;
                        }

                        MethodBody newBody;
                        if (methods.TryGetValue(method.FullName, out newBody))
                        {
                            var mbody = method.Body;
                            mbody.Instructions.Clear();
                            foreach (var instr in newBody.Instructions)
                            {
                                switch (instr.OpCode.OperandType)
                                {
                                case OperandType.InlineType:
                                    var tr = (TypeReference)instr.Operand;
                                    foreach (var t in method.GenericParameters)
                                    {
                                        if (tr.FullName == t.FullName)
                                        {
                                            instr.Operand = t;
                                            break;
                                        }
                                    }

                                    break;
                                }

                                mbody.Instructions.Add(instr);
                            }

                            method.Body.Variables.Clear();
                            foreach (var variable in newBody.Variables)
                            {
                                mbody.Variables.Add(variable);
                            }
                        }

                        foreach (var instr in method.Body.Instructions)
                        {
                            if (instr.OpCode != OpCodes.Ldstr)
                            {
                                continue;
                            }

                            string value;
                            if (resourcesStrings.TryGetValue((string)instr.Operand, out value))
                            {
                                if (options.Verbose)
                                {
                                    Console.WriteLine($"Replacing '{instr.Operand}' with '{value}'");
                                }

                                instr.Operand = value;
                            }
                        }
                    }
                }
            }

            var writerParameters = new WriterParameters()
            {
                WriteSymbols = assembly.MainModule.HasSymbols
            };

            assembly.Write(writerParameters);
        }
    }
Ejemplo n.º 33
0
	static void GenerateFile (string outputFile, List<Tuple<string, string>> txtStrings, CmdOptions options)
	{
		using (var str = new StreamWriter (outputFile)) {
			str.WriteLine ("//");
			str.WriteLine ("// This file was generated by txt2sr tool");
			str.WriteLine ("//");
			str.WriteLine ();

			str.WriteLine ("partial class SR");
			str.WriteLine ("{");
			foreach (var entry in txtStrings) {
				var value = entry.Item2;

				if (value.StartsWith ("\"") && value.EndsWith ("\";")) {
					value = value.Substring (1, value.Length - 3);
				}

				int idx;
				int startIndex = 1;
				while (startIndex <= value.Length && (idx = value.IndexOf ("\"", startIndex, StringComparison.Ordinal)) > 0) {
					startIndex = idx + 1;

					if (value [idx - 1] == '\\')
						continue;
					
					value = value.Insert (idx, "\\");
					++startIndex;
				}

				str.WriteLine ($"\tpublic const string {entry.Item1} = \"{value}\";");
			}
			str.WriteLine ("}");
		}
	}
Ejemplo n.º 34
0
    static void GenerateFile(string outputFile, List <Tuple <string, string> > txtStrings, CmdOptions options)
    {
        using (var str = new StreamWriter(outputFile)) {
            str.WriteLine("//");
            str.WriteLine("// This file was generated by txt2sr tool");
            str.WriteLine("//");
            str.WriteLine();

            str.WriteLine("partial class SR");
            str.WriteLine("{");
            foreach (var entry in txtStrings)
            {
                var value = entry.Item2;

                if (value.StartsWith("\"") && value.EndsWith("\";"))
                {
                    value = value.Substring(1, value.Length - 3);
                }

                int idx;
                int startIndex = 1;
                while (startIndex <= value.Length && (idx = value.IndexOf("\"", startIndex, StringComparison.Ordinal)) > 0)
                {
                    startIndex = idx + 1;

                    if (value [idx - 1] == '\\')
                    {
                        continue;
                    }

                    value = value.Insert(idx, "\\");
                    ++startIndex;
                }

                str.WriteLine($"\tpublic const string {entry.Item1} = \"{value}\";");
            }
            str.WriteLine("}");
        }
    }
Ejemplo n.º 35
0
	static bool LoadStrings (List<Tuple<string, string>> resourcesStrings, CmdOptions options)
	{
		var keys = new Dictionary<string, string> ();
		foreach (var fileName in options.ResourcesStrings) {
			if (!File.Exists (fileName)) {
				Console.Error.WriteLine ($"Error reading resource file '{fileName}'");
				return false;
			}

			foreach (var l in File.ReadLines (fileName)) {
				var line = l.Trim ();
				if (line.Length == 0 || line [0] == '#')
					continue;

				int start = 0;
 				if (line [0] == ';') {
 					if (!options.IgnoreSemicolon)
 						continue;

 					start = 1;
 				}

				var epos = line.IndexOf ('=');
				if (epos < 0)
					continue;

				var key = line.Substring (start, epos - start).Trim ();
				if (key.Contains (" "))
					continue;

				var value = line.Substring (epos + 1).Trim ();

				string existing;
				if (keys.TryGetValue (key, out existing)) {					
					continue;
				}

				keys.Add (key, value);
				resourcesStrings.Add (Tuple.Create (key, value));				
			}
		}

		return true;
	}
Ejemplo n.º 36
0
    static void RewriteAssembly(string assemblyLocation, Dictionary <string, string> resourcesStrings, CmdOptions options)
    {
        var debugSymbols    = Path.ChangeExtension(assemblyLocation, "pdb");
        var useDebugSymbols = File.Exists(debugSymbols);

        var readerParameters = new ReaderParameters {
            ReadWrite = true,
        };

        if (useDebugSymbols)
        {
            readerParameters.SymbolReaderProvider = new PortablePdbReaderProvider();
        }

        using (var assembly = AssemblyDefinition.ReadAssembly(assemblyLocation, readerParameters)) {
            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody)
                        {
                            continue;
                        }

                        foreach (var instr in method.Body.Instructions)
                        {
                            if (instr.OpCode != OpCodes.Ldstr)
                            {
                                continue;
                            }

                            string value;
                            if (resourcesStrings.TryGetValue((string)instr.Operand, out value))
                            {
                                if (options.Verbose)
                                {
                                    Console.WriteLine($"Replacing '{instr.Operand}' with '{value}'");
                                }

                                instr.Operand = value;
                            }
                        }
                    }
                }
            }

            var writerParameters = new WriterParameters();

            if (useDebugSymbols)
            {
                writerParameters.SymbolWriterProvider = new PortablePdbWriterProvider();
            }

            assembly.Write(writerParameters);
        }
    }
Ejemplo n.º 37
0
        private static void StartMessageGun(CmdOptions cmdOptions)
        {
            if (cmdOptions.MqOption != null && cmdOptions.NewConnectionInfo != null)
            {
                System.Console.WriteLine(cmdOptions.HelpInfo);
            }

            if (cmdOptions.MqOption != null)
            {
                if (CmdOptions.MqOptionStringCheck(cmdOptions.MqOption) != MqOptionEnum.Error)
                {
                    ConsoleCommands.MqOption(CmdOptions.MqOptionStringCheck(cmdOptions.MqOption), MGOptions.Mq.MqProp, MGOptions.Mq.QueueName);
                    return;
                }
                else
                {
                    System.Console.WriteLine("Error in argument of Mq option");
                    return;
                }
            }

            bool newConn = MGOptions.Telegram.NewConnection;

            if (cmdOptions.NewConnectionInfo != null)
            {
                if (CmdOptions.ConnectionStringCheck(cmdOptions.NewConnectionInfo))
                {
                    newConn = Convert.ToBoolean(cmdOptions.NewConnectionInfo);
                }
                else
                {
                    System.Console.WriteLine("Error : (-n /--new-connection requieres true or false)");
                    return;
                }
            }


            System.Console.WriteLine("Message Gun starting...");
            System.Console.WriteLine("Press 'Escape' for exit\n");

            //return;



            newConn = true;

            DomainModel.DomainModel domainModel = new DomainModel.DomainModel(MGOptions.DataBase.DBProperties);

            domainModel.StartTeleDomain(MGOptions.Telegram.Api_Id,
                                        MGOptions.Telegram.Api_hash,
                                        MGOptions.Telegram.PhoneNumber,
                                        PasswordFunc,
                                        newConn,
                                        MGOptions.Telegram.TeleInterval);

            // domainModel.StartWhatsAppDomain("e707b32d1ea8caab83838e45c1a6f6cb5ad71bf8287de", "79169557171");

            domainModel.StartMqDomain(MGOptions.Mq.MqProp,
                                      MGOptions.Mq.QueueName,
                                      MGOptions.Mq.MqInterval);



            WaitForExit();

            domainModel.Dispose();
        }
Ejemplo n.º 38
0
	static void RewriteAssembly (string assemblyLocation, Dictionary<string, string> resourcesStrings, CmdOptions options)
	{
		var readerParameters = new ReaderParameters { ReadSymbols = true, ReadWrite = true };
		using (var assembly = AssemblyDefinition.ReadAssembly (assemblyLocation, readerParameters)) {
			foreach (var module in assembly.Modules) {
				foreach (var type in module.GetTypes ()) {
					foreach (var method in type.Methods) {
						if (!method.HasBody)
							continue;
						
						foreach (var instr in method.Body.Instructions) {
							if (instr.OpCode != OpCodes.Ldstr)
								continue;

							string value;
							if (resourcesStrings.TryGetValue ((string)instr.Operand, out value)) {
								if (options.Verbose) {
									Console.WriteLine ($"Replacing '{instr.Operand}' with '{value}'");
								}

								instr.Operand = value;
							}
						}
					}
				}
			}

			var writerParameters = new WriterParameters { WriteSymbols = true };
			assembly.Write (writerParameters);
		}
	}
Ejemplo n.º 39
0
    static void RewriteAssembly(string assemblyLocation, Dictionary <string, string> resourcesStrings, CmdOptions options)
    {
        var readerParameters = new ReaderParameters {
            ReadSymbols          = true,
            ReadWrite            = true,
            SymbolReaderProvider = new DefaultSymbolReaderProvider(false)
        };

        using (var assembly = AssemblyDefinition.ReadAssembly(assemblyLocation, readerParameters)) {
            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody)
                        {
                            continue;
                        }

                        foreach (var instr in method.Body.Instructions)
                        {
                            if (instr.OpCode != OpCodes.Ldstr)
                            {
                                continue;
                            }

                            string value;
                            if (resourcesStrings.TryGetValue((string)instr.Operand, out value))
                            {
                                if (options.Verbose)
                                {
                                    Console.WriteLine($"Replacing '{instr.Operand}' with '{value}'");
                                }

                                instr.Operand = value;
                            }
                        }
                    }
                }
            }

            var writerParameters = new WriterParameters()
            {
                WriteSymbols = assembly.MainModule.HasSymbols
            };

            assembly.Write(writerParameters);
        }
    }