Ejemplo n.º 1
0
        /// <summary>
        /// Mëtodo que devuelve una lista de tiempos almacenados en la BD.
        /// </summary>
        /// <param name="proyect"></param>
        /// <param name="var"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public List <float> GetTime(Proyect proyect, int amount)
        {
            using (SqlConnection con = new SqlConnection(@"Server = localhost\sqlexpress; Database=" + GlobalParameters.DBName + ";Integrated Security = True;"))
            {
                List <float> result = new List <float>();
                try
                {
                    // Open the SqlConnection.
                    con.Open();

                    if (CheckDBExists(proyect))
                    {
                        using (SqlCommand command = new SqlCommand("SELECT TOP " + amount + "[Time] " +
                                                                   "FROM [" + GlobalParameters.DBName + "].[dbo].[" + proyect.Name + "] ORDER BY ID DESC ", con))
                        {
                            SqlDataReader columnsDataReader = command.ExecuteReader();
                            while (columnsDataReader.Read())
                            {
                                result.Add(float.Parse(String.Format("{0}", columnsDataReader[0])));
                            }
                        }
                    }
                    return(result);
                }
                catch (Exception ex)
                {
                    _exMg.HandleException(ex);
                    return(result);
                }
                finally
                {
                    CloseConnection(con);
                }
            }
        }
