Пример #1
0
        public void Deflate_InflateAndDeflate_ShouldEqualOriginal()
        {
            for (int n = 100; n < 20000; n += 100)
            {
                for (int seed = 0; seed < 3; seed++)
                {
                    var input = new byte[n];
                    for (int i = 0; i < n; i++)
                    {
                        input[i] = (byte)(Math.Sin(i) * 255);
                    }

                    // Compress with System.IO.Compression
                    var compressedData = input.Compress();

                    // Decompress with System.IO.Compression
                    var deflated1 = compressedData.Decompress();
                    AssertArrayEquals(deflated1, input);

                    // Decompress with local Deflate implementation
                    var deflated2 = Deflate.Decompress(compressedData);
                    AssertArrayEquals(deflated2, input);
                }
            }
        }
Пример #2
0
        public void Deflate_InflateAndDeflate_ShouldEqualOriginal()
        {
            for (int n = 100; n < 20000; n += 100)
            {
                for (int seed = 0; seed < 3; seed++)
                {
                    var input = new byte[n];
                    for (int i = 0; i < n; i++)
                    {
                        input[i] = (byte)(Math.Sin(i) * 255);
                    }

                    // Compress with System.IO.Compression
                    var compressedData = input.Compress();

                    // Decompress with System.IO.Compression
                    var w1        = Stopwatch.StartNew();
                    var deflated1 = compressedData.Decompress();
                    var t1        = w1.ElapsedTicks;
                    AssertArrayEquals(deflated1, input);

                    // Decompress with local Deflate implementation
                    var w2        = Stopwatch.StartNew();
                    var deflated2 = Deflate.Decompress(compressedData);
                    var t2        = w2.ElapsedTicks;
                    AssertArrayEquals(deflated2, input);

                    Console.WriteLine("{0}:{1}/{2}", n, t1, t2);
                }
            }
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var content           = actionContext.Request.Content;
            var zipContentBytes   = content == null ? null : content.ReadAsByteArrayAsync().Result;
            var unzipContentBytes = zipContentBytes == null ? new byte[0] : Deflate.Decompress(zipContentBytes);

            actionContext.Request.Content = new ByteArrayContent(unzipContentBytes);
            base.OnActionExecuting(actionContext);
        }
        public void Server_DeflateCompress_Client_DeflateDecompress_should_be_yao()
        {
            Console.WriteLine("用戶端用訪問伺服器→伺服器用Deflate壓縮資料→Client解壓縮,驗證解壓縮結果是否包含關鍵字");

            var url        = "api/test/DeflateCompression/yao";
            var response   = MsTestHook.Client.GetAsync(url).Result;
            var content    = response.Content.ReadAsByteArrayAsync().Result;
            var decompress = Deflate.Decompress(content);
            var result     = Encoding.UTF8.GetString(decompress);

            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
            Assert.AreEqual(true, result.Contains("yao"));
        }
Пример #5
0
        private static Dictionary <string, MapcacheMapData> ReadMapcache(string path)
        {
            Dictionary <string, MapcacheMapData> mapdata = new Dictionary <string, MapcacheMapData>();

            byte[] decodedBuf, encodedBuf;

            // We want a relative path
            if (path[0] == '/' || path[0] == '\\')
            {
                path = path.Substring(1);
            }
            //path = Path.Combine(Core.Conf.ConfigDir, path);
            using (FileStream fs = File.OpenRead(path)) {
                using (BinaryReader bin = new BinaryReader(fs)) {
                    uint mapCount = bin.ReadUInt32();

                    for (int i = 0; i < mapCount; i++)
                    {
                        // Mapinfo
                        string mapname = bin.ReadString();
                        short  xs      = bin.ReadInt16();
                        short  ys      = bin.ReadInt16();
                        int    len     = bin.ReadInt32();

                        encodedBuf = bin.ReadBytes(len);
                        decodedBuf = Deflate.Decompress(encodedBuf);

                        // encodedBuf now contains the cell array
                        mapdata.Add(mapname, new MapcacheMapData {
                            Width    = xs,
                            Height   = ys,
                            CellData = decodedBuf
                        });

                        encodedBuf = null;
                        decodedBuf = null;
                    }
                }
            }

            return(mapdata);
        }
        /* Utility method */

        // 'input' is a string of 0's and 1's (with optional spaces) representing the input bit sequence.
        // 'refOutput' is a string of pairs of hexadecimal digits (with optional spaces) representing
        // the expected decompressed output byte sequence.
        private static void test(string input, string refOutput)
        {
            refOutput = refOutput.Replace(" ", string.Empty);
            if (refOutput.Length % 2 != 0)
            {
                throw new ArgumentException();
            }

            var refOut = new byte[refOutput.Length / 2];

            for (int i = 0; i < refOut.Length; i++)
            {
                refOut[i] = (byte)int.Parse(refOutput.Substring(i * 2, 2), NumberStyles.HexNumber);
            }

            input = input.Replace(" ", string.Empty);
            var inputStream = new StringBitReader(input);

            byte[] actualOut = Deflate.Decompress(inputStream);
            AssertArrayEquals(refOut, actualOut);
        }
Пример #7
0
        /// <summary>
        /// Returns the file data, decompressed if needed
        /// </summary>
        /// <param name="item">The grf file</param>
        /// <param name="decompress">Should the data decompressed?</param>
        /// <returns></returns>
        public byte[] GetFileData(FileItem item, bool decompress)
        {
            byte[] buf       = null;
            bool   isUpdated = item.IsAdded || item.IsUpdated;

            if (isUpdated)
            {
                // Load data from file
                buf = File.ReadAllBytes(item.NewFilepath);
            }
            else if (item.FileData == null || item.FileData.Length != item.LengthCompressedAlign)
            {
                // Cache data
                CacheFileData(item);
                buf = item.FileData;
            }
            else
            {
                buf = item.FileData;
            }

            if (isUpdated == false && buf != null && buf.Length > 0)
            {
                // deocde, if needed
                if (item.Cycle >= 0 && Deflate.IsMagicHead(buf) == false)
                {
                    EncryptionHelper.DecryptFileData(buf, item.Cycle == 0, item.Cycle);
                }

                // Decompress data
                if (decompress)
                {
                    buf = Deflate.Decompress(buf);
                }
            }

            return(buf);
        }
