Exemplo n.º 1
0
        public void Run(string[] args)
        {
            var conArgs  = new ConArgs(args, "-");
            var jsonFile = conArgs[1];

            if (!AlertUtility.ConfirmUseOnlineService())
            {
                return;
            }
            Echo.Print("Connect to dawnx service...").Line();

            var resp = Http.PostFor <JSend>($"{Program.SUPPORT_URL}/JsonToCsFile", new Dictionary <string, object>
            {
                ["Namespace"] = Program.ProjectInfo.RootNamespace,
                ["ClassName"] = Path.GetFileNameWithoutExtension(jsonFile),
                ["Json"]      = File.ReadAllText(jsonFile),
            });

            if (resp.IsSuccess())
            {
                var path = $"{Path.GetPathRoot(Path.GetFullPath(jsonFile))}/{Path.GetFileNameWithoutExtension(jsonFile)}.cs";
                File.WriteAllText(path, resp.data as string);

                Echo.Print($"{resp.message}").Line();
                Echo.Print($"  File Saved: {Path.GetFullPath(path)}").Line();
            }
            else
            {
                AlertUtility.PrintErrorMessage(resp);
            }
        }
Exemplo n.º 2
0
        protected Command(CmdContainer container, string[] args)
        {
            Container = container;
            Arguments = new ConArgs(args, "-");

            var props = from prop in GetType().GetProperties()
                        let attr = prop.GetCustomAttributes(typeof(CmdPropertyAttribute), false).FirstOrDefault() as CmdPropertyAttribute
                                   where attr is not null
                                   select new { Property = prop, Attribute = attr };

            foreach (var prop in props)
            {
                var valueList = new List <string>();
                if (!prop.Attribute.Abbreviation.IsNullOrWhiteSpace())
                {
                    valueList.AddRange(Arguments[$"-{prop.Attribute.Abbreviation}"]);
                }
                if (!prop.Attribute.Name.IsNullOrWhiteSpace())
                {
                    valueList.AddRange(Arguments[$"--{prop.Attribute.Name}"]);
                }

                if (valueList.Any())
                {
                    var propertyType = prop.Property.PropertyType;
Exemplo n.º 3
0
        public void Run(string[] args)
        {
            var conArgs = new ConArgs(args, "-");
            var aesKey  = conArgs[1] == "hex" ? AesKey.HexString : AesKey.Base64String;

            var aes = new AesProvider();

            Console.WriteLine($"New {aesKey.ToString()}:\t{aes.ExportKey(aesKey)}");
        }
Exemplo n.º 4
0
        public void Run(string[] args)
        {
            var conArgs = new ConArgs(args, "-");

            if (conArgs.Properties.For(x => x.ContainsKey("-h") || x.ContainsKey("--help")))
            {
                PrintUsage();
                return;
            }

            var outFolder = conArgs["-o"]?.FirstOrDefault() ?? conArgs["--out"].FirstOrDefault() ?? ".";
            var setBOM    = conArgs.Properties.ContainsKey("-b") || conArgs.Properties.ContainsKey("--bom");

            GenerateTypeScript(outFolder, setBOM);
        }
Exemplo n.º 5
0
        public void Test3()
        {
            var conArgs = new ConArgs(@"-o -n -i Ink", new[] { "-" });
            var actual  = conArgs.Properties.ToDictionary(x => x.Key, x => x.Value.ToArray());

            Assert.Equal(new Dictionary <string, string[]>
            {
                ["-o"] = new[] { "" },
                ["-n"] = new[] { "" },
                ["-i"] = new[] { "Ink" },
            }, actual);

            Assert.Equal("", conArgs["-o"].FirstOrDefault());
            Assert.Equal("", conArgs["-n"].FirstOrDefault());
            Assert.Equal("Ink", conArgs["-i"].FirstOrDefault());
        }
Exemplo n.º 6
0
        public void Run(string[] args)
        {
            var conArgs = new ConArgs(args, "-");

            if (conArgs.Properties.For(x => x.ContainsKey("-h") || x.ContainsKey("--help")) || conArgs.Contents.Length < 2)
            {
                PrintUsage();
                return;
            }

            var headerFile = conArgs[1];
            var headerName = Path.GetFileNameWithoutExtension(headerFile);
            var language   = conArgs["-l"].Concat(conArgs["--lang"]).FirstOrDefault() ?? "cs";
            var outFile    = conArgs["-o"].Concat(conArgs["--out"]).FirstOrDefault() ?? $"PI_{headerName}.{language}";

            var _headerFile = $"_{headerFile}";
            var content     = File.ReadAllText(headerFile)
                              .RegexReplace(new Regex(@"#include (?:(""|<)).+(?:(""|>))"), "")
                              .RegexReplace(new Regex(@"using namespace .+;"), "");

            File.WriteAllText(_headerFile, content);

            var sigimp = Process.Start(new ProcessStartInfo
            {
                Arguments              = $"{_headerFile} /lang:{language} /out:{outFile}",
                FileName               = $"{Program.ProjectInfo.CliPackagePath}/lib/netstandard2.0/sigimp.exe",
                UseShellExecute        = false,
                CreateNoWindow         = true,
                RedirectStandardOutput = true,
            });

            sigimp.OutputDataReceived += Sigimp_OutputDataReceived;
            sigimp.BeginOutputReadLine();
            sigimp.WaitForExit();

            var finalContent = File.ReadAllText(outFile)
                               .Replace(@"[System.Runtime.InteropServices.DllImportAttribute(""<Unknown>""", $@"[DllImport(""{headerName}.dll"")")
                               .RegexReplace(new Regex(@"System\.Runtime\.InteropServices\.(\w+)Attribute"), "$1")
                               .Replace("System.Runtime.InteropServices.", "")
                               .Replace("public static extern  ", "    public static extern ");

            File.WriteAllText(outFile, finalContent);
            File.Delete(_headerFile);
        }
Exemplo n.º 7
0
        public void Test2()
        {
            var conArgs = new ConArgs(@"-h 127.0.0.1 -u root ""C:\Program Files"" -h 2130706433 -p", new[] { "-" });
            var actual  = conArgs.Properties.ToDictionary(x => x.Key, x => x.Value.ToArray());

            Assert.Equal(new Dictionary <string, string[]>
            {
                ["-h"] = new[] { "127.0.0.1", "2130706433" },
                ["-u"] = new[] { "root" },
                ["-p"] = new[] { "" },
            }, actual);

            Assert.Equal("127.0.0.1", conArgs["-h"].FirstOrDefault());
            Assert.Equal("root", conArgs["-u"].FirstOrDefault());
            Assert.Equal(string.Empty, conArgs["-p"].FirstOrDefault());
            Assert.Empty(conArgs["-t"]);

            Assert.Equal(new[] { "C:\\Program Files" }, conArgs.Contents);
            Assert.Equal("C:\\Program Files", conArgs[0]);
        }
Exemplo n.º 8
0
        public void Run(string[] args)
        {
            var conArgs = new ConArgs(args, "-");

            if (conArgs.Properties.For(x => x.ContainsKey("-h") || x.ContainsKey("--help")))
            {
                PrintUsage();
                return;
            }

            string[] jsonFiles = conArgs.Contents.Skip(1).ToArray();

            if (!jsonFiles.Any())
            {
                var json = "compress.json";

                if (!File.Exists(json))
                {
                    using (var file = new FileStream(json, FileMode.Create))
                        using (var stream = new StreamWriter(file))
                        {
                            stream.WriteLine($@"[
  {{
    ""{nameof(archive)}"": ""<Destination>.zip"",
    ""{nameof(sources)}"": {{
      ""<Archive-Directory or Archive-File>"": [""<Real-File>""]
    }}
  }}
]");
                        }

                    Console.Error.WriteLine("File compress.json is created.");
                    return;
                }
                else
                {
                    jsonFiles = new string[] { json }
                };
            }

            foreach (var jsonFile in jsonFiles)
            {
                var json    = File.ReadAllText(jsonFile);
                var zipDefs = JsonConvert.DeserializeObject(json) as JArray;

                foreach (var zipDef in zipDefs.Select(x => x.Value <JObject>()))
                {
                    string archive;
                    var    sources = new Dictionary <string, string>();

                    if (!zipDef.Properties().Any(x => x.Name == nameof(archive)))
                    {
                        throw new ArgumentException($"The compress json file has no property({nameof(archive)}).");
                    }
                    if (zipDef[nameof(archive)].Type != JTokenType.String ||
                        !FileUtility.IsFilePath(zipDef[nameof(archive)].Value <string>()))
                    {
                        throw new ArgumentException($"The compress json file's property({nameof(archive)}) must be a file path.");
                    }

                    if (!zipDef.Properties().Any(x => x.Name == nameof(sources)))
                    {
                        throw new ArgumentException($"The compress json file has no property(${nameof(sources)}).");
                    }
                    if (zipDef["sources"].Type != JTokenType.Object)
                    {
                        throw new ArgumentException($"The compress json file's property(${nameof(sources)}) must be a {JTokenType.Object}.");
                    }

                    archive = zipDef[nameof(archive)].Value <string>();
                    using (var zip = new ZipStream())
                    {
                        foreach (var source in zipDef["sources"].Value <JObject>().Properties())
                        {
                            var ext = Path.GetExtension(source.Name);

                            // Guess the name is a directory name
                            if (ext == string.Empty)
                            {
                                var dir = source.Name;
                                if (DirectoryUtility.IsDirectoryPath(dir))
                                {
                                    switch (source.Value.Type)
                                    {
                                    case JTokenType.String:
                                    {
                                        var file = source.Value.Value <string>();
                                        if (File.Exists(file))
                                        {
                                            zip.AddFileEntry(Path.Combine(dir, Path.GetFileName(file)), file);
                                        }
                                        else
                                        {
                                            throw new FileNotFoundException($"Can not find the file({file}).");
                                        }
                                    }
                                    break;

                                    case JTokenType.Array:
                                        var files = source.Value.Value <JArray>().Select(x => x.Value <string>());

                                        if (!dir.IsNullOrWhiteSpace())
                                        {
                                            zip.AddDictionary(dir);
                                        }
                                        foreach (var file in files)
                                        {
                                            if (File.Exists(file))
                                            {
                                                zip.AddFileEntry(Path.Combine(dir, Path.GetFileName(file)), file);
                                            }
                                            else
                                            {
                                                throw new FileNotFoundException($"Can not find the file({file}).");
                                            }
                                        }
                                        break;

                                    default:
                                        throw new ArgumentException($"The compress json file's property(${nameof(sources)}/${dir})'s value must be a file path or file path list.");
                                    }
                                }
                                else
                                {
                                    throw new ArgumentException($"The compress json file's property(${nameof(sources)}/${dir}) must be a directory path or file path.");
                                }
                            }
                            // Guess the name is a file name
                            else
                            {
                                var embededFile = source.Name;

                                if (FileUtility.IsFilePath(embededFile))
                                {
                                    if (source.Value.Type == JTokenType.String)
                                    {
                                        var file = source.Value.Value <string>();
                                        if (File.Exists(file))
                                        {
                                            zip.AddFileEntry(embededFile, file);
                                        }
                                        else
                                        {
                                            throw new FileNotFoundException($"Can not find the file({file}).");
                                        }
                                    }
                                    else
                                    {
                                        throw new ArgumentException($"The compress json file's property(${nameof(sources)}/${embededFile})'s value must be a file path.");
                                    }
                                }
                                else
                                {
                                    throw new ArgumentException($"The compress json file's property(${nameof(sources)}/${embededFile}) must be a directory path or file path.");
                                }
                            }
                        }

                        zip.SaveAs(archive);
                        Console.WriteLine($"Zip file has been created: {new FileInfo(archive).FullName}");
                    }
                }
            }
        }
    }
Exemplo n.º 9
0
        public void Run(string[] args)
        {
            var conArgs = new ConArgs(args, "-");
            var name    = conArgs[1];

            var resp = Http.PostFor <JSend>($"{Program.SUPPORT_URL}/Install", new Dictionary <string, object>
            {
                ["name"] = name,
            });

            try
            {
                if (resp.IsSuccess())
                {
                    var model       = resp.data as JObject;
                    var cli_version = model["cli_version"].Value <string>();

                    if (new Version(Program.CLI_VERSION) >= new Version(cli_version))
                    {
                        int fileCount = model["count"].Value <int>();
                        int fileDownload = 0;
                        int fileSkip = 0;
                        int fileDone() => fileDownload + fileSkip;

                        int fileVerifySuccess = 0;
                        int fileVerifyFailed  = 0;

                        int   colLength1   = fileCount * 2 + 1;
                        int[] tableLengths = new[] { colLength1, 67 - colLength1, 7 };

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

                        foreach (var item in model["files"] as JArray)
                        {
                            var url      = item["url"].Value <string>();
                            var md5      = item["md5"].Value <string>();
                            var fileName = item["fileName"].Value <string>();
                            var saveas   = $@"{Program.DOWNLOAD_DIRECTORY}\{fileName}";
                            var extract  = item["extract"].Value <bool>();

                            if (!File.Exists(saveas) || FileUtility.ComputeMD5(saveas) != md5)
                            {
                                #region Download files
                                using (var file = new FileStream(saveas, FileMode.Create))
                                {
                                    var web = new HttpAccess();
                                    web.DownloadProgress += (sender, _url, received, length) =>
                                    {
                                        Echo.Row(new[]
                                        {
                                            $"{fileDone() + 1}/{fileCount}", $"| {fileName}", ((double)received / length).ToString("0.00%")
                                        }, tableLengths);
                                    };

                                    int retry = 0, allowedRetry = 3;
retry:
                                    try
                                    {
                                        web.GetDownload(file, url);

                                        if (extract)
                                        {
                                            extractFileList.Add(saveas);
                                        }
                                        fileDownload++;
                                    }
                                    catch (Exception ex)
                                    {
                                        Echo.Line();
                                        if (retry < allowedRetry)
                                        {
                                            Echo.Print($"  {ex.Message}, retry {++retry}/{allowedRetry}").Line();
                                            goto retry;
                                        }
                                        else
                                        {
                                            Echo.Print($"  File can not be downloaded from {url}").Line();

                                            Echo.AskYN("Retry?", out var ansRetry);
                                            if (ansRetry)
                                            {
                                                retry = 0; goto retry;
                                            }
                                            else
                                            {
                                                fileSkip++; continue;
                                            }
                                        }
                                    }
                                }
                                #endregion

                                #region Check file md5
                                var status = "";
                                if (FileUtility.ComputeMD5(saveas) == md5)
                                {
                                    fileVerifySuccess++;
                                    status = "Safe";
                                }
                                else
                                {
                                    fileVerifyFailed++;
                                    status = "WARNING";
                                }

                                Echo.Row(new[]
                                {
                                    $"{fileDone()}/{fileCount}",
                                    $"| {Path.GetFileName(saveas)}",
                                    status
                                }, tableLengths).Line();
                                #endregion
                            }
                            else
                            {
                                if (extract)
                                {
                                    extractFileList.Add(saveas);
                                }
                                fileDownload++;

                                Echo.Row(new[]
                                {
                                    $"{fileDone()}/{fileCount}",
                                    $"| {Path.GetFileName(saveas)}",
                                    "Found"
                                }, tableLengths).Line();
                            }
                        }

                        Echo
                        .Line()
                        .Print($"  " +
                               $"{fileDownload} downloaded." +
                               $"  {fileVerifySuccess} safe, {fileVerifyFailed} warning, {fileSkip} skiped.").Line()
                        .Print($"---- All files has been downloaded using engine {typeof(Http).FullName} ----").Line()
                        .Line();

                        // Setup
                        void extractFiles()
                        {
                            foreach (var file in extractFileList)
                            {
                                ZipFile.ExtractToDirectory(file, Program.ProjectInfo.ProjectRoot, true);
                                Echo.Print($"Extract {file} done.").Line();
                            }
                            Echo
                            .Print($"---- Extract files completed ----").Line()
                            .Line();
                        };

                        if (fileVerifyFailed > 0)
                        {
                            Echo.AskYN("Setup now?", out var ans);
                            if (ans)
                            {
                                extractFiles();
                            }
                        }
                        else
                        {
                            extractFiles();
                        }
                    }
                    else
                    {
                        Echo.Print($"Install service requires the lowest cli tool version: {cli_version}.").Line();
                    }
                }
                else
                {
                    AlertUtility.PrintErrorMessage(resp);
                }
            }
            catch (JsonReaderException ex)
            {
                Echo.Print($"Error occurred. ({ex.Message})").Line();
            }
        }