Esempio n. 1
0
        public static bool LogAction(Models.Log log)
        {
            if (log.Description.Length == 0)
            {
                log.Description = "[NO DESCRIPTION GIVEN]";
            }
            if (log.UserId <= 0)
            {
                log.Description = "[INVALID USER] " + log.Description;
            }
            if (log.ModifiedId <= 0)
            {
                log.Description = "[INVALID MODIFIED ID] " + log.Description;
            }
            if (log.Changes.Length == 0 && (log.Action == Models.Log.ActionType.ModifyInstaller || log.Action == Models.Log.ActionType.ModifyManager ||
                                            log.Action == Models.Log.ActionType.ModifySite || log.Action == Models.Log.ActionType.ModifyUser))
            {
                log.Description = "[NO CHANGES GIVEN] " + log.Description;
                log.Changes     = "[NO CHANGES GIVEN]";
            }

            using (var context = new Data.ApplicationDbContext()) {
                context.Add(log);
                context.SaveChanges();
            }
            return(true);
        }
Esempio n. 2
0
        public void AdicionarProduto(Produto produto)
        {
            using var db = new Data.ApplicationDbContext();

            db.Add(produto);
            db.SaveChanges();
        }
Esempio n. 3
0
        /// <summary>
        /// This method allows you to create and send a notification, with the
        /// necessary data related to the operation of changing the type of account.
        /// The process of sending the notification to moderators involves adding it
        /// to the database and showing it whenever requested.
        /// </summary>
        /// <param name="user">User asking to update account type.</param>
        /// <see cref="User"/>
        /// <see cref="Notification"/>
        private void SendNotification(User user)
        {
            var subject = "Foi feito um novo pedido de alteração de conta para prestador";
            var content = user.FirstName + " " + user.LastName + " fez um pedido de alteração de conta. Por favor responda o quanto antes.";

            //NotificationsController notificationController = new NotificationsController(_context, _userManager);

            /*52c6c3c1-843a-4baf-b12f-c8f39ba31fcb -> ID do Role Moderador*/
            List <string> ids = _context.UserRoles
                                .Where(ur => ur.RoleId == "52c6c3c1-843a-4baf-b12f-c8f39ba31fcb")
                                .Select(ur => ur.UserId).ToList();

            ids.ForEach(id =>
            {
                Notification notification = new()
                {
                    DestinaryID  = id,
                    Subject      = subject,
                    Content      = content,
                    IsRead       = false,
                    Action       = "/Requests",
                    CreationDate = DateTime.Now,
                };
                //var result = notificationController.Create(notification).Result;
                _context.Add(notification);
                _context.SaveChanges();
            });
        }
Esempio n. 4
0
 public IActionResult Registro([FromBody] Usuario usuario)
 {
     //Verificar se as credenciais são válidas
     //Verificar se o e-mail já está cadastrado no banco
     //Encriptar a senha
     database.Add(usuario);
     database.SaveChanges();
     return(Ok(new { msg = "Usuário cadastrado com sucesso!" }));
 }
Esempio n. 5
0
 public IActionResult Create(ProductTypes productTypes)
 {
     if (ModelState.IsValid)
     {
         _db.Add(productTypes);
         _db.SaveChanges();
         return(RedirectToAction(nameof(Index)));
     }
     return(View());
 }
        public async Task <IActionResult> Create([Bind("Id,NomeProfessor,SenhaProfessor,Cpf")] Professor professor)
        {
            if (ModelState.IsValid)
            {
                _context.Add(professor);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(professor));
        }
        public async Task <IActionResult> Create([Bind("Id,NomeAluno,SenhaAluno,Matricula")] Aluno aluno)
        {
            if (ModelState.IsValid)
            {
                _context.Add(aluno);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(aluno));
        }