Пример #8
0
        static void Deflatetest()
        {
            BufferFormat fan = new BufferFormat(1000, new FDataExtraHandle((o) =>
            {
                return(Deflate.Compress(o));
            }));

            fan.AddItem(true);
            fan.AddItem("abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc");
            fan.AddItem(123);

            byte[] data = fan.Finish();


            ReadBytes read = new ReadBytes(data, 4, -1, new RDataExtraHandle((o) =>
            {
                return(Deflate.Decompress(o));
            }));

            int    lengt;
            int    cmd;
            bool   var1;
            string var2;
            int    var3;

            if (read.IsDataExtraSuccess &&
                read.ReadInt32(out lengt) &&
                lengt == read.Length &&
                read.ReadInt32(out cmd) &&
                read.ReadBoolean(out var1) &&
                read.ReadString(out var2) &&
                read.ReadInt32(out var3))
            {
                Console.WriteLine("压缩前长度:{0}", read.Data.Length);
                Console.WriteLine("压缩后长度:{0}", read.Length);
                Console.WriteLine("This Deflate-> Length:{0} Cmd:{1} var1:{2} var2:{3} var3:{4}", lengt, cmd, var1, var2, var3);
            }
        }
Пример #9
0
        private void btnBuild_Click(object sender, EventArgs e)
        {
            if (this._tables.Find(delegate(TableInfo table) {
                return(table.IsOutput);
            }) == null)
            {
                DataGridViewCellMouseEventArgs e2 = new DataGridViewCellMouseEventArgs(1, -1, 1, 1, new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 1));
                this.dgvGridview_ColumnHeaderMouseClick(this, e2);
            }
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string           selectedPath = fbd.SelectedPath;
            List <BuildInfo> bs           = null;
            SocketMessager   messager     = new SocketMessager("Build", new object[] {
                this.txtSolution.Text,
                this.chkSolution.Checked,
                string.Join("", this._tables.ConvertAll <string>(delegate(TableInfo table){
                    return(string.Concat(table.IsOutput ? 1 : 0));
                }).ToArray()),
                this.chkWebAdmin.Checked,
                this.chkDownloadRes.Checked
            });

            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                bs = e2.Messager.Arg as List <BuildInfo>;
                if (e2.Messager.Arg is Exception)
                {
                    throw e2.Messager.Arg as Exception;
                }
            }, TimeSpan.FromSeconds(60 * 5));
            if (bs == null)
            {
                return;
            }

            foreach (BuildInfo b in bs)
            {
                string path = Path.Combine(selectedPath, b.Path);
                Directory.CreateDirectory(Path.GetDirectoryName(path));
                string   fileName = Path.GetFileName(b.Path);
                string   ext      = Path.GetExtension(b.Path);
                Encoding encode   = Encoding.UTF8;

                if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll"))
                {
                    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                        fs.Write(b.Data, 0, b.Data.Length);
                        fs.Close();
                    }
                    continue;
                }

                byte[] data    = Deflate.Decompress(b.Data);
                string content = Encoding.UTF8.GetString(data);

                if (string.Compare(fileName, "web.config") == 0)
                {
                    string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString);
                    content = content.Replace("{connectionString}", place);
                }
                //if (string.Compare(fileName, "procedure.sql") == 0) {
                //    this.ExecuteNonQuery(content);
                //}
                if (string.Compare(ext, ".refresh") == 0)
                {
                    encode = Encoding.Unicode;
                }
                using (StreamWriter sw = new StreamWriter(path, false, encode)) {
                    sw.Write(content);
                    sw.Close();
                }
            }
            GC.Collect();

            Lib.Msgbox("The code files be maked in \"" + selectedPath + "\", please check.");
            //System.Diagnostics.Process.Start("iexplore.exe", "http://www.penzz.com/");
        }
Пример #10
0
    public static SocketMessager Parse(byte[] data)
    {
        if (data == null)
        {
            return(new SocketMessager("NULL"));
        }
        if (data.Length == 1 && data[0] == 0)
        {
            return(SocketMessager.SYS_TEST_LINK);
        }
        int    idx  = BaseSocket.findBytes(data, new byte[] { 13, 10 }, 0);
        string text = Encoding.UTF8.GetString(data, 0, idx);

        string[]     loc1 = text.Split(new string[] { "\t" }, 4, StringSplitOptions.None);
        string       loc2 = loc1[0];
        string       loc3 = loc1.Length > 1 ? loc1[1].Replace("\\\\", "\\").Replace("\\t", "\t").Replace("\\n", "\r\n") : null;
        string       loc4 = loc1.Length > 2 ? loc1[2].Replace("\\\\", "\\").Replace("\\t", "\t").Replace("\\n", "\r\n") : null;
        string       loc5 = loc1.Length > 3 ? loc1[3] : null;
        MemoryStream ms   = new MemoryStream();

        ms.Write(data, idx + 2, data.Length - idx - 2);
        SocketMessager messager = new SocketMessager(loc3, loc4,
                                                     ms.Length > 0 ? BaseSocket.Deserialize(Deflate.Decompress(ms.ToArray())) : null);

        if (int.TryParse(loc2, out idx))
        {
            messager._id = idx;
        }
        if (!string.IsNullOrEmpty(loc5))
        {
            DateTime.TryParse(loc5, out messager._remoteTime);
        }
        if (messager._arg is Exception)
        {
            messager._exception = messager._arg as Exception;
        }
        return(messager);
    }
