trayToDB/trayToDB/MainWindow.cs

277 lines
11 KiB
C#

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
/*
* Author: David Baranyai | 2019.03.13
* divaldo95@gmail.com
*/
namespace trayToDB
{
struct SiPMData
{
public int trayNo;
public double Vopl;
public double Voph;
public int noOfSipm;
public string GetValues()
{
return "Tray number: " + trayNo + "\nVop: " + Vopl + " - " + Voph + "\nNumber of SiPM: " + noOfSipm + "\n";
}
};
public partial class MainWindow : Form
{
private List<SiPMData> listOfData;
private DateTime shippingDate;
private static string server = "localhost";
private static string user = "sipm";
private static string database = "sipmtest";
private static string port = "3306";
//private static string password = "";
public MainWindow()
{
InitializeComponent();
uploadButton.Enabled = false;
//Set the file extensions to xls and xlsx and turn on warnings if the file not exists
openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Excel sheets (*.xls;*.xlsx)|*.xls;*.xlsx";
openFileDialog1.Multiselect = false;
openFileDialog1.CheckFileExists = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void browseButton_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filenameTextbox.Text = openFileDialog1.FileName;
try
{
xlWorkBook = xlApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range currentFind = xlWorkSheet.UsedRange;
//Find cell that contains "Shipping date" and extract the value next to it
Excel.Range tempRange = currentFind.Find("Shipping date", LookAt: Excel.XlLookAt.xlWhole);
if(tempRange == null)
{
throw new Exception("Not found any cells that contains 'Shipping date'. Maybe the file structure is changed\n");
}
int shipdateRow = tempRange.Row;
int shipdateColumn = tempRange.Column;
shippingDate = DateTime.FromOADate(currentFind.Cells[shipdateRow, shipdateColumn + 1].Value2);
//Print out the date
statusTextbox.AppendText("Shipping date: " + shippingDate.ToLongDateString() + "\n");
/*Find cell that contains "Tray No."
*In the first version the structure is the following:
* Tray no | Vop range | Quantum
*/
tempRange = currentFind.Find("Tray No.", LookAt: Excel.XlLookAt.xlWhole);
if (tempRange == null)
{
throw new Exception("Not found any cells that contains 'Tray No.'. Maybe the file structure is changed\n");
}
int trayNoRow = tempRange.Row;
int trayNoColumn = tempRange.Column;
int iterator = trayNoRow + 1; //the iterator starts from the next row
listOfData = new List<SiPMData>(); //make a list from every row
SiPMData data = new SiPMData(); //Helper for inserting into the list
//Read every row until found an empty one
while (currentFind.Cells[iterator, trayNoColumn].Value2 != null)
{
data.trayNo = Convert.ToInt16(currentFind.Cells[iterator, trayNoColumn].Value2); //Get tray number
string Vop = currentFind.Cells[iterator, trayNoColumn + 1].Value2.ToString(); //Get Vops
//Split the Vops into low and high
//Use dot as decimal point
CultureInfo culture = new CultureInfo("en");
string[] splittedString = Vop.Split('-');
if(splittedString.Length == 2)
{
data.Vopl = Double.Parse(splittedString[0], culture);
data.Voph = Double.Parse(splittedString[1], culture);
}
else
{
throw new Exception("Invalid Vop format!");
}
//double[] doubles = Vop.Split('-').Select(double.Parse).ToArray();
/*if(doubles.Length == 2)
{
data.Vopl = doubles[0];
data.Voph = doubles[1];
}
*/
data.noOfSipm = Convert.ToInt16(currentFind.Cells[iterator, trayNoColumn + 2].Value2); //Get number of sipms
statusTextbox.AppendText(data.GetValues()); //Write the data to the status textbox
listOfData.Add(data); //add every row into the list
iterator++; //increment the row iterator
}
//Close the excel related things
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
uploadButton.Enabled = true;
}
catch(Exception ex)
{
statusTextbox.AppendText(ex.Message);
uploadButton.Enabled = false;
}
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void uploadButton_Click(object sender, EventArgs e)
{
string connStr = "server=" + Properties.Settings.Default.server + "; user=" + Properties.Settings.Default.user + "; database=" + Properties.Settings.Default.database + "; port=" + Properties.Settings.Default.port + "; password=" + Settings.Decrypt(Properties.Settings.Default.password);
//"server=" + server + "; user=" + user + "; database=" + database + "; port=" + port + "; password=";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
statusTextbox.AppendText("Connecting to " + user + "@" + server + ":" + port + "\n");
conn.Open();
statusTextbox.AppendText("Successfully connected\n");
// Perform database operations
MySqlCommand cmd = conn.CreateCommand();
//Check if row already exists
cmd.CommandText = "SELECT COUNT(*) AS numofshippingid FROM hamamatsushippingtable WHERE shipdate = convert(@shipping, DATE) AND arrivedate = convert(@arrival,DATE);";
cmd.Parameters.AddWithValue("@arrival", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("@shipping", shippingDate);
cmd.Parameters.AddWithValue("@numoftrays", listOfData.Count);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
if(reader.GetInt16("numofshippingid") != 0)
{
throw new Exception("Database contains data with the same dates, check it!");
}
else
{
statusTextbox.AppendText("Adding new shipping id!\n");
reader.Close();
}
}
else
{
throw new Exception("Query error!");
}
cmd.CommandText = "INSERT INTO hamamatsushippingtable (arrivedate, shipdate, ntrays) VALUES (@arrival, @shipping, @numoftrays)";
if (cmd.ExecuteNonQuery() == 1) //Affected rows should be one
{
statusTextbox.AppendText("Succesfully inserted the tray's data\n");
}
else
{
statusTextbox.AppendText("Something went wrong!");
}
for (int i = 0; i < listOfData.Count; i++)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO hamamatsutraytable (shippingid, traynumber, vlow, vhigh, nsipms) VALUES ((SELECT MAX(shippingid) AS shippingid FROM hamamatsushippingtable), @trayno, @vl, @vh, @noofsipm)";
cmd.Parameters.AddWithValue("@trayno", listOfData[i].trayNo);
cmd.Parameters.AddWithValue("@vl", listOfData[i].Vopl);
cmd.Parameters.AddWithValue("@vh", listOfData[i].Voph);
cmd.Parameters.AddWithValue("@noofsipm", listOfData[i].noOfSipm);
if (cmd.ExecuteNonQuery() == 1)
{
statusTextbox.AppendText("Succesfully inserted! Tray ID: " + listOfData[i].trayNo + "\n");
}
else
{
statusTextbox.AppendText("Something went wrong!");
}
}
conn.Close();
uploadButton.Enabled = false;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
//MessageBox.Show("Cannot connect to server. Contact administrator");
MessageBox.Show(ex.ToString());
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
}
catch (Exception ex)
{
statusTextbox.AppendText(ex.Message);
}
}
private void statusTextbox_TextChanged(object sender, EventArgs e)
{
statusTextbox.ScrollToCaret();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
Settings settings = new Settings();
settings.Show();
}
}
}