SaveChangesAsync() public method

public SaveChangesAsync ( CancellationToken cancellationToken ) : Task
cancellationToken CancellationToken
return Task
Exemplo n.º 1
0
 public async Task AddPostAsync(Vendor vendor, Post post)
 {
     vendor.Posts.Add(post);
     _context.Update(vendor);
     await _context.SaveChangesAsync();
 }
        public async Task <bool> EliminarUsuarioAsync(UsuariosEntidad usuario)
        {
            _context.Users.Remove(usuario);

            return(await _context.SaveChangesAsync() > 0 ? true : false);
        }
        public async Task <ActionResult> RecargarSaldo(Tags modelTag, string ReturnController)
        {
            try
            {
                db.Configuration.ValidateOnSaveEnabled = false;
                var FoundTag = await db.Tags.Join(
                    db.CuentasTelepeajes,
                    tag => tag.CuentaId,
                    cue => cue.Id,
                    (tag, cue) => new { tag, cue })
                               .Where(x => x.tag.NumTag == modelTag.NumTag)
                               .FirstOrDefaultAsync();

                if (FoundTag == null)
                {
                    TempData["ECreate"] = $"El tag no existe.";
                    return(RedirectToAction("Index", ReturnController));
                }

                var UserId = User.Identity.GetUserId();

                var lastCorteUser = await db.CortesCajeros
                                    .Where(x => x.IdCajero == UserId)
                                    .OrderByDescending(x => x.DateTApertura).FirstOrDefaultAsync();

                if (lastCorteUser != null)
                {
                    var FoundCliente = await db.CuentasTelepeajes.Join(
                        db.Clientes,
                        cue => cue.ClienteId,
                        cli => cli.Id,
                        (cue, cli) => new { cue, cli })
                                       .Where(x => x.cli.Id == FoundTag.cue.ClienteId)
                                       .FirstOrDefaultAsync();

                    if (FoundCliente.cli.StatusCliente == false)
                    {
                        TempData["ECreate"] = "No se puede recargar saldo al tag: " + modelTag.NumTag + " porque el cliente al que pertenece está dado de baja.";
                        return(RedirectToAction("Index", ReturnController));
                    }

                    if (FoundTag.cue.TypeCuenta == "Individual")
                    {
                        if (FoundTag.cue.StatusCuenta == true)
                        {
                            var Saldo = (double.Parse(FoundTag.tag.SaldoTag) / 100).ToString("F2");

                            var SaldoNuevo = (Convert.ToDouble(Saldo) + double.Parse(modelTag.SaldoARecargar, new NumberFormatInfo {
                                NumberDecimalSeparator = ".", NumberGroupSeparator = ","
                            }));

                            var SaldoSend = Math.Round(SaldoNuevo, 2).ToString("F2");

                            SaldoSend             = SaldoSend.Replace(",", string.Empty);
                            FoundTag.tag.SaldoTag = SaldoSend.Replace(".", string.Empty);

                            if ((double.Parse(FoundTag.tag.SaldoTag, new NumberFormatInfo {
                                NumberDecimalSeparator = ".", NumberGroupSeparator = ","
                            }) / 100) >= 20)
                            {
                                if (FoundTag.tag.StatusTag == false)
                                {
                                    FoundTag.tag.StatusTag = true;
                                }
                            }

                            var detalle = new OperacionesCajero
                            {
                                Concepto       = "TAG RECARGA",
                                DateTOperacion = DateTime.Now,
                                Numero         = FoundTag.tag.NumTag,
                                Tipo           = "TAG",
                                TipoPago       = "EFE",
                                Monto          = double.Parse(modelTag.SaldoARecargar, new NumberFormatInfo {
                                    NumberDecimalSeparator = ".", NumberGroupSeparator = ","
                                }),
                                CorteId      = lastCorteUser.Id,
                                NoReferencia = await methods.RandomNumReferencia(),
                            };

                            db.OperacionesCajeros.Add(detalle);

                            db.Tags.Attach(FoundTag.tag);
                            db.Entry(FoundTag.tag).State = EntityState.Modified;
                            await db.SaveChangesAsync();

                            TempData["SCreate"] = $"Se recargó Q{modelTag.SaldoARecargar} al tag: {FoundTag.tag.NumTag} con éxito.";
                            return(RedirectToAction("Index", ReturnController));
                        }

                        TempData["ECreate"] = "No se puede recargar saldo al tag: " + modelTag.NumTag + " porque la cuenta a la que pertenece está dada de baja.";
                        return(RedirectToAction("Index", ReturnController));
                    }

                    TempData["ECreate"] = "El tag: " + modelTag.NumTag + " es colectivo.";
                    return(RedirectToAction("Index", ReturnController));
                }

                TempData["ECreate"] = "¡Ups! ocurrio un error inesperado.";
                return(RedirectToAction("Index", ReturnController));
            }
            catch (Exception ex)
            {
                TempData["ECreate"] = $"¡Ups! ocurrio un error inesperado, {ex.Message}";
                return(RedirectToAction("Index", ReturnController));
            }
        }