Пример #11
0
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            this.OutputPath = Directory.GetCurrentDirectory();
            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                var bgcolor = Console.BackgroundColor;
                var fgcolor = Console.ForegroundColor;

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#######################################");
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                       ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.Write("    .NETCore 2.1 + SQLServer 生成器    ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                       ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#######################################");
                Console.Write("##");

                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write(@"

用于快速创建和更新 .NETCore 2.1 + SQLServer 项目,非常合适敏捷开发;
Github: https://github.com/2881099/dotnetgen_sqlserver

");
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write("Example:");
                Console.ForegroundColor = fgcolor;
                Console.WriteLine(@"

	> GenMs 127.0.0.1 -U sa -P 123456 -D dyschool -N dyschool -S -A -R
	> GenMs 127.0.0.1 -D dyschool -N dyschool -S -A -R //使用windows登陆

		-U	SQLServer账号
		-P	SQLServer密码
		-D	需要生成的数据库

		-N	字符串,生成代码的解决方案名和命名空间
		-S	生成解决方案,在项目第一次生成时使用
		-A	生成后台管理
		-R	下载资源
		
		-O	输出路径(默认:当前目录)"            );
                wait.Set();
                return;
            }
            this.Server = args[0];
            for (int a = 1; a < args.Length; a++)
            {
                switch (args[a])
                {
                case "-U":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-U 参数错误");
                    }
                    else
                    {
                        this.Username = args[a + 1];
                    }
                    a++;
                    break;

                case "-P":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-P 参数错误");
                    }
                    else
                    {
                        this.Password = args[a + 1];
                    }
                    a++;
                    break;

                case "-D":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-D 参数错误");
                    }
                    else
                    {
                        this.Database = args[a + 1];
                    }
                    a++;
                    break;

                case "-N":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-N 参数错误");
                    }
                    else
                    {
                        this.SolutionName = args[a + 1];
                    }
                    a++;
                    break;

                case "-O":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-O 参数错误");
                    }
                    else
                    {
                        this.OutputPath = args[a + 1];
                    }
                    a++;
                    break;

                case "-S":
                    this.IsMakeSolution = true;
                    break;

                case "-A":
                    this.IsMakeWebAdmin = true;
                    break;

                case "-R":
                    this.IsDownloadRes = true;
                    break;
                }
            }
            this._client = new ClientInfo(this.Server, this.Username, this.Password);
            StreamReader sr     = new StreamReader(System.Net.WebRequest.Create("https://files.cnblogs.com/files/kellynic/GenMs_server.css").GetResponse().GetResponseStream(), Encoding.UTF8);
            string       server = sr.ReadToEnd()?.Trim();
            //server = "127.0.0.1:29918";
            Uri uri = new Uri("tcp://" + server + "/");

            this._socket          = new ClientSocket();
            this._socket.Error   += Socket_OnError;
            this._socket.Receive += Socket_OnReceive;
            this._socket.Connect(uri.Host, uri.Port);
            Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
            if (this._socket.Running == false)
            {
                wait.Set();
                return;
            }

            SocketMessager messager = new SocketMessager("GetDatabases", this._client);

            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                List <DatabaseInfo> dbs = e2.Messager.Arg as List <DatabaseInfo>;
            });
            this._client.Database = this.Database;
            List <TableInfo> tables = null;

            messager = new SocketMessager("GetTablesByDatabase", this._client.Database);
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                tables = e2.Messager.Arg as List <TableInfo>;
            });
            if (tables == null)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] 无法读取表");
                this._socket.Close();
                this._socket.Dispose();

                wait.Set();
                return;
            }
            tables.ForEach(a => a.IsOutput = true);
            List <BuildInfo> bs = null;

            messager = new SocketMessager("Build", new object[] {
                SolutionName,
                IsMakeSolution,
                string.Join("", tables.ConvertAll <string>(delegate(TableInfo table){
                    return(string.Concat(table.IsOutput ? 1 : 0));
                }).ToArray()),
                IsMakeWebAdmin,
                IsDownloadRes
            });
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                bs = e2.Messager.Arg as List <BuildInfo>;
                if (e2.Messager.Arg is Exception)
                {
                    throw e2.Messager.Arg as Exception;
                }
            }, TimeSpan.FromSeconds(60 * 5));
            if (bs != null)
            {
                foreach (BuildInfo b in bs)
                {
                    string path = Path.Combine(OutputPath, b.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    string   fileName = Path.GetFileName(b.Path);
                    string   ext      = Path.GetExtension(b.Path);
                    Encoding encode   = Encoding.UTF8;

                    if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll"))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                            fs.Write(b.Data, 0, b.Data.Length);
                            fs.Close();
                        }
                        continue;
                    }

                    byte[] data    = Deflate.Decompress(b.Data);
                    string content = Encoding.UTF8.GetString(data);

                    if (string.Compare(fileName, "web.config") == 0)
                    {
                        string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString);
                        content = content.Replace("{connectionString}", place);
                    }
                    if (fileName.EndsWith(".json"))
                    {
                        content = content.Replace("{connectionString}", this.ConnectionString);
                    }
                    if (string.Compare(ext, ".refresh") == 0)
                    {
                        encode = Encoding.Unicode;
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, encode)) {
                        sw.Write(content);
                        sw.Close();
                    }
                }
                var appsettingsPath        = Path.Combine(OutputPath, "appsettings.json");
                var appsettingsPathWebHost = Path.Combine(OutputPath, @"src\WebHost\appsettings.json");
                //如果三个选项为false,并且 src\WebHost\appsettings.json 不存在,则在当前目录使用 appsettings.json
                if (this.IsDownloadRes == false && this.IsMakeSolution == false && this.IsMakeWebAdmin == false && File.Exists(appsettingsPathWebHost) == false)
                {
                    var appsettings = Newtonsoft.Json.JsonConvert.DeserializeObject(File.Exists(appsettingsPath) ? File.ReadAllText(appsettingsPath) : "{}") as JToken;
                    var oldtxt      = appsettings.ToString();
                    if (appsettings["ConnectionStrings"] == null)
                    {
                        appsettings["ConnectionStrings"] = new JObject();
                    }
                    if (appsettings["ConnectionStrings"][$"{this.SolutionName}_mssql"] == null)
                    {
                        appsettings["ConnectionStrings"][$"{this.SolutionName}_mssql"] = this.ConnectionString + "Pooling=true;Max Pool Size=100";
                    }
                    if (appsettings["ConnectionStrings"]["redis1"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis1"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings["ConnectionStrings"]["redis2"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis2"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] == null)
                    {
                        appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] = JToken.FromObject(new {
                            Timeout = 180
                        });
                    }
                    if (appsettings["Logging"] == null)
                    {
                        appsettings["Logging"] = new JObject();
                    }
                    if (appsettings["Logging"]["IncludeScopes"] == null)
                    {
                        appsettings["Logging"]["IncludeScopes"] = false;
                    }
                    if (appsettings["Logging"]["LogLevel"] == null)
                    {
                        appsettings["Logging"]["LogLevel"] = new JObject();
                    }
                    if (appsettings["Logging"]["LogLevel"]["Default"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Default"] = "Debug";
                    }
                    if (appsettings["Logging"]["LogLevel"]["System"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["System"] = "Information";
                    }
                    if (appsettings["Logging"]["LogLevel"]["Microsoft"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Microsoft"] = "Information";
                    }
                    var newtxt = appsettings.ToString();
                    if (newtxt != oldtxt)
                    {
                        File.WriteAllText(appsettingsPath, newtxt, Encoding.UTF8);
                    }
                    //增加当前目录 .csproj nuguet 引用 <PackageReference Include="dng.Mssql" Version="" />
                    string csprojPath = Directory.GetFiles(OutputPath, "*.csproj").FirstOrDefault();
                    if (!string.IsNullOrEmpty(csprojPath) && File.Exists(csprojPath))
                    {
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"dng\.Mssql""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package dng.Mssql")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"CSRedisCore""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package CSRedisCore")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                    }
                    //向startup.cs注入代码
                    string startupPath = Path.Combine(OutputPath, "Startup.cs");
                    if (!string.IsNullOrEmpty(startupPath) && File.Exists(startupPath))
                    {
                        //web项目才需要 Caching.CSRedis
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"Caching.CSRedis""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package Caching.CSRedis")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }

                        bool isChanged   = false;
                        var  startupCode = File.ReadAllText(startupPath);
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Caching\.Distributed;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Caching.Distributed;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Logging;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Logging;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Configuration;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Configuration;\r\n" + startupCode;
                        }

                        var servicesName = "services";
                        if (startupCode.IndexOf("RedisHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;

                                var connStr1 = @"Configuration[""ConnectionStrings:redis2""]";
                                var connStr2 = @"Configuration[""ConnectionStrings:redis1""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr1 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                    connStr2 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                }

                                return(m.Groups[0].Value + $@"


			//单redis节点模式,如需开启集群负载,请将注释去掉并做相应配置
			RedisHelper.Initialization(
				csredis: new CSRedis.CSRedisClient(//null,
					//{connStr1},
					{connStr2}),
				serialize: value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
				deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
			{servicesName = m.Groups[1].Value}.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));


");
                            }, RegexOptions.Multiline);
                        }
                        if (Regex.IsMatch(startupCode, @"\s+IConfiguration(Root)?\s+Configuration(;|\s+\{)") == false)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;
                                return($@"
		public IConfiguration Configuration {{ get; set; }}
{m.Groups[0].Value}

			Configuration = {servicesName = m.Groups[1].Value}.BuildServiceProvider().GetService<IConfiguration>();"            );
                            }, RegexOptions.Multiline);
                        }
                        if (startupCode.IndexOf(this.SolutionName + ".BLL.SqlHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"([\t ]+public\s+void\s+Configure\s*\()([^\{]+)\{", m => {
                                isChanged         = true;
                                var str1          = m.Groups[1].Value;
                                var str2          = m.Groups[2].Value;
                                var loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                if (loggerFactory.Success == false)
                                {
                                    str2 = "ILoggerFactory loggerFactory, " + str2;
                                }
                                loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                var appName   = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");
                                if (appName.Success == false)
                                {
                                    str2 = "IApplicationBuilder app, " + str2;
                                }
                                appName = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");

                                var connStr = $@"Configuration[""ConnectionStrings:{this.SolutionName}_mssql""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr = $"{this.ConnectionString};Pooling=true;Maximum Pool Size=100";
                                }

                                return(str1 + str2 + $@"{{

			
			{this.SolutionName}.BLL.SqlHelper.Initialization({appName.Groups[1].Value}.ApplicationServices.GetService<IDistributedCache>(), Configuration.GetSection(""{this.SolutionName}_BLL_ITEM_CACHE""),
				{connStr}, {loggerFactory.Groups[1].Value}.CreateLogger(""{this.SolutionName}_DAL_sqlhelper""));


");
                            }, RegexOptions.Multiline);
                        }
                        if (isChanged)
                        {
                            File.WriteAllText(startupPath, startupCode);
                        }
                    }
                }
                if (File.Exists(Path.Combine(OutputPath, "GenMs只更新db.bat")) == false)
                {
                    var batPath = Path.Combine(OutputPath, $"GenMs_{this.SolutionName}_{this.Server}_{this.Database}.bat");
                    if (File.Exists(batPath) == false)
                    {
                        if (string.IsNullOrEmpty(this.Username))
                        {
                            File.WriteAllText(batPath, $@"
GenMs {this.Server} -D {this.Database} -N {this.SolutionName}");
                        }
                        else
                        {
                            File.WriteAllText(batPath, $@"
GenMs {this.Server} -U {this.Username} -P {this.Password} -D {this.Database} -N {this.SolutionName}");
                        }
                    }
                }
            }
            this._socket.Close();
            this._socket.Dispose();
            GC.Collect();

            ConsoleColor fc = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + OutputPath + "\", please check.");
            Console.ForegroundColor = fc;
            wait.Set();
        }
