コード例 #1
0
 private void actualizarDepreciacion()
 {
     if (depreciacionDAL.GetDepreciaciones() != null) //Si no hay depreciaciones, no hace el proceso.
     {
         bool depreciado = false;
         for (int i = 0; depreciacionDAL.GetDepreciaciones().Count > i; i++)                        //Recorre lista de depreciaciones.
         {
             Depreciacion    depreciacion  = depreciacionDAL.GetDepreciaciones()[i];                //Variable de depreciación actual en el recorrido.
             System.TimeSpan dif           = DateTime.Now.Subtract(depreciacion.FechaDepreciacion); //Esta vabiable guarda la diferencia de días entre el día actual y la fecha de la última depreciación.
             int             diasSobrantes = dif.Days;
             while (diasSobrantes >= 30 && depreciacion.Valor > 0)                                  //Mientras haya más de 30 días de diferencia (se deprecia cada 30 días)...
             {
                 depreciacion.Valor = depreciacion.Valor - depreciacion.MontoDepreciacion;          //Se le resta al valor actual el monto de la depreciación del activo.
                 diasSobrantes      = diasSobrantes - 30;                                           //Se hace una resta de los días sobrantes al mes para ver si hay que realizar otra resta.
                 depreciado         = true;
             }
             if (depreciacion.Valor < 0)
             {
                 diasSobrantes      = diasSobrantes + 30;
                 depreciacion.Valor = 0;
             }
             if (depreciado == true)
             {
                 depreciacion.FechaDepreciacion = DateTime.Now.AddDays(-diasSobrantes); //La fecha de depreciación se actualiza, restándole a la fecha actual la cantidad de días que sobraron después del cálculo para que sea exacta.
                 depreciacionDAL.Update(depreciacion);                                  //Se actualiza la depreciación correspondiente y se continúa con el recorrido.
                 depreciado = false;
             }
         }
     }
 }
コード例 #2
0
        public Depreciacion GetDepreciacionByID(string id)
        {
            Depreciacion depreciacion = null;

            try
            {
                using (MyContext ctx = new MyContext())
                {
                    ctx.Configuration.LazyLoadingEnabled = false;
                    depreciacion = ctx.Depreciacion.
                                   Include("Activo").
                                   Where(p => p.IdDepreciacion == id).
                                   FirstOrDefault <Depreciacion>();
                }

                return(depreciacion);
            }
            catch (DbUpdateException dbEx)
            {
                string mensaje = "";
                Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                throw new Exception(mensaje);
            }
            catch (Exception ex)
            {
                string mensaje = "";
                Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                throw;
            }
        }
コード例 #3
0
        public void DeleteDepreciacion(string id)
        {
            int returno;

            try
            {
                using (MyContext ctx = new MyContext())
                {
                    ctx.Configuration.LazyLoadingEnabled = false;
                    Depreciacion depreciacion = new Depreciacion()
                    {
                        IdDepreciacion = id
                    };
                    ctx.Entry(depreciacion).State = EntityState.Deleted;
                    returno = ctx.SaveChanges();
                }
            }
            catch (DbUpdateException dbEx)
            {
                string mensaje = "";
                Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                throw new Exception(mensaje);
            }
            catch (Exception ex)
            {
                string mensaje = "";
                Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                throw;
            }
        }
コード例 #4
0
        public ActionResult DepreciacionByDate(int ActivoID, DateTime FechaDepreciacion)
        {
            IEnumerable <Depreciacion> lista = null;
            Depreciacion oDepreciacion       = new Depreciacion();

            try
            {
                Log.Info("Visita");


                IServiceDepreciacion _ServiceDepreciacion = new ServiceDepreciacion();

                oDepreciacion = _ServiceDepreciacion.SaveTransaccion(ActivoID, FechaDepreciacion);

                if (oDepreciacion != null)
                {
                    //Looking for "Depreciacion" we just added in order to show it in the partial view
                    lista = _ServiceDepreciacion.GetDepreciacionByID(oDepreciacion.DepreciacionID);
                }
            }
            catch (Exception ex)
            {
                // Salvar el error en un archivo
                Log.Error(ex, MethodBase.GetCurrentMethod());

                TempData["Message"] = "Error al procesar los datos! " + ex.Message;
                TempData.Keep();
                // Redireccion a la captura del Error
                return(RedirectToAction("Default", "Error"));
            }

            return(PartialView("_ListDepreciacion", lista));
        }