Exemplo n.º 4
0
        public async Task InvokeAsync(HttpContext context, AppDbContext dbContext)
        {
            await _next(context);

            await dbContext.SaveChangesAsync();
        }
        public async Task AddUserAsync(User user)
        {
            await _appDbContext.Users.AddAsync(user);

            await _appDbContext.SaveChangesAsync();
        }
Exemplo n.º 6
0
 public async Task DeleteAsync(Player Player)
 {
     _appDbContext.Players.Remove(Player);
     await _appDbContext.SaveChangesAsync();
 }
        public async Task <IActionResult> Add(BookCreateModel model)
        {
            if (ModelState.IsValid)
            {
                string[]   tags     = model.Tags.Split(',');
                List <Tag> bookTags = new List <Tag>();
                foreach (var tag in tags)
                {
                    Tag t = await _dbContext.Tags.FirstOrDefaultAsync(x => x.Name.ToLower() == tag.Trim().ToLower());

                    bookTags.Add(t);
                }

                Image img = new Image()
                {
                    Path = Path.Combine("/images", model.Cover.FileName)
                };
                await _dbContext.Images.AddAsync(img);

                await Uploader.UploadToServer(new Uploader(_environment).DefineBookPath(model.Book), model.Book);

                await Uploader.UploadToServer(new Uploader(_environment).DefineImagePath(model.Cover), model.Cover);

                Book book = new Book()
                {
                    Author       = model.Author,
                    CreationDate = DateTime.Now,
                    Description  = model.Description,
                    Language     = await _dbContext.Languages.FirstOrDefaultAsync(x => x.Id == model.LanguageId),
                    PageCount    = model.PageCount,
                    Name         = model.Name,
                    FilePath     = Path.Combine("/books", model.Book.FileName),
                    Image        = img,
                    Faculty      = await _dbContext.Faculties.FirstOrDefaultAsync(x => x.Id == model.FacultyId),
                    User         = await _userManager.Users.FirstOrDefaultAsync(x => x.Email == HttpContext.User.Identity.Name)
                };

                List <TagPost> tagPosts = new List <TagPost>();
                foreach (var tag in bookTags)
                {
                    tagPosts.Add(new TagPost()
                    {
                        Post = book, Tag = tag
                    });
                }

                book.TagPosts = tagPosts;

                if (await _dbContext.Books.AddAsync(book) != null)
                {
                    if (await _dbContext.SaveChangesAsync() > 0)
                    {
                        return(Json(new BookViewModel(book)));
                    }
                }
                else
                {
                    return(Json("Wrong!!!"));
                }
            }
            else
            {
                ModelState.AddModelError("", "Check your inputs");
            }
            return(Ok());
        }