Пример #12
0
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                Console.WriteLine(@"
Example:

	> MakeCode 127.0.0.1[:3306] -U root -P 123456 -D dyschool -N dyschool -S -A -R -O ""c:/dyschool/""

		-U	MySql账号
		-P	MySql密码
		-D	需要生成的数据库,多个使用,分隔

		-N	字符串,生成代码的解决方案名,命名空间
		-S	生成解决方案,在项目第一次生成时使用
		-A	生成后台管理
		-R	下载资源

		-O	路径,生成后的代码保存到哪里"            );
                wait.Set();
                return;
            }
            string[] ss = args[0].Split(new char[] { ':' }, 2);
            this.Server = ss[0];
            if (int.TryParse(ss.Length == 2 ? ss[1] : "5432", out this.Port) == false)
            {
                this.Port = 5432;
            }
            for (int a = 1; a < args.Length; a++)
            {
                switch (args[a])
                {
                case "-U":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-U 参数错误");
                    }
                    else
                    {
                        this.Username = args[a + 1];
                    }
                    a++;
                    break;

                case "-P":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-P 参数错误");
                    }
                    else
                    {
                        this.Password = args[a + 1];
                    }
                    a++;
                    break;

                case "-D":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-D 参数错误");
                    }
                    else
                    {
                        this.Database = args[a + 1];
                    }
                    a++;
                    break;

                case "-O":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-O 参数错误");
                    }
                    else
                    {
                        this.OutputPath = args[a + 1];
                    }
                    a++;
                    break;

                case "-N":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-N 参数错误");
                    }
                    else
                    {
                        this.SolutionName = args[a + 1];
                    }
                    a++;
                    break;

                case "-S":
                    this.IsMakeSolution = true;
                    break;

                case "-A":
                    this.IsMakeWebAdmin = true;
                    break;

                case "-R":
                    this.IsDownloadRes = true;
                    break;
                }
            }
            this._client = new ClientInfo(this.Server, this.Port, this.Username, this.Password);
            Uri uri = new Uri("tcp://" + Settings.Default.server + "/");

            this._socket          = new ClientSocket();
            this._socket.Error   += Socket_OnError;
            this._socket.Receive += Socket_OnReceive;
            this._socket.Connect(uri.Host, uri.Port);
            Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
            if (this._socket.Running == false)
            {
                wait.Set();
                return;
            }

            SocketMessager messager = new SocketMessager("GetDatabases", this._client);

            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                List <DatabaseInfo> dbs = e2.Messager.Arg as List <DatabaseInfo>;
            });
            this._client.Database = this.Database;
            List <TableInfo> tables = null;

            messager = new SocketMessager("GetTablesByDatabase", this._client.Database);
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                tables = e2.Messager.Arg as List <TableInfo>;
            });
            if (tables == null)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] 无法读取表");
                this._socket.Close();
                this._socket.Dispose();

                wait.Set();
                return;
            }
            tables.ForEach(a => a.IsOutput = true);
            List <BuildInfo> bs = null;

            messager = new SocketMessager("Build", new object[] {
                SolutionName,
                IsMakeSolution,
                string.Join("", tables.ConvertAll <string>(delegate(TableInfo table){
                    return(string.Concat(table.IsOutput ? 1 : 0));
                }).ToArray()),
                IsMakeWebAdmin,
                IsDownloadRes
            });
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                bs = e2.Messager.Arg as List <BuildInfo>;
                if (e2.Messager.Arg is Exception)
                {
                    throw e2.Messager.Arg as Exception;
                }
            }, TimeSpan.FromSeconds(60 * 5));
            if (bs != null)
            {
                foreach (BuildInfo b in bs)
                {
                    string path = Path.Combine(OutputPath, b.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    string   fileName = Path.GetFileName(b.Path);
                    string   ext      = Path.GetExtension(b.Path);
                    Encoding encode   = Encoding.UTF8;

                    if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll"))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                            fs.Write(b.Data, 0, b.Data.Length);
                            fs.Close();
                        }
                        continue;
                    }

                    byte[] data    = Deflate.Decompress(b.Data);
                    string content = Encoding.UTF8.GetString(data);

                    if (string.Compare(fileName, "web.config") == 0)
                    {
                        string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString);
                        content = content.Replace("{connectionString}", place);
                    }
                    if (fileName.EndsWith(".json"))
                    {
                        content = content.Replace("{connectionString}", this.ConnectionString);
                    }
                    if (string.Compare(ext, ".refresh") == 0)
                    {
                        encode = Encoding.Unicode;
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, encode)) {
                        sw.Write(content);
                        sw.Close();
                    }
                }
            }
            this._socket.Close();
            this._socket.Dispose();
            GC.Collect();

            ConsoleColor fc = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + OutputPath + "\", please check.");
            Console.ForegroundColor = fc;
            wait.Set();
        }
