frmExport.cs
上传用户:lyg_rssy
上传日期:2022-04-14
资源大小:104k
文件大小:28k
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.SqlClient;
- using System.IO;
- using System.Threading;
- namespace HKBU_DataExport
- {
- public partial class frmExportData : Form
- {
- public frmExportData()
- {
- InitializeComponent();
- }
- private static List<Thread> backendThread = new List<Thread>();
- private static List<string> backendThreadName = new List<string>();
- private const string TempFilePath = "";
- private static string GoodlistFileName = "\" + Properties.Settings.Default.Table1 + ".ecp";
- private static string VisitorFileName = "\" + Properties.Settings.Default.Table2 + ".ecp";
- private const string TempFileName = "\Temp.ecp";
- private const string LogFileName = "\Log.txt";
- private const string Key = "P@ssw0rd";
- private StreamWriter UpdateLog = null;
- private bool isTable1Updated = false;
- private bool isTable2Updated = false;
- private string NullValue = "NULL";
- private object updateLock = new object();
- private const string FILE_UPDATE_TABLE = "UpdateTable_log";
- private const string LOG_SEPERATOR = "-----------------------------------------------";
- private const char FileSeperator = 't';
- private delegate void InvokeDelegate(string msg);
- private delegate void setupGVDelegate(DataGridView gvData, string file);
- private void frmExportData_Load(object sender, EventArgs e)
- {
- try
- {
- if (!File.Exists(Properties.Settings.Default.Output_Path))
- {
- Directory.CreateDirectory(Properties.Settings.Default.Output_Path);
- }
- UpdateLog = new StreamWriter(Properties.Settings.Default.Output_Path + LogFileName, true);
- UpdateLog.AutoFlush = true;
- UpdateLog.WriteLine("------------------------------------------------------------------------------------------------------");
- UpdateLog.WriteLine("Application Launched At: " + DateTime.Today.ToString("yyyy/MM/dd HH:mm:ss"));
- UpdateLog.WriteLine ("------------------------------------------------------------------------------------------------------");
- writeLog("System Loading ...");
- txtOutputPath.Text = Properties.Settings.Default.Output_Path;
- txtUpdateHour.Text = Properties.Settings.Default.update_hour.ToString();
- txtUpdateMinute.Text = Properties.Settings.Default.update_minute.ToString();
- txtConnectionString.Text = Properties.Settings.Default.ConnectionString;
- txtTable1.Text = Properties.Settings.Default.Table1;
- txtTable2.Text = Properties.Settings.Default.Table2;
- btnTable1.Text = Properties.Settings.Default.Table1;
- btnTable2.Text = Properties.Settings.Default.Table2;
- writeLog("Initialize Completed");
- }
- catch (Exception ex)
- {
- MessageBox.Show("Initialize System Failed, Error Message: " + ex.ToString());
- }
- }
- private void setupGridView(DataGridView gvData,string table)
- {
- if (this.InvokeRequired)
- {
- this.Invoke(new setupGVDelegate(setupGridView),gvData,table);
- }
- else
- {
- try
- {
- using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.ConnectionString))
- {
- string command = "Select * from " + table;
- using (SqlDataAdapter sda = new SqlDataAdapter(command, conn))
- {
- DataSet ds = new DataSet();
- sda.Fill(ds);
- gvData.DataSource = ds.Tables[0];
- }
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("Open Data Table Failed, Error Message: " + ex.ToString(), "Error", MessageBoxButtons.OK);
- writeLog("Open Data Table Failed, Error Message: " + ex.ToString());
- }
- }
- }
- private void btnSave_Click(object sender, EventArgs e)
- {
- writeLog("------------------------------------------------");
- try
- {
- this.Cursor = Cursors.WaitCursor;
- SaveFileDialog saveFileDialog = new SaveFileDialog();
- saveFileDialog.Filter = "Encrypted files (*.ecp)|*.ecp|Excel files (*.xls)|*.xls|Comma Separated Value File(*.csv)|*.csv|Microsoft SQL Server Query File(*.sql)|*.sql";
- saveFileDialog.FilterIndex = 0;
- saveFileDialog.RestoreDirectory = true;
- saveFileDialog.CreatePrompt = true;
- saveFileDialog.Title = "Export File To";
- string filePath = "";
- string msg;
- if (saveFileDialog.ShowDialog() == DialogResult.OK)
- {
- filePath = saveFileDialog.FileName;
- writeLog("Saving file as: " + filePath);
- string tempPath = Properties.Settings.Default.Output_Path + TempFileName;
- string extension = filePath.Split('.').Last().ToLower();
- switch(extension)
- {
- case "sql":
- SaveAs(gvDataView, tempPath, FileSeperator);
- generateSqlFile(filePath,tempPath,btnTable1.Enabled?btnTable2.Text.Trim():btnTable1.Text.Trim());
- break;
- case "ecp":
- SaveAs(gvDataView, tempPath, FileSeperator);
- if (EncryptFunction.EncryptFile(tempPath, filePath, Key, out msg))
- try
- {
- File.Delete(tempPath);
- }
- catch { }
- break;
- case "csv":
- SaveAs(gvDataView, filePath, ',');
- break;
- case "xls":
- SaveAs(gvDataView, filePath,FileSeperator);
- break;
- }
- System.Windows.Forms.MessageBox.Show("File Saved", "Message", MessageBoxButtons.OK);
- writeLog("File Saved");
- }
- this.Cursor = Cursors.Default;
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show("Error occured, Error Message: n" + ex.ToString(), "Message", MessageBoxButtons.OK);
- writeLog("Error occured, Error Message: n" + ex.ToString());
- this.Cursor = Cursors.Default;
- }
- }
- /// <summary>
- /// 另存新档按钮
- /// </summary>
- private void SaveAs(DataGridView gvData,string fileName,char seperator) //另存新档按钮 导出成CSV
- {
- Stream myStream;
- myStream = File.Open(fileName, FileMode.Create);
- StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.UTF8);
- string str = "";
- try
- {
- //写标题
- for (int i = 0; i < gvData.ColumnCount; i++)
- {
- if (i > 0)
- {
- str += seperator;
- }
- str += gvData.Columns[i].HeaderText;
- }
- sw.WriteLine(str);
- for (int j = 0; j < gvData.Rows.Count; j++)
- {
- string tempStr = "";
- for (int k = 0; k < gvData.Columns.Count; k++)
- {
- if (k > 0)
- {
- tempStr += seperator;
- }
- if (gvData.Rows[j].Cells[k].Value == gvData.DefaultCellStyle.NullValue || gvData.Rows[j].Cells[k].Value == DBNull.Value)
- {
- tempStr += NullValue;
- }
- else if (gvData.Rows[j].Cells[k].ValueType.Name.ToLower().CompareTo("datetime") == 0)
- {
- tempStr += Convert.ToDateTime(gvData.Rows[j].Cells[k].Value).ToString("yyyy-MM-dd HH:mm:ss");
- }
- else
- {
- tempStr += gvData.Rows[j].Cells[k].Value.ToString();
- }
- }
- sw.WriteLine(tempStr);
- }
- sw.Close();
- myStream.Close();
- }
- catch (Exception e)
- {
- MessageBox.Show(e.ToString());
- writeLog("Export File Error, Error Message: " + e.ToString());
- }
- finally
- {
- sw.Close();
- myStream.Close();
- }
- }
- private void btnOutputPath_Click(object sender, EventArgs e)
- {
- FolderBrowserDialog fbdOutputPath = new FolderBrowserDialog();
- fbdOutputPath.RootFolder = Environment.SpecialFolder.Desktop;
- if (fbdOutputPath.ShowDialog() == DialogResult.OK)
- {
- txtOutputPath.Text = fbdOutputPath.SelectedPath;
- }
- }
- private void changeOutputPath(string origin_path, string new_path)
- {
- string msg = "";
- writeLog("Changing OutputPath...");
- writeLog("Moving Log File to New Output Floder...");
- UpdateLog.Close();
- if (EncryptFunction.EncryptFile(origin_path + LogFileName, origin_path + TempFileName, Key, out msg))
- {
- if (EncryptFunction.DecryptFile(origin_path + TempFileName, new_path + LogFileName, Key, out msg))
- {
- Properties.Settings.Default.Output_Path = new_path;
- UpdateLog = new StreamWriter(Properties.Settings.Default.Output_Path + LogFileName, true);
- UpdateLog.AutoFlush = true;
- try
- {
- File.Delete(origin_path + LogFileName);
- }
- catch { }
- writeLog("Output Path Changed");
- }
- else
- {
- Properties.Settings.Default.Output_Path = origin_path;
- UpdateLog = new StreamWriter(Properties.Settings.Default.Output_Path + LogFileName, true);
- UpdateLog.AutoFlush = true;
- writeLog("Change Output Path Failed, Error Message: " + msg);
- return;
- }
- }
- else
- {
- Properties.Settings.Default.Output_Path = origin_path;
- UpdateLog = new StreamWriter(Properties.Settings.Default.Output_Path + LogFileName, true);
- UpdateLog.AutoFlush = true;
- writeLog("Change Output Path Failed, Error Message: " + msg);
- }
- try
- {
- File.Delete(origin_path + TempFileName);
- }
- catch(Exception ex)
- { }
- }
- private void btnSaveSetting_Click(object sender, EventArgs e)
- {
- try
- {
- writeLog("------------------------------------------------");
- writeLog("Modifying System Setting");
- writeLog("Original Output Path: " + Properties.Settings.Default.Output_Path);
- writeLog("Original Update Time: " + Properties.Settings.Default.update_hour + " : " + Properties.Settings.Default.update_minute);
- writeLog("Original Connection String: " + Properties.Settings.Default.ConnectionString);
- writeLog("Original Table 1: " + Properties.Settings.Default.Table1);
- writeLog("Original Table 2: " + Properties.Settings.Default.Table2);
- changeOutputPath(Properties.Settings.Default.Output_Path, txtOutputPath.Text);
- Properties.Settings.Default.update_hour = Int32.Parse(txtUpdateHour.Text);
- Properties.Settings.Default.update_minute = Int32.Parse(txtUpdateMinute.Text);
- Properties.Settings.Default.ConnectionString = txtConnectionString.Text;
- Properties.Settings.Default.Table1 = txtTable1.Text;
- Properties.Settings.Default.Table2 = txtTable2.Text;
- btnTable1.Text = txtTable1.Text;
- btnTable2.Text = txtTable2.Text;
- System.Windows.Forms.MessageBox.Show("System Setting Saved", "Message", MessageBoxButtons.OK);
- writeLog("System Setting Modified");
- writeLog("Current Output Path: " + txtOutputPath.Text);
- writeLog("Current Update Time: " + txtUpdateHour.Text + " : " + txtUpdateMinute.Text);
- writeLog("Current Connection String: " + txtConnectionString.Text);
- writeLog("Current Table 1: " + txtTable1.Text);
- writeLog("Current Table 2: " + txtTable2.Text);
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show("Error occured, Error Message: n" + ex.ToString(), "Message", MessageBoxButtons.OK);
- writeLog("Error occured, Error Message: n" + ex.ToString());
- writeLog("Original Output Path: " + Properties.Settings.Default.Output_Path);
- writeLog("Original Update Time: " + Properties.Settings.Default.update_hour + " : " + Properties.Settings.Default.update_minute);
- writeLog("Original Connection String: " + Properties.Settings.Default.ConnectionString);
- writeLog("Original Table 1: " + Properties.Settings.Default.Table1);
- writeLog("Original Table 2: " + Properties.Settings.Default.Table2);
- }
- finally
- {
- resetManualPanel();
- }
- }
- private void exportGoodlist()
- {
- try
- {
- this.Cursor = Cursors.WaitCursor;
- if (!isTable1Updated)
- {
- writeLog("------------------------------------------------");
- writeLog("Exproting Data Table: [" + Properties.Settings.Default.Table1 + "]");
- string inputfilePath = Properties.Settings.Default.Output_Path + TempFilePath;
- if (!File.Exists(inputfilePath)) Directory.CreateDirectory(inputfilePath);
- string outputfilePath = Properties.Settings.Default.Output_Path;
- if (!File.Exists(outputfilePath)) Directory.CreateDirectory(outputfilePath);
- inputfilePath += TempFileName;
- outputfilePath += GoodlistFileName;
- string msg = "";
- setupGridView(gvGoodlist, Properties.Settings.Default.Table1);
- SaveAs(gvGoodlist, inputfilePath, FileSeperator);
- this.Cursor = Cursors.WaitCursor;
- if (EncryptFunction.EncryptFile(inputfilePath, outputfilePath, Key, out msg))
- {
- writeLog("Data Table: [" + Properties.Settings.Default.Table1 + "] Exported");
- isTable1Updated = true;
- }
- else
- {
- writeLog("Error occured, Error Message: " + msg);
- }
- try
- {
- File.Delete(inputfilePath);
- }
- catch { }
- }
- }
- catch
- {
- isTable1Updated = false;
- }
- this.Cursor = Cursors.Default;
- }
- private void exportVisitor()
- {
- try
- {
- this.Cursor = Cursors.WaitCursor;
- if (!isTable2Updated)
- {
- writeLog("------------------------------------------------");
- writeLog("Exproting Data Table: [" + Properties.Settings.Default.Table2 + "]");
- string inputfilePath = Properties.Settings.Default.Output_Path + TempFilePath;
- if (!File.Exists(inputfilePath)) Directory.CreateDirectory(inputfilePath);
- string outputfilePath = Properties.Settings.Default.Output_Path;
- if (!File.Exists(outputfilePath)) Directory.CreateDirectory(outputfilePath);
- inputfilePath += TempFileName;
- outputfilePath += VisitorFileName;
- string msg = "";
- setupGridView(gvVisitor, Properties.Settings.Default.Table2);
- SaveAs(gvVisitor, inputfilePath, FileSeperator);
- this.Cursor = Cursors.WaitCursor;
- if (EncryptFunction.EncryptFile(inputfilePath, outputfilePath, Key, out msg))
- {
- writeLog("Data Table: [" + Properties.Settings.Default.Table2 + "] Exported");
- isTable2Updated = true;
- }
- else
- {
- writeLog("Error occured, Error Message: " + msg);
- }
- try
- {
- File.Delete(inputfilePath);
- }
- catch { }
- }
- }
- catch
- {
- isTable2Updated = false;
- }
- this.Cursor = Cursors.Default;
- }
- private void btnStart_Click(object sender, EventArgs e)
- {
- writeLog("------------------------------------------------");
- writeLog("Launching Update Threads...");
- Thread tdExportTable = new Thread(ExportTableInSchedule);
- tdExportTable.Start();
- writeLog("Update Thread Started");
- backendThread.Insert(0,tdExportTable);
- backendThreadName.Insert(0,"ExportTable");
- btnStart.Enabled = false;
- btnStop.Enabled = true;
- writeLog("Update Threads Launched");
- }
- private void btnStop_Click(object sender, EventArgs e)
- {
- writeLog("------------------------------------------------");
- writeLog("Aborting Update Threads...");
- foreach (Thread td in backendThread)
- {
- td.Abort();
- }
- backendThread.Clear();
- backendThreadName.Clear();
- btnStart.Enabled = true;
- btnStop.Enabled = false;
- writeLog("All Thread Aborted");
- }
- private void btnTable2_Click(object sender, EventArgs e)
- {
- writeLog("------------------------------------------------");
- writeLog("Opening Data Table [" + Properties.Settings.Default.Table2 + "] ...");
- this.Cursor = Cursors.WaitCursor;
- btnTable1.Enabled = true;
- btnTable2.Enabled = false;
- btnSave.Enabled = true;
- setupGridView(gvDataView, Properties.Settings.Default.Table2);
- writeLog("Data Table [" + Properties.Settings.Default.Table2 + "] Opened");
- }
- private void btnTable1_Click(object sender, EventArgs e)
- {
- writeLog("------------------------------------------------");
- writeLog("Opening Data Table [" + Properties.Settings.Default.Table1 + "] ...");
- this.Cursor = Cursors.WaitCursor;
- btnTable1.Enabled = false;
- btnTable2.Enabled = true;
- btnSave.Enabled = true;
- setupGridView(gvDataView,Properties.Settings.Default.Table1);
- writeLog("Data Table [" + Properties.Settings.Default.Table1 + "] Opened");
- }
- private void writeLog(string msg)
- {
- if (this.InvokeRequired)
- {
- this.Invoke(new InvokeDelegate(writeLog), msg);
- }
- else
- {
- txtMessage.AppendText("[ " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]:t" + msg + "n");
- txtMessage.ScrollToCaret();
- UpdateLog.WriteLine("[ " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]:t" + msg );
- }
- }
- private void btnKey_Click(object sender, EventArgs e)
- {
- writeLog("------------------------------------------------");
- if (btnKey.Text.Trim().CompareTo("Confirm") == 0)
- {
- if (txtKey.Text.Trim().CompareTo(Key) == 0)
- {
- plManual.Enabled = true;
- plSetting.Enabled = true;
- btnKey.Text = "Lock";
- txtKey.Enabled = false;
- System.Windows.Forms.MessageBox.Show("Administrator Control Unlocked", "Message", MessageBoxButtons.OK);
- writeLog("Access Administrator Control Mode");
- }
- else
- {
- System.Windows.Forms.MessageBox.Show("Access Administrator Control Mode Failed, Please Check Key.", "Message", MessageBoxButtons.OK);
- writeLog("Access Administrator Control Mode Faile");
- }
- }
- else
- {
- resetManualPanel();
- plManual.Enabled = false;
- plSetting.Enabled = false;
- txtKey.Enabled = true;
- txtKey.Text = "";
- btnKey.Text = "Confirm";
- System.Windows.Forms.MessageBox.Show("Administrator Control Locked", "Message", MessageBoxButtons.OK);
- writeLog("Lock Administrator Control Mode");
- }
- }
- private void resetManualPanel()
- {
- gvDataView.DataSource = null;
- btnTable1.Enabled = true;
- btnTable2.Enabled = true;
- btnSave.Enabled = false;
- }
- private void DataView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
- {
- this.Cursor = Cursors.Default;
- }
- private void frmExportData_FormClosing(object sender, FormClosingEventArgs e)
- {
- if (MessageBox.Show("Are you sure to Exit?", "Message", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
- {
- e.Cancel = true;
- }
- else
- {
- try
- {
- File.Delete(Properties.Settings.Default.Output_Path + TempFileName);
- }
- catch { }
- UpdateLog.WriteLine("------------------------------------------------------------------------------------------------------");
- UpdateLog.WriteLine("Application Aborted At: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
- UpdateLog.WriteLine("------------------------------------------------------------------------------------------------------");
- UpdateLog.Close();
- }
- }
- private void ExportTableInSchedule()
- {
- while (true)
- {
- if (DateTime.Now.Hour == Properties.Settings.Default.update_hour && DateTime.Now.Minute == Properties.Settings.Default.update_minute)
- {
- exportGoodlist();
- exportVisitor();
- }
- else
- {
- isTable1Updated = false;
- isTable2Updated = false;
- Thread.Sleep(Properties.Settings.Default.update_frequency * 1000);
- }
- }
- }
- private void btnExportAtOnce_Click(object sender, EventArgs e)
- {
- btnExportAtOnce.Enabled = false;
- exportGoodlist();
- exportVisitor();
- isTable1Updated = false;
- isTable2Updated = false;
- MessageBox.Show("Operation Completed", "Message", MessageBoxButtons.OK);
- btnExportAtOnce.Enabled = true;
- }
- public bool generateSqlFile(string outFilePath, string inFilePath, string tableName)
- {
- int successRecord = 0;
- int failRecord = 0;
- string inputPath = inFilePath;
- StreamReader inputFile = new StreamReader(inputPath, System.Text.Encoding.UTF8);
- StreamWriter updatelog = new StreamWriter(outFilePath,false,System.Text.Encoding.Unicode);
- try
- {
- string tempLine = inputFile.ReadLine(); // skip header(first line)
- string[] values;
- string tempCmd = "";
- int i = 0;
- values = Properties.Settings.Default.ConnectionString.Split(';');
- values = values[1].Split('=');
- tempCmd = "USE [" + values[1].Trim() + "]";
- WriteLine(updatelog, tempCmd);
- WriteLine(updatelog, "GO");
- while (!inputFile.EndOfStream)
- {
- tempLine = inputFile.ReadLine();
- values = tempLine.Split(FileSeperator);
- tempCmd = "Insert into [" + tableName + "] Values (";
- for (i = 0; i < values.Count() - 1; i++)
- {
- if (values[i].CompareTo(NullValue) == 0)
- {
- tempCmd += "NULL,";
- }
- else
- {
- tempCmd += "'" + values[i].Replace("'", "''") + "', ";
- }
- }
- if (values[i].CompareTo(NullValue) == 0)
- {
- tempCmd += "NULL)";
- }
- else
- {
- tempCmd += "'" + values[i].Replace("'", "''") + "')";
- }
- WriteLine(updatelog, tempCmd);
- }
- WriteLine(updatelog, "--" + LOG_SEPERATOR);
- WriteLine(updatelog, "--Finish Updating At: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
- WriteLine(updatelog, "--Total Updated Records: " + (successRecord + failRecord).ToString());
- WriteLine(updatelog, "--Successed Records: " + (successRecord).ToString());
- WriteLine(updatelog, "--Failed Records: " + (failRecord).ToString());
- inputFile.Close();
- File.Delete(inputPath);
- updatelog.Flush();
- updatelog.Close();
- return true;
- }
- catch (Exception ex)
- {
- WriteLine(updatelog, "--" + LOG_SEPERATOR);
- WriteLine(updatelog, "--Error Occured, Error Message: " + ex.ToString());
- inputFile.Close();
- File.Delete(inputPath);
- return false;
- }
- }
- private void WriteLine(StreamWriter updatelog,string msg)
- {
- updatelog.WriteLine(msg);
- }
- }
- }