yz_server/Server/Winforms/InitMysqlForm.cs

361 lines
14 KiB
C#
Raw Normal View History

2022-04-16 07:48:12 +00:00
using ICSharpCode.SharpZipLib.Zip;
using Server.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server.Winforms
{
internal partial class InitMysqlForm : DefaultForm
{
Client Client;
public InitMysqlForm(Client Client)
{
InitializeComponent();
this.Client = Client;
}
private void InitMysqlForm_Load(object sender, EventArgs e)
{
}
private void SetStatusText(string text)
{
if (!this.IsDisposed)
{
this.Invoke(new Action(delegate ()
{
this.tool_status.Text = text;
}));
}
}
public void DownloadFile(string URL, string filename, ProgressBar prog = null)
{
float percent = 0;
if (File.Exists(filename)) File.Delete(filename);
Stream st = null;
Stream so = null;
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
prog?.Invoke(new Action(delegate
{
prog.Value = 0;
prog.Maximum = (int)totalBytes;
}));
st = myrp.GetResponseStream();
so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
try
{
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
Application.DoEvents();
so.Write(by, 0, osize);
prog?.Invoke(new Action(delegate { prog.Value = (int)totalDownloadedByte; }));
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
if (prog != null) Application.DoEvents(); //必须加注这句代码否则label1将因为循环执行太快而来不及显示信息
}
}
catch (Exception ex)
{
if (File.Exists(filename)) File.Delete(filename);
if (so != null)
{
so.Close();
so.Dispose();
so = null;
}
if (st != null)
{
st.Close();
st.Dispose();
st = null;
}
throw ex;
}
finally
{
if (so != null)
{
so.Close();
so.Dispose();
so = null;
}
if (st != null)
{
st.Close();
st.Dispose();
st = null;
}
}
}
/// <summary>
/// 功能解压zip格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <param name="err">出错信息</param>
/// <returns>解压是否成功</returns>
public void UnZip(string zipFilePath, string unZipDir)
{
try
{
if (zipFilePath == string.Empty)
{
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath))
{
throw new System.IO.FileNotFoundException("压缩文件不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath),
Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("/"))
unZipDir += "/";
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName.Length > 0)
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (!directoryName.EndsWith("/"))
directoryName += "/";
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
int size = 1024 * 10;
byte[] data = new byte[size];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
//如果解压失败,删除掉. 刚刚解压的内容
DeletePath(unZipDir);
throw ex;
}
}
//创建方法,删除文件夹中的所有文件包括文件夹本身
public void DeletePath(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
}
else
{
//循环递归删除子文件夹
DeletePath(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
}
catch (Exception)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
this.button1.Enabled = false;
Task.Factory.StartNew(delegate ()
{
try
{
var mysql_name = textBox1.Text.Trim().ToLower();
var mysql_port = (int)numericUpDown1.Value;
var mysql_user = textBox2.Text.Trim();
var mysql_pass = textBox3.Text.Trim();
var mysql_host = textBox4.Text.Trim();
SetStatusText("正在检测...");
if (this.radioButton1.Checked)
{
var ServerName = "mysql8.0";
var Server = ServiceInstaller.GetServiceController(ServerName);
if (Server == null)
{
var mysqlPath = @"C:\mysql8.0";
//确认没有解压文件
if (!System.IO.Directory.Exists(mysqlPath))
{
//找到压缩包
var mysqlFile = CsharpHttpHelper.HttpExtend.MapFile("mysql8.0.zip", "File");
if (!File.Exists(mysqlFile))
{
SetStatusText("正在下载mysql8.0安装包...");
DownloadFile("http://qiniu.down.api.52cmg.cn/mysql8.0.zip", mysqlFile);
}
if (!File.Exists(mysqlFile)) throw new Exception("找不到mysql8.0的安装包");
SetStatusText("正在安装mysql8.0...");
UnZip(mysqlFile, mysqlPath);
}
Thread.Sleep(1000);
ServiceInstaller.InitServer(@"C:\mysql8.0\bin\mysqld", ServerName);
Server = ServiceInstaller.GetServiceController(ServerName);
int index = 0;
while (index < 30 && Server == null)
{
index++;
System.Threading.Thread.Sleep(1000);
Server = ServiceInstaller.GetServiceController(ServerName);
}
}
if (Server == null)
{
throw new Exception("安装失败,请联系客服人员处理");
}
else if (Server.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
SetStatusText("MySQL 8.0 环境监测通过!");
}
else
{
Server.Start();
SetStatusText("MySQL 8.0 环境监测通过!");
}
mysql_name = "fanli_v2";
mysql_user = "root";
mysql_pass = "123456";
mysql_port = 3306;
mysql_host = "127.0.0.1";
}
else
{
if (string.IsNullOrEmpty(mysql_name)) mysql_name = "fanli_v2";
}
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = $"Data Source={mysql_host};Persist Security Info=True;User ID={mysql_user};Password={mysql_pass};Port={mysql_port};Min Pool Size = 1; Max Pool Size = 1;Charset=utf8mb4;",//连接符字串
DbType = SqlSugar.DbType.MySql, //数据库类型
IsAutoCloseConnection = true //不设成true要手动close
});
var DbList = db.DbMaintenance.GetDataBaseList(db);
if (!DbList.Contains(mysql_name))
{
// COLLATE utf8mb4_general_ci
if (db.Ado.ExecuteCommand($"CREATE DATABASE {mysql_name} DEFAULT CHARACTER SET utf8mb4 ;") == 0)
{
throw new Exception("自动创建数据库失败!");
}
}
Client.Config.Ini.SetValue("Mysql", "名称", mysql_name);
Client.Config.Ini.SetValue("Mysql", "账号", mysql_user);
Client.Config.Ini.SetValue("Mysql", "密码", mysql_pass);
Client.Config.Ini.SetValue("Mysql", "IP", mysql_host);
Client.Config.Ini.SetValue("Mysql", "端口", mysql_port.ToString());
Client.Config.MysqlPort = mysql_port;
Client.Config.MysqlPass = mysql_pass;
Client.Config.MysqlName = mysql_name;
Client.Config.MysqlHost = mysql_host;
Client.Config.MysqlUser = mysql_user;
this.Invoke(new Action(delegate
{
this.DialogResult = DialogResult.Yes;
this.Close();
}));
}
catch (Exception ex)
{
this.Invoke(new Action(delegate ()
{
this.tool_status.Text = ex.Message;
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}));
}
finally
{
//if (this.IsAccessible)
{
this.Invoke(new Action(delegate
{
this.button1.Enabled = true;
}));
}
}
});
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
groupBox2.Enabled = radioButton2.Checked;
}
}
}