Пример #13
0
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            this.OutputPath = Directory.GetCurrentDirectory();
            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                var bgcolor = Console.BackgroundColor;
                var fgcolor = Console.ForegroundColor;

                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#################################");
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                 ");
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("   .NETCore 2.1 + MySQL 生成器   ");
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                 ");
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#################################");
                Console.Write("##");

                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Write(@"

用于快速创建和更新 .NETCore 2.1 + MySQL 项目,非常合适敏捷开发;
Github: https://github.com/2881099/dotnetgen_mysql

");
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Write("Example:");
                Console.ForegroundColor = fgcolor;
                Console.WriteLine(@"

	> GenMy 127.0.0.1[:3306] -U root -P 123456 -D dyschool -N dyschool -S -A -R -O ""c:/dyschool/""

		-U	MySql账号
		-P	MySql密码
		-D	需要生成的数据库,多个使用,分隔

		-N	字符串,生成代码的解决方案名,命名空间
		-S	生成解决方案,在项目第一次生成时使用
		-A	生成后台管理
		-R	下载资源

		-O	输出路径(默认:当前目录)"            );
                wait.Set();
                return;
            }
            string[] ss = args[0].Split(new char[] { ':' }, 2);
            this.Server = ss[0];
            if (int.TryParse(ss.Length == 2 ? ss[1] : "3306", out this.Port) == false)
            {
                this.Port = 3306;
            }
            for (int a = 1; a < args.Length; a++)
            {
                switch (args[a])
                {
                case "-U":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-U 参数错误");
                    }
                    else
                    {
                        this.Username = args[a + 1];
                    }
                    a++;
                    break;

                case "-P":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-P 参数错误");
                    }
                    else
                    {
                        this.Password = args[a + 1];
                    }
                    a++;
                    break;

                case "-D":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-D 参数错误");
                    }
                    else
                    {
                        this.Database = args[a + 1];
                    }
                    a++;
                    break;

                case "-O":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-O 参数错误");
                    }
                    else
                    {
                        this.OutputPath = args[a + 1];
                    }
                    a++;
                    break;

                case "-N":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-N 参数错误");
                    }
                    else
                    {
                        this.SolutionName = args[a + 1];
                    }
                    a++;
                    break;

                case "-S":
                    this.IsMakeSolution = true;
                    break;

                case "-A":
                    this.IsMakeWebAdmin = true;
                    break;

                case "-R":
                    this.IsDownloadRes = true;
                    break;
                }
            }
            this._client = new ClientInfo(this.Server, this.Port, this.Username, this.Password);
            StreamReader sr     = new StreamReader(System.Net.WebRequest.Create("https://files.cnblogs.com/files/kellynic/GenMy_server.css").GetResponse().GetResponseStream(), Encoding.UTF8);
            string       server = sr.ReadToEnd()?.Trim();
            //server = "127.0.0.1:18888";
            Uri uri = new Uri("tcp://" + server + "/");

            this._socket          = new ClientSocket();
            this._socket.Error   += Socket_OnError;
            this._socket.Receive += Socket_OnReceive;
            this._socket.Connect(uri.Host, uri.Port);
            Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
            if (this._socket.Running == false)
            {
                wait.Set();
                return;
            }

            WriteLine("正在生成,稍候 …", ConsoleColor.DarkGreen);

            SocketMessager messager = new SocketMessager("GetDatabases", this._client);

            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                List <DatabaseInfo> dbs = e2.Messager.Arg as List <DatabaseInfo>;
            });
            this._client.Database = this.Database;
            List <TableInfo> tables = null;

            messager = new SocketMessager("GetTablesByDatabase", this._client.Database);
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                tables = e2.Messager.Arg as List <TableInfo>;
            });
            if (tables == null)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] 无法读取表");
                this._socket.Close();
                this._socket.Dispose();

                wait.Set();
                return;
            }
            tables.ForEach(a => a.IsOutput = true);
            List <BuildInfo> bs = null;

            messager = new SocketMessager("Build", new object[] {
                SolutionName,
                IsMakeSolution,
                string.Join("", tables.ConvertAll <string>(delegate(TableInfo table){
                    return(string.Concat(table.IsOutput ? 1 : 0));
                }).ToArray()),
                IsMakeWebAdmin,
                IsDownloadRes
            });
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                bs = e2.Messager.Arg as List <BuildInfo>;
                if (e2.Messager.Arg is Exception)
                {
                    throw e2.Messager.Arg as Exception;
                }
            }, TimeSpan.FromSeconds(60 * 5));
            if (bs != null)
            {
                foreach (BuildInfo b in bs)
                {
                    string path = Path.Combine(OutputPath, b.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    string   fileName = Path.GetFileName(b.Path);
                    string   ext      = Path.GetExtension(b.Path);
                    Encoding encode   = Encoding.UTF8;

                    if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll"))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                            fs.Write(b.Data, 0, b.Data.Length);
                            fs.Close();
                        }
                        continue;
                    }

                    byte[] data    = Deflate.Decompress(b.Data);
                    string content = Encoding.UTF8.GetString(data);

                    if (string.Compare(fileName, "web.config") == 0)
                    {
                        string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString);
                        content = content.Replace("{connectionString}", place);
                    }
                    if (fileName.EndsWith(".json"))
                    {
                        content = content.Replace("{connectionString}", this.ConnectionString);
                    }
                    if (string.Compare(ext, ".refresh") == 0)
                    {
                        encode = Encoding.Unicode;
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, encode)) {
                        sw.Write(content);
                        sw.Close();
                    }
                }
                var appsettingsPath        = Path.Combine(OutputPath, "appsettings.json");
                var appsettingsPathWebHost = Path.Combine(OutputPath, @"src\WebHost\appsettings.json");
                var htmZipPath             = Path.Combine(OutputPath, "htm.zip");
                //解压htm.zip
                if (this.IsDownloadRes && File.Exists(htmZipPath))
                {
                    try {
                        System.IO.Compression.ZipFile.ExtractToDirectory(htmZipPath, OutputPath, Encoding.UTF8, true);
                    } catch (Exception ex) {
                        var color = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"解压 htm.zip 失败:{ex.Message}");
                        Console.ForegroundColor = color;
                    }
                }
                if (this.IsMakeSolution)
                {
                    WriteLine("代码已生成完毕!使用 -S 生成完整项目,正在建立脚手架,大约需要10秒 …", ConsoleColor.DarkGreen);

                    var shellret = ShellRun(OutputPath, "gulp -v");

                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine("");
                        WriteLine(@"正在安装gulp-cli …", ConsoleColor.DarkGreen);
                        shellret = ShellRun(OutputPath, "npm install --global gulp-cli");
                        if (!string.IsNullOrEmpty(shellret.err))
                        {
                            WriteLine(shellret.err, ConsoleColor.Red);
                        }
                        if (!string.IsNullOrEmpty(shellret.warn))
                        {
                            WriteLine(shellret.warn, ConsoleColor.Yellow);
                        }
                        if (!string.IsNullOrEmpty(shellret.info))
                        {
                            WriteLine(shellret.info, ConsoleColor.DarkGray);
                        }
                    }

                    //WriteLine("");
                    //WriteLine("正在还原项目 …", ConsoleColor.DarkGreen);
                    //shellret = ShellRun(OutputPath, "dotnet1 restore");
                    //if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red);
                    //if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow);
                    //if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray);

                    WriteLine("");
                    WriteLine(@"正在编译Module\Test …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Test"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine(@"正在编译Module\Admin …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Admin"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine("正在安装npm包 …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "npm install");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine("正在编译WebHost …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine($"脚手架建立完成。", ConsoleColor.DarkGreen);

                    //WriteLine("");
                    //Write($"项目运行依赖 ", ConsoleColor.DarkYellow);
                    //Write($"redis-server", ConsoleColor.Green);
                    //Write($",安装地址:", ConsoleColor.DarkYellow);
                    //Write("https://files.cnblogs.com/files/kellynic/Redis-x64-2.8.2402.zip", ConsoleColor.Blue);
                    //WriteLine($",或前往官方下载", ConsoleColor.DarkYellow);

                    WriteLine("");
                    WriteLine($"{Path.Combine(OutputPath, @"src\WebHost")} 目执行 dotnet run", ConsoleColor.DarkYellow);
                    WriteLine("");
                    //Console.WriteLine(ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet run"));

                    var pro = new System.Diagnostics.Process();
                    pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "run --urls=http://0.0.0.0:5000")
                    {
                        WorkingDirectory     = Path.Combine(OutputPath, @"src\WebHost"),
                        EnvironmentVariables = { ["ASPNETCORE_ENVIRONMENT"] = "Development" }
                    };
                    pro.Start();
                    pro.WaitForExit();
                }
                //如果三个选项为false,并且 src\WebHost\appsettings.json 不存在,则在当前目录使用 appsettings.json
                if (this.IsDownloadRes == false && this.IsMakeSolution == false && this.IsMakeWebAdmin == false && File.Exists(appsettingsPathWebHost) == false)
                {
                    var appsettings = Newtonsoft.Json.JsonConvert.DeserializeObject(File.Exists(appsettingsPath) ? File.ReadAllText(appsettingsPath) : "{}") as JToken;
                    var oldtxt      = appsettings.ToString();
                    if (appsettings["ConnectionStrings"] == null)
                    {
                        appsettings["ConnectionStrings"] = new JObject();
                    }
                    if (appsettings["ConnectionStrings"][$"{this.SolutionName}_mysql"] == null)
                    {
                        appsettings["ConnectionStrings"][$"{this.SolutionName}_mysql"] = this.ConnectionString + ";SslMode=none;Max pool size=100";
                    }
                    if (appsettings["ConnectionStrings"]["redis1"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis1"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings["ConnectionStrings"]["redis2"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis2"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] == null)
                    {
                        appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] = JToken.FromObject(new {
                            Timeout = 180
                        });
                    }
                    if (appsettings["Logging"] == null)
                    {
                        appsettings["Logging"] = new JObject();
                    }
                    if (appsettings["Logging"]["IncludeScopes"] == null)
                    {
                        appsettings["Logging"]["IncludeScopes"] = false;
                    }
                    if (appsettings["Logging"]["LogLevel"] == null)
                    {
                        appsettings["Logging"]["LogLevel"] = new JObject();
                    }
                    if (appsettings["Logging"]["LogLevel"]["Default"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Default"] = "Debug";
                    }
                    if (appsettings["Logging"]["LogLevel"]["System"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["System"] = "Information";
                    }
                    if (appsettings["Logging"]["LogLevel"]["Microsoft"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Microsoft"] = "Information";
                    }
                    var newtxt = appsettings.ToString();
                    if (newtxt != oldtxt)
                    {
                        File.WriteAllText(appsettingsPath, newtxt, Encoding.UTF8);
                    }
                    //增加当前目录 .csproj nuguet 引用 <PackageReference Include="dng.Mysql" Version="" />
                    string csprojPath = Directory.GetFiles(OutputPath, "*.csproj").FirstOrDefault();
                    if (!string.IsNullOrEmpty(csprojPath) && File.Exists(csprojPath))
                    {
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"dng\.Mysql""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package dng.Mysql")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"CSRedisCore""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package CSRedisCore")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                    }

                    //向startup.cs注入代码
                    string startupPath = Path.Combine(OutputPath, "Startup.cs");
                    if (!string.IsNullOrEmpty(startupPath) && File.Exists(startupPath))
                    {
                        //web项目才需要 Caching.CSRedis
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"Caching.CSRedis""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package Caching.CSRedis")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }

                        bool isChanged   = false;
                        var  startupCode = File.ReadAllText(startupPath);
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Caching\.Distributed;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Caching.Distributed;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Logging;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Logging;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Configuration;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Configuration;\r\n" + startupCode;
                        }

                        var servicesName = "services";
                        if (startupCode.IndexOf("RedisHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;

                                var connStr1 = @"Configuration[""ConnectionStrings:redis2""]";
                                var connStr2 = @"Configuration[""ConnectionStrings:redis1""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr1 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                    connStr2 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                }

                                return(m.Groups[0].Value + $@"


			//单redis节点模式,如需开启集群负载,请将注释去掉并做相应配置
			RedisHelper.Initialization(
				csredis: new CSRedis.CSRedisClient(//null,
					//{connStr1},
					{connStr2}));
			{servicesName = m.Groups[1].Value}.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));


");
                            }, RegexOptions.Multiline);
                        }
                        if (Regex.IsMatch(startupCode, @"\s+IConfiguration(Root)?\s+Configuration(;|\s+\{)") == false)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;
                                return($@"
		public IConfiguration Configuration {{ get; set; }}
{m.Groups[0].Value}

			Configuration = {servicesName = m.Groups[1].Value}.BuildServiceProvider().GetService<IConfiguration>();"            );
                            }, RegexOptions.Multiline);
                        }
                        if (startupCode.IndexOf(this.SolutionName + ".BLL.SqlHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"([\t ]+public\s+void\s+Configure\s*\()([^\{]+)\{", m => {
                                isChanged         = true;
                                var str1          = m.Groups[1].Value;
                                var str2          = m.Groups[2].Value;
                                var loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                if (loggerFactory.Success == false)
                                {
                                    str2 = "ILoggerFactory loggerFactory, " + str2;
                                }
                                loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                var appName   = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");
                                if (appName.Success == false)
                                {
                                    str2 = "IApplicationBuilder app, " + str2;
                                }
                                appName = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");

                                var connStr = $@"Configuration[""ConnectionStrings:{this.SolutionName}_mysql""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr = $"{this.ConnectionString};SslMode=none;Max pool size=100";
                                }

                                return(str1 + str2 + $@"{{

			
			{this.SolutionName}.BLL.SqlHelper.Initialization({appName.Groups[1].Value}.ApplicationServices.GetService<IDistributedCache>(), Configuration.GetSection(""{this.SolutionName}_BLL_ITEM_CACHE""),
				{connStr}, /* 此参数可以配置【从数据库】 */ null, {loggerFactory.Groups[1].Value}.CreateLogger(""{this.SolutionName}_DAL_sqlhelper""));


");
                            }, RegexOptions.Multiline);
                        }
                        if (isChanged)
                        {
                            File.WriteAllText(startupPath, startupCode);
                        }
                    }
                }
                if (File.Exists(Path.Combine(OutputPath, "GenMy只更新db.bat")) == false)
                {
                    var batPath = Path.Combine(OutputPath, $"GenMy_{this.SolutionName}_{this.Server}_{this.Database}.bat");
                    if (File.Exists(batPath) == false)
                    {
                        File.WriteAllText(batPath, $@"
GenMy {this.Server}:{this.Port} -U {this.Username} -P {this.Password} -D {this.Database} -N {this.SolutionName}");
                    }
                }
            }
            this._socket.Close();
            this._socket.Dispose();
            GC.Collect();

            ConsoleColor fc = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + OutputPath + "\", please check.");
            Console.ForegroundColor = fc;
            wait.Set();
        }
