예제 #1
0
        public async Task <IActionResult> AddSale([FromBody] SaleHeader Sale)
        {
            try
            {
                var sale_detail = Sale.SaleDetails.ToList();
                // var totalLine = sale_detail.Sum(x=>x.TotalAmount);//from s in sale_detail.Select(x=>x.TotalAmount).Sum();
                // Sale.TotalLine = totalLine == 0 ? 0: totalLine;
                foreach (var sd in sale_detail)
                {
                    var p = _ProductService.Find(sd.ProductId);
                    p.Inventory     -= sd.Quantity;
                    sd.WarrantyStart = DateTime.Now;
                    sd.WarrantyEnd   = DateTime.Now.AddMonths(p.Warranty);
                }
                _SaleHeaderService.Add(Sale);
                int res = await _unitOfWork.SaveChangesAsync();

                if (res > 0)
                {
                    operationResult.Success = true;
                    operationResult.Message = "Added new record";
                    operationResult.Caption = "Add complete";
                }
            }
            catch (System.Exception ex)
            {
                operationResult.Success = false;
                operationResult.Message = ex.ToString();
                operationResult.Caption = "Add failed!";
            }
            return(Ok(operationResult));
        }
        public async Task <ActionResult> SettingsEmailUpdate(Setting setting)
        {
            var settingExisting = _settingService.Queryable().FirstOrDefault();

            settingExisting.SmtpDeliveryMethod      = setting.SmtpDeliveryMethod;
            settingExisting.PickupDirectoryLocation = setting.PickupDirectoryLocation;
            settingExisting.SmtpHost         = setting.SmtpHost;
            settingExisting.SmtpPassword     = setting.SmtpPassword;
            settingExisting.SmtpPort         = setting.SmtpPort;
            settingExisting.SmtpUserName     = setting.SmtpUserName;
            settingExisting.SmtpPassword     = setting.SmtpPassword;
            settingExisting.SmtpSSL          = setting.SmtpSSL;
            settingExisting.EmailDisplayName = setting.EmailDisplayName;
            settingExisting.EmailAddress     = setting.EmailAddress;

            settingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;

            _settingService.Update(settingExisting);

            await _unitOfWorkAsync.SaveChangesAsync();

            _dataCacheService.UpdateCache(CacheKeys.Settings, settingExisting);

            return(RedirectToAction("SettingsEmail"));
        }
예제 #3
0
        public async Task <IHttpActionResult> Put(Chore chore)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            chore.ObjectState = ObjectState.Modified;
            _choreService.Update(chore);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ChoreExists(chore.Id))
                {
                    return(NotFound());
                }
                throw;
            }

            return(new NoContentActionResult(Request, Url.Link("GetChore", new { id = chore.Id })));
        }
예제 #4
0
        //
        //GET: /Manage/BuyCoin

        public async Task <ActionResult> BuyCoin(string tx)
        {
            if (tx != null)
            {
                string scheme       = HttpContext.Request.Url.AbsoluteUri;
                string response     = scheme;
                var    Arr_response = response.Split('&');

                if (Arr_response[1] == "st=Completed")
                {
                    var    Arr_price = Arr_response[2].Split('=');
                    double price     = Convert.ToDouble(Arr_price[1]);
                    int    coins     = 0;
                    if (price == 10)
                    {
                        coins = 1000;
                    }
                    if (price == 13)
                    {
                        coins = 1500;
                    }
                    if (price == 16)
                    {
                        coins = 2000;
                    }

                    string user_id = User.Identity.GetUserId();

                    OrderBuyCoin orderbuycoin = new OrderBuyCoin();
                    orderbuycoin.Date        = DateTime.Now;
                    orderbuycoin.Price       = price;
                    orderbuycoin.Coins       = coins;
                    orderbuycoin.UserBuyCoin = user_id;
                    orderbuycoin.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;

                    _orderBuyCoinsService.Insert(orderbuycoin);

                    //update coins of user
                    var userExisting = await UserManager.FindByIdAsync(user_id);

                    userExisting.Coins = userExisting.Coins + coins;
                    await UserManager.UpdateAsync(userExisting);



                    await _unitOfWorkAsync.SaveChangesAsync();

                    return(RedirectToAction("Dashboard"));
                }
                else
                {
                    //error
                    return(RedirectToAction("BuyCoin"));
                }
            }
            else
            {
                return(View());
            }
        }