Exemplo n.º 8
0
        public async Task <IActionResult> EditOrCreateUserAddress(ProfileEditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = await _userManager.FindByIdAsync(model.User.Id);

                Address address = _appDbContext.Addresses.Find(model.User.Id);

                if (address != null)
                {
                    address.District = model.User.Address.District;
                    address.Street   = model.User.Address.Street;
                    address.City     = model.User.Address.City;
                    address.ZipCode  = model.User.Address.ZipCode;
                    address.POBox    = model.User.Address.POBox;

                    var authResult = await _authorizationService.AuthorizeAsync(User, user.Address, CRUD.Update);

                    if (authResult.Succeeded)
                    {
                        var tmp_address = _appDbContext.Addresses.Attach(address);
                        tmp_address.State = EntityState.Modified;


                        await _appDbContext.SaveChangesAsync();

                        _logger.LogInformation($"EditOrCreateUserAddress, Address: {tmp_address.ToString()} Updated");
                    }
                    else if (User.Identity.IsAuthenticated)
                    {
                        return(new ForbidResult());
                    }
                    else
                    {
                        return(new ChallengeResult());
                    }
                }
                else
                {
                    Address new_address = new Address
                    {
                        Id       = model.User.Id,
                        District = model.User.Address.District,
                        Street   = model.User.Address.Street,
                        City     = model.User.Address.City,
                        ZipCode  = model.User.Address.ZipCode,
                        POBox    = model.User.Address.POBox
                    };

                    var authResult = await _authorizationService.AuthorizeAsync(User, new_address, CRUD.Create);

                    if (authResult.Succeeded)
                    {
                        _appDbContext.Addresses.Add(new_address);
                        await _appDbContext.SaveChangesAsync();

                        _logger.LogInformation($"EditOrCreateUserAddress, Address: {new_address.ToString()} Cretaed");
                    }
                    else if (User.Identity.IsAuthenticated)
                    {
                        return(new ForbidResult());
                    }
                    else
                    {
                        return(new ChallengeResult());
                    }
                }

                return(RedirectToAction("UserInformation", "Profile"));
            }

            return(RedirectToAction("UserInformation", new { ProfileEditUserViewModel = model }));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Create([Bind("OrderID,TransactionNumber,OrderDate,OrderStatus")] Order order, int?showingID, String customer)
        {
            //Find order in database that corresponds to user
            //Create dummy order that will be changed later
            Order orderInDB = _context.Order.FirstOrDefault();

            if ((User.IsInRole("Employee") || User.IsInRole("Manager")) && customer == null)
            {
                //Find order in database that corresponds to user
                order = _context.Order
                        .Include(ord => ord.Tickets.OrderBy(t => t.Showing.StartTime)).ThenInclude(ord => ord.Showing).ThenInclude(ord => ord.Movie)
                        .Include(ord => ord.Recipient)
                        .Include(ord => ord.Purchaser)
                        .Include(ord => ord.Seller)
                        .Where(ord => ord.OrderStatus == "Active")
                        .FirstOrDefault(o => o.Seller.UserName == User.Identity.Name);

                if ((User.IsInRole("Employee") || User.IsInRole("Manager")) & order == null)
                {
                    return(View("Error", new String[] { "You cannot place an order on this account. Please sign into a customer account." }));
                }

                customer = order.Purchaser.UserName;
            }



            if (customer != null)
            {
                //Checks if there's an active order
                orderInDB = _context.Order
                            .Include(ord => ord.Tickets).ThenInclude(ord => ord.Showing).ThenInclude(ord => ord.Movie)
                            .Include(ord => ord.Recipient)
                            .Include(ord => ord.Purchaser)
                            .Where(ord => ord.OrderStatus == "Active")
                            .FirstOrDefault(o => o.Purchaser.UserName == customer);
            }
            //a customer is buying for themselves
            else
            {
                //Checks if there's an active order
                orderInDB = _context.Order
                            .Include(ord => ord.Tickets).ThenInclude(ord => ord.Showing).ThenInclude(ord => ord.Movie)
                            .Include(ord => ord.Recipient)
                            .Include(ord => ord.Purchaser)
                            .Where(ord => ord.OrderStatus == "Active")
                            .FirstOrDefault(o => o.Purchaser.UserName == User.Identity.Name);
            }

            if (orderInDB != null)
            {
                order = orderInDB;

                if (customer != null)
                {
                    AppUser customerDB = _context.Users.Where(u => u.Email == customer).FirstOrDefault();
                    order.Purchaser = customerDB;
                    order.Seller    = _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

                    //if code gets this far, add the registration to the database
                    _context.Update(order);
                    await _context.SaveChangesAsync();
                }

                //make sure all properties are valid
                if (ModelState.IsValid == false)
                {
                    return(View(order));
                }
            }
            else
            {
                //if an employee specified the customer they're selling to
                if (customer != null)
                {
                    AppUser customerDB = _context.Users.Where(u => u.Email == customer).FirstOrDefault();
                    order.Purchaser = customerDB;
                    order.Seller    = _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
                }
                //a customer is buying for themselves
                else
                {
                    //Associate order with the logged in customer TODO: add logic here for gifting?
                    order.Purchaser = _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
                }
                //TODO: Set order number automatically
                order.TransactionNumber = Utilities.GenerateNextTransactionNumber.GetNextTransactionNumber(_context);

                //Set order date to right now
                order.OrderDate = DateTime.Now;

                order.OrderStatus = "Active";

                //make sure all properties are valid
                if (ModelState.IsValid == false)
                {
                    return(View(order));
                }

                //if code gets this far, add the registration to the database
                _context.Add(order);
                await _context.SaveChangesAsync();
            }

            if (order.Seller != null)
            {
                if (showingID == null)
                {
                    return(RedirectToAction("ActiveOrder", "Order", new { customer }));
                }
                else
                {
                    return(RedirectToAction("Create", "Ticket", new { orderID = order.OrderID, showingID }));
                }
            }
            else
            {
                //send the user on to the action that will allow them to
                //create a registration detail.  Be sure to pass along the RegistrationID
                //that you created when you added the registration to the database above
                if (showingID == null)
                {
                    return(RedirectToAction("Create", "Ticket", new { orderID = order.OrderID }));
                }
                else
                {
                    return(RedirectToAction("Create", "Ticket", new { orderID = order.OrderID, showingID }));
                }
            }
        }