Ejemplo n.º 2
0
        public MainForm()
        {
            InitializeComponent();

            toolStripMenuItemSpanish.Checked = true;
            toolStripMenuItemEnglish.Checked = false;//default language is spanish
            _res_man     = new ResourceManager("PlantaPiloto.Resources.Res", typeof(MainForm).Assembly);
            _proyect     = new Proyect();
            _variable    = new Variable();
            _db_services = new DB_services(_cul);
            Switch_language();
            _timerRefreshDataGrid          = new System.Timers.Timer(2000);
            _timerRefreshDataGrid.Enabled  = false;
            _timerRefreshDataGrid.Elapsed += this.TimerElapsedEvent;
            _timerSaveFile                 = new System.Timers.Timer(2000);
            _timerSaveFile.Enabled         = false;
            _timerSaveFile.Elapsed        += this.TimerSaveFile;
            dgvProVars.Columns[0].ReadOnly = true;
            dgvProVars.Columns[1].ReadOnly = true;
            _helpProvider = new HelpProvider();
            _configsPath  = GlobalParameters.ConfigsPath;
            _filesPath    = GlobalParameters.FilesPath;
            _helpProvider.HelpNamespace = Path.Combine(_filesPath, "helpProyect.chm");
            _pdfPath   = Path.Combine(_filesPath, "Manual_Usuario.pdf");
            _exMg      = new ExceptionManagement(_cul);
            _fileSaver = new FileSaver();
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Método que actualiza la columna del dataGrid que contiene los valores actuales que recibe de la placa
 /// </summary>
 /// <param name="rows">Proyecto que guarda todas las variables con su último valor</param>
 private void FillDataGridView(Proyect rows)
 {
     try
     {
         if (this.dgvProVars.InvokeRequired)
         {
             //Para evitar concurrencia se llama a un delegado puesto que los datos se han obtenido en otro hilo
             StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(FillDataGridView);
             this.Invoke(d, new object[] { rows });
         }
         else
         {
             for (int j = 0; j < dgvProVars.Rows.Count; j++)
             {
                 for (int i = 0; i < rows.Variables.Count; i++)
                 {
                     if (dgvProVars[0, j].Value.ToString() == rows.Variables[i].Name)
                     {
                         dgvProVars[1, j].Value = rows.Variables[i].Value;
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         _exMg.HandleException(ex);
     }
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Evento que lee un archivo en el que está guardada una configuración y la carga al programa.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void toolStripMenuItemLoadConfig_Click(object sender, EventArgs e)
 {
     CloseSP_services();
     if (!Directory.Exists(_configsPath))
     {
         Directory.CreateDirectory(_configsPath);
     }
     openFileDialog1.InitialDirectory = _configsPath;
     openFileDialog1.Filter           = _res_man.GetString("showDialogFilter", _cul);
     openFileDialog1.Title            = _res_man.GetString("showDialogTitle", _cul);
     openFileDialog1.FileName         = "";
     if (openFileDialog1.ShowDialog() == DialogResult.OK)
     {
         try
         {
             StreamReader sr = new StreamReader(openFileDialog1.FileName);
             _proyect = new Proyect();
             sr.ReadLine();
             _proyect.Name        = sr.ReadLine();
             _proyect.Description = sr.ReadLine();
             _proyect.ImagePath   = sr.ReadLine();
             do
             {
                 if (sr.ReadLine() == "****************************************")
                 {
                     _variable = new Variable();
                     string fL = sr.ReadLine();
                     if (fL == "****************************************")
                     {
                         break;
                     }
                     _variable.Name        = fL;
                     _variable.Type        = (EnumVarType)Enum.Parse(typeof(EnumVarType), sr.ReadLine());
                     _variable.Description = sr.ReadLine();
                     _variable.Access      = (EnumVarAccess)Enum.Parse(typeof(EnumVarAccess), sr.ReadLine());
                     if (_variable.Type != EnumVarType.String)
                     {
                         _variable.BoardUnits     = sr.ReadLine();
                         _variable.InterfaceUnits = sr.ReadLine();
                         _variable.LinearAdjustA  = float.Parse(sr.ReadLine());
                         _variable.LinearAdjustB  = float.Parse(sr.ReadLine());
                         _variable.RangeLow       = float.Parse(sr.ReadLine());
                         _variable.RangeHigh      = float.Parse(sr.ReadLine());
                     }
                     _variable.CommunicationType = (EnumVarCommunicationType)Enum.Parse(typeof(EnumVarCommunicationType), sr.ReadLine());
                     _proyect.Variables.Add(_variable);
                 }
             } while (true);
             sr.Close();
             this.LoadProyect();
         }
         catch (Exception ex)
         {
             _exMg.HandleException(ex);
         }
     }
 }
Ejemplo n.º 5
0
 public SP_services()
 {
     _serialPort  = new SerialPort();
     _ports       = SerialPort.GetPortNames();
     _res_man     = new ResourceManager("PlantaPiloto.Resources.Res", typeof(MainForm).Assembly);
     _db_services = new DB_services(_cul);
     _lastRow     = new Proyect();
     _saveFile    = false;
     _exMg        = new ExceptionManagement(_cul);
     _time        = 0;
     _ts          = GlobalParameters.DefaultTs;
 }
Ejemplo n.º 6
0
 public VarSelection()
 {
     InitializeComponent();
     _mainForm     = new MainForm();
     _res_man      = new ResourceManager("PlantaPiloto.Resources.Res", typeof(MainForm).Assembly);
     _proyect      = new Proyect();
     _db_services  = new DB_services(_cul);
     _helpProvider = new HelpProvider();
     _filesPath    = GlobalParameters.FilesPath;
     _helpProvider.HelpNamespace = Path.Combine(_filesPath, "helpProyect.chm");
     _exMg = new ExceptionManagement(_cul);
 }
Ejemplo n.º 7
0
 public ConfigForm(CultureInfo cul)
 {
     InitializeComponent();
     _res_man      = new ResourceManager("PlantaPiloto.Resources.Res", typeof(MainForm).Assembly);
     _proyect      = new Proyect();
     _db_services  = new DB_services(_cul);
     _eagerLoading = 0;
     _helpProvider = new HelpProvider();
     _filesPath    = GlobalParameters.FilesPath;
     _configsPath  = GlobalParameters.ConfigsPath;
     _helpProvider.HelpNamespace = Path.Combine(_filesPath, "helpProyect.chm");
     _cul       = cul;
     _exMg      = new ExceptionManagement(_cul);
     _fileSaver = new FileSaver();
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Método que rellena el data grid view con las variables modificables del proyecto
 /// </summary>
 private void TimerElapsedEvent(object source, ElapsedEventArgs e)
 {
     try
     {
         _lastRowSP = _sp_services.LastRow;
         if (_lastRowSP.Variables.Count() == _proyect.Variables.Count() &&
             _lastRowSP.Variables.Where(p => p.Value == null).Count() == 0)
         {
             this.FillDataGridView(_lastRowSP);
             this.ViewConnectionOpen();
         }
     }
     catch (Exception ex)
     {
         _exMg.HandleException(ex);
     }
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Método que limpia los campos del formulario
 /// </summary>
 internal void CleanForm(int eagerLoading)
 {
     CleanVarForm();
     if (eagerLoading == 1)
     {
         foreach (Control c in this.gbProyectDetails.Controls)
         {
             if (c is TextBox || c is RichTextBox)
             {
                 c.Text = "";
             }
         }
         this.txtVarLinearAdjA.Text = "1";
         this.txtVarLinearAdjB.Text = "0";
         _proyect = new Proyect();
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Método que crea la tabla donde se van a guardar los datos a partir de las variables del proyecto
        /// </summary>
        /// <param name="pr">Proyecto del que toma los datos</param>
        public void CreateTableDB(Proyect proyect)
        {
            using (SqlConnection con = new SqlConnection(@"Server = localhost\sqlexpress; Database=" + GlobalParameters.DBName + ";Integrated Security = True;"))
            {
                try
                {
                    // Open the SqlConnection.
                    con.Open();

                    if (CheckDBExists(proyect))
                    {
                        using (SqlCommand command = new SqlCommand("DROP TABLE dbo." + proyect.Name, con))
                            command.ExecuteNonQuery();
                    }

                    // Create table string
                    StringBuilder sqlStr = new StringBuilder("CREATE TABLE " + proyect.Name + "([Id] [int] IDENTITY(1,1) NOT NULL, [Time] [nvarchar](20) NOT NULL");
                    foreach (Variable v in proyect.Variables)
                    {
                        sqlStr.Append(", [" + v.Name + "] ");
                        if (v.Type == EnumVarType.String)
                        {
                            sqlStr.Append("[nvarchar](20) NULL");
                        }
                        else
                        {
                            sqlStr.Append("[float] NULL");
                        }
                    }
                    sqlStr.Append(")");

                    // The following code uses an SqlCommand based on the SqlConnection.
                    using (SqlCommand command = new SqlCommand(sqlStr.ToString(), con))
                        command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    _exMg.HandleException(ex);
                }
                finally
                {
                    CloseConnection(con);
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Método que añade una nueva fila a la BD
        /// </summary>
        /// <param name="proyect">Proyecto del que obtiene los datos para crear la consulta</param>
        public void SaveRow(Proyect proyect, float time)
        {
            using (SqlConnection con = new SqlConnection(@"Server = localhost\sqlexpress; Database=" + GlobalParameters.DBName + ";Integrated Security = True;"))
            {
                try
                {
                    // Open the SqlConnection.
                    con.Open();

                    // Cadena para insertar una nueva fila
                    StringBuilder insertCmd = new StringBuilder("INSERT INTO [dbo].[" + proyect.Name + "]([Time]");
                    foreach (Variable v in proyect.Variables)
                    {
                        insertCmd.Append(",[" + v.Name + "]");
                    }
                    insertCmd.Append(") VALUES ('" + time + "'");

                    foreach (Variable v in proyect.Variables)
                    {
                        insertCmd.Append(v.Type == EnumVarType.String ? ",'" + v.Value.ToString() + "'" : "," + v.Value);
                    }
                    insertCmd.Append(")");

                    // Comprobamos si está
                    if (CheckDBExists(proyect))
                    {
                        using (SqlCommand command = new SqlCommand(insertCmd.ToString(), con))
                            command.ExecuteNonQuery();
                    }
                    else
                    {
                        CreateTableDB(proyect);
                    }
                }
                catch (Exception ex)
                {
                    _exMg.HandleException(ex);
                }
                finally
                {
                    CloseConnection(con);
                }
            }
        }
Ejemplo n.º 12
0
 public ChartForm()
 {
     InitializeComponent();
     _mainForm       = new MainForm();
     _res_man        = new ResourceManager("PlantaPiloto.Resources.Res", typeof(MainForm).Assembly);
     _variables      = new List <Variable>();
     _db_services    = new DB_services(_cul);
     _proyect        = new Proyect();
     _sqlData        = new List <List <Variable> >();
     _sqlTime        = new List <float>();
     _timer          = new System.Timers.Timer(2000);
     _timer.Enabled  = false;
     _timer.Elapsed += new ElapsedEventHandler(this.LoadChartsTimer);
     _chartAmount    = 100;
     _helpProvider   = new HelpProvider();
     _filesPath      = GlobalParameters.FilesPath;
     _helpProvider.HelpNamespace = Path.Combine(_filesPath, "helpProyect.chm");
     _exMg = new ExceptionManagement(_cul);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Mëtodo que devuelve una lista de variables con los valores almacenados en la BD.
        /// </summary>
        /// <param name="proyect"></param>
        /// <param name="var"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public List <Variable> GetVarValue(Proyect proyect, Variable var, int amount)
        {
            using (SqlConnection con = new SqlConnection(@"Server = localhost\sqlexpress; Database=" + GlobalParameters.DBName + ";Integrated Security = True;"))
            {
                List <Variable> result = new List <Variable>();
                try
                {
                    // Open the SqlConnection.
                    con.Open();

                    if (CheckDBExists(proyect))
                    {
                        using (SqlCommand command = new SqlCommand("SELECT TOP " + amount + "[" + var.Name + "] " +
                                                                   "FROM [" + GlobalParameters.DBName + "].[dbo].[" + proyect.Name + "] ORDER BY ID DESC ", con))
                        {
                            SqlDataReader varDataReader = command.ExecuteReader();
                            while (varDataReader.Read())
                            {
                                Variable v = new Variable
                                {
                                    Name              = var.Name,
                                    Type              = var.Type,
                                    Access            = var.Access,
                                    CommunicationType = var.CommunicationType,
                                    Value             = var.Type == EnumVarType.String ? varDataReader.GetString(0) : varDataReader.GetDouble(0).ToString()
                                };
                                result.Add(v);
                            }
                        }
                    }
                    return(result);
                }
                catch (Exception ex)
                {
                    _exMg.HandleException(ex);
                    return(result);
                }
                finally
                {
                    CloseConnection(con);
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Método que obtiene el nombre de las columnas del proyecto que se pasa por parámetro
        /// </summary>
        /// <param name="proyect">Proyecto del que se quieren conocer los nombres de las columnas</param>
        public string GetLastRowValue(Proyect proyect, List <string> vars)
        {
            StringBuilder row = new StringBuilder("");

            using (SqlConnection con = new SqlConnection(@"Server = localhost\sqlexpress; Database=" + GlobalParameters.DBName + ";Integrated Security = True;"))
            {
                try
                {
                    // Open the SqlConnection.
                    con.Open();
                    StringBuilder sqlStr = new StringBuilder("SELECT TOP 1 [Time]");
                    vars.ForEach(f => sqlStr.Append(",[" + f + "]"));
                    sqlStr.Append(" FROM [" + GlobalParameters.DBName + "].[dbo].[" + proyect.Name + "] ORDER BY ID DESC ");
                    if (CheckDBExists(proyect))
                    {
                        using (SqlCommand command = new SqlCommand(sqlStr.ToString(), con))
                        {
                            SqlDataReader columnsDataReader = command.ExecuteReader();
                            while (columnsDataReader.Read())
                            {
                                for (int i = 0; i < columnsDataReader.FieldCount; i++)
                                {
                                    row.Append(String.Format("{0};", columnsDataReader[i]));
                                }
                            }
                        }
                    }
                    return(row.ToString());
                }
                catch (Exception ex)
                {
                    _exMg.HandleException(ex);
                    return(row.ToString());
                }
                finally
                {
                    CloseConnection(con);
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Método que evalúa si la BD existe
        /// </summary>
        /// <param name="proyect">Proyecto que se utiliza para saber el nombre de la BD</param>
        /// <returns></returns>
        public bool CheckDBExists(Proyect proyect)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(@"Server = localhost\sqlexpress; Database=" + GlobalParameters.DBName + ";Integrated Security = True;"))
                {
                    con.Open();

                    string sCmd = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG = '" + GlobalParameters.DBName + "'" +
                                  " AND TABLE_NAME = '" + proyect.Name + "'";

                    SqlCommand cmd = new SqlCommand(sCmd, con);

                    return((int)cmd.ExecuteScalar() == 1);
                }
            }
            catch (Exception ex)
            {
                _exMg.HandleException(ex);
                return(false);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Método que abre la conexión con el puerto serie y guarda los datos recibidos en la BD.
        /// </summary>
        public void OpenConnection()
        {
            try
            {
                // Set the read/write timeouts
                //_serialPort.ReadBufferSize = 8192;
                _serialPort.Open();
                int oldMoment = -1;

                while (_serialPort.IsOpen)
                {
                    // Lectura del puerto serie
                    string[] spLine = _serialPort.ReadLine().Split(';');
                    if (spLine.Count() == 3)
                    {
                        if (oldMoment == -1)
                        {
                            Int32.TryParse(spLine[0], out oldMoment);
                        }

                        int newMoment = Int32.Parse(spLine[0]);

                        if (newMoment != oldMoment)
                        {
                            _time    += _ts;
                            _time     = (float)(Math.Round((double)_time, 2));
                            oldMoment = newMoment;
                        }

                        // Asignación del valor a la variable
                        if (_proyect.Variables.Count(p => p.Name == spLine[1]) > 0)
                        {
                            _proyect.Variables.FirstOrDefault(p => p.Name == spLine[1]).BoardMoment = Int32.Parse(spLine[0]);
                            _proyect.Variables.FirstOrDefault(p => p.Name == spLine[1]).Value       = spLine[2];

                            //Se actualiza el valor del periodo de la placa
                            if (spLine[1] == "Ts")
                            {
                                _ts = float.Parse(spLine[2], CultureInfo.InvariantCulture);
                            }

                            //Asigno valor a las variables que son sólo de escritura para tener una referencia en la vista
                            if (spLine[1].EndsWith("_eco") && _proyect.Variables.Where(p => p.Name + "_eco" == spLine[1]).Count() != 0)
                            {
                                _proyect.Variables.FirstOrDefault(p => p.Name + "_eco" == spLine[1]).BoardMoment = Int32.Parse(spLine[0]);
                                _proyect.Variables.FirstOrDefault(p => p.Name + "_eco" == spLine[1]).Value       = spLine[2];
                            }
                            if (spLine[1].EndsWith("_x3_eco") && _proyect.Variables.Where(p => p.Name + "_x3_eco" == spLine[1]).Count() != 0)
                            {
                                _proyect.Variables.FirstOrDefault(p => p.Name + "_x3_eco" == spLine[1]).BoardMoment = Int32.Parse(spLine[0]);
                                _proyect.Variables.FirstOrDefault(p => p.Name + "_x3_eco" == spLine[1]).Value       = spLine[2];
                            }
                        }
                        // Comprobación que todas las variables tienen valor y llamada al método que las guarda en la BD
                        // Se crea el requisito de que todas las variables del proyecto deben existir en la placa
                        if (_proyect.Variables.Count(p => p.Value == null) == 0)
                        {
                            _db_services.SaveRow(_proyect, _time);
                            _lastRow = new Proyect();

                            foreach (Variable v in _proyect.Variables)
                            {
                                _lastRow.Variables.Add(new Variable
                                {
                                    Name        = v.Name,
                                    Access      = v.Access,
                                    BoardMoment = v.BoardMoment,
                                    Value       = v.Value
                                });
                                v.BoardMoment = null;
                                v.Value       = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _exMg.HandleException(ex);
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Sobrecarga del método LoadProyect() para poder recibir un proyecto como parámetro
 /// </summary>
 /// <param name="pr">Proyecto para cargar en MainForm</param>
 public void LoadProyect(Proyect pr)
 {
     _proyect = pr;
     this.LoadProyect();
 }