예제 #5
0
        // PUT: odata/Customers(5)
        public async Task <IHttpActionResult> Put(string key, Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (key != customer.CustomerID)
            {
                return(BadRequest());
            }

            customer.TrackingState = TrackingState.Modified;
            _customerService.Update(customer);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(key))
                {
                    return(NotFound());
                }
                throw;
            }

            return(Updated(customer));
        }
        public async Task <IHttpActionResult> Put([FromODataUri] System.Int64 ColdRoomTemperatureID, ColdRoomTemperature item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (ColdRoomTemperatureID == item.ColdRoomTemperatureID)
            {
                return(BadRequest());
            }

            item.ObjectState = ObjectState.Modified;
            _service.Update(item);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemExists(ColdRoomTemperatureID))
                {
                    return(NotFound());
                }
                throw;
            }

            return(Updated(item));
        }
예제 #7
0
        public async Task <ActionResult> SaveData(MessageChangeViewModel messages)
        {
            if (messages.updated != null)
            {
                foreach (var updated in messages.updated)
                {
                    _messageService.Update(updated);
                }
            }
            if (messages.deleted != null)
            {
                foreach (var deleted in messages.deleted)
                {
                    _messageService.Delete(deleted);
                }
            }
            if (messages.inserted != null)
            {
                foreach (var inserted in messages.inserted)
                {
                    _messageService.Insert(inserted);
                }
            }
            await _unitOfWork.SaveChangesAsync();

            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
예제 #8
0
        public async Task <ActionResult> SaveData(NotificationChangeViewModel notifications)
        {
            if (notifications.updated != null)
            {
                foreach (var item in notifications.updated)
                {
                    _notificationService.Update(item);
                }
            }
            if (notifications.deleted != null)
            {
                foreach (var item in notifications.deleted)
                {
                    _notificationService.Delete(item);
                }
            }
            if (notifications.inserted != null)
            {
                foreach (var item in notifications.inserted)
                {
                    _notificationService.Insert(item);
                }
            }
            await _unitOfWork.SaveChangesAsync();

            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
        public async Task <ActionResult> Editar(ComplejoDeportivoViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.CodTipoComplejo == 1 && !model.CodLocalizacion.HasValue)
                {
                    goto Validacion;
                }

                var id      = int.Parse(Session["id"].ToString());
                var entidad = await _complejoDeportivoRepository.FindAsync(id);

                Mapper.Map(model, entidad);
                Session.EstablecerAuditoriaActualizacion(entidad);
                _complejoDeportivoRepository.Update(entidad);
                await _unitOfWorkAsync.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

Validacion:
            if (model.CodTipoComplejo == 1 && !model.CodLocalizacion.HasValue)
            {
                ModelState.AddModelError("CodLocalizacion", "Para los tipos Polideportivos se debe seleccionar localización");
            }


            ViewBag.Title  = "Edición Complejo Deportivo";
            ViewBag.Accion = "Editar";
            CargarListas(model.CodJefe, model.CodSede, model.CodLocalizacion.HasValue ? model.CodLocalizacion.Value : 0, model.CodTipoComplejo);
            return(View("Editar", model));
        }
예제 #10
0
        public async Task <IHttpActionResult> Put([FromODataUri] int PurchaseOrderLineID, PurchaseOrderLine item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (PurchaseOrderLineID == item.PurchaseOrderLineID)
            {
                return(BadRequest());
            }

            item.ObjectState = ObjectState.Modified;
            _service.Update(item);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemExists(PurchaseOrderLineID))
                {
                    return(NotFound());
                }
                throw;
            }

            return(Updated(item));
        }
예제 #11
0
        // PUT: odata/subinventory(5)
        public async Task <IHttpActionResult> Put(string key, SubInventory subinventory)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (key != subinventory.SubInvCode)
            {
                return(BadRequest());
            }

            subinventory.ObjectState = ObjectState.Modified;
            _subInventoryService.Update(subinventory);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemExists(key))
                {
                    return(NotFound());
                }

                throw;
            }

            return(Updated(subinventory));
        }