Пример #14
0
    void decompressDeflate()
    {
        string t = @"Hco7DoAgEEXRvbwak/kwwrAVYmxsiFR+KuPeJZb35NYH97G2DYU1EccwsrfzQqmYnEVdkmUmM3ZXBDi5UCTPlGnWGPm3ZOMwnmU4qWAJ6DsK8C4f";

        ConsoleEx.DebugLog("decompress : " + Deflate.Decompress(t));
    }
Пример #15
0
        /// <summary>
        /// Writes the binary data to the stream.
        /// </summary>
        /// <param name="grf"></param>
        /// <param name="writer"></param>
        internal void WriteToBinaryTable(Format grf, BinaryWriter writer)
        {
            // Skip deleted files
            if (IsDeleted)
            {
                return;
            }

            byte[] buf;

            // Update new offset
            DataOffset = (uint)writer.BaseStream.Position;

            // Either new or changed?
            if (IsUpdated == false && IsAdded == false)
            {
                // Auto-convert to 0x200 compression (deflate)
                if (grf.Version != 0x200)
                {
                    // #1: Decompress buf and update length
                    buf = grf.GetFileData(NameHash, true);
                    LengthUnCompressed = (uint)buf.Length;
                    // #2: Compress and update length
                    buf = Deflate.Compress(buf, true);
                    LengthCompressed      = (uint)buf.Length;
                    LengthCompressedAlign = (uint)buf.Length;
                }
                else
                {
                    // Get compressed data
                    buf = grf.GetFileData(NameHash, false);
                }
            }
            else
            {
                // Added or updated files, load data from origin filepath
                if (File.Exists(NewFilepath) == false)
                {
                    throw new Exception("WriteItems(): File of new or updated item not found: " + NewFilepath);
                }

                buf = File.ReadAllBytes(NewFilepath);
                LengthUnCompressed = (uint)buf.Length;
                buf = Deflate.Compress(buf, true);
                LengthCompressed = LengthCompressedAlign = (uint)buf.Length;
            }

            try {
                // Check if the buf is compressed
                if (buf.Length != LengthCompressed && buf.Length != LengthCompressedAlign)
                {
                    // The buf has to be compressed, so decompress it
                    byte[] bufUncompressed = Deflate.Decompress(buf);
                    // Update length, if decompression seems to be correct
                    if (bufUncompressed.Length == 0 || bufUncompressed.Length != LengthUnCompressed)
                    {
                        // Narf, corrupt file or something like that
                        // Just write it..
                        //throw new Exception("WriteItems(): Item " + Filepath + ", DataLen missmatch");
                    }
                    else
                    {
                        // Decompression was succesfull, so update size
                        LengthCompressed = (uint)Deflate.GetCompressedLength(bufUncompressed);
                    }
                }

                // Seems like a valid buf, write it
                writer.Write(buf);
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine(e);
            }
        }
