static void Main(string[] args) { var client = new ClientSocket(); client.Error += (sender, e) => { Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] " + e.Exception.Message + e.Exception.StackTrace); }; client.Receive += (sender, e) => { switch (e.Messager.Action) { } }; client.Connect("localhost", 19990); SocketMessager messager = new SocketMessager("GetDatabases", 1); object dbs = null; //以下代码等于同步,直到服务端响应(会执行委托)或超时 client.Write(messager, (sender2, e2) => { //服务端正常响应会执行这里 dbs = e2.Messager; }); Console.WriteLine(dbs); Console.WriteLine("sldkjglsjdglksdg"); //若不传递第二个委托参数,线程不会等待结果,服务端响应后由 client.Receive 处理 //Console.ReadKey(); client.Close(); }
private void Socket_OnReceive(object sender, ClientSocketReceiveEventArgs e) { SocketMessager messager = null; switch (e.Messager.Action) { case "ExecuteDataSet": string sql = e.Messager.Arg.ToString(); DataSet ds = null; try { ds = ConsoleApp.ExecuteDataSet(this.ConnectionString, sql); } catch (Exception ex) { this.Socket_OnError(this, new ClientSocketErrorEventArgs(ex, 0)); } messager = new SocketMessager(e.Messager.Action, ds); messager.Id = e.Messager.Id; this._socket.Write(messager); break; case "ExecuteNonQuery": string sql2 = e.Messager.Arg.ToString(); int val = 0; try { val = ConsoleApp.ExecuteNonQuery(this.ConnectionString, sql2); } catch (Exception ex) { this.Socket_OnError(this, new ClientSocketErrorEventArgs(ex, 0)); } messager = new SocketMessager(e.Messager.Action, val); messager.Id = e.Messager.Id; this._socket.Write(messager); break; default: Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] " + "您当前使用的版本未能实现功能!"); break; } }
protected SocketMessager Read(Stream stream) { byte[] data = new byte[8]; int bytes = 0; int overs = data.Length; string size = string.Empty; while (overs > 0) { bytes = stream.Read(data, 0, overs); overs -= bytes; size += Encoding.UTF8.GetString(data, 0, bytes); } if (int.TryParse(size, NumberStyles.HexNumber, null, out overs) == false) { return(null); } overs -= data.Length; MemoryStream ms = new MemoryStream(); data = new Byte[1024]; while (overs > 0) { bytes = stream.Read(data, 0, overs < data.Length ? overs : data.Length); overs -= bytes; ms.Write(data, 0, bytes); } data = ms.ToArray(); ms.Close(); return(SocketMessager.Parse(data)); }
void OnDestroy() { Logger.Log("socket destroy"); messager.Dispose(); messager = null; GC.Collect(); }
private DataSet GetDataSet(string commandText) { SocketMessager messager = new SocketMessager("ExecuteDataSet", commandText); _socket.Write(messager, delegate(object sender, ServerSocketReceiveEventArgs e) { messager = e.Messager; }); return(messager.Arg as DataSet); }
private int ExecuteNonQuery(string commandText) { SocketMessager messager = new SocketMessager("ExecuteNonQuery", commandText); _socket.Write(messager, delegate(object sender, ServerSocketReceiveEventArgs e) { messager = e.Messager; }); int val; int.TryParse(string.Concat(messager.Arg), out val); return(val); }
protected void Write(Stream stream, SocketMessager messager) { MemoryStream ms = new MemoryStream(); byte[] buff = Encoding.UTF8.GetBytes(messager.GetCanParseString()); ms.Write(buff, 0, buff.Length); if (messager.Arg != null) { buff = Deflate.Compress(BaseSocket.Serialize(messager.Arg)); ms.Write(buff, 0, buff.Length); } this.Write(stream, ms.ToArray()); ms.Close(); }
public void Write(SocketMessager messager, ServerSocketReceiveEventHandler receiveHandler, TimeSpan timeout) { if (!messager._isChangeId) { messager.Id = -messager.Id; } SyncReceive syncReceive = null; try { if (receiveHandler != null) { syncReceive = new SyncReceive(receiveHandler); lock (this._receiveHandlers_lock) { if (!this._receiveHandlers.ContainsKey(messager.Id)) { this._receiveHandlers.Add(messager.Id, syncReceive); } else { this._receiveHandlers[messager.Id] = syncReceive; } } } lock (_write_lock) { NetworkStream ns = this._tcpClient.GetStream(); base.Write(ns, messager); } this._lastActive = DateTime.Now; if (syncReceive != null) { syncReceive.Wait.Reset(); syncReceive.Wait.WaitOne(timeout, false); syncReceive.Wait.Set(); lock (this._receiveHandlers_lock) { this._receiveHandlers.Remove(messager.Id); } } } catch (Exception ex) { this._running = false; this.OnError(ex); if (syncReceive != null) { syncReceive.Wait.Set(); lock (this._receiveHandlers_lock) { this._receiveHandlers.Remove(messager.Id); } } } }
private void cmbDatabase_SelectedIndexChanged(object sender, EventArgs e) { if (this.btnConnect.Text == "DisConnect" && this.btnConnect.Enabled == false) { return; } this._client.Database = this.cmbDatabase.Text; List <TableInfo> tables = null; SocketMessager messager = new SocketMessager("GetTablesByDatabase", this._client.Database); this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) { tables = e2.Messager.Arg as List <TableInfo>; }); this._tables = tables; this.BindGridView(); }
private void btnConnect_Click(object sender, EventArgs e) { this.btnConnect.Enabled = false; if (this.btnConnect.Text == "Connect") { this._client = new ClientInfo(this.txtServer.Text, this.txtUsername.Text, this.txtPassword.Text); List <DatabaseInfo> dbs = null; SocketMessager messager = new SocketMessager("GetDatabases", this._client); this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) { dbs = e2.Messager.Arg as List <DatabaseInfo>; }); if (dbs == null) { this.btnConnect.Enabled = true; return; } this.cmbDatabase.DisplayMember = "Name"; this.cmbDatabase.DataSource = dbs; if (this.cmbDatabase.Items.Count > 0) { this.cmbDatabase.SelectedIndex = 0; this.cmbDatabase.Enabled = true; } this.txtServer.Enabled = false; this.chkIntegrated.Enabled = false; this.chkIntegrated_CheckedChanged(sender, e); } else { this.txtSolution.Clear(); this.cmbDatabase.DataSource = null; this.cmbDatabase.Enabled = false; this.btnBuild.Enabled = false; this.txtServer.Enabled = true; this.chkIntegrated.Enabled = true; this.chkIntegrated_CheckedChanged(sender, e); this.dgvGridview.DataSource = null; } this.btnConnect.Text = this.btnConnect.Text == "Connect" ? "DisConnect" : "Connect"; this.btnConnect.Enabled = true; }
private void btnConnect_Click(object sender, EventArgs e) { this.btnConnect.Enabled = false; if (this.btnConnect.Text == "Connect") { this._client = new ClientInfo(this.txtServer.Text, int.Parse(this.txtPort.Text), this.txtUsername.Text, this.txtPassword.Text); List <DatabaseInfo> dbs = null; SocketMessager messager = new SocketMessager("GetDatabases", this._client); this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) { dbs = e2.Messager.Arg as List <DatabaseInfo>; }); if (dbs == null) { this.btnConnect.Enabled = true; return; } string[] dbs2 = new string[dbs.Count]; for (int a = 0; a < dbs2.Length; a++) { dbs2[a] = dbs[a].Name; } this.clbDatabase.DataSource = dbs2; if (this.clbDatabase.Items.Count > 0) { this.clbDatabase.Enabled = true; } this.txtServer.Enabled = this.txtUsername.Enabled = this.txtPassword.Enabled = false; } else { this.txtSolution.Clear(); this.clbDatabase.DataSource = null; this.clbDatabase.Enabled = false; this.btnBuild.Enabled = false; this.txtServer.Enabled = this.txtUsername.Enabled = this.txtPassword.Enabled = true; this.dgvGridview.DataSource = null; } this.btnConnect.Text = this.btnConnect.Text == "Connect" ? "DisConnect" : "Connect"; this.btnConnect.Enabled = true; }
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; SocketMessager messager; using (MemoryStream ms = new MemoryStream()) { ms.Write(data, idx + 2, data.Length - idx - 2); messager = new SocketMessager(loc3, loc4, ms.Length > 0 ? BaseSocket.Deserialize(ms.ToArray()) : null); //using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress)) { // using (MemoryStream msOut = new MemoryStream()) { // ds.CopyTo(msOut); // messager = new SocketMessager(loc3, loc4, ms.Length > 0 ? BaseSocket.Deserialize(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); }
protected byte[] GetWriteBuffer(SocketMessager messager) { using (MemoryStream ms = new MemoryStream()) { byte[] buff = Encoding.UTF8.GetBytes(messager.GetCanParseString()); ms.Write(buff, 0, buff.Length); if (messager.Arg != null) { var data = BaseSocket.Serialize(messager.Arg); using (MemoryStream msBuf = new MemoryStream()) { using (DeflateStream ds = new DeflateStream(msBuf, CompressionMode.Compress)) { ds.Write(data, 0, data.Length); buff = msBuf.ToArray(); ms.Write(buff, 0, buff.Length); } } } return(this.GetWriteBuffer(ms.ToArray())); } }
protected void Write(Stream stream, SocketMessager messager) { using (MemoryStream ms = new MemoryStream()) { byte[] buff = Encoding.UTF8.GetBytes(messager.GetCanParseString()); ms.Write(buff, 0, buff.Length); if (messager.Arg != null) { using (MemoryStream msArg = new MemoryStream(Lib.Serialize(messager.Arg))) { using (DeflateStream ds = new DeflateStream(msArg, CompressionMode.Compress)) { using (MemoryStream msBuf = new MemoryStream()) { ds.CopyTo(msBuf); buff = msBuf.ToArray(); ms.Write(buff, 0, buff.Length); } } } } this.Write(stream, ms.ToArray()); } }
public void Write(SocketMessager messager) { int[] keys = new int[this._clients.Count]; try { this._clients.Keys.CopyTo(keys, 0); } catch { lock (this._clients_lock) { keys = new int[this._clients.Count]; this._clients.Keys.CopyTo(keys, 0); } } foreach (int key in keys) { AcceptSocket client = null; if (this._clients.TryGetValue(key, out client)) { client.Write(messager); } } }
private object[][] GetDataSet(string commandText) { SocketMessager messager = new SocketMessager("ExecuteDataSet", commandText); _socket.Write(messager, delegate(object sender, ServerSocketReceiveEventArgs e) { messager = e.Messager; }); object[][] ret = messager.Arg as object[][]; //兼容.netcore传过来的数据 if (ret == null) { DataSet ds = messager.Arg as DataSet; //兼容.net传过来的数据 if (ds != null) { List <object[]> tmp = new List <object[]>(); foreach (DataRow row in ds.Tables[0].Rows) { tmp.Add(row.ItemArray); } ret = tmp.ToArray(); } } return(ret); }
private void Socket_OnReceive(object sender, ClientSocketReceiveEventArgs e) { SocketMessager messager = null; switch (e.Messager.Action) { case "ExecuteDataSet": string sql = e.Messager.Arg.ToString(); DataSet ds = null; try { ds = ExecuteDataSet(sql); } catch (Exception ex) { this.Socket_OnError(this, new ClientSocketErrorEventArgs(ex, 0)); } messager = new SocketMessager(e.Messager.Action, ds); messager.Id = e.Messager.Id; this._socket.Write(messager); break; case "ExecuteNonQuery": string sql2 = e.Messager.Arg.ToString(); int val = 0; try { val = ExecuteNonQuery(sql2); } catch (Exception ex) { this.Socket_OnError(this, new ClientSocketErrorEventArgs(ex, 0)); } messager = new SocketMessager(e.Messager.Action, val); messager.Id = e.Messager.Id; this._socket.Write(messager); break; default: Lib.Msgbox("您当前使用的版本未能实现功能!"); break; } }
public void Connect(string hostname, int port) { if (this._isDisposed == false && this._running == false) { this._running = true; try { IPAddress[] ips = Dns.GetHostAddresses(hostname); if (ips.Length == 0) { throw new Exception("无法解析“" + hostname + "”"); } this._remotePoint = new IPEndPoint(ips[0], port); this._tcpClient = new TcpClient(); this._tcpClient.Connect(this._remotePoint); } catch (Exception ex) { this._running = false; this.OnError(ex); this.OnClosed(); return; } this._receives = 0; this._errors = 0; this._lastActive = DateTime.Now; this._thread = new Thread(delegate() { while (this._running) { try { NetworkStream ns = this._tcpClient.GetStream(); ns.ReadTimeout = 1000 * 20; if (ns.DataAvailable) { SocketMessager messager = base.Read(ns); if (string.Compare(messager.Action, SocketMessager.SYS_TEST_LINK.Action) == 0) { } else if (this._receives == 0 && string.Compare(messager.Action, SocketMessager.SYS_HELLO_WELCOME.Action) == 0) { this._receives++; this.Write(messager); } else if (string.Compare(messager.Action, SocketMessager.SYS_ACCESS_DENIED.Action) == 0) { throw new Exception(SocketMessager.SYS_ACCESS_DENIED.Action); } else { ClientSocketReceiveEventArgs e = new ClientSocketReceiveEventArgs(this._receives++, messager); SyncReceive receive = null; if (this._receiveHandlers.TryGetValue(messager.Id, out receive)) { new Thread(delegate() { try { receive.ReceiveHandler(this, e); } catch (Exception ex) { this.OnError(ex); } finally { receive.Wait.Set(); } }).Start(); } else if (this.Receive != null) { new Thread(delegate() { this.OnReceive(e); }).Start(); } } this._lastActive = DateTime.Now; } else { TimeSpan ts = DateTime.Now - _lastActive; if (ts.TotalSeconds > 3) { this.Write(SocketMessager.SYS_TEST_LINK); } } if (!ns.DataAvailable) { Thread.CurrentThread.Join(1); } } catch (Exception ex) { this._running = false; this.OnError(ex); } } this.Close(); this.OnClosed(); }); this._thread.Start(); } }
public void Connect(string hostname, int port) { if (this._isDisposed == false && this._running == false) { this._running = true; try { this._tcpClient = new TcpClient(); this._tcpClient.Connect(hostname, port); this._receiveWQ = new WorkQueue(); this._receiveSyncWQ = new WorkQueue(); } catch (Exception ex) { this._running = false; this.OnError(ex); this.OnClosed(); return; } this._receives = 0; this._errors = 0; this._lastActive = DateTime.Now; ManualResetEvent waitWelcome = new ManualResetEvent(false); this._thread = new Thread(delegate() { while (this._running) { try { NetworkStream ns = this._tcpClient.GetStream(); ns.ReadTimeout = 1000 * 20; if (ns.DataAvailable) { SocketMessager messager = base.Read(ns); if (string.Compare(messager.Action, SocketMessager.SYS_TEST_LINK.Action) == 0) { } else if (this._receives == 0 && string.Compare(messager.Action, SocketMessager.SYS_HELLO_WELCOME.Action) == 0) { this._receives++; this.Write(messager); waitWelcome.Set(); } else if (string.Compare(messager.Action, SocketMessager.SYS_ACCESS_DENIED.Action) == 0) { throw new Exception(SocketMessager.SYS_ACCESS_DENIED.Action); } else { ClientSocketReceiveEventArgs e = new ClientSocketReceiveEventArgs(this._receives++, messager); SyncReceive receive = null; if (this._receiveHandlers.TryGetValue(messager.Id, out receive)) { this._receiveSyncWQ.Enqueue(delegate() { try { receive.ReceiveHandler(this, e); } catch (Exception ex) { this.OnError(ex); } finally { receive.Wait.Set(); } }); } else if (this.Receive != null) { this._receiveWQ.Enqueue(delegate() { this.OnReceive(e); }); } } this._lastActive = DateTime.Now; } else { TimeSpan ts = DateTime.Now - _lastActive; if (ts.TotalSeconds > 3) { this.Write(SocketMessager.SYS_TEST_LINK); } } if (!ns.DataAvailable) { Thread.CurrentThread.Join(1); } } catch (Exception ex) { this._running = false; this.OnError(ex); } } this.Close(); this.OnClosed(); try { this._tcpClient.Close(); } catch { } this._tcpClient.Dispose(); this._tcpClient = null; int[] keys = new int[this._receiveHandlers.Count]; try { this._receiveHandlers.Keys.CopyTo(keys, 0); } catch { lock (this._receiveHandlers_lock) { keys = new int[this._receiveHandlers.Count]; this._receiveHandlers.Keys.CopyTo(keys, 0); } } foreach (int key in keys) { SyncReceive receiveHandler = null; if (this._receiveHandlers.TryGetValue(key, out receiveHandler)) { receiveHandler.Wait.Set(); } } lock (this._receiveHandlers_lock) { this._receiveHandlers.Clear(); } if (this._receiveWQ != null) { this._receiveWQ.Dispose(); } if (this._receiveSyncWQ != null) { this._receiveSyncWQ.Dispose(); } if (this._closeWait != null) { this._closeWait.Set(); } }); this._thread.Start(); waitWelcome.Reset(); waitWelcome.WaitOne(TimeSpan.FromSeconds(5)); } }
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(); }
public ServerSocketReceiveEventArgs(int receives, SocketMessager messager, AcceptSocket acceptSocket) { this._receives = receives; this._messager = messager; this._acceptSocket = acceptSocket; }
public ClientSocketReceiveEventArgs(int receives, SocketMessager messager) { this._receives = receives; this._messager = messager; }
public void Write(SocketMessager messager, ServerSocketReceiveEventHandler receiveHandler) { this.Write(messager, receiveHandler, TimeSpan.FromSeconds(20)); }
protected void WriteAsync(Stream stream, SocketMessager messager) { var buffer = this.GetWriteBuffer(messager); stream.WriteAsync(buffer, 0, buffer.Length); }
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(); }
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(); }
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/"); }
public AcceptSocket(ServerSocket server, TcpClient tcpClient, int id) { this._running = true; this._id = id; this._server = server; this._tcpClient = tcpClient; this._lastActive = DateTime.Now; this._thread = new Thread(delegate() { while (this._running) { try { NetworkStream ns = this._tcpClient.GetStream(); ns.ReadTimeout = 1000 * 20; if (ns.DataAvailable) { SocketMessager messager = base.Read(ns); Server.Protocol.debugAppendLog?.Invoke(messager.ToString()); if (string.Compare(messager.Action, SocketMessager.SYS_TEST_LINK.Action) != 0) { ServerSocketReceiveEventArgs e = new ServerSocketReceiveEventArgs(this._receives++, messager, this); SyncReceive receive = null; if (this._receiveHandlers.TryGetValue(messager.Id, out receive)) { new Thread(delegate() { try { receive.ReceiveHandler(this, e); } catch (Exception ex) { this.OnError(ex); } finally { receive.Wait.Set(); } }).Start(); } else { new Thread(delegate() { this.OnReceive(e); }).Start(); } } this._lastActive = DateTime.Now; } else if (_accepted) { TimeSpan ts = DateTime.Now - _lastActive; if (ts.TotalSeconds > 5) { this.Write(SocketMessager.SYS_TEST_LINK); } } if (!ns.DataAvailable) { Thread.CurrentThread.Join(100); } } catch (Exception ex) { this._running = false; this.OnError(ex); } } this.Close(); this.OnClosed(); }); this._thread.Start(); }
protected virtual void OnReceive(object sender, ServerSocketReceiveEventArgs e) { switch (e.Messager.Action) { case "GetDatabases": ClientInfo ci = e.Messager.Arg as ClientInfo; if (ci == null) { e.AcceptSocket.AccessDenied(); } else { CodeBuild build = new CodeBuild(ci, e.AcceptSocket); lock (_builds_lock) { _builds.Remove(e.AcceptSocket.Id); _builds.Add(e.AcceptSocket.Id, build); } List <DatabaseInfo> dbs = build.GetDatabases(); SocketMessager messager = new SocketMessager(e.Messager.Action, dbs); messager.Id = e.Messager.Id; e.AcceptSocket.Write(messager); } break; case "GetTablesByDatabase": string database = string.Concat(e.Messager.Arg); if (string.IsNullOrEmpty(database)) { e.AcceptSocket.AccessDenied(); } else { CodeBuild build = null; if (!_builds.TryGetValue(e.AcceptSocket.Id, out build)) { e.AcceptSocket.AccessDenied(); } else { List <TableInfo> tables = build.GetTablesByDatabase(database); SocketMessager messager = new SocketMessager(e.Messager.Action, tables); messager.Id = e.Messager.Id; e.AcceptSocket.Write(messager); } } break; case "Build": object[] parms = e.Messager.Arg as object[]; if (parms.Length < 4) { e.AcceptSocket.AccessDenied(); } else { string solutionName = string.Concat(parms[0]); bool isSolution, isMakeAdmin, isDownloadRes; string op10 = string.Concat(parms[2]); if (string.IsNullOrEmpty(solutionName) || !bool.TryParse(string.Concat(parms[1]), out isSolution) || string.IsNullOrEmpty(op10)) { e.AcceptSocket.AccessDenied(); } else { isMakeAdmin = false; isDownloadRes = false; if (parms.Length >= 4) { bool.TryParse(string.Concat(parms[3]), out isMakeAdmin); } if (parms.Length >= 5) { bool.TryParse(string.Concat(parms[4]), out isDownloadRes); } CodeBuild build = null; if (!_builds.TryGetValue(e.AcceptSocket.Id, out build)) { e.AcceptSocket.AccessDenied(); } else { List <bool> outputs = new List <bool>(); char[] cs = op10.ToCharArray(); foreach (char c in cs) { outputs.Add(c == '1'); } build.SetOutput(outputs.ToArray()); object parm = null; try { parm = build.Build(solutionName, isSolution, isMakeAdmin, isDownloadRes); } catch (Exception ex) { parm = ex; } SocketMessager messager = new SocketMessager(e.Messager.Action, parm); messager.Id = e.Messager.Id; e.AcceptSocket.Write(messager); } } } break; default: e.AcceptSocket.AccessDenied(); break; } }
public void Write(SocketMessager messager) { this.Write(messager, null, TimeSpan.Zero); }