예제 #12
0
        //[ValidateAntiForgeryToken]
        public async Task <ActionResult> Create([Bind(Include = "BaseCode,Id,Code,Text,Description,IsDisabled,BaseCodeId,CreatedDate,CreatedBy,LastModifiedDate,LastModifiedBy")] CodeItem codeItem)
        {
            if (ModelState.IsValid)
            {
                _codeItemService.Insert(codeItem);
                await _unitOfWork.SaveChangesAsync();

                if (Request.IsAjaxRequest())
                {
                    return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
                }
                //DisplaySuccessMessage("Has append a CodeItem record");
                return(RedirectToAction("Index"));
            }
            else
            {
                var modelStateErrors = String.Join("", this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors.Select(n => n.ErrorMessage)));
                if (Request.IsAjaxRequest())
                {
                    return(Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet));
                }
            }



            return(View(codeItem));
        }
    public async Task <TModel> Insert(TModel model)
    {
        var entity = _unitOfWork.RepositoryAsync <TEntity>().Insert(_mapper.Map <TEntity>(model));
        await _unitOfWork.SaveChangesAsync();

        return(_mapper.Map <TModel>(entity));
    }
예제 #14
0
        /// <summary>
        /// Update an item
        /// </summary>
        /// <param name="id">Item id</param>
        /// <param name="model">Item model</param>
        /// <returns></returns>
        public virtual async Task <IHttpActionResult> Put(long id, T model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != model.Id)
            {
                return(BadRequest());
            }


            try
            {
                _unitOfWork.BeginTransaction();
                _service.Insert(model);
                await _unitOfWork.SaveChangesAsync();

                _unitOfWork.Commit();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ModelExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #15
0
        public async Task <JsonResult> SaveData(DepartmentChangeViewModel departments)
        {
            if (departments.updated != null)
            {
                foreach (var item in departments.updated)
                {
                    _departmentService.Update(item);
                }
            }
            if (departments.deleted != null)
            {
                foreach (var item in departments.deleted)
                {
                    _departmentService.Delete(item);
                }
            }
            if (departments.inserted != null)
            {
                foreach (var item in departments.inserted)
                {
                    _departmentService.Insert(item);
                }
            }
            await _unitOfWork.SaveChangesAsync();

            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
예제 #16
0
        public async Task <JsonResult> SaveData(OrderDetailChangeViewModel orderdetails)
        {
            if (orderdetails.updated != null)
            {
                foreach (var item in orderdetails.updated)
                {
                    _orderDetailService.Update(item);
                }
            }
            if (orderdetails.deleted != null)
            {
                foreach (var item in orderdetails.deleted)
                {
                    _orderDetailService.Delete(item);
                }
            }
            if (orderdetails.inserted != null)
            {
                foreach (var item in orderdetails.inserted)
                {
                    _orderDetailService.Insert(item);
                }
            }
            await _unitOfWork.SaveChangesAsync();

            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
예제 #17
0
        // PUT: odata/item(5)
        public async Task <IHttpActionResult> Put([FromODataUri] string key, [FromBody] Item item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (key != item.ItemFullCode)
            {
                return(BadRequest());
            }

            item.ObjectState = ObjectState.Modified;
            _itemService.Update(item);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemExists(key))
                {
                    return(NotFound());
                }

                throw;
            }

            return(Updated(item));
        }
예제 #18
0
        public async Task <IActionResult> Index()
        {
            CharityMaker charityMaker = new CharityMaker()
            {
                FullName = new FullName()
                {
                    Name = "33", Surname = "33", Patronymic = "3"
                },
                Address = new Address()
                {
                    City = "test2", Country = "test2", House = "test2", Region = "test2", Street = "test2"
                },
                Birthday = DateTime.Now,
                Contacts = new Contacts()
                {
                    Email = "test2"
                },
                Donations = null,
                Rating    = 2
            };
            await _unitOfWorkAsync.CharityMakers.Create(charityMaker);

            _unitOfWorkAsync.SaveChangesAsync();
            var list  = _unitOfWorkAsync.CharityMakers.GetAll().ToList();
            var list2 = _unitOfWorkAsync.CharityMakers.GetById(1).Result;
            var temp  = list2.Address;

            list[0].Rating = 250;
            await _unitOfWorkAsync.CharityMakers.Update(list[0]);

            _unitOfWorkAsync.SaveChangesAsync();


            return(View());
        }
예제 #19
0
 public async Task InsertAsync(TEntity entity, bool?commit = false)
 {
     _Insert(entity);
     if (commit.GetValueOrDefault())
     {
         await _unitOfWork.SaveChangesAsync();
     }
 }
        public async Task <IHttpActionResult> UpdateAccount([FromBody] UpdateAccountEmailDto accountEmailDto)
        {
            User user = await UserManager.FindByIdAsync(accountEmailDto.UserId);

            user.Email = accountEmailDto.Email;
            _unitOfWork.GetContext().Entry(user).State = EntityState.Modified;
            await _unitOfWork.SaveChangesAsync();

            return(Ok(true));
        }
        public async Task <Guid> CreateRoulette(Roulette input)
        {
            //Setup
            input.State = false;

            await _rouletteRepositoryAsync.InsertAsync(input);

            await _unitOfWorkAsync.SaveChangesAsync();

            return(input.Id);
        }
        public async Task <ActionResult> Create([Bind(Include = "Id,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                _categoryService.Insert(category);
                await _unitOfWork.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(category));
        }
예제 #23
0
        public async Task <IHttpActionResult> PutDish([FromBody] DishModelDto dish)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            _mfdDishPriceService.UpdateDish(dish);

            await _unitOfWork.SaveChangesAsync();

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #24
0
        public async Task <JsonResult> SaveDataAsync(MenuItemChangeViewModel menuitems)
        {
            if (menuitems == null)
            {
                throw new ArgumentNullException(nameof(menuitems));
            }
            if (ModelState.IsValid)
            {
                if (menuitems.updated != null)
                {
                    foreach (var item in menuitems.updated)
                    {
                        menuItemService.Update(item);
                    }
                }
                if (menuitems.deleted != null)
                {
                    foreach (var item in menuitems.deleted)
                    {
                        menuItemService.Delete(item);
                    }
                }
                if (menuitems.inserted != null)
                {
                    foreach (var item in menuitems.inserted)
                    {
                        menuItemService.Insert(item);
                    }
                }
                try
                {
                    var result = await unitOfWork.SaveChangesAsync();

                    return(Json(new { success = true, result = result }, JsonRequestBehavior.AllowGet));
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException e)
                {
                    var errormessage = string.Join(",", e.EntityValidationErrors.Select(x => x.ValidationErrors.FirstOrDefault()?.PropertyName + ":" + x.ValidationErrors.FirstOrDefault()?.ErrorMessage));
                    return(Json(new { success = false, err = errormessage }, JsonRequestBehavior.AllowGet));
                }
                catch (Exception e)
                {
                    return(Json(new { success = false, err = e.GetBaseException().Message }, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                var modelStateErrors = string.Join(",", ModelState.Keys.SelectMany(key => ModelState[key].Errors.Select(n => n.ErrorMessage)));
                return(Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #25
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Name,Price,DeliveryPeriod,CategoryId,SupplierId,MinimumStock")] Product product)
        {
            if (ModelState.IsValid)
            {
                _productService.Insert(product);
                await _unitOfWork.SaveChangesAsync();

                TempData.Add("AddedSuccessfully", true);
                return(RedirectToAction("Index"));
            }

            ViewBag.CategoryId = new SelectList(await _categoryService.Queryable().ToListAsync(), "Id", "Name", product.CategoryId);
            ViewBag.SupplierId = new SelectList(await _supplierService.Queryable().ToListAsync(), "Id", "Name", product.SupplierId);
            return(View(product));
        }
예제 #26
0
        public async Task TryFindByUserAndFollowsIdGoodFlowTest()
        {
            _followerService.Insert(new Follower
            {
                User      = user1,
                UserId    = user1.Id,
                Follows   = user2,
                FollowsId = user2.Id
            });
            await _unitOfWork.SaveChangesAsync();

            var value = _followerService.TryFindByUserAndFollowsId(user1.Id, user2.Id, out var follower);

            Assert.IsTrue(value);
        }
예제 #27
0
        /// <summary>
        /// return messages sent from a specific user to the current user
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task <ActionResult> Message(int threadId)
        {
            var userIdCurrent = User.Identity.GetUserId();

            var messageThread = await _messageThreadService
                                .Query(x => x.ID == threadId)
                                .Include(x => x.Messages)
                                .Include(x => x.Messages.Select(y => y.AspNetUser))
                                .Include(x => x.Messages.Select(y => y.MessageReadStates))
                                .Include(x => x.MessageParticipants)
                                .Include(x => x.MessageParticipants.Select(y => y.AspNetUser))
                                .Include(x => x.Listing)
                                .Include(x => x.Listing.ListingReviews)
                                .Include(x => x.Listing.ListingPictures)
                                .Include(x => x.Listing.ListingType)
                                .SelectAsync();

            var model = messageThread.FirstOrDefault();

            // Redirect to inbox if the thread doesn't contain anything
            if (model == null)
            {
                return(RedirectToAction("Messages"));
            }

            // Redirect to inbox if the thread doesn't contain current user
            if (!model.MessageParticipants.Any(x => x.UserID == userIdCurrent))
            {
                return(RedirectToAction("Messages"));
            }

            // Update message read states
            var messageReadStates = await _messageReadStateService
                                    .Query(x => x.UserID == userIdCurrent && !x.ReadDate.HasValue && x.Message.MessageThreadID == threadId)
                                    .SelectAsync();

            foreach (var messageReadState in messageReadStates)
            {
                messageReadState.ReadDate    = DateTime.Now;
                messageReadState.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;

                _messageReadStateService.Update(messageReadState);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            return(View(model));
        }
예제 #28
0
        /// <summary>
        /// If AutoSaveChanges is set this method will auto commit changes
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected virtual Task <int> SaveChanges(CancellationToken cancellationToken)
        {
            var source = new TaskCompletionSource <int>();

            if (AutoSaveChanges)
            {
                var registration = new CancellationTokenRegistration();
                if (cancellationToken.CanBeCanceled)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        source.SetCanceled();
                        return(source.Task);
                    }
                    registration = cancellationToken.Register(CancelIgnoreFailure);
                }

                try
                {
                    return(_uow.SaveChangesAsync(cancellationToken));
                }
                catch (Exception e)
                {
                    source.SetException(e);
                }
                finally
                {
                    registration.Dispose();
                }
            }
            return(source.Task);
        }
예제 #29
0
        /// <summary>
        /// Overriding base implementation
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public override async Task <IHttpActionResult> Post(Role model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                _unitOfWork.BeginTransaction();
                var modelToUpdate = await _service.FindAsync(model.Id);

                modelToUpdate.CopyFrom(model);
                _service.Update(modelToUpdate);
                await _unitOfWork.SaveChangesAsync();

                _unitOfWork.Commit();
            }
            catch (System.Exception ex)
            {
                return(InternalServerError(ex));
            }

            return(CreatedAtRoute("DefaultApi", new { id = model.Id }, model));
        }
예제 #30
0
        public virtual async Task <int> BulkInsertOrUpdateAsync(IEnumerable <TEntity> entities)
        {
            var dbContext = _context as DbContext;

            if (dbContext != null)
            {
                var previousAutoDetectSetting     = dbContext.Configuration.AutoDetectChangesEnabled;
                var previousValidatoOnSaveSetting = dbContext.Configuration.ValidateOnSaveEnabled;

                try
                {
                    dbContext.Configuration.AutoDetectChangesEnabled = false;
                    dbContext.Configuration.ValidateOnSaveEnabled    = false;
                    InsertOrUpdateGraphRange(entities);

                    return(await _unitOfWork.SaveChangesAsync());
                }
                finally
                {
                    dbContext.Configuration.AutoDetectChangesEnabled = previousAutoDetectSetting;
                    dbContext.Configuration.ValidateOnSaveEnabled    = previousValidatoOnSaveSetting;
                }
            }

            return(-1);
        }