Example #1
0
        public ActionResult SaveVoluntary(Voluntary voluntary)
        {
            if (ModelState.IsValid)
            {
                dynamic json_affinity = JsonConvert.DeserializeObject(voluntary.Affinity);
                voluntary.Affinities = new List <Affinity>();
                foreach (var affinity in json_affinity)
                {
                    voluntary.Affinities.Add(new Affinity()
                    {
                        AffinityId = Guid.Parse(affinity["value"].ToString()),
                        Name       = affinity["text"]
                    });
                }

                var id = clientHttp.Post <Voluntary>(@"Voluntary/", voluntary);

                return(RedirectToAction("Login", "Login"));
            }

            var affinities = clientHttp.Get <List <Affinity> >(@"Affinity");

            ViewBag.affinities = affinities;
            return(View("RegisterVoluntary", voluntary));
        }
Example #2
0
 public static VoluntaryDTO ToDTO(Voluntary voluntary)
 {
     return(new VoluntaryDTO()
     {
         VoluntaryId = voluntary.VoluntaryId,
         UserId = voluntary.UserId,
         IsApproved = voluntary.IsApproved,
         Name = voluntary.Name,
         Email = voluntary.Email,
         Password = voluntary.Password,
         Phone = voluntary.Phone,
         SocialNetwork = voluntary.SocialNetwork,
         Affinities = AffinityAdapter.ListToDTO(voluntary.Affinities),
         Address = new AddressDTO()
         {
             AddressId = voluntary.Address.AddressId,
             CEP = voluntary.Address.CEP,
             Avenue = voluntary.Address.Avenue,
             Number = voluntary.Address.Number,
             Neighborhood = voluntary.Address.Neighborhood,
             City = voluntary.Address.City,
             State = voluntary.Address.State
         }
     });
 }
 // PUT api/values/5
 public HttpResponseMessage Put(Guid id, [FromBody] Voluntary voluntary)
 {
     Console.WriteLine("PUT CONTROLLER");
     try
     {
         //Neste local faria a alteracao do voluntario no repositorio
         //Antes de fazer a alteracao, o sistema deve verificar se existe o voluntario
         //Se existir aplica as mudanças
         VoluntaryDTO voluntaryDto = Find(id);
         if (voluntaryDto == null)
         {
             return(Request.CreateResponse(HttpStatusCode.NotFound, "Voluntario não encontrado"));
         }
         else
         {
             Alter(voluntary);
             return(Request.CreateResponse(HttpStatusCode.OK, id));
         }
     }
     catch (ApplicationException ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
Example #4
0
        public static int Save(Voluntary voluntary)
        {
            var a = new Voluntary
            {
                VoluntaryNo           = voluntary.VoluntaryNo,
                PersonnelNo           = voluntary.PersonnelNo,
                VoluntaryOrganization = voluntary.VoluntaryOrganization,
                VoluntaryDate1        = voluntary.VoluntaryDate1,
                VoluntaryDate2        = voluntary.VoluntaryDate2,
                VoluntaryNoHours      = voluntary.VoluntaryNoHours,
                VoluntaryPosition     = voluntary.VoluntaryPosition,
                IsActive     = voluntary.IsActive,
                modifieddate = voluntary.modifieddate
            };

            using (_d = new DataRepository <Voluntary>())
            {
                if (voluntary.VoluntaryNo > 0)
                {
                    _d.Update(a);
                }
                else
                {
                    _d.Add(a);
                }

                _d.SaveChanges();
            }

            return(a.VoluntaryNo);
        }
Example #5
0
        public void Edit(Voluntary volutary)
        {
            Voluntary voluntarioOld = GetById(volutary.Id);

            voluntarioOld = volutary;
            Save();
        }
        public ActionResult DeleteConfirmed(string id)
        {
            Voluntary voluntary = db.Voluntary.Find(id);
            Photo     Photo     = db.Photo.Find(voluntary.photo_id);

            //Valida si ya existe un voluntario asociado a una actividad

            if (voluntary.Activity.Count() > 0)
            {
                List <Activity> activities = voluntary.Activity.ToList();

                for (int i = 0; i > activities.Count(); i++)
                {
                    voluntary.Activity.Remove(activities[i]);
                }
            }

            //eliminar imagen
            var locationStatic = Path.Combine(Server.MapPath("/Static/"));

            System.IO.File.Delete(locationStatic + Photo.image);

            db.Photo.Remove(Photo);
            db.Voluntary.Remove(voluntary);

            db.SaveChanges();
            return(RedirectToAction("Index", new { mensaje = "El voluntario " + voluntary.name + " " + voluntary.last_name + " ha sido eliminado exitosamente" }));
        }
        private void CadastroVoluntarioNew_Load(object sender, EventArgs e)
        {
            CarregarComboboxCidade();
            CarregarComboboxFuncao();

            if (VoluntarioId == 0)
            {
                Voluntario = new Voluntary();
            }
            else
            {
                Voluntario        = voluntaryService.GetById(VoluntarioId);
                tbCodigo.Text     = Voluntario.Id.ToString();
                tbCPF.Text        = Voluntario.CPF;
                cbFuncao.Text     = Voluntario.Function.ToString();
                tbCRM.Text        = Voluntario.CRM.ToString();
                tbNome.Text       = Voluntario.Name;
                cbCidade.Text     = Voluntario.City.Name;
                tbEndereco.Text   = Voluntario.Address;
                tbEmail.Text      = Voluntario.Email;
                tbTelefone.Text   = Voluntario.Phone;
                tbEntrada.Text    = Voluntario.DateEntry.ToString();
                tbObservacao.Text = Voluntario.Note;
            }
        }
Example #8
0
        public void InsertDateDeparture(Voluntary voluntary)
        {
            Voluntary voluntarioOld = GetById(voluntary.Id);

            voluntarioOld.DateDeparture = voluntary.DateDeparture;

            Save();
        }
Example #9
0
        public void Update(Voluntary volutary)
        {
            if (volutary == null)
            {
                throw new Exception("O voluntario não pode ser nulo");
            }

            if (string.IsNullOrEmpty(volutary.CPF))
            {
                throw new Exception("O voluntario precisa ter CPF");
            }

            if (string.IsNullOrEmpty(volutary.Name))
            {
                throw new Exception("O voluntario precisa ter Name");
            }

            if (volutary.Function.Procedure == "Sim")
            {
                if (string.IsNullOrEmpty(volutary.CRM))
                {
                    throw new Exception("Função com procedimento médico, preencha o CRM");
                }
            }

            if (string.IsNullOrEmpty(volutary.Address))
            {
                throw new Exception("O voluntario precsa ter Endereço");
            }

            if (string.IsNullOrEmpty(volutary.Email))
            {
                throw new Exception("O voluntario precisa ter Email");
            }

            if (string.IsNullOrEmpty(volutary.Phone))
            {
                throw new Exception("O voluntario precisa ter Telefone");
            }

            if (string.IsNullOrEmpty(volutary.Address))
            {
                throw new Exception("O voluntario precsa ter Endereço");
            }

            if (string.IsNullOrEmpty(volutary.Email))
            {
                throw new Exception("O voluntario precisa ter Email");
            }

            if (volutary.DateEntry == null || volutary.DateEntry == DateTime.MinValue)
            {
                throw new Exception("Informe a data de entrada do voluntário");
            }

            voluntaryRepository.Edit(volutary);
        }
Example #10
0
        public static bool Delete(Voluntary voluntary)
        {
            using (_d = new DataRepository <Voluntary>())
            {
                _d.Delete(voluntary);
                _d.SaveChanges();
            }

            return(true);
        }
Example #11
0
        public void Delete(long id)
        {
            Voluntary voluntary = voluntaryRepository.GetById(id);

            if (voluntary == null)
            {
                throw new Exception("Voluntary não encontrado");
            }

            voluntaryRepository.Delete(voluntary);
        }
        public Guid Update(Voluntary voluntary)
        {
            using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
            {
                con.Open();
                using (var trans = con.BeginTransaction())
                {
                    try
                    {
                        Guid userId = userRepository.Update(new User()
                        {
                            UserId      = voluntary.UserId,
                            IsApproved  = voluntary.IsApproved,
                            IsEntity    = voluntary.IsEntity,
                            IsVoluntary = voluntary.IsVoluntary,
                            IsModerator = voluntary.IsModerator,
                            Email       = voluntary.Email,
                            Password    = voluntary.Password
                        });

                        NpgsqlCommand cmd = new NpgsqlCommand();
                        cmd.Connection  = con;
                        cmd.Transaction = trans;

                        cmd.CommandText = @"UPDATE voluntary SET name = @name, socialnetwork = @socialnetwork WHERE voluntary_id = @voluntary_id";
                        cmd.Parameters.AddWithValue("voluntary_id", voluntary.VoluntaryId.ToString());
                        cmd.Parameters.AddWithValue("name", voluntary.Name);
                        cmd.Parameters.AddWithValue("phone", voluntary.Phone);
                        cmd.Parameters.AddWithValue("socialnetwork", voluntary.SocialNetwork);
                        cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();
                        cmd.CommandText = @"UPDATE address SET cep=@cep,avenue=@avenue,number=@number,neighborhood=@neighborhood,city=@city,state=@state WHERE address_id=@address_id";
                        cmd.Parameters.AddWithValue("address_id", voluntary.Address.AddressId.ToString());
                        cmd.Parameters.AddWithValue("cep", voluntary.Address.CEP);
                        cmd.Parameters.AddWithValue("avenue", voluntary.Address.Avenue);
                        cmd.Parameters.AddWithValue("number", voluntary.Address.Number);
                        cmd.Parameters.AddWithValue("neighborhood", voluntary.Address.Neighborhood);
                        cmd.Parameters.AddWithValue("city", voluntary.Address.City);
                        cmd.Parameters.AddWithValue("state", voluntary.Address.State);
                        cmd.ExecuteNonQuery();

                        trans.Commit();
                        return(voluntary.VoluntaryId);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
        public ActionResult Create([Bind(Include = "identification,name,last_name,state,photo_id,email,address,phone_number,link,description")] Voluntary voluntary, Boolean state, HttpPostedFileBase File, string nameFile, string description)
        {
            var query = (from r in db.Voluntary where r.identification == voluntary.identification select r).Count();

            if (query == 1)
            {
                return(RedirectToAction("Create/" + voluntary.identification, new { mensaje = "El voluntario con la identificación " + voluntary.identification + " ya se encuentra registrado en el sistema" }));
            }
            else
            {
                if (ModelState.IsValid)
                {
                    voluntary.state = state;

                    if (File == null)
                    {
                        ViewBag.MessagePhoto = "Debe ingresar una imagen";
                        return(View());
                    }
                    else
                    {
                        if (nameFile == "")
                        {
                            ViewBag.MessagePhotoName = "Debe ingresar un nombre";
                            ViewBag.MessagePhoto     = "Debe ingresar una imagen";
                            return(View());
                        }
                        else
                        {
                            var extension = Path.GetExtension(File.FileName);
                            var path      = Path.Combine(Server.MapPath("/Static/"), nameFile + extension);

                            var Photo = new DB.Photo();
                            Photo.name  = nameFile;
                            Photo.image = nameFile + extension;
                            File.SaveAs(path);

                            db.Photo.Add(Photo);

                            voluntary.description = description;
                            db.Voluntary.Add(voluntary);
                            db.SaveChanges();
                        }
                    }

                    return(RedirectToAction("Index", new { mensaje = "El voluntario " + voluntary.name + " " + voluntary.last_name + " ha sido ingresado exitosamente" }));
                }
            }

            return(View(voluntary));
        }
        // GET: Voluntaries/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Voluntary voluntary = db.Voluntary.Find(id);

            if (voluntary == null)
            {
                return(HttpNotFound());
            }
            ViewBag.image = Path.Combine("/Static/", voluntary.Photo.image);
            ViewBag.name  = voluntary.name + " " + voluntary.last_name;

            return(View(voluntary));
        }
        public bool Delete(Guid id)
        {
            using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
            {
                con.Open();
                using (var trans = con.BeginTransaction())
                {
                    try
                    {
                        Voluntary voluntary = this.Find(id);

                        NpgsqlCommand cmd = new NpgsqlCommand();
                        cmd.Connection  = con;
                        cmd.Transaction = trans;

                        cmd.CommandText = @"DELETE FROM voluntary_affinity WHERE voluntary_id=@voluntary_id";
                        cmd.Parameters.AddWithValue("voluntary_id", voluntary.VoluntaryId.ToString());
                        cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();

                        cmd.CommandText = @"DELETE FROM voluntary WHERE voluntary_id=@voluntary_id";
                        cmd.Parameters.AddWithValue("voluntary_id", voluntary.VoluntaryId.ToString());
                        cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();

                        cmd.CommandText = @"DELETE FROM address WHERE address_id=@address_id";
                        cmd.Parameters.AddWithValue("address_id", voluntary.Address.ToString());
                        cmd.ExecuteNonQuery();

                        trans.Commit();

                        userRepository.Delete(voluntary.UserId);

                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
        private Guid Insert(Voluntary voluntary)
        {
            Console.WriteLine("POST METHOD CONTROLLER");
            //return Guid.NewGuid();
            //executa o mapeamento

            List <AffinityDTO> affinities = new List <AffinityDTO>();

            foreach (var affinity in voluntary.Affinities)
            {
                AffinityDTO affinityDTO = new AffinityDTO()
                {
                    AffinityId = affinity.AffinityId,
                    Name       = affinity.Name
                };
                affinities.Add(affinityDTO);
            }

            VoluntaryDTO voluntaryDTO = new VoluntaryDTO()
            {
                VoluntaryId   = voluntary.VoluntaryId,
                UserId        = voluntary.UserId,
                IsApproved    = voluntary.IsApproved,
                IsVoluntary   = voluntary.IsVoluntary,
                Name          = voluntary.Name,
                Email         = voluntary.Email,
                Phone         = voluntary.Phone,
                Password      = voluntary.Password,
                SocialNetwork = voluntary.SocialNetwork,
                Affinities    = affinities,
                Address       = new AddressDTO()
                {
                    CEP          = voluntary.Address.CEP,
                    Avenue       = voluntary.Address.Avenue,
                    Number       = voluntary.Address.Number,
                    Neighborhood = voluntary.Address.Neighborhood,
                    City         = voluntary.Address.City,
                    State        = voluntary.Address.State
                }
            };

            return(voluntaryApplication.Insert(voluntaryDTO));
        }
Example #17
0
        public IActionResult SaveVoluntary(Voluntary s)
        {
            var r = new RequestModel();

            try
            {
                s.CreateTime = DateTime.Now;
                if (s.Id > 0)
                {
                    //修改
                    db.Voluntarys.Update(s);
                    if (db.SaveChanges() > 0)
                    {
                        r.code = 1;
                    }
                    else
                    {
                        r.msg = "保存失败";
                    }
                }
                else
                {
                    //新增
                    db.Voluntarys.Add(s);
                    if (db.SaveChanges() > 0)
                    {
                        r.code = 1;
                    }
                    else
                    {
                        r.msg = "保存失败";
                    }
                }
                return(Ok(r));
            }
            catch (Exception e)
            {
                //打印日志
                r.msg = e.Message;
            }
            return(Ok(r));
        }
Example #18
0
        public ActionResult ApproveVoluntary(Guid id)
        {
            if (!isAuthenticated())
            {
                return(Json(new { status = "error" }));
            }

            Voluntary voluntary = (Voluntary)clientHttp.Get <Voluntary>(string.Format(@"Voluntary/{0}", id.ToString()));

            if (voluntary != null)
            {
                voluntary.IsApproved = true;

                var voluntary_id = clientHttp.Put <Voluntary>(@"Voluntary/", id, voluntary);

                return(Json(new { status = "success", message_title = "Voluntário aprovado com sucesso" }));
            }

            return(Json(new { status = "error", message_title = "Erro ao aprovar voluntário" }));
        }
        public ActionResult Edit([Bind(Include = "identification,name,last_name,description,state,photo_id,email,address,phone_number,link")] Voluntary voluntary, Boolean state, HttpPostedFileBase File, string nameFile, string description)
        {
            if (ModelState.IsValid)
            {
                db.Entry(voluntary).State = EntityState.Modified;
                voluntary.state           = state;

                if (File != null)
                {
                    if (nameFile != "")
                    {
                        var Photo = db.Photo.Find(voluntary.photo_id);
                        Photo.name = nameFile;

                        //elimina la imagen anterior
                        var locationStatic = Path.Combine(Server.MapPath("/Static/"));
                        System.IO.File.Delete(locationStatic + Photo.image);

                        var extension = Path.GetExtension(File.FileName);
                        var path      = Path.Combine(Server.MapPath("/Static/"), nameFile + extension);
                        File.SaveAs(path);
                        Photo.image = nameFile + extension;

                        db.SaveChanges();
                    }
                }
                if (nameFile != "")
                {
                    var Photo = db.Photo.Find(voluntary.photo_id);
                    Photo.name = nameFile;

                    db.SaveChanges();
                }

                voluntary.description = description;
                db.SaveChanges();

                return(RedirectToAction("Index", new { mensaje = "El voluntario " + voluntary.name + " " + voluntary.last_name + " ha sido actualizado exitosamente" }));
            }
            return(View(voluntary));
        }
        // POST api/values
        public HttpResponseMessage Post([FromBody] Voluntary voluntary)
        {
            Console.WriteLine("POST CONTROLLER");
            try
            {
                //Neste local faria a inclusao do voluntario no repositorio
                //Antes de fazer a inclusão o voluntario seria consistido
                //Se o voluntario for inserido é de responsabilidade da API retornar o código do voluntario gerado no processo de inclusão

                Guid id = Insert(voluntary);
                return(Request.CreateResponse(HttpStatusCode.OK, id));
            }
            catch (ApplicationException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
        private void Alter(Voluntary voluntary)
        {
            List <AffinityDTO> affinities = new List <AffinityDTO>();

            foreach (var affinity in voluntary.Affinities)
            {
                AffinityDTO affinityDTO = new AffinityDTO()
                {
                    AffinityId = affinity.AffinityId,
                    Name       = affinity.Name
                };
                affinities.Add(affinityDTO);
            }

            VoluntaryDTO voluntaryDTO = new VoluntaryDTO()
            {
                VoluntaryId   = voluntary.VoluntaryId,
                UserId        = voluntary.UserId,
                IsApproved    = voluntary.IsApproved,
                IsVoluntary   = voluntary.IsVoluntary,
                Name          = voluntary.Name,
                Email         = voluntary.Email,
                Phone         = voluntary.Phone,
                Password      = voluntary.Password,
                SocialNetwork = voluntary.SocialNetwork,
                Affinities    = affinities,
                Address       = new AddressDTO()
                {
                    CEP          = voluntary.Address.CEP,
                    Avenue       = voluntary.Address.Avenue,
                    Number       = voluntary.Address.Number,
                    Neighborhood = voluntary.Address.Neighborhood,
                    City         = voluntary.Address.City,
                    State        = voluntary.Address.State
                }
            };

            voluntaryApplication.Update(voluntaryDTO);
        }
        public Voluntary Find(Guid id)
        {
            Voluntary voluntary = null;

            using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
            {
                con.Open();

                NpgsqlCommand cmd = new NpgsqlCommand();
                cmd.Connection  = con;
                cmd.CommandText = @"SELECT * FROM voluntary WHERE voluntary_id=@voluntary_id";
                cmd.Parameters.AddWithValue("voluntary_id", id.ToString());
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    voluntary               = new Voluntary();
                    voluntary.VoluntaryId   = Guid.Parse(reader["voluntary_id"].ToString());
                    voluntary.UserId        = Guid.Parse(reader["user_id"].ToString());
                    voluntary.Name          = reader["Name"].ToString();
                    voluntary.Phone         = reader["Phone"].ToString();
                    voluntary.SocialNetwork = reader["SocialNetwork"].ToString();
                    voluntary.Address       = new Address()
                    {
                        AddressId = Guid.Parse(reader["address_id"].ToString())
                    };
                }
                reader.Close();
                cmd.Parameters.Clear();

                User user = userRepository.Find(voluntary.UserId);
                voluntary.UserId      = user.UserId;
                voluntary.IsApproved  = user.IsApproved;
                voluntary.IsEntity    = user.IsEntity;
                voluntary.IsVoluntary = user.IsVoluntary;
                voluntary.IsModerator = user.IsModerator;
                voluntary.Email       = user.Email;
                voluntary.Password    = user.Password;

                cmd.CommandText = @"SELECT * FROM address WHERE address_id=@Id";
                cmd.Parameters.AddWithValue("Id", voluntary.Address.AddressId.ToString());
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    voluntary.Address.CEP          = reader["cep"].ToString();
                    voluntary.Address.Avenue       = reader["avenue"].ToString();
                    voluntary.Address.Number       = reader["number"].ToString();
                    voluntary.Address.Neighborhood = reader["neighborhood"].ToString();
                    voluntary.Address.City         = reader["city"].ToString();
                    voluntary.Address.State        = reader["state"].ToString();
                }
                reader.Close();
                cmd.Parameters.Clear();

                cmd.CommandText = @"SELECT * FROM affinity af join voluntary_affinity av on af.affinity_id = av.affinity_id join voluntary vo on vo.voluntary_id = av.voluntary_id WHERE av.voluntary_id = @Id";
                cmd.Parameters.AddWithValue("Id", voluntary.VoluntaryId.ToString());
                reader = cmd.ExecuteReader();
                voluntary.Affinities = new List <Affinity>();
                while (reader.Read())
                {
                    voluntary.Affinities.Add(new Affinity()
                    {
                        AffinityId = Guid.Parse(reader["voluntary_id"].ToString()),
                        Name       = reader["name"].ToString()
                    });
                }

                return(voluntary);
            }
        }
Example #23
0
 public void Insert(Voluntary volutary)
 {
     db.Voluntaries.Add(volutary);
     Save();
 }
        public Guid Insert(Voluntary voluntary)
        {
            using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
            {
                con.Open();
                //Inicia a transação
                using (var trans = con.BeginTransaction())
                {
                    try
                    {
                        Guid userId = userRepository.Insert(new User()
                        {
                            UserId      = voluntary.UserId,
                            IsApproved  = voluntary.IsApproved,
                            IsEntity    = voluntary.IsEntity,
                            IsVoluntary = voluntary.IsVoluntary,
                            IsModerator = voluntary.IsModerator,
                            Email       = voluntary.Email,
                            Password    = voluntary.Password
                        });

                        NpgsqlCommand cmd = new NpgsqlCommand();
                        cmd.Connection  = con;
                        cmd.Transaction = trans;
                        cmd.Parameters.Clear();
                        cmd.CommandText = @"INSERT Into address (address_id,cep,avenue,number,neighborhood,city,state)values(@address_id,@cep,@avenue,@number,@neighborhood,@city,@state)";
                        cmd.Parameters.AddWithValue("address_id", voluntary.Address.AddressId);
                        cmd.Parameters.AddWithValue("cep", voluntary.Address.CEP);
                        cmd.Parameters.AddWithValue("avenue", voluntary.Address.Avenue);
                        cmd.Parameters.AddWithValue("number", voluntary.Address.Number);
                        cmd.Parameters.AddWithValue("neighborhood", voluntary.Address.Neighborhood);
                        cmd.Parameters.AddWithValue("city", voluntary.Address.City);
                        cmd.Parameters.AddWithValue("state", voluntary.Address.State);
                        cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();
                        cmd.CommandText = @"INSERT Into voluntary (voluntary_id,name,phone,socialnetwork,user_id,address_id) values (@voluntary_id,@name,@phone,@socialnetwork,@user_id,@address_id)";
                        cmd.Parameters.AddWithValue("voluntary_id", voluntary.VoluntaryId);
                        cmd.Parameters.AddWithValue("name", voluntary.Name);
                        cmd.Parameters.AddWithValue("phone", voluntary.Phone);
                        cmd.Parameters.AddWithValue("socialnetwork", voluntary.SocialNetwork);
                        cmd.Parameters.AddWithValue("user_id", voluntary.UserId);
                        cmd.Parameters.AddWithValue("address_id", voluntary.Address.AddressId);
                        cmd.ExecuteNonQuery();


                        foreach (var affinity in voluntary.Affinities)
                        {
                            cmd.Parameters.Clear();
                            cmd.CommandText = @"INSERT Into voluntary_affinity (voluntary_id, affinity_id) VALUES (@voluntary_id, @affinity_id)";
                            cmd.Parameters.AddWithValue("voluntary_id", voluntary.VoluntaryId);
                            cmd.Parameters.AddWithValue("affinity_id", affinity.AffinityId);
                            cmd.ExecuteNonQuery();
                        }

                        //commit na transação
                        trans.Commit();
                        return(voluntary.VoluntaryId);
                    }
                    catch (Exception ex)
                    {
                        //rollback da transação
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
Example #25
0
 public void Delete(Voluntary voluntario)
 {
     db.Voluntaries.Remove(voluntario);
     Save();
 }
Example #26
0
        public void InsertDateDeparture(Voluntary voluntario, DateTime saida)
        {
            voluntario.DateDeparture = saida;

            voluntaryRepository.InsertDateDeparture(voluntario);
        }
        public ActionResult Edit([Bind(Include = "id,name,descripcion,start_date,end_date,photo_id")] Activity activity, List <string> sponsors, List <string> voluntaries, List <string> users, HttpPostedFileBase File, string nameFile)
        {
            if (ModelState.IsValid)
            {
                db.Entry(activity).State = EntityState.Modified;

                Activity act = db.Activity.Include(a => a.Sponsor)
                               .Include(a => a.Voluntary).Include(a => a.User).ToList().Find(ca => ca.id == activity.id);
                var imageAct = db.Photo.Find(act.photo_id);

                //se ejecuta si hubo un cambio de imagen
                if (File != null)
                {
                    Photo image = db.Photo.Find(act.photo_id);
                    image.name = nameFile;

                    //elimina la imagen anterior
                    var locationStatic = Path.Combine(Server.MapPath("/Static/"));
                    System.IO.File.Delete(locationStatic + image.image);

                    //Escribe la nueva ruta de la imagen
                    var fileName = Path.GetExtension(File.FileName);
                    image.image = nameFile + fileName;
                    var path = Path.Combine(Server.MapPath("/Static/"), nameFile + fileName);

                    File.SaveAs(path);

                    db.SaveChanges();
                }

                if (nameFile != imageAct.name)
                {
                    var Photo = db.Photo.Find(act.photo_id);
                    Photo.name = nameFile;

                    db.SaveChanges();
                }

                act.Sponsor.Clear();
                act.Voluntary.Clear();

                if (sponsors != null)
                {
                    if (sponsors.Count > 0)
                    {
                        System.Collections.IList listSponsors = sponsors;
                        for (int i = 0; i < listSponsors.Count; i++)
                        {
                            string  id = "" + listSponsors[i];
                            Sponsor s  = db.Sponsor.Find(id);
                            act.Sponsor.Add(s);
                        }
                    }
                }
                if (voluntaries != null)
                {
                    if (voluntaries.Count > 0)
                    {
                        System.Collections.IList listVoluntaries = voluntaries;
                        for (int i = 0; i < listVoluntaries.Count; i++)
                        {
                            string    id = "" + listVoluntaries[i];
                            Voluntary s  = db.Voluntary.Find(id);
                            act.Voluntary.Add(s);
                        }
                    }
                }
                if (users == null)
                {
                    return(RedirectToAction("Edit/" + activity.id, new { message = "Debe seleccionar almenos un usuario" }));
                }
                else
                {
                    if (users.Count > 0)
                    {
                        act.User.Clear();
                        System.Collections.IList listUsers = users;
                        for (int i = 0; i < listUsers.Count; i++)
                        {
                            string id = "" + listUsers[i];
                            User   s  = db.User.Find(id);
                            act.User.Add(s);
                        }
                    }
                }


                db.SaveChanges();

                return(RedirectToAction("Index", new { message = "Se actualizó la actividad exitosamente" }));
            }

            return(View(activity));
        }
        public ActionResult Create([Bind(Include = "id,name,descripcion,start_date,end_date")]
                                   Activity activity, List <string> sponsors, List <string> users, List <string> voluntaries, HttpPostedFileBase File, string nameFile)
        {
            //refill the lists
            List <Sponsor>   sponsorReturn   = db.Sponsor.ToList();
            List <User>      userReturn      = db.User.ToList();
            List <Voluntary> voluntaryReturn = db.Voluntary.ToList();
            List <Photo>     photoVerify     = db.Photo.ToList();

            if (ModelState.IsValid)
            {
                //if the sponsors list are fill
                if (sponsors != null)
                {
                    if (sponsors.Count > 0)
                    {
                        System.Collections.IList listSponsors = sponsors;
                        for (int i = 0; i < listSponsors.Count; i++)
                        {
                            string  id      = "" + listSponsors[i];
                            Sponsor sponsor = db.Sponsor.Find(id);
                            activity.Sponsor.Add(sponsor);
                        }
                    }
                }

                //if the users list are empty
                if (users == null)
                {
                    //if the sponsors list are fill so fill the viewbag
                    if (sponsors != null)
                    {
                        System.Collections.IList listSponsors = sponsors;
                        for (int i = 0; i < listSponsors.Count; i++)
                        {
                            string  id      = "" + listSponsors[i];
                            Sponsor sponsor = db.Sponsor.Find(id);
                            activity.Sponsor.Add(sponsor);
                        }
                    }
                    //if the voluntaries list are fill so fill the viewbag
                    if (voluntaries != null)
                    {
                        System.Collections.IList listVoluntaries = voluntaries;
                        for (int i = 0; i < listVoluntaries.Count; i++)
                        {
                            string    id        = "" + listVoluntaries[i];
                            Voluntary voluntary = db.Voluntary.Find(id);
                            activity.Voluntary.Add(voluntary);
                        }
                    }
                    //if the nameFile is different of null so fill the viewbag
                    if (nameFile != "")
                    {
                        ViewBag.name = nameFile;
                    }


                    //refill the lists
                    ViewBag.sponsors    = sponsorReturn;
                    ViewBag.users       = userReturn;
                    ViewBag.voluntaries = voluntaryReturn;

                    ViewBag.message = "Debe seleccionar al menos un usuario";
                    return(View(activity));
                }

                //if the user list are fill
                else
                {
                    System.Collections.IList listUsers = users;
                    for (int i = 0; i < listUsers.Count; i++)
                    {
                        string id   = "" + listUsers[i];
                        User   user = db.User.Find(id);
                        activity.User.Add(user);
                    }
                }

                //if the voluntaries are fill
                if (voluntaries != null)
                {
                    if (voluntaries.Count > 0)
                    {
                        System.Collections.IList listVoluntaries = voluntaries;
                        for (int i = 0; i < listVoluntaries.Count; i++)
                        {
                            string    id        = "" + listVoluntaries[i];
                            Voluntary voluntary = db.Voluntary.Find(id);
                            activity.Voluntary.Add(voluntary);
                        }
                    }
                }

                //if the photo file is empty
                if (File == null)
                {
                    //if the name file is different of null fill the viewbag
                    if (nameFile != "")
                    {
                        ViewBag.name = nameFile;
                    }

                    //refill the lists
                    ViewBag.sponsors    = sponsorReturn;
                    ViewBag.users       = userReturn;
                    ViewBag.voluntaries = voluntaryReturn;
                    ViewBag.message     = "Debe ingresar una imagen";
                    return(View(activity));
                }

                //if the File is fill
                else
                {
                    //but the name file is empty
                    if (nameFile == "")
                    {
                        //refill the lists
                        ViewBag.sponsors    = sponsorReturn;
                        ViewBag.users       = userReturn;
                        ViewBag.voluntaries = voluntaryReturn;
                        ViewBag.message     = "Debe ingresar un nombre de imagen";
                        return(View(activity));
                    }

                    //if the file is fill and name too
                    else
                    {
                        foreach (Photo photo in photoVerify)
                        {
                            //if(nameFile == photo.image)
                        }

                        //add the image in the folder, in the activity and database
                        var extension = Path.GetExtension(File.FileName);
                        var path      = Path.Combine(Server.MapPath("/Static/"), nameFile + extension);

                        var Photo = new DB.Photo();
                        Photo.name  = nameFile;
                        Photo.image = nameFile + extension;
                        File.SaveAs(path);

                        db.Photo.Add(Photo);

                        db.Activity.Add(activity);
                        db.SaveChanges();
                    }
                }
                return(RedirectToAction("Index", new { message = "La actividad se ingresó exitosamente" }));
            }


            return(View(activity));
        }