/// <summary> /// Define la transaccción que actualiza un circuito /// </summary> /// <param name="circuit">El circuito actualizar.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> public static void UpdateCircuitTr(this Circuito circuit, Action <Object> task_completed, double longitud = Double.NaN, double fac_agrup = Double.NaN, string interruptor = null, string calibre = null) { KeyValuePair <string, object>[] updateData = new KeyValuePair <string, object>[] { !Double.IsNaN(longitud) ? new KeyValuePair <string, object>("longitud", longitud) : new KeyValuePair <string, object>(String.Empty, null), !Double.IsNaN(fac_agrup) ? new KeyValuePair <string, object>("fac_agrup", fac_agrup) : new KeyValuePair <string, object>(String.Empty, null), interruptor != null ? new KeyValuePair <string, object>("interruptor", interruptor) : new KeyValuePair <string, object>(String.Empty, null), calibre != null ? new KeyValuePair <string, object>("calibre", calibre) : new KeyValuePair <string, object>(String.Empty, null) }.Where(x => x.Key != String.Empty).ToArray(); if (updateData.Length > 0) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Object[] data = input as Object[]; var cto = data[0] as Circuito; var uData = data[1] as KeyValuePair <string, object>[]; return(cto.Update(conn, uData)); }, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(new Object[] { circuit, updateData }); } }
/// <summary> /// Actualizá la ruta de guardado de un tablero /// </summary> /// <param name="tablero">El tablero a guardar.</param> /// <param name="savePath">La ruta del tablero a guardar.</param> private static void UpdateTableroPathTr(Tablero tablero, string savePath, Action <Object> task_completed = null) { KeyValuePair <string, object>[] updateData = new KeyValuePair <string, object>[] { savePath != null ? new KeyValuePair <string, object>("ruta", savePath) : new KeyValuePair <string, object>(String.Empty, null) }.Where(x => x.Key != String.Empty).ToArray(); SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Boolean flag = false; String msg = String.Empty; try { Object[] data = input as Object[]; Tablero tab = data[0] as Tablero; var uData = data[1] as KeyValuePair <string, object>[]; flag = tab.Update(conn, uData); if (flag) { tab.Path = uData[0].Value.ToString(); } msg = "El tablero ha sido actualizado"; } catch (Exception exc) { msg = exc.Message; } return(new Object[] { flag, msg }); }, TaskCompleted = (Object obj) => { task_completed(obj); }, }; tr.Run(new Object[] { tablero, updateData }); }
/// <summary> /// Creates the extra data and destinations. /// </summary> /// <param name="id">The identifier.</param> /// <param name="extraData">The extra data.</param> /// <param name="alimoAddedTask">The alimo added task.</param> /// <exception cref="NotImplementedException"></exception> private static void CreateExtraDataAndDestinations(int alimId, ExtraData extraData, Action <object, int> connectionCreated) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = CreateExtraDataConnections, TaskCompleted = (Object result) => { connectionCreated(result, alimId); } }; tr.Run(new Object[] { alimId, extraData }); }
/// <summary> /// Crea la conexión del alimentador /// </summary> /// <param name="alimId">El id del alimentador.</param> /// <param name="conn_id">El id del elemento conectado.</param> /// <param name="typeId">El tipo de elemento conectado al alimentador.</param> /// <param name="connectionCreated">La tarea a ejecutarse una vez que la conexión fue creada.</param> private static void CreateAlimentadorDestinationTr(int alimId, int conn_id, int typeId, Action <Object, int> connectionCreated) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = CreateAlimentadorConnection, TaskCompleted = (Object result) => { connectionCreated(result, alimId); } }; tr.Run(new Object[] { alimId, conn_id, typeId }); }
/// <summary> /// Creates the motor and destinations. /// </summary> /// <param name="alimId">The alim identifier.</param> /// <param name="motors">The motors.</param> /// <param name="connectionCreated">The connection created.</param> private static void CreateMotorAndDestinations(int alimId, IEnumerable <BigMotor> motors, Action <object, int> connectionCreated) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = CreateMotorsConnections, TaskCompleted = (Object result) => { connectionCreated(result, alimId); } }; tr.Run(new Object[] { alimId, motors }); }
/// <summary> /// Crea un nuevo alimentador y lo guarda en la aplicación /// </summary> /// <param name="alimentador">El tablero a insertar</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> public static void CreateAlimentadorTr(this AlimInput alimentador, Action <Object> task_completed) { //1: Se agregá el tablero a la aplicación SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = InsertAlimTask, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(alimentador); }
/// <summary> /// Crea un nuevo tablero y lo guarda en la aplicación /// </summary> /// <param name="tablero">El tablero a insertar</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> public static void CreateTableroTr(this Tablero tablero, Action <Object> task_completed) { //1: Se agregá el tablero a la aplicación SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = InsertTableroTask, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(tablero); }
/// <summary> /// Define la transacción que elimina un circuito /// </summary> /// <param name="circuit">El circuito a eliminar.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> public static void DeleteCircuitTr(this Circuito circuit, Action <Object> task_completed) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Circuito cto = input as Circuito; return(cto.Delete(conn)); }, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(circuit); }
/// <summary> /// Define la transacción que elimina un tablero /// </summary> /// <param name="tablero">El tablero a eliminar.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> public static void DeleteTableroTr(this Tablero tablero, Action <Object> task_completed) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Tablero tab = input as Tablero; return(tab.Delete(conn)); }, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(tablero); }
/// <summary> /// Guarda una copia del tablero en la ruta del archivo especificado. /// </summary> /// <param name="filePath">La ruta en donde se guardará el archivo.</param> /// <param name="saveInput">Los parametros de entrada que recibe la función de guardado.</param> private static Boolean SaveTablero(String filePath, Object saveInput) { var data = (Object[])saveInput; Tablero tablero = data[0] as Tablero; Action <Object> task_completed = data[1] as Action <Object>; Boolean flag = false; try { //Copiamos el archivo base de tableros File.Copy(TabalimApp.TableroDBPath, filePath, tablero.Path == filePath); SQLiteWrapper tr = new SQLiteWrapper(filePath) { TransactionTask = (SQLite_Connector conn, Object input) => { try { List <Componente> cmps; List <Circuito> ctos; Tablero t = ((Tablero)input).Clone(out cmps, out ctos); //Se inserta el tablero InsertTableroTask(conn, t); //Se se insertan los circuitos ctos.ForEach(x => x.GetLastId <Circuito>(conn, t)); //Se insertan los componentes cmps.ForEach(cmp => cmp.GetLastId <Componente>(conn, ctos.FirstOrDefault(cto => cto.ToString() == cmp.CircuitoName))); return(new object[] { true, String.Format("Tablero guardado de forma correcta en \n{0}.", filePath) }); } catch (Exception exc) { return(new object[] { false, String.Format("Error al guardar el tablero\nDetalles: {0}", exc.Message) }); } }, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(tablero); flag = true; } catch (IOException exc) { task_completed(new object[] { false, String.Format("Error al guardar el tablero\nDetalles: {0}\nPara remplazar el archivo utilice guardar como.", exc.Message) }); } catch (Exception exc) { task_completed(new object[] { false, String.Format("Error al guardar el tablero\nDetalles: {0}", exc.Message) }); } return(flag); }
/// <summary> /// Importa un tablero al proyecto seleccionado /// </summary> /// <param name="window">La ventana que llama a esta función</param> /// <param name="project">El proyecto al cual se le importará un tablero.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> public static void ImportTableroTr(this MetroWindow window, Project project, Action <Object> task_completed) { FileManager fm = new FileManager("Tabalim", "Abrir Tablero", "tabalim"); String filePath; if (fm.PickPath(out filePath)) { try { SQLiteWrapper tr = new SQLiteWrapper(filePath) { TransactionTask = PickTableroName, TaskCompleted = async(Object result) => { Tablero fileTablero = result as Tablero; String tabName = fileTablero.NombreTablero; Tablero existant = project.Tableros.Values.FirstOrDefault(x => x.NombreTablero == tabName); if (existant != null) { MessageDialogResult res = await window.ShowMessageAsync("Tablero Existente", "El tablero ya existe en el proyecto actual\n¿Quiere remplazarlo?", MessageDialogStyle.AffirmativeAndNegative); if (res == MessageDialogResult.Affirmative) { DeleteTableroAndLoadTr(project, existant, fileTablero, task_completed); } } else { LoadTableroTr(project, fileTablero, task_completed); } } }; tr.Run(null); } catch (Exception exc) { task_completed(new object[] { false, String.Format("Error al abrir el tablero\nDetalles: {0}", exc.Message) }); } } else { task_completed(new object[] { false, String.Empty }); } }
/// <summary> /// Realizá la carga del tablero /// </summary> /// <param name="project">El nombre del proyecto.</param> /// <param name="fileTablero">El tablero leido del archivo.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> private static void LoadTableroTr(Project project, Tablero fileTablero, Action <object> task_completed) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Object[] data = input as Object[]; Project prj = data[0] as Project; Tablero fileTab = data[1] as Tablero; return(InsertTableroTr(conn, prj, fileTab)); }, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(new Object[] { project, fileTablero }); }
/// <summary> /// Define la transacción que actualiza un tablero /// El nombre del tablero debe ser único /// </summary> /// <param name="tablero">El tablero actualizar.</param> /// <param name="project">El proyecto al que pertenece el tablero.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> /// <param name="tab_name">El nombre del tablero.</param> /// <param name="tab_desc">La descripción del tablero.</param> public static void UpdateTableroTr(this Tablero tablero, Project project, Action <Object> task_completed, String tab_name = null, string tab_desc = null) { KeyValuePair <string, object>[] updateData = new KeyValuePair <string, object>[] { tab_name != null ? new KeyValuePair <string, object>("tab_name", tab_name) : new KeyValuePair <string, object>(String.Empty, null), tab_desc != null ? new KeyValuePair <string, object>("tab_desc", tab_desc) : new KeyValuePair <string, object>(String.Empty, null) }.Where(x => x.Key != String.Empty).ToArray(); if (updateData.Length > 0) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Boolean flag = false; String msg = String.Empty; try { Object[] data = input as Object[]; Tablero tab = data[0] as Tablero; var uData = data[1] as KeyValuePair <string, object>[]; Project prj = data[2] as Project; var uDataName = uData.FirstOrDefault(x => x.Key == "tab_name"); if ((uDataName.Value != null && uDataName.Value.ToString() != tab.NombreTablero) && prj.Tableros.Values.Count(x => x.NombreTablero == uDataName.Value.ToString()) > 0) { throw new Exception("El nombre del tablero ya existe en el proyecto.\n Favor de utilizar otro nombre."); } flag = tab.Update(conn, uData); msg = "El tablero ha sido actualizado"; } catch (Exception exc) { msg = exc.Message; } return(new Object[] { flag, msg }); }, TaskCompleted = (Object obj) => { task_completed(obj); }, }; tr.Run(new Object[] { tablero, updateData, project }); } }
/// <summary> /// Define la transacción que actualiza un componente /// </summary> /// <param name="component">El componente actualizar.</param> /// <param name="tablero">El tablero actualizar.</param> /// <param name="task_completed">La tarea que se ejecuta al terminar la transacción.</param> /// <param name="cto">El nuevo circuito.</param> /// <param name="cmp_count">El número total de componentes.</param> /// <param name="potencia">La potencia del circuito.</param> public static void UpdateComponentTr(this Componente component, Tablero tablero, Action <Object> task_completed, Circuito circuit = null, int cmp_count = 0, Potencia potencia = null) { KeyValuePair <string, object>[] updateData = new KeyValuePair <string, object>[] { circuit != null ? new KeyValuePair <string, object>("cir_id", circuit) : new KeyValuePair <string, object>(String.Empty, null), cmp_count > 0 ? new KeyValuePair <string, object>("comp_count", cmp_count) : new KeyValuePair <string, object>(String.Empty, null), potencia != null ? new KeyValuePair <string, object>("potencia", potencia) : new KeyValuePair <string, object>(String.Empty, null) }.Where(x => x.Key != String.Empty).ToArray(); if (updateData.Length > 0) { SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath) { TransactionTask = (SQLite_Connector conn, Object input) => { Object[] data = input as Object[]; Componente cmp = data[0] as Componente; var uData = data[1] as KeyValuePair <string, object>[]; Circuito cto = data[2] as Circuito; Tablero tab = data[3] as Tablero; //Crear el circuito if (cto != null && cto.Id < 1) { cto = conn.InsertCircuitTr(cto, tab); tab.Circuitos.Add(cto.ToString(), cto); int index = uData.Select(x => x.Key).ToList().IndexOf("cir_id"); uData[index] = new KeyValuePair <string, object>("cir_id", cto); if (cmp.Circuito.Componentes.Count == 1) { conn.Delete(TABLE_CIRCUIT, cmp.Circuito.CreatePrimaryKeyCondition()); } } return(cmp.Update(conn, uData)); }, TaskCompleted = (Object obj) => { task_completed(obj); }, }; tr.Run(new Object[] { component, updateData, circuit, tablero }); } }
/// <summary> /// Define una transacción que agregá un componente a un tablero /// </summary> /// <param name="tablero">El tablero</param> /// <param name="component">El componente agregar</param> public static void AddComponentTr(this Tablero tablero, Componente component, Action <Object> componenteAddedTask = null) { //Primero se guarda el circuito SQLiteWrapper tr = new SQLiteWrapper(TabalimApp.AppDBPath); Circuito circuito = component.Circuito; //Se revisa si el ciruito ya existe if (tablero.Circuitos.ContainsKey(circuito.ToString())) { tr.TransactionTask = (SQLite_Connector conn, Object input) => { Object[] data = (Object[])input; Circuito cto = data[0] as Circuito; Componente cmp = conn.InsertComponentTr(data[1] as Componente, cto); return(new Object[] { cmp.Id > 0, cto, cmp }); } } ; else { tr.TransactionTask = (SQLite_Connector conn, Object input) => { Object[] data = (Object[])input; Tablero tab = data[2] as Tablero; Circuito cto = conn.InsertCircuitTr(data[0] as Circuito, tab); Componente cmp = conn.InsertComponentTr(data[1] as Componente, cto); return(new Object[] { cto.Id > 0 && cmp.Id > 0, cto, cmp }); } }; tr.TaskCompleted = (Object qResult) => { Object[] result = qResult as Object[]; bool succed = (bool)result[0]; if (succed) { Circuito cto = (Circuito)result[1]; Componente cmp = (Componente)result[2]; if (!tablero.Circuitos.ContainsKey(cto.ToString())) { tablero.Circuitos.Add(cto.ToString(), cto); } if (!tablero.Componentes.ContainsKey(cmp.Id)) { tablero.Componentes.Add(cmp.Id, cmp); } if (!cto.Componentes.ContainsKey(cmp.Id)) { cto.Componentes.Add(cmp.Id, cmp); } if (componenteAddedTask != null) { componenteAddedTask(cto); } } else { throw new Exception("Error al anexar el componente."); } }; tr.Run(new Object[] { circuito, component, TabalimApp.CurrentTablero }); }
/// <summary> /// Guarda una copia del tablero en la ruta del archivo especificado. /// </summary> /// <param name="filePath">La ruta en donde se guardará el archivo.</param> /// <param name="saveInput">Los parametros de entrada que recibe la función de guardado.</param> private static Boolean SaveTableroAs(String filePath, Object saveInput) { var data = (Object[])saveInput; Tablero tablero = data[0] as Tablero; List <Componente> componentes = data[1] as List <Componente>; List <Circuito> circuitos = data[2] as List <Circuito>; Action <Object> task_completed = data[3] as Action <Object>; Boolean flag = false; try { SQLiteWrapper.QuickTransaction(TabalimApp.AppDBPath, (SQLite_Connector conn, Object[] input) => { String query = TABLE_TABLERO.SelectAll(String.Format("ruta ='{0}'", filePath)); Tablero t = conn.Select <Tablero>(query).FirstOrDefault(); if (t != null) { t.LoadComponentesAndCircuits(conn, t); t.Delete(conn); } }, filePath); //Copiamos el archivo base de tableros File.Copy(TabalimApp.TableroDBPath, filePath, true); SQLiteWrapper tr = new SQLiteWrapper(filePath) { TransactionTask = (SQLite_Connector conn, Object input) => { try { Object[] tData = input as Object[]; Tablero t = tData[0] as Tablero; List <Componente> cmps = tData[1] as List <Componente>; List <Circuito> ctos = tData[2] as List <Circuito>; //Primero se realiza la copia externa, luego la interna if (InsertTablero(conn, t, cmps, ctos)) { var localClone = t.Clone(out cmps, out ctos); SQLiteWrapper.QuickTransaction(TabalimApp.AppDBPath, (SQLite_Connector localConn, Object[] localInput) => { (localInput[0] as Tablero).Path = localInput[3] as String; var succed = InsertTablero(localConn, localInput[0] as Tablero, localInput[1] as List <Componente>, localInput[2] as List <Circuito>); Tablero nT = localInput[0] as Tablero; if (succed && !TabalimApp.CurrentProject.Tableros.ContainsKey(nT.Id)) { TabalimApp.CurrentProject.Tableros.Add(nT.Id, nT); } }, t, cmps, ctos, new SQLiteConnectionStringBuilder(conn.Connection.ConnectionString).DataSource); } return(new object[] { true, String.Format("Tablero guardado de forma correcta en \n{0}.", filePath) }); } catch (Exception exc) { return(new object[] { false, String.Format("Error al guardar el tablero\nDetalles: {0}", exc.Message) }); } }, TaskCompleted = (Object result) => { task_completed(result); } }; tr.Run(new object[] { tablero, componentes, circuitos }); flag = true; } catch (IOException exc) { task_completed(new object[] { false, String.Format("Error al guardar el tablero\nDetalles: {0}\nPara remplazar el archivo utilice guardar como.", exc.Message) }); } catch (Exception exc) { task_completed(new object[] { false, String.Format("Error al guardar el tablero\nDetalles: {0}", exc.Message) }); } return(flag); }