Esempio n. 8
0
        [ValidateAntiForgeryToken] // Security mechanism that .net implmented for us. Gets added to request and server checks if the request is not altered on the way
        public async Task <IActionResult> Create(Models.ProductTypes productTypes)
        {
            if (ModelState.IsValid)
            {
                _db.Add(productTypes);
                await _db.SaveChangesAsync();

                //return RedirectToAction("Index"); //This can have typo
                return(RedirectToAction(nameof(Index)));
            }
            return(View(productTypes));
        }
        public async Task Post([FromForm] Models.CoffeeMakerTelemetry telemetry, IFormFile file)
        {
            var folder = $"telemetry/{telemetry.CoffeeMakerId}";

            Directory.CreateDirectory(folder);

            telemetry.DataFileName = $"{folder}/{telemetry.Date.ToString("yyyyMMdd-hhmmss")}.txt";

            using (var stream = new FileStream(telemetry.DataFileName, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            _context.Add(telemetry);
            await _context.SaveChangesAsync();
        }
Esempio n. 10
0
        async public void AddAssignment(Models.Assignment assignment)
        {
            _context.Assignment.Add(assignment);
            List <Enrollment> enrollments = _context.Enrollment.Where(x => x.SectionId == assignment.SectionId).ToList();
            await _context.SaveChangesAsync();

            foreach (Enrollment x in enrollments)
            {
                StudentAssignment studentAssignment = new StudentAssignment();
                studentAssignment.StudentId    = x.StudentId;
                studentAssignment.Grade        = null;
                studentAssignment.AssignmentId = assignment.Id;
                _context.Add(studentAssignment);
                _context.SaveChanges();
            }
            ;
        }
Esempio n. 11
0
        public async Task <IActionResult> Create([Bind("GiveAwayItemId,Title,Key,SteamID,Link,Views,Owner,Receiver")] GiveAwayItem item)
        {
            if (ModelState.IsValid)
            {
                //TODO: Attribute Verification aka if links are links and etc
                var user = await _manager.GetUserAsync(HttpContext.User);

                user       = _context.ChatUserModels.Where(x => x.Id == user.Id).Include(x => x.OwnedItems).FirstOrDefault();
                item.Owner = user;
                _context.Add(item);
                await _context.SaveChangesAsync();
            }
            else
            {
                return(View(item));
            }
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> RegisterAsNGO([Bind(nameof(NGO.Name))] NGO ngo)
        {
            if (ModelState.IsValid)
            {
                Identity identity = ControllerContext.GetIdentity();

                ngo.ID          = Guid.NewGuid();
                ngo.CreatedByID = identity.ID;
                ngo.NGOStatus   = NGOStatus.PendingVerification;

                applicationDbContext.Add(ngo);

                await applicationDbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(ngo));
        }
Esempio n. 13
0
        public async Task <IActionResult> AddandRemoveSchedule(Schedule s)
        {
            try
            {
                var user = await GetCurrentUserAsync();

                var userId = user?.Id;
                var slots  = _context.Student.Where(p => p.IdentityId.Equals(userId)).FirstOrDefault();
                s.StudentId = slots.Id;
                var schedule = _context.Slots.Where(p => p.Id == s.SlotId).FirstOrDefault();
                var studentslotvalidation = _context.Schedule.Where(p => p.StudentId.Equals(s.StudentId) && p.Date == schedule.ScheduleDateTime && schedule.Id != p.SlotId).FirstOrDefault();
                if (studentslotvalidation == null)
                {
                    var slot = _context.Schedule.Where(p => p.StudentId.Equals(s.StudentId) && p.Date == s.Date).FirstOrDefault();
                    if (slot == null)
                    {
                        s.CreatedBy   = "test";
                        s.CreatedDate = System.DateTime.Now;
                        s.UpdatedBy   = "test1";
                        s.UpdatedDate = System.DateTime.Now;
                        _context.Add(s);
                        _context.SaveChanges();
                        return(Json(new { success = true }));
                    }
                    else
                    {
                        _context.Remove(slot);
                        _context.SaveChanges();
                        return(Json(new { success = false }));
                    }
                }
                else
                {
                    return(Json(new { success = studentslotvalidation }));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 14
0
        public IActionResult Index()
        {
            MailSetting cms;

            cms = context.MailSettings.FirstOrDefault();
            if (cms == null)
            {
                cms                     = new MailSetting();
                cms.FromAddress         = "*****@*****.**";
                cms.FromAddressPassword = "******";
                cms.FromAddressTitle    = "Cv Havuzu";
                cms.Subject             = "Ýletiþim";
                cms.BodyContent         = "Mesajýnýz Bize Ýletilmiþtir. Ýlginiz Ýçin Teþekkür Ederiz";
                cms.SmptServer          = "smtp.gmail.com";
                cms.SmptPortNumber      = 587;
                cms.UseSSL              = false;
                context.Add(cms);
                context.SaveChanges();
            }
            return(View(cms));
        }
Esempio n. 15
0
        public IActionResult Index()
        {
            MailSetting cms;

            cms = context.MailSettings.FirstOrDefault();
            if (cms == null)
            {
                cms                  = new MailSetting();
                cms.FromAddress      = "*****@*****.**";
                cms.MailUsername     = "******";
                cms.MailPassword     = "******";
                cms.FromAddressTitle = "Cv Havuzu";
                cms.Subject          = "CV Havuzu İletişim Formu - {0}";
                cms.BodyContent      = "Mesaj�n�z Bize �letilmi�tir. �lginiz ��in Te�ekk�r Ederiz";
                cms.SmptServer       = "smtp.gmail.com";
                cms.SmptPortNumber   = 587;
                cms.UseSSL           = false;
                cms.ToAddress        = "*****@*****.**";
                context.Add(cms);
                context.SaveChanges();
            }
            return(View(cms));
        }
Esempio n. 16
0
 public void Add(Learner learner)
 {
     _context.Add(learner);
     _context.SaveChanges();
 }
 public void Add(Playlist playlist)
 {
     _dbContext.Add(playlist);
 }
Esempio n. 18
0
 public void Add(Report report)
 {
     _context.Add(report);
     _context.SaveChanges();
 }
        public async Task <IActionResult> OnPostAsync(List <IFormFile> files, string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser
                {
                    UserName                  = Input.Email,
                    Email                     = Input.Email,
                    PhoneNumber               = Input.PhoneNumber,
                    DialingCode               = Input.DialingCode,
                    Address                   = Input.Address,
                    Longitude                 = Input.Longitude.Value,
                    Latitude                  = Input.Latitude.Value,
                    HasDriverLicence          = Input.HasDriverLicence,
                    TransportationMethod      = Input.TransportationMethod,
                    OtherTransportationMethod = Input.OtherTransportationMethod,
                    RangeInKm                 = Input.RangeInKm
                };

                IdentityResult result = await userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    logger.LogInformation("User created a new account with password.");

                    if (Input.RegisterAs == RegisterAs.NGO)
                    {
                        NGO ngo = new NGO();
                        ngo.ID          = Guid.NewGuid();
                        ngo.CreatedByID = Guid.Parse(user.Id);
                        ngo.NGOStatus   = NGOStatus.PendingVerification;

                        ngo.IdentificationNumber = Input.NGORegistrationModel.IdentificationNumber;
                        ngo.Name = Input.NGORegistrationModel.Name;
                        ngo.HeadquartersAddress          = Input.NGORegistrationModel.HeadquartersAddress;
                        ngo.HeadquartersAddressLatitude  = Input.NGORegistrationModel.HeadquartersAddressLatitude;
                        ngo.HeadquartersAddressLongitude = Input.NGORegistrationModel.HeadquartersAddressLongitude;
                        ngo.HeadquartersEmail            = Input.NGORegistrationModel.HeadquartersEmail;
                        ngo.HeadquartersPhoneNumber      = Input.NGORegistrationModel.HeadquartersPhoneNumber;
                        ngo.DialingCode = Input.NGORegistrationModel.DialingCode;
                        ngo.Website     = Input.NGORegistrationModel.Website;

                        ngo.CategoryID = Input.NGORegistrationModel.CategoryID;
                        ngo.ServiceID  = Input.NGORegistrationModel.ServiceID;

                        if (files.Any())
                        {
                            ngo.FileIDs = await UploadFiles(files);
                        }

                        applicationDbContext.Add(ngo);
                    }
                    else if (Input.RegisterAs == RegisterAs.Volunteer)
                    {
                        Volunteer volunteer = new Volunteer();
                        volunteer.ID              = Guid.Parse(user.Id);
                        volunteer.NGOID           = Input.NGOID;
                        volunteer.Name            = user.Email;
                        volunteer.VolunteerStatus = VolunteerStatus.PendingVerification;
                        volunteer.ActivateNotificationsFromOtherNGOs = Input.ActivateNotificationsFromOtherNGOs;
                        if (!volunteer.NGOID.HasValue)
                        {
                            volunteer.UnaffiliationStartTime = DateTime.UtcNow;
                        }

                        applicationDbContext.Add(volunteer);
                    }
                    else if (Input.RegisterAs == RegisterAs.Beneficiary)
                    {
                        // pentru inregistrarea de Beneficiar
                    }

                    await userManager.AddToRoleAsync(user, CustomIdentityRole.Guest);

                    await applicationDbContext.SaveChangesAsync();

                    var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    if (userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        await emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                         $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, DisplayConfirmAccountLink = false }));
                    }
                    else
                    {
                        await signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            await FillRegistrationDataAsync(Input.RegisterAs);

            // If we got this far, something failed, redisplay form
            return(Page());
        }
 public void Add(Activity activity)
 {
     _context.Add(activity);
     _context.SaveChanges();
 }
Esempio n. 21
0
 public void Add(Behavior behavior)
 {
     _context.Add(behavior);
     _context.SaveChanges();
 }