Ejemplo n.º 1
0
        private static void consultarAvances(Tarea tarea)
        {
            gestor.GestorBaseDatos DbConnection = new gestor.bd.PostgresBaseDatos("35.239.31.249", "postgres", "5432", "E@05face", "asana_upgradedb");
            Consulta consulta = new Consulta()
                                .Select("a.id_avance, fecha, horasdedicadas,descripcion,creador")
                                .From("avance a inner join  avanceportarea t on (a.id_avance = t.id_avance)")
                                .Where("t.id_tarea = '" + tarea.codigo + "'");

            Object[][] resultSet = DbConnection.consultar(consulta.Get(), 5);
            for (int i = 0; i < resultSet.Count(); i++)
            {
                Avance   a      = new Avance();
                String[] result = Array.ConvertAll(resultSet[i], p => (p ?? String.Empty).ToString());
                a.id = result[0];
                DateTime fchEntrega;
                string   fchs = result[1].Split()[0];
                try
                {
                    a.Fecha = DateTime.ParseExact(fchs, "d/M/yyyy", CultureInfo.InvariantCulture);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                a.HorasDedicadas = int.Parse(result[2]);
                a.descripción    = result[3];
                a.creador        = DAOUsuario.consultarUsuario(result[4]);
                a.nbrActividad   = tarea.nombre;
                consultarEvidencias(a);
                tarea.avances.Add(a);
            }
        }
Ejemplo n.º 2
0
        public static Avance Insertar(Avance Avance)
        {
            DataSource DataSource      = DataSource.GetInstancia();
            Avance     AvanceInsertado = null;

            try
            {
                using (SqlDataReader Reader =
                           DataSource.ConsultarProcedimiento("AvanceInsertar", Avance.ToParams()))
                {
                    if (Reader != null && Reader.Read())
                    {
                        AvanceInsertado                   = new Avance();
                        AvanceInsertado.Clave             = Convert.ToInt32(Reader["cveAvance"].ToString());
                        AvanceInsertado.Ejecutado         = Convert.ToDouble(Reader["ejecutado"].ToString());
                        AvanceInsertado.Observacioens     = Reader["observaciones"].ToString();
                        AvanceInsertado.FechaCreacion     = Convert.ToDateTime(Reader["fechaCreacion"].ToString());
                        AvanceInsertado.ClaveProgramacion = Convert.ToInt32(Reader["cveProgramacion"].ToString());
                    }

                    DataSource.Cerrar();
                }
            }catch (Exception e)
            {
                throw e;
            }

            return(AvanceInsertado);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Simula la acción de correr de un objeto corredor
 /// </summary>
 /// <param name="ct">Token de cancelación para los subprocesos</param>
 public void Correr(CancellationToken ct)
 {
     while (Avance.Value < 100 && Running)
     {
         //Verifica si la tarea aún no ha sido cancelada
         if (!ct.IsCancellationRequested)
         {
             //Aumenta el contador
             Avance.Count();
             ThreadSafeRandom rnd = new ThreadSafeRandom();
             //Simula que los corredores no corran todos al mismo ritmo
             //Se lanza el evento indicando que el valor de Estado.Value ha cambiado
             ValueChanged(this, EventArgs.Empty);
             Thread.Sleep(750 + rnd.Next(500));
         }
         else
         {
             //Si la tarea ha sido cancelada, detener el ciclo
             break;
         }
     }
     if (Avance.Value == 100)
     {
         //Se alcanzó el máximo, el corredor gana la carrera
         MaxReached(this, EventArgs.Empty);
     }
 }
Ejemplo n.º 4
0
        protected void btnRegistrarAvance_Click(object sender, EventArgs e)
        {
            Avance avance = new Avance();

            avance.Ejecutado     = Convert.ToInt32(txtEjecutado.Text);
            avance.Observacioens = txtObservaciones.Text;
            avance.FechaCreacion = Utilerias.ParsearFecha(txtFechaCreacion.Text);
            string       claveMes     = cmbMes.SelectedValue;
            Programacion programacion = ProgramacionDAO.Listar().Where(r => r.ClaveMes == Convert.ToInt32(claveMes)).First();

            avance.ClaveProgramacion = programacion.Clave;

            Avance nuevoAvance = AvanceDAO.Insertar(avance);

            if (nuevoAvance == null)
            {
                Mensaje m = new Mensaje()
                {
                    Titulo    = "ERROR!",
                    Contenido = "El avance no se pudo registrar en la base de datos",
                    Tipo      = TipoMensaje.ERROR
                };
                litMensaje.Text = Disenio.GenerarMensaje(m);
            }
            else
            {
                Mensaje m = new Mensaje()
                {
                    Titulo    = "Exito!",
                    Contenido = "El avance fue registrado correctamente",
                    Tipo      = TipoMensaje.EXITO
                };
                litMensaje.Text = Disenio.GenerarMensaje(m);
            }
        }
Ejemplo n.º 5
0
 private void TreeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
 {
     if (e.Node.Tag is Tarea)
     {
         gBEvidencias.Visible = false;
         Tarea t = (Tarea)e.Node.Tag;
         lNombreTarea.Text        = t.nombre;
         lEncargado.Text          = (t.encargado != null ? t.encargado.nombre : "Sin asignar");
         lFchEntrega.Text         = (t.fchEntrega != null ? t.fchEntrega.ToString("dd/MM/yyyy") : "Sin asignar");
         lNotas.Text              = (t.notas != null ? t.notas : "");
         btnAgregarAvance.Enabled = t.tareas.Count == 0;
     }
     else
     {
         btnAgregarAvance.Enabled = false;
         gBEvidencias.Visible     = true;
         Avance a = (Avance)e.Node.Tag;
         lNombreTarea.Text = "Avance";
         lEncargado.Text   = a.creador.nombre;
         lFchEntrega.Text  = a.Fecha.ToString("dd/MM/yyyy");
         lNotas.Text       = "Horas dedicadas: " + a.HorasDedicadas + "\n" + a.descripción;
         dataGridView1.Rows.Clear();
         foreach (Evidencia evidencia in a.evidencias)
         {
             dataGridView1.Rows.Add(a.id, a.creador.nombre, a.Fecha.ToString("dd/MM/yyyy"));
         }
         NewController.getInstance().dto.setAvance(a);
     }
 }
Ejemplo n.º 6
0
 static private void imprimirAvance(Avance avance, string tabs)
 {
     print(tabs + "Nota: " + avance.descripción);
     print(tabs + "Horas dedicadas: " + avance.HorasDedicadas.ToString());
     print(tabs + "Creador: " + (avance.creador == null ? "" : avance.creador.nombre));
     print();
 }
Ejemplo n.º 7
0
        public static List <Avance> Listar()
        {
            DataSource    DataSource = DataSource.GetInstancia();
            List <Avance> Avances    = new List <Avance>();

            try
            {
                using (SqlDataReader Reader =
                           DataSource.ConsultarProcedimiento("AvanceListar"))
                {
                    if (Reader != null)
                    {
                        while (Reader.Read())
                        {
                            Avance Avance = new Avance();
                            Avance.Clave             = Convert.ToInt32(Reader["cveAvance"].ToString());
                            Avance.Ejecutado         = Convert.ToDouble(Reader["ejecutado"].ToString());
                            Avance.Observacioens     = Reader["observaciones"].ToString();
                            Avance.FechaCreacion     = Convert.ToDateTime(Reader["fechaCreacion"].ToString());
                            Avance.ClaveProgramacion = Convert.ToInt32(Reader["cveProgramacion"].ToString());

                            Avances.Add(Avance);
                        }
                    }

                    DataSource.Cerrar();
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(Avances);
        }
        public IHttpActionResult AddAdvances(AvanceEntity model)
        {
            try
            {
                using (var ts = new TransactionScope())
                {
                    Avance avance = new Avance();
                    if (!model.AvanceId.HasValue)
                    {
                        context.Avance.Add(avance);
                        avance.Estado        = ConstantHelpers.ESTADO.ACTIVO;
                        avance.FechaRegistro = DateTime.Now;
                    }

                    avance.HijoId    = model.HijoId;
                    avance.ParrafoId = model.ParrafoId;

                    var parrafo          = context.Parrafo.FirstOrDefault(x => x.ParrafoId == model.ParrafoId);
                    var cantidadParrafos = context.Parrafo.Where(x => x.HistoriaId == parrafo.HistoriaId).ToList().Count();

                    avance.PorcentajeAvance = (parrafo.Orden / cantidadParrafos);
                    context.SaveChanges();
                    ts.Complete();
                }
                response.Data    = "Avance agregado con éxito";
                response.Error   = false;
                response.Message = "Success";
                return(Ok(response));
            }
            catch (Exception ex)
            {
                return(Unauthorized());
            }
        }
Ejemplo n.º 9
0
 public DTO()
 {
     usuario  = new Usuario();
     proyecto = new Proyecto();
     tarea    = new Tarea();
     avance   = new Avance();
     avances  = new List <Avance>();
 }
        public ActionResult DeleteConfirmed(int id)
        {
            Avance avance = db.Avance.Find(id);
            int?   idrela = avance.IdObra;

            db.Avance.Remove(avance);
            db.SaveChanges();
            return(RedirectToAction("Index", new { id = idrela }));
        }
Ejemplo n.º 11
0
        public async Task Update(Avance model)
        {
            try
            {
                var _model = await _db.DbSetAvance.FirstOrDefaultAsync(e => e.AvanceId == model.AvanceId);

                if (_model != null)
                {
                    if (model.AdjuntoId != null)
                    {
                        int id = Convert.ToInt32(model.AdjuntoId);
                        model.AdjuntoId = null;
                        _db.Entry(_model).CurrentValues.SetValues(model);
                        await _db.SaveChangesAsync();

                        await _adjuntoRepo.Delete(id);
                    }
                    if (model.Adjunto != null && model.AdjuntoId == null)
                    {
                        Adjunto key = await _adjuntoRepo.CreateAd(model.Adjunto);

                        model.AdjuntoId         = key.AdjuntoId;
                        model.Adjunto.AdjuntoId = key.AdjuntoId;
                    }
                    if (model.avances != null)
                    {
                        //Se eliminan los anteriores para crear un nuevo registro de los agregados
                        var Autores = await _db.DbSetAvanceMiembros.Where(e => e.AvanceId == model.AvanceId).
                                      Select(x => x.AvanceMiembroId).ToListAsync();

                        AvanceMiembrosRepository av = new AvanceMiembrosRepository();
                        foreach (var aut in Autores)
                        {
                            await av.Delete(aut);
                        }

                        //Ahora se crean los nuevos autores
                        foreach (var c in model.avances)
                        {
                            c.AvanceId      = model.AvanceId;
                            c.FechaRegistro = DateTime.Now;;
                            await av.Create(c);
                        }
                    }

                    _db.Entry(_model).CurrentValues.SetValues(model);
                    await _db.SaveChangesAsync();
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
        }
 public ActionResult Edit([Bind(Include = "IdAvance,porcentajePrevisto,porcentajeReal,porcentajeAtraso,IdObra,FechaAvance")] Avance avance)
 {
     if (ModelState.IsValid)
     {
         db.Entry(avance).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index", new { id = avance.IdObra }));
     }
     ViewBag.IdObra = new SelectList(db.Obra.Where(x => x.IdObra == avance.IdObra), "IdObra", "Obra1");
     return(View(avance));
 }
 internal void ActualizarAvance(Avance avance)
 {
     if (avance.IdAvance != 0)
     {
         throw new NegocioException("El identificador de avance que se desea modificar no es válido. Verifique.");
     }
     if (string.IsNullOrEmpty(avance.Fechaavance.ToString()))
     {
         throw new NegocioException("Fecha es requerida.");
     }
     avanceDatos.ActualizarAvance(avance);
 }
Ejemplo n.º 14
0
 public void AgregarAvance(Avance avance)
 {
     try
     {
         avanceLogica.AgregarAvance(avance);
     }
     catch (NegocioException ex) { throw (ex); }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Crea un objeto avance y se lo envía el método de la capa de datos que agrega el avance a la BD
        /// </summary>
        /// <param name="idSolicitud">ID de la solicitud a la que se le desea agregar un avance</param>
        /// <param name="descripcion">Descripción del avance</param>

        public void agregarAvance(int idSolicitud, String descripcion, String postBy)
        {
            Avance _avance = new Avance();

            _avance.ID          = idSolicitud;
            _avance.Descripcion = descripcion;
            _avance.PostBy      = postBy;

            _manejoBD.agregarAvance(_avance);

            _avances.Add(_avance);
        }
 internal void AgregarAvance(Avance avance)
 {
     if (avance.IdAvance != 0)
     {
         throw new NegocioException("El identificador de avance no es válido. Verifique.");
     }
     if (string.IsNullOrEmpty(avance.Fechaavance.ToString()))
     {
         throw new NegocioException("La fecha de avance debe ser ingresados.");
     }
     //datos
     avanceDatos.AgregarAvance(avance);
 }
Ejemplo n.º 17
0
        private void Btn_registrar_avance_Click(object sender, EventArgs e)
        {
            Avance avance = controlador.dto.getAvance();

            avance.creador        = controlador.dto.getUsuario();
            avance.descripción    = txt_descripcion.Text;
            avance.HorasDedicadas = (int)spn_horas_dedicadas.Value;
            avance.Fecha          = DateTime.Now;
            avance.id             = "" + controlador.dto.getTarea().codigo + controlador.dto.getTarea().avances.Count;
            controlador.agregarAvance();

            System.Windows.Forms.MessageBox.Show("Avance agregado correctamente");
            this.DialogResult = DialogResult.OK;
        }
        // GET: Avances/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Avance avance = db.Avance.Find(id);

            if (avance == null)
            {
                return(HttpNotFound());
            }
            return(View(avance));
        }
        // GET: Avances/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Avance avance = db.Avance.Find(id);

            if (avance == null)
            {
                return(HttpNotFound());
            }
            ViewBag.IdObra = new SelectList(db.Obra.Where(x => x.IdObra == idObra), "IdObra", "Obra1");
            return(View(avance));
        }
Ejemplo n.º 20
0
        public bool agregarAvance()
        {
            GestorAvance gestorAvance = new GestorAvance();
            Avance       avance       = dto.getAvance();

            if (gestorAvance.agregarAvance(avance))
            {
                if ((gestorAvance.agregarAvancePorTarea(dto.getTarea().codigo, avance.id.ToString())))
                {
                    dto.getTarea().avances.Add(avance);
                    return(true);
                }
            }
            return(false);
        }
        private static Avance  ObtenerAvanceMapping(SqlDataReader dr)
        {
            Avance avance = new Avance();

            try
            {
                avance.IdAvance = int.Parse(dr["IdAvance"].ToString());
            }
            catch (Exception opd)
            {
            }
            try
            {
                avance.IdObra = int.Parse(dr["IdObra"].ToString());
            }
            catch (Exception opd)
            {
            }
            try
            {
                avance.Fechaavance = DateTime.Parse(dr["FechaAvance"].ToString());
            }
            catch (Exception opd)
            {
            }
            try
            {
                avance.PorcentajeAtraso = float.Parse(dr["PorcentajeAtraso"].ToString());
            }
            catch (Exception opd)
            {
            }
            try
            {
                avance.PorcentajePrevisto = float.Parse(dr["PorcentajePrevisto"].ToString());
            }
            catch (Exception opd)
            {
            }
            try
            {
                avance.PorcentajeReal = float.Parse(dr["PorcentajeReal"].ToString());
            }
            catch (Exception opd)
            {
            }
            return(avance);
        }
Ejemplo n.º 22
0
        public static Boolean crearAvance(Avance avance)
        {
            gestor.GestorBaseDatos db = new gestor.bd.PostgresBaseDatos("35.239.31.249", "postgres", "5432", "E@05face", "asana_upgradedb");
            db.conectar();
            string query = "insert into Avance values ('{0}', '{1}', '{2}', '{3}', '{4}')";

            query = string.Format(query, avance.id, avance.Fecha.ToString("yyyy-MM-dd"), avance.HorasDedicadas, avance.descripción, avance.creador.id);
            bool result = db.executeNonQuery(query);

            foreach (Evidencia evidencia in avance.evidencias)
            {
                result &= agregarEvidencia(evidencia, avance.id);
            }
            db.desconectar();
            return(result);
        }
Ejemplo n.º 23
0
        public async Task <IHttpActionResult> Update([FromBody] Avance model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                log.Info(new MDCSet(this.ControllerContext.RouteData));
                await _entityRepo.Update(model);

                return(Ok("Registro actualizado exitosamente!"));
            }
            catch (Exception e)
            {
                log.Error(new MDCSet(this.ControllerContext.RouteData), e);
                return(InternalServerError(e));
            }
        }
Ejemplo n.º 24
0
        public async Task <IHttpActionResult> Create([FromBody] Avance model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                log.Info(new MDCSet(this.ControllerContext.RouteData));
                var modelo = await _entityRepo.Create(model);

                return(Ok(modelo));
            }
            catch (Exception e)
            {
                log.Error(new MDCSet(this.ControllerContext.RouteData), e);
                return(InternalServerError(e));
            }
        }
Ejemplo n.º 25
0
        private static void consultarEvidencias(Avance avance)
        {
            gestor.GestorBaseDatos DbConnection = new gestor.bd.PostgresBaseDatos("35.239.31.249", "postgres", "5432", "E@05face", "asana_upgradedb");
            Consulta consulta = new Consulta()
                                .Select("tipo,documento")
                                .From("evidenciaporavance")
                                .Where("id_avance = '" + avance.id + "'");

            Object[][] resultSet = DbConnection.consultar(consulta.Get(), 2);
            avance.cantidadEvidencias = 0;
            for (int i = 0; i < resultSet.Count(); i++)
            {
                Evidencia e      = new Evidencia();
                object[]  result = resultSet[i];
                e.tipo = (string)result[0];

                e.documento = getByteArrayFromObjectArray(result[1]);
                avance.evidencias.Add(e);
                avance.cantidadEvidencias++;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Método que ejecuta un SP que recupera de la BD los avance de una solicitud
        /// </summary>
        /// <param name="idSolicitud">identificador de la solicitud</param>
        /// <returns>Lista de Avances</returns>

        public List <Avance> recuperarAvances(int idSolicitud)
        {
            List <Avance> _resultado = new List <Avance>();

            SqlCommand buscar = new SqlCommand("SP_SOL_RecuperarAvancesPorSolicitud", _conexion);

            buscar.CommandType = CommandType.StoredProcedure;
            SqlParameter[] parametros = new SqlParameter[1];
            parametros[0]       = new SqlParameter("@idSolicitud", SqlDbType.Int);
            parametros[0].Value = idSolicitud;
            buscar.Parameters.AddRange(parametros);

            if (_conexion.State == ConnectionState.Closed)
            {
                _conexion.Open();
            }

            try
            {
                SqlDataReader reader = buscar.ExecuteReader();
                while (reader.Read())
                {
                    Avance _avance = new Avance();
                    _avance.ID          = reader.GetInt32(0);    //ID del Avance
                    _avance.fecha       = reader.GetDateTime(1); //Fecha del Avance
                    _avance.Descripcion = reader.GetString(2);   //Descripción del Avance
                    _resultado.Add(_avance);
                }
                _conexion.Close();
            }
            catch (Exception)
            {
                if (_conexion.State == ConnectionState.Open)
                {
                    _conexion.Close();
                }
            }

            return(_resultado);
        }
        internal void AgregarAvance(Avance avance)
        {
            using (SqlConnection cnn = ObtenerConexion())
            {
                SqlCommand cmd       = ObtenerComando(cnn, " sp_ABM_avance", CommandType.StoredProcedure);
                int        resultado = 0;
                cmd.Parameters.Add("@IdxAvance", SqlDbType.Int);
                cmd.Parameters["@xIdAvance"].Value = avance.IdAvance;

                cmd.Parameters.Add("@xIdObra", SqlDbType.Int);
                cmd.Parameters["@xIdObra"].Value = avance.IdObra;

                cmd.Parameters.Add("@xPorcentajeAtraso", SqlDbType.Float);
                cmd.Parameters["@xPorcentajeAtraso"].Value = avance.PorcentajeAtraso;

                cmd.Parameters.Add("@xPorcentajePrevisto", SqlDbType.Float);
                cmd.Parameters["@xPorcentajePrevisto"].Value = avance.PorcentajePrevisto;

                cmd.Parameters.Add("@xPorcentajeReal", SqlDbType.Float);
                cmd.Parameters["@xPorcentajeReal"].Value = avance.PorcentajeReal;

                cmd.Parameters.Add("@xAccion", SqlDbType.VarChar);
                cmd.Parameters["@xAccion"].Value = "A";

                cmd.Parameters.Add("@xresult", SqlDbType.Int);
                cmd.Parameters["@xresult"].Direction = ParameterDirection.Output;

                cnn.Open();
                cmd.ExecuteScalar();

                resultado = Convert.ToInt32(cmd.Parameters["@xresult"].Value);

                if (resultado == 1)
                {
                    throw new NegocioException("No se agrego el avance de obra. Verifique los datos.");
                }
            }
        }
        internal Avance TraerAvance(int avanceId)
        {
            Avance avance = null;

            using (var cnn = ObtenerConexion())
            {
                SqlCommand cmd = ObtenerComando(cnn, "sp_avance_traer", CommandType.StoredProcedure);

                cmd.Parameters.Add(new SqlParameter("@Id", avanceId));

                cnn.Open();

                SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                if (dr.HasRows)
                {
                    dr.Read();
                    avance = ObtenerAvanceMapping(dr);
                }
            }

            return(avance);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Método que se encarga de ejecutar el SP que agrega un avance a una solicitud
        /// </summary>
        /// <param name="idSolicitud">id de la solicitud</param>
        /// <param name="descripcion">descripción del avance</param>
        /// <param name="postBy">la identificación de la persona que agregó el avance</param>
        /// <returns>Un valor de true si la inserción fue exitosa, false si no se logró</returns>

        public Boolean agregarAvance(Avance avance)
        {
            Boolean resultado = false;

            SqlCommand agregar = new SqlCommand("SP_SOL_AgregarAvance", _conexion);

            agregar.CommandType = CommandType.StoredProcedure;
            SqlParameter[] parametros = new SqlParameter[3];
            parametros[0]       = new SqlParameter("@idSolicitud", SqlDbType.Int);
            parametros[0].Value = avance.ID;
            parametros[1]       = new SqlParameter("@descripcion", SqlDbType.NText);
            parametros[1].Value = avance.Descripcion;
            parametros[2]       = new SqlParameter("@postBy", SqlDbType.VarChar);
            parametros[2].Value = avance.PostBy;
            agregar.Parameters.AddRange(parametros);

            if (_conexion.State == ConnectionState.Closed)
            {
                _conexion.Open();
            }
            try
            {
                SqlDataReader reader = agregar.ExecuteReader();
                reader.Read();
                resultado = !(reader.HasRows);
                _conexion.Close();
            }
            catch (Exception)
            {
                if (_conexion.State == ConnectionState.Open)
                {
                    _conexion.Close();
                }
            }

            return(resultado);
        }
Ejemplo n.º 30
0
        public async Task <Avance> Create(Avance model)
        {
            try
            {
                _db.DbSetAvance.Add(model);
                await _db.SaveChangesAsync();

                if (model.avances != null)
                {
                    AvanceMiembrosRepository av = new AvanceMiembrosRepository();
                    foreach (var c in model.avances)
                    {
                        c.AvanceId      = model.AvanceId;
                        c.FechaRegistro = DateTime.Now;;
                        await av.Create(c);
                    }
                }
                return(model);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
        }
Ejemplo n.º 31
0
        //Passe l'avance en Validé ( Gauche -> Droite )
        private void _buttonPasserAvancesEnValide_Click(object sender, RoutedEventArgs e)
        {
            int nb;
            //si une Avance est selectionnée
            if (this._dataGridAvancesDemande.SelectedItem != null && this._dataGridAvancesDemande.SelectedItems.Count == 1)
            {
                Avance temp = new Avance();

                temp = ((Avance)this._dataGridAvancesDemande.SelectedItem);
                temp.Frais1 = ((Frais)this.DataContext);//met l'avance en validé

                this.listAvanceValider.Add(temp);
                this.listAvanceDemande.Remove((Avance)this._dataGridAvancesDemande.SelectedItem);
            }
            if (this._dataGridAvancesDemande.SelectedItem != null && this._dataGridAvancesDemande.SelectedItems.Count > 1)//si plusieurs Avance sont selectionnées
            {   //pour chaque Avance selectionnées
                int compteur = 0; nb = this._dataGridAvancesDemande.SelectedItems.Count;
                while (compteur < nb)
                {
                    Avance temp = new Avance(); //Avance temporaire
                    temp = ((Avance)this._dataGridAvancesDemande.SelectedItems[0]);
                    temp.Frais1 = ((Frais)this.DataContext);

                    this.listAvanceValider.Add(temp);
                    this.listAvanceDemande.Remove((Avance)this._dataGridAvancesDemande.SelectedItems[0]);

                    compteur++;
                }
            }
            this._dataGridAvancesValide.Items.Refresh();
            this._dataGridAvancesDemande.Items.Refresh();
            RefreshAllTotaux();
        }
        /// <summary>
        /// Ajoute une nouvelle Commande_Fournisseur à la liste à l'aide d'une nouvelle fenêtre
        /// </summary>
        public Avance Add()
        {
            //Affichage du message "ajout en cours"
            ((App)App.Current)._theMainWindow.progressBarMainWindow.IsIndeterminate = true;
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Ajout d'une avance en cours ...");

            //Initialisation de la fenêtre
            AvanceWindow avanceWindow = new AvanceWindow();

            //Création de l'objet temporaire
            Avance tmp = new Avance();

            //Mise de l'objet temporaire dans le datacontext
            avanceWindow.DataContext = tmp;

            //booléen nullable vrai ou faux ou null
            bool? dialogResult = avanceWindow.ShowDialog();

            if (dialogResult.HasValue && dialogResult.Value == true)
            {
                //Si j'appuie sur le bouton Ok, je renvoi l'objet commande se trouvant dans le datacontext de la fenêtre
                return (Avance)avanceWindow.DataContext;
            }
            else
            {
                try
                {
                    //On détache l'avance
                    ((App)App.Current).mySitaffEntities.Detach((Avance)avanceWindow.DataContext);
                }
                catch (Exception)
                {
                }

                //Si j'appuie sur le bouton annuler, je préviens que j'annule mon ajout
                ((App)App.Current)._theMainWindow.progressBarMainWindow.IsIndeterminate = false;
                this.recalculMax();
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Ajout d'une avance annulé : " + this.listAvances.Count() + " / " + this.max);

                return null;
            }
        }
        /// <summary>
        /// Met à jour l'état en bas pour l'utilisateur
        /// </summary>
        /// <param name="typeEtat">texte : "Filtrage", "Ajout", "Modification", "Suppression", "Look", "" ("" = Chargement)</param>
        /// <param name="dao">un objet Commande_Fournisseur soit pour l'ajouter au listing, soit pour afficher qui a été modifié ou supprimé</param>
        public void MiseAJourEtat(string typeEtat, Avance ava)
        {
            //Je racalcul le nombre max d'élements
            this.recalculMax();
            //En fonction de l'action, j'affiche le message
            if (typeEtat == "Filtrage")
            {
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("filtrage des avances terminée : " + this.listAvances.Count() + " / " + this.max);
            }
            else if (typeEtat == "Ajout")
            {
                //J'ajoute la commande_fournisseur dans le linsting
                this.listAvances.Add(ava);
                //Je racalcul le nombre max d'élements après l'ajout
                this.recalculMax();
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Ajout d'une avance effectué avec succès. Nombre d'élements : " + this.listAvances.Count() + " / " + this.max);
                try
                {
                    this._DataGridMain.SelectedItem = ava;
                }
                catch (Exception) { }
            }
            else if (typeEtat == "Modification")
            {
                //Je raffraichis mon datagrid
                this._DataGridMain.Items.Refresh();
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Modification de l'avance effectuée avec succès. Nombre d'élements : " + this.listAvances.Count() + " / " + this.max);
            }
            else if (typeEtat == "Suppression")
            {
                //Je supprime de mon listing l'élément supprimé
                this.listAvances.Remove(ava);
                //Je racalcul le nombre max d'élements après la suppression
                this.recalculMax();
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Suppression de l'avance effectuée avec succès. Nombre d'élements : " + this.listAvances.Count() + " / " + this.max);
            }
            else if (typeEtat == "Look")
            {

            }
            else
            {
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Chargement des avances terminé : " + this.listAvances.Count() + " / " + this.max);
            }
            //Je retri les données dans le sens par défaut
            this.triDatas();
            //J'arrete la progressbar
            ((App)App.Current)._theMainWindow.progressBarMainWindow.IsIndeterminate = false;
        }
        /// <summary>
        /// Ouvre l'avance séléctionnée en lecture seule à l'aide d'une nouvelle fenêtre
        /// </summary>
        public Avance Look(Avance avance)
        {
            if (this._DataGridMain.SelectedItem != null || avance != null)
            {
                if (this._DataGridMain.SelectedItems.Count == 1 || avance != null)
                {
                    //Affichage du message "affichage en cours"
                    ((App)App.Current)._theMainWindow.progressBarMainWindow.IsIndeterminate = true;
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Affichage d'une commande fournisseur en cours ...");

                    //Création de la fenêtre
                    AvanceWindow avanceWindow = new AvanceWindow();

                    //Initialisation du Datacontext en Commande_Fournisseur et association à la Commande_Fournisseur sélectionnée
                    avanceWindow.DataContext = new Avance();
                    if (avance != null)
                    {
                        avanceWindow.DataContext = avance;
                    }
                    else
                    {
                        avanceWindow.DataContext = (Avance)this._DataGridMain.SelectedItem;
                    }

                    //Je positionne la lecture seule sur la fenêtre
                    avanceWindow.lectureSeule();

                    //J'affiche la fenêtre
                    bool? dialogResult = avanceWindow.ShowDialog();

                    //Affichage du message "affichage en cours"
                    ((App)App.Current)._theMainWindow.progressBarMainWindow.IsIndeterminate = false;
            ((App)App.Current)._theMainWindow.changementTexteStatusBar("Affichage d'une avance terminé : " + this.listAvances.Count() + " / " + this.max);

                    //Renvoi null
                    return null;
                }
                else
                {
                    MessageBox.Show("Vous ne devez sélectionner qu'une seule avance.", "Attention", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return null;
                }
            }
            else
            {
                MessageBox.Show("Vous devez sélectionner une avance.", "Attention", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return null;
            }
        }
Ejemplo n.º 35
0
 public void LookAvance(UIElement uIElement, Avance avanceToLook)
 {
     ((ListeAvanceControl)uIElement).Look(avanceToLook);
 }