コード例 #5
0
        public Depreciacion SaveTransaccion(Depreciacion depreciacion)
        {
            int          retorno       = 0;
            Depreciacion oDepreciacion = null;

            using (MyContext ctx = new MyContext())
            {
                //Transaction Begin statement
                using (DbContextTransaction transaccion = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        //Validar la fecha!!!!
                        ctx.Depreciacion.Add(depreciacion);
                        retorno = ctx.SaveChanges();


                        if (retorno >= 0)//Se insertan llena la tabla Activos y depreciacion en la DB
                        {
                            transaccion.Commit();
                            oDepreciacion = depreciacion;
                        }

                        return(oDepreciacion);
                    }
                    catch (DbUpdateException dbEx)
                    {
                        transaccion.Rollback(); //Rollback si algo sale mal
                        string mensaje = "";
                        Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                        throw new Exception(mensaje);
                    }
                    //Checking any Entity Validation Exception
                    catch (DbEntityValidationException e)
                    {
                        transaccion.Rollback(); //Rollback si algo sale mal
                        foreach (var eve in e.EntityValidationErrors)
                        {
                            Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                              eve.Entry.Entity.GetType().Name, eve.Entry.State);
                            foreach (var ve in eve.ValidationErrors)
                            {
                                Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                  ve.PropertyName, ve.ErrorMessage);
                            }
                        }
                        throw;
                    }
                    catch (Exception ex)
                    {
                        transaccion.Rollback(); //Rollback si algo sale mal
                        string mensaje = "";
                        Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                        throw;
                    }
                }
            }
        }
コード例 #6
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Depreciacion depreciacion = await db.Depreciacions.FindAsync(id);

            db.Depreciacions.Remove(depreciacion);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
コード例 #7
0
        public async Task <ActionResult> Edit([Bind(Include = "DepreciacionId,DepreciacionPorcentaje")] Depreciacion depreciacion)
        {
            if (ModelState.IsValid)
            {
                db.Entry(depreciacion).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(depreciacion));
        }
コード例 #8
0
        public async Task <ActionResult> Create([Bind(Include = "DepreciacionId,DepreciacionPorcentaje")] Depreciacion depreciacion)
        {
            if (ModelState.IsValid)
            {
                db.Depreciacions.Add(depreciacion);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(depreciacion));
        }
コード例 #9
0
        // GET: /Depreciacion/Delete/5
        public async Task <ActionResult> Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Depreciacion depreciacion = await db.Depreciacions.FindAsync(id);

            if (depreciacion == null)
            {
                return(HttpNotFound());
            }
            return(View(depreciacion));
        }