Exemplo n.º 10
0
 public async Task AddTransaction(TransactionEntity transaction)
 {
     _dbContext.TransactionSet.Add(transaction);
     await _dbContext.SaveChangesAsync();
 }
Exemplo n.º 11
0
 public async Task UpdateAsync(AppUser appUser)
 {
     _appDbContext.Users.Update(appUser);
     await _appDbContext.SaveChangesAsync();
 }
Exemplo n.º 12
0
 /// <summary>
 ///  SaveAsync Method For Saving Type T where : BaseEntity
 /// </summary>
 protected void SaveAsync() => _context.SaveChangesAsync();
Exemplo n.º 13
0
        public async Task AddAsync(Core.Domain.Shop.Shop shop)
        {
            await _appDbContext.Shops.AddAsync(shop);

            await _appDbContext.SaveChangesAsync();
        }
Exemplo n.º 14
0
 protected async Task <int> SaveChangesAsync() => await _dbContext.SaveChangesAsync();
Exemplo n.º 15
0
 protected async Task SaveAsync()
 {
     await _dbContext.SaveChangesAsync();
 }
        public async Task <IActionResult> Create(Invoice invoice)
        {
            if (ModelState.IsValid)
            {
                DateTime dDate = new DateTime(0001, 01, 01);
                DateTime nDate = DateTime.Today;

                if (invoice.InvoiceDate == dDate)
                {
                    if (invoice.InvoiceExpiry == dDate)
                    {
                        var clientID     = _context.Project.Where(s => s.ProjectID == invoice.ProjectID).Select(s => s.ClientID).FirstOrDefault();
                        var invoicePrice = _context.Project.Where(s => s.ProjectID == invoice.ProjectID).Select(s => s.OffertePrice).FirstOrDefault();

                        invoice.InvoicePrice = invoicePrice;
                        invoice.ClientID     = clientID;

                        invoice.InvoiceExpiry = nDate.AddMonths(1);
                        invoice.InvoiceDate   = nDate;

                        _context.Add(invoice);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                    else
                    {
                        var clientID     = _context.Project.Where(s => s.ProjectID == invoice.ProjectID).Select(s => s.ClientID).FirstOrDefault();
                        var invoicePrice = _context.Project.Where(s => s.ProjectID == invoice.ProjectID).Select(s => s.OffertePrice).FirstOrDefault();

                        invoice.InvoiceDate = nDate;

                        invoice.InvoicePrice = invoicePrice;
                        invoice.ClientID     = clientID;
                        _context.Add(invoice);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                }
                else
                {
                    var clientID     = _context.Project.Where(s => s.ProjectID == invoice.ProjectID).Select(s => s.ClientID).FirstOrDefault();
                    var invoicePrice = _context.Project.Where(s => s.ProjectID == invoice.ProjectID).Select(s => s.OffertePrice).FirstOrDefault();

                    invoice.InvoicePrice = invoicePrice;
                    invoice.ClientID     = clientID;
                    _context.Add(invoice);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            InvoiceClientProjectViewModel model = new InvoiceClientProjectViewModel()
            {
                ProjectList = await _context.Project.ToListAsync(),
                Invoice     = invoice
            };

            return(View(model));
        }
Exemplo n.º 17
0
        public async Task <ActionResult> CreatePollForGroupEvent([FromBody] JObject objJson)
        {
            try
            {
                if (string.IsNullOrEmpty(Convert.ToString(Request.Headers["api_key"])))
                {
                    return(StatusCode(StatusCodes.Status401Unauthorized, (new { Status = "Error", Error = "Invalid ApiKey" })));
                }

                string strUserId = UserLoginSessionKeys.GetUserIdByApiKey(_appDbContext, Guid.Parse(Request.Headers["api_key"]));
                if (string.IsNullOrEmpty(strUserId))
                {
                    return(StatusCode(StatusCodes.Status401Unauthorized, (new { Status = "Error", Error = "Invalid ApiKey" })));
                }

                var objEvents = from e in _appDbContext.Events
                                where (e.Id == Convert.ToInt32(objJson.SelectToken("eventid")))
                                select e;

                if (objEvents.Count() <= 0)
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, (new { Status = "Error", Error = "Event doesn’t exist." })));
                }

                GroupPoll objGroupPoll = new GroupPoll();
                objGroupPoll.EventId = Convert.ToInt32(objJson.SelectToken("eventid"));
                //objGroupPoll.RestaurantName = Convert.ToString(objJson.SelectToken("restaurantname"));
                objGroupPoll.EventDate1 = Convert.ToDateTime(objJson.SelectToken("eventdate1"));
                DateTime dt;
                if (!DateTime.TryParseExact(Convert.ToString(objJson.SelectToken("eventtime1")), "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                {
                    objGroupPoll.EventTime1 = TimeSpan.Parse("00:00");
                }
                else
                {
                    objGroupPoll.EventTime1 = dt.TimeOfDay;
                }
                objGroupPoll.EventDate2 = Convert.ToDateTime(objJson.SelectToken("eventdate2"));
                if (!DateTime.TryParseExact(Convert.ToString(objJson.SelectToken("eventtime2")), "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                {
                    objGroupPoll.EventTime2 = TimeSpan.Parse("00:00");
                }
                else
                {
                    objGroupPoll.EventTime2 = dt.TimeOfDay;
                }
                objGroupPoll.StartDate   = DateTime.UtcNow;
                objGroupPoll.EndDate     = DateTime.UtcNow.AddHours(Convert.ToInt32(configuration.GetSection("appSettings").GetSection("PollEndHrs").Value));
                objGroupPoll.PollStatus  = "active";
                objGroupPoll.OwnerUserId = strUserId;
                //objGroupPoll.TiltCount = 0;
                objGroupPoll.CreatedDate = DateTime.UtcNow;
                await _appDbContext.GroupPoll.AddAsync(objGroupPoll);

                int returnVal = await _appDbContext.SaveChangesAsync();

                if (returnVal > 0)
                {
                    return(Ok(new { Status = "OK", Detail = "Poll created." }));
                }
                else
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, (new { Status = "Error", Error = "Internal Server error. Please contact customer support" })));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, (new { Status = "Error", Error = "Internal Server error. Please contact customer support", SystemError = ex.Message })));
            }
        }