Пример #16
0
        /// <summary>
        /// Reads the uncompressed body of versions equal or above 0x200.
        /// The body is ZIP (deflate) compressed.
        /// </summary>
        /// <param name="binReader"></param>
        /// <param name="fileCount"></param>
        /// <param name="skipFiles"></param>
        /// <returns></returns>
        private bool ReadFilesVersion2(BinaryReader binReader, int fileCount, bool skipFiles)
        {
            int lengthCompressed   = binReader.ReadInt32();
            int lengthUnCompressed = binReader.ReadInt32();

            _fileTableLength = (ulong)lengthUnCompressed;
            var bufCompressed = new byte[lengthCompressed];

            _filetableUncompressed = new byte[(int)_fileTableLength];
            binReader.Read(bufCompressed, 0, lengthCompressed);

            _filetableUncompressed = Deflate.Decompress(bufCompressed);

            /*
             * if (_filetableUncompressed.Length != (int)_fileTableLength) {
             *      throw new Exception("Filesize missmatch! Uncompressed Body Size is not equal to Uncompressed Length!");
             * }
             */
            // Only read body?
            if (skipFiles == false)
            {
                for (int i = 0, offset = 0; i < fileCount; i++)
                {
                    var  filepath = string.Empty;
                    char c;
                    var  itemTableOffset = (uint)offset;

                    while ((c = (char)_filetableUncompressed[offset++]) != '\0')
                    {
                        filepath += c;
                    }

                    filepath = Tools.UnifyPath(filepath);
                    var item = new FileItem {
                        TableOffset = itemTableOffset,
                        Index       = Files.Count,
                        Filepath    = filepath,
                        Flags       = _filetableUncompressed[offset + 12]
                    };

                    // File or directory?
                    if (item.IsFile)
                    {
                        item.LengthCompressed      = BitConverter.ToUInt32(_filetableUncompressed, offset);
                        item.LengthCompressedAlign = BitConverter.ToUInt32(_filetableUncompressed, offset + 4);
                        item.LengthUnCompressed    = BitConverter.ToUInt32(_filetableUncompressed, offset + 8);
                        // Offset is base offset + grf header
                        item.DataOffset = BitConverter.ToUInt32(_filetableUncompressed, offset + 13) + GrfHeaderLen;

                        // from eAtehna, DES encryption
                        item.Cycle = 1;
                        switch (item.Flags)
                        {
                        case 3:
                            for (var lop = 10; item.LengthCompressed >= lop; lop = lop * 10, item.Cycle++)
                            {
                            }
                            break;

                        case 5:
                            item.Cycle = 0;
                            break;

                        default:
                            item.Cycle = -1;
                            break;
                        }
                    }
                    else
                    {
                        // skip dirs
                        offset += (int)GrfFileLen;
                        continue;
                    }

                    // FIX: Some files in a tested grf are duplicated?
                    //		I cant remember grf version or something else..
                    if (GetFileByHash(item.NameHash) != null)
                    {
                        // Duplicate file, just skip it
                        offset += (int)GrfFileLen;
                        continue;
                    }
                    Files.Add(item.NameHash, item);
                    _stringlist.Add(item.NameHash);

                    _fileDataLength += item.LengthCompressedAlign;

                    offset += (int)GrfFileLen;

#if !DISABLE_GRF_EVENTS
                    OnItemAdded(item, i, fileCount);
#endif
                }
            }

            return(true);
        }