コード例 #10
0
 //Actualiza una depreciación
 public void Update(Depreciacion depreciacion)
 {
     try
     {
         using (context = new BDContext())
         {
             context.sp_ModificaDepreciacion(depreciacion.Activo, depreciacion.FechaDepreciacion, depreciacion.Valor);
             context.SaveChanges();
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
コード例 #11
0
        public Depreciacion Save(Depreciacion depreciacion)
        {
            int          retorno       = 0;
            Depreciacion oDepreciacion = null;

            try
            {
                using (MyContext ctx = new MyContext())
                {
                    ctx.Configuration.LazyLoadingEnabled = false;
                    oDepreciacion = GetDepreciacionByID(depreciacion.IdDepreciacion);
                    if (oDepreciacion == null)
                    {
                        ctx.Depreciacion.Add(depreciacion);
                    }
                    else
                    {
                        ctx.Entry(depreciacion).State = EntityState.Modified;
                    }
                    retorno = ctx.SaveChanges();
                }

                if (retorno >= 0)
                {
                    oDepreciacion = GetDepreciacionByID(depreciacion.IdDepreciacion);
                }

                return(oDepreciacion);
            }
            catch (DbUpdateException dbEx)
            {
                string mensaje = "";
                Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                throw new Exception(mensaje);
            }
            catch (Exception ex)
            {
                string mensaje = "";
                Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                throw;
            }
        }
コード例 #12
0
        public Depreciacion SaveTransaccion(int activo, DateTime date)
        {
            int diferenciaMeses;
            IEnumerable <Depreciacion> lista = null;

            RepositoryDepreciacion repository       = new RepositoryDepreciacion();
            RepositoryActivos      repositoryActivo = new RepositoryActivos();
            Activos      oActivo           = repositoryActivo.GetActivoByID(activo);
            Depreciacion oDepreciacion     = new Depreciacion();
            int          valorDepreciacion = 0;

            ////Averiguando los meses que han pasado desde la compra al dia de hoy cuando lo guardamos en el sistema
            ///Recibimos date como parametro
            lista = repository.GetDepreciacionByActivo(activo).ToList();

            foreach (var item in lista)
            {
                if (((item.Fecha.Month) == (date.Month)) && ((item.Fecha.Year) == (date.Year)))     // si el mes es diferente
                {
                    //return item
                    return(item);
                }
            }


            //Calculando la diferencia de meses
            diferenciaMeses = (date.Month - oActivo.FechaCompra.Month) + 12 * (date.Year - oActivo.FechaCompra.Year);


            ////Calculando depreciacion por mes ==> Multiplicando depreciacion por los meses actuales para saber el valor actual
            ////Debo cambiar el valor en la base de datos a decimal!!!!
            ////(activos.CostoColones / (activos.VidaUtil * 12) ===> Averiguamos cuanto se gasta por mes * la difernecia de meses
            //// Le restamos el costo total a el valor actual ==> activos.CostoColones(necesito cambiar ValorActual a decimal en la DB)
            valorDepreciacion = Convert.ToInt32(oActivo.CostoColones - ((oActivo.CostoColones / (oActivo.VidaUtil * 12) * diferenciaMeses)));


            oDepreciacion.Valor  = valorDepreciacion.ToString();
            oDepreciacion.Activo = oActivo.ActivoID;
            oDepreciacion.Fecha  = date;

            return(oDepreciacion = repository.SaveTransaccion(oDepreciacion));
        }
コード例 #13
0
 //Retorna una depreciación
 public Depreciacion GetDepreciacion(int idActivo)
 {
     try
     {
         //Se crea una nueva instancia de depreciación
         Depreciacion depreciacion = new Depreciacion();
         sp_RetornaDepreciacionId_Result result;
         using (context = new BDContext())
         {
             //Se crea una nueva instancia del objeto que retona el procemiento almacenado.
             result = context.sp_RetornaDepreciacionId(idActivo).FirstOrDefault();
             //Se asignan los valores a los atributos de la depreciación
             depreciacion.MontoDepreciacion = result.MontoDepreciacion;
             depreciacion.FechaDepreciacion = result.fechaDepreciacion;
         }
         //Retorna la depreciación
         return(depreciacion);
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #14
0
//        public Activos Save(Activos activo)
//        {
//            int retorno = 0;
//            Activos oActivo = null;
//            try
//            {

//                using (MyContext ctx = new MyContext())
//                {

//                    ctx.Configuration.LazyLoadingEnabled = false;
//                    oActivo = GetActivoByID(activo.ActivoID);
//                    if (oActivo == null)
//                    {
//                        ctx.Activos.Add(activo);
//                    }
//                    else
//                    {
//                        ctx.Entry(activo).State = EntityState.Modified;
//                    }
//                    retorno = ctx.SaveChanges();


//#if !DEBUG
//                   // Error por exception
//                    int x = 0;
//                    x = 25 / x;

//                    // Error por Entity Framework
//                    // Forzar un error por duplicidad
//                   // bodega.IdBodega = 1;
//                   // ctx.Bodega.Add(bodega);
//                   // retorno = ctx.SaveChanges();
//#endif
//                }

//                if (retorno >= 0)
//                    oActivo = GetActivoByID(activo.ActivoID);

//                return oActivo;
//            }
//            catch (DbUpdateException dbEx)
//            {
//                string mensaje = "";
//                Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
//                throw new Exception(mensaje);
//            }
//            //Checking any Entity Validation Exception
//            catch (DbEntityValidationException e)
//            {
//                foreach (var eve in e.EntityValidationErrors)
//                {
//                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
//                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
//                    foreach (var ve in eve.ValidationErrors)
//                    {
//                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
//                            ve.PropertyName, ve.ErrorMessage);
//                    }
//                }
//                throw;
//            }
//            catch (Exception ex)
//            {
//                string mensaje = "";
//                Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
//                throw;
//            }
//        }


        //SaveTransaccion is in charge of save "Activo" and "Depreciacion"
        //Based on "FechaCompra" the value of "ValorActual" is received
        //update from the previous method ServiceActivo >> "SaveTransaccion"
        public Activos SaveTransaccion(Activos activo)
        {
            int     retorno = 0;
            Activos oActivo = null;

            using (MyContext ctx = new MyContext())
            {
                //Transaction Begin statement
                using (DbContextTransaction transaccion = ctx.Database.BeginTransaction())
                {
                    int indicador = 0; // variable creada [ara saber cuando un activo se esta editando

                    try
                    {
                        ctx.Configuration.LazyLoadingEnabled = false;
                        oActivo = GetActivoByID(activo.ActivoID);
                        if (oActivo == null)
                        {
                            ctx.Activos.Add(activo);
                        }
                        else
                        {
                            ctx.Entry(activo).State = EntityState.Modified;
                            indicador = 1;
                        }
                        retorno = ctx.SaveChanges();


                        if ((retorno >= 0) && (indicador == 0))
                        {
                            //oActivo = GetActivoByID(activo.ActivoID);

                            //Guardamos la depreciacion basados en el nuevo ID y en el calculo realizado previamente
                            //Necesito cambiar Valor a decimal en la base de datos
                            Depreciacion oDepreciacion = new Depreciacion();
                            oDepreciacion.Valor  = activo.ValorActual.ToString();
                            oDepreciacion.Fecha  = DateTime.Now;
                            oDepreciacion.Activo = activo.ActivoID;

                            ctx.Depreciacion.Add(oDepreciacion);
                            retorno = ctx.SaveChanges();
                        }

                        if (retorno >= 0)//Se insertan llena la tabla Activos y depreciacion en la DB
                        {
                            transaccion.Commit();
                        }

                        return(oActivo);
                    }
                    catch (DbUpdateException dbEx)
                    {
                        transaccion.Rollback(); //Rollback si algo sale mal
                        string mensaje = "";
                        Log.Error(dbEx, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                        throw new Exception(mensaje);
                    }
                    //Checking any Entity Validation Exception
                    catch (DbEntityValidationException e)
                    {
                        transaccion.Rollback(); //Rollback si algo sale mal
                        foreach (var eve in e.EntityValidationErrors)
                        {
                            Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                              eve.Entry.Entity.GetType().Name, eve.Entry.State);
                            foreach (var ve in eve.ValidationErrors)
                            {
                                Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                  ve.PropertyName, ve.ErrorMessage);
                            }
                        }
                        throw;
                    }
                    catch (Exception ex)
                    {
                        transaccion.Rollback(); //Rollback si algo sale mal
                        string mensaje = "";
                        Log.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), ref mensaje);
                        throw;
                    }
                }
            }

            //docs.microsoft.com/en-us/dotnet/api/system.data.linq.table-1.insertonsubmit?view=netframework-4.8
            //techfunda.com/howto/288/insert-record-using-transactions
        }
コード例 #15
0
        public Depreciacion Save(Depreciacion marca)
        {
            RepositoryDepreciacion repository = new RepositoryDepreciacion();

            return(repository.Save(marca));
        }