Exemplo n.º 18
0
 public async Task <bool> SaveChangesAsync()
 {
     return(await _context.SaveChangesAsync() >= 0);
 }
Exemplo n.º 19
0
 public async Task <bool> SaveAll()
 {
     return(await appDbContext.SaveChangesAsync() > 0);
 }
Exemplo n.º 20
0
 public async Task InitializeAsync()
 {
     await _dbContext.SaveChangesAsync();
 }
Exemplo n.º 21
0
        public async Task <IActionResult> Create([FromForm] UpComingEventCreateVM upComingEventCreateVM)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!upComingEventCreateVM.Photo.IsImage())
            {
                ModelState.AddModelError("Photo", "Zehmet olmasa shekil formati sechin");
                return(BadRequest(ModelState));
            }

            if (upComingEventCreateVM.Photo.MaxLength(2000))
            {
                ModelState.AddModelError("Photo", "Shekilin olchusu max 200kb ola biler");
                return(BadRequest(ModelState));
            }
            if (upComingEventCreateVM.SpeakerEventsId == null)
            {
                ModelState.AddModelError("", "Speaker Secmelisiniz!");
                return(BadRequest(ModelState));
            }
            string        path          = Path.Combine("img", "event");
            UpComingEvent upComingEvent = new UpComingEvent
            {
                Title       = upComingEventCreateVM.Title,
                Image       = await upComingEventCreateVM.Photo.SaveImg(_env.WebRootPath, path),
                Month       = upComingEventCreateVM.Month,
                Day         = upComingEventCreateVM.Day,
                Location    = upComingEventCreateVM.Location,
                StartTime   = upComingEventCreateVM.StartTime,
                EndTime     = upComingEventCreateVM.EndTime,
                Description = upComingEventCreateVM.Description,
                CategoryId  = upComingEventCreateVM.CategoryId
            };



            await _db.UpComingEvents.AddAsync(upComingEvent);

            await _db.SaveChangesAsync();

            foreach (var speakerId in upComingEventCreateVM.SpeakerEventsId)
            {
                var speaker = _db.Speakers.Include(p => p.SpeakerEvents).ThenInclude(p => p.UpComingEvent).
                              FirstOrDefault(p => p.Id == speakerId);
                foreach (var se in speaker.SpeakerEvents)
                {
                    if (upComingEvent.StartTime > se.UpComingEvent.StartTime && upComingEvent.EndTime < se.UpComingEvent.EndTime)
                    {
                        ModelState.AddModelError("", "Busy");
                        return(BadRequest(ModelState));
                    }
                }

                SpeakerEvent speakerEvent = new SpeakerEvent
                {
                    SpeakerId       = speakerId,
                    UpComingEventId = upComingEvent.Id
                };
                _db.SpeakerEvents.Add(speakerEvent);

                await _db.SaveChangesAsync();
            }
            var callbackUrl = Url.Action(
                "Detail",
                "Event",
                new { Id = upComingEventCreateVM.Id },
                protocol: HttpContext.Request.Scheme);
            EmailService  email = new EmailService();
            List <string> e     = _db.Subscriptions.Select(x => x.Email).ToList();
            await email.SendEmailAsync(e, "Yeni event",
                                       "Yeni event: <a href=https://localhost:44375/Event/Detail/" + $"{upComingEvent.Id}" + ">link</a>");


            return(Ok($"{upComingEvent.Id} li element yaradildi"));
        }
        public async Task <IActionResult> Update(int?id, Event @event, int[] Categories)
        {
            List <Category> ctg = _context.Categories.Where(c => !c.IsDeleted && c.Activeted).ToList();

            ViewBag.Categories = ctg;

            if (id == null)
            {
                return(NotFound());
            }

            EventModerator moder = await _context.EventModerators.Where(c => !c.IsDeleted && c.ModeratorId == _userManager.GetUserId(User) && c.EventId == id).Include(c => c.Event).FirstOrDefaultAsync();

            if (moder == null)
            {
                return(NotFound());
            }
            Event eventDb = await _context.Events.Where(e => !e.IsDeleted && e.Id == id).FirstOrDefaultAsync();

            _context.IncludeCategoryEvent(false);
            if (@event == null)
            {
                return(NotFound());
            }

            if (id == null)
            {
                return(NotFound());
            }
            if (Helpers.Helper.CheckLengthArray(Categories, ModelState))
            {
                return(View(eventDb));
            }


            if (!ModelState.IsValid)
            {
                return(View(eventDb));
            }

            if (@event.Title != eventDb.Title)
            {
                bool IsExist = _context.Events.Where(e => !e.IsDeleted).Any(e => e.Title.ToLower() == @event.Title.ToLower());
                if (IsExist)
                {
                    ModelState.AddModelError("Name", "This course name already exist!!!");
                    return(View(eventDb));
                }
            }

            if (@event.Photo != null)
            {
                if ([email protected](ModelState))
                {
                    return(View(eventDb));
                }
                string folder   = Path.Combine("site", "img", "event");
                string fileName = await @event.Photo.SaveImage(_env.WebRootPath, folder);

                eventDb.Image = fileName;
            }



            List <EventCategory> eventCategories = new List <EventCategory>();

            foreach (int categoryId in Categories)
            {
                eventCategories.Add(new EventCategory
                {
                    CategoryId = categoryId,
                    EventId    = @event.Id,
                    Activeted  = @event.Activeted
                });
            }


            eventDb.Title           = @event.Title;
            eventDb.StartTime       = @event.StartTime;
            eventDb.EndTime         = @event.EndTime;
            eventDb.Description     = @event.Description;
            eventDb.Venue           = @event.Venue;
            eventDb.EventCategories = eventCategories;
            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemplo n.º 23
0
        public async Task <int> Save()
        {
            var rowcount = await _context.SaveChangesAsync();

            return(rowcount);
        }
Exemplo n.º 24
0
        public async Task <IActionResult> AddNews(NewsImageTagsViewModel newsViewModel)
        {
            newsViewModel.News.ReleaseDate = DateTime.Now;
            if (!ModelState.IsValid)
            {
                return(View(newsViewModel));
            }

            if (newsViewModel.File.Length > 0 && newsViewModel.File.Length < 500000)
            {
                try
                {
                    newsViewModel.News.ImageName = Guid.NewGuid() + Path.GetExtension(newsViewModel.File.FileName);
                    string savePath = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot/Administrators/assets/images/news",
                        newsViewModel.News.ImageName
                        );
                    await using var stream = new FileStream(savePath, FileMode.Create);
                    await newsViewModel.File.CopyToAsync(stream);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Image upload incomplete. error = {ex.Message}");
                    Console.WriteLine(ex.Data);
                }
            }
            else
            {
                TempData["Error"] = "حجم عکس بارگذاری شده برای خبر بیشتر از 500 کیلوبایت می باشد";
                return(RedirectToAction("DoctorsList"));
            }

            await _db.News.AddAsync(newsViewModel.News);

            await _db.SaveChangesAsync();

            TempData["Success"] = "خبر با موفقیت اضافه شد";
            return(RedirectToAction("News"));
        }
Exemplo n.º 25
0
 public async Task CompleteAsync()
 {
     await _context.SaveChangesAsync();
 }
Exemplo n.º 26
0
        public static async Task Initialize(this AppDbContext db)
        {
            Console.WriteLine("Initializing database");
            await db.Database.MigrateAsync();

            Console.WriteLine("Database initialized");

            if (!await db.Roles.AnyAsync())
            {
                Console.WriteLine("Seeding roles...");

                var roles = new List <Role>
                {
                    new Role {
                        Name = "Tech", Description = "A technical role"
                    },
                    new Role {
                        Name = "User", Description = "A user role"
                    },
                    new Role {
                        Name = "Executive", Description = "An executive role"
                    }
                };

                await db.Roles.AddRangeAsync(roles);

                await db.SaveChangesAsync();
            }

            List <TableCategory> categories;

            if (!await db.TableCategories.AnyAsync())
            {
                Console.WriteLine("Seeding table categories...");

                categories = new List <TableCategory>
                {
                    new TableCategory {
                        Label = "Gender"
                    },
                    new TableCategory {
                        Label = "Hair Color"
                    },
                    new TableCategory {
                        Label = "Blood Type"
                    }
                };

                await db.TableCategories.AddRangeAsync(categories);

                await db.SaveChangesAsync();
            }
            else
            {
                Console.WriteLine("Retrieving seed table categories...");

                categories = await db.TableCategories.ToListAsync();
            }

            if (!await db.TableData.AnyAsync())
            {
                Console.WriteLine("Seeding table data...");

                var gender = categories.FirstOrDefault(x => x.Label == "Gender");
                var hair   = categories.FirstOrDefault(x => x.Label == "Hair Color");
                var blood  = categories.FirstOrDefault(x => x.Label == "Blood Type");

                var data = new List <TableDatum>
                {
                    new TableDatum {
                        TableCategoryId = gender.Id, Data = "Male"
                    },
                    new TableDatum {
                        TableCategoryId = gender.Id, Data = "Female"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Blonde"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Red"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Light Brown"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Brown"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Dark Brown"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Black"
                    },
                    new TableDatum {
                        TableCategoryId = hair.Id, Data = "Gray"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "O Positive"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "O Negative"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "A Positive"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "A Negative"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "B Positive"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "B Negative"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "AB Positive"
                    },
                    new TableDatum {
                        TableCategoryId = blood.Id, Data = "AB Negative"
                    }
                };

                await db.TableData.AddRangeAsync(data);

                await db.SaveChangesAsync();
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// Calls SaveChangesAsync() of db context
 /// </summary>
 public async Task SaveChangesAsync()
 {
     await _db.SaveChangesAsync();
 }
Exemplo n.º 28
0
 public async Task SaveAsync()
 {
     await _dbContext.SaveChangesAsync();
 }
Exemplo n.º 29
0
        public async Task AddAsync(Domain.Models.User user)
        {
            await _context.Users.AddAsync(user);

            await _context.SaveChangesAsync();
        }
Exemplo n.º 30
0
        //todo move to core level
        public async Task <BaseResponse> Handle(ForfeitMatchCommand request, CancellationToken cancellationToken)
        {
            var match = await _ctx.Matches
                        .Include(x => x.MatchUsers)
                        .ThenInclude(x => x.User)
                        .FirstOrDefaultAsync(x => x.Id == request.MatchId,
                                             cancellationToken: cancellationToken);

            if (match == null)
            {
                return(BaseResponse.Fail(await _translator.GetTranslation("Match", "NotFound")));
            }

            if (!match.CanGo(request.UserId))
            {
                return(BaseResponse.Fail(await _translator.GetTranslation("Match", "CantForfeit")));
            }

            var host     = match.GetHost();
            var opponent = match.GetOpponent();
            var notificationExtension = "";

            if (match.Round == 1 || (match.Mode == Mode.ThreeRoundPass && match.TurnType == TurnType.Blitz))
            {
                _ctx.Matches.Remove(match);
                notificationExtension = $". {await _translator.GetTranslation("Match", "Deleted")}";
            }
            else
            {
                if (match.IsTurn(MatchRole.Host))
                {
                    host.SetLoserAndLock(match.Round + 5)
                    .AwardExp(4 + match.Round);

                    opponent.SetWinnerAndLock(match.Round + 5)
                    .AwardExp(7 + match.Round);
                }
                else if (match.IsTurn(MatchRole.Opponent))
                {
                    host.SetWinnerAndLock(match.Round + 5)
                    .AwardExp(7 + match.Round);
                    opponent.SetLoserAndLock(match.Round + 5)
                    .AwardExp(4 + match.Round);
                }

                match.Status     = Status.Complete;
                match.LastUpdate = DateTime.Now;
                match.Finished   = DateTime.Now.GetFinishTime();
            }

            host.User.Hosting--;
            opponent.User.Joined--;

            await _ctx.SaveChangesAsync(cancellationToken);

            var notificationType = IsNullOrEmpty(notificationExtension)
                                       ? NotificationMessageType.MatchHistory
                                       : NotificationMessageType.Empty;

            var user    = match.GetUser(request.UserId);
            var message =
                await _translator.GetTranslation("Notification", "Forfeited", user.User.DisplayName,
                                                 notificationExtension);

            _notification.QueueNotification(message,
                                            new[] { match.Id.ToString() }.DefaultJoin(),
                                            notificationType,
                                            match.GetOtherUserIds(request.UserId));

            return(BaseResponse.Ok(await _translator.GetTranslation("Match", "Forfeited")));
        }