Esempio n. 1
0
        public ActionResult EditCategory(int id, string newCategoryName)
        {
            var db             = new MainDbContext();
            var neededCategory = db.deviceCategory.Find(id);

            if (neededCategory == null)
            {
                return(HttpNotFound());
            }

            string oldCategoryName = neededCategory.deviceCategoryName;

            neededCategory.deviceCategoryName = newCategoryName;
            db.Entry(neededCategory).State    = EntityState.Modified;

            db.SaveChanges();

            var devicesWithOldName = db.clientDeviceInfo.Where(d => d.deviceCategory == oldCategoryName).ToList();

            if (devicesWithOldName.Count > 0)
            {
                foreach (ClientDeviceInfo cdi in devicesWithOldName)
                {
                    cdi.deviceCategory  = newCategoryName;
                    db.Entry(cdi).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }

            return(Json(new { success = true, responseText = "Updated category" }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 2
0
        protected async Task DbUpdate(TEntity entity)
        {
            var local = _db.Set <TEntity>()
                        .Local
                        .FirstOrDefault(entry => entry.Id.Equals(entity.Id));

            if (entity is IAuditableEntity)
            {
                var user = GetAuthenticatedUser();
                var date = DateTime.UtcNow;
                (entity as IAuditableEntity).UpdatedBy = user;
                (entity as IAuditableEntity).UpdatedOn = date;
            }

            if (local != null)
            {
                _db.Entry(local).CurrentValues.SetValues(entity);
            }
            else
            {
                _db.Entry(entity).State = EntityState.Modified;
            }

            await _db.SaveChangesAsync();
        }
 public void Update <T>(T entity) where T : class
 {
     if (Db.Entry(entity).State == EntityState.Detached)
     {
         Db.Set <T>().Attach(entity);
     }
     Db.Entry(entity).State = EntityState.Modified;
 }
 public virtual void Delete(TEntity entityToDelete)
 {
     if (context.Entry(entityToDelete).State == EntityState.Detached)
     {
         dbSet.Attach(entityToDelete);
     }
     dbSet.Remove(entityToDelete);
 }
Esempio n. 5
0
        public ActionResult Edit([Bind(Include = "Id,Ipaddress,Port,SerialNumber,Password,IsNeedToSendDisplay,Comment,OwnerName,PlaceAddress")] Config config,
                                 [Bind(Include = "IdAddress,City,Mkrn,Latitude,Longitude")] Address address, [Bind(Include = "IdOwner, Fio, Email")] Owner owner)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // TODO check security restrainment
                    //var _config = db.DvHeads.Find(config.Id);

                    var _address = db.Addresses.Find(address.IdAddress);
                    var _owner   = db.Owners.Find(owner.IdOwner);
                    // не обязательно
                    _address.City      = address.City;
                    _address.Mkrn      = address.Mkrn;
                    _address.Latitude  = address.Latitude;
                    _address.Longitude = address.Longitude;

                    db.Entry(_address).State = EntityState.Modified;
                    db.SaveChanges();
                    // не обязательно
                    _owner.Fio             = owner.Fio;
                    _owner.Email           = owner.Email;
                    db.Entry(_owner).State = EntityState.Modified;
                    db.SaveChanges();


                    // Id,Ipaddress,Port,SerialNumber,Password,NeedToSend,Comment,OwnerName,PlaceAddress
                    var _config = db.DvHeads.Find(config.Id);
                    _config.Owner   = _owner;
                    _config.Address = _address;

                    _config.SerialNumber = config.SerialNumber;
                    _config.Port         = config.Port;
                    _config.Ipaddress    = config.Ipaddress;
                    _config.Password     = config.Password;
                    _config.IsNeedToSend = config.IsNeedToSendDisplay.IsChecked;
                    _config.Comment      = config.Comment;
                    _config.OwnerName    = config.OwnerName;
                    _config.PlaceAddress = config.PlaceAddress;

                    //config.Address = _address;
                    //config.Owner = _owner;
                    //db.Entry(config).State = EntityState.Modified;

                    db.Entry(_config).State = EntityState.Modified;
                    db.SaveChanges();
                } catch (DbUpdateException ex)
                {
                    // todo: use almah for remote logs
                    ;
                }
                return(RedirectToAction("Index"));
            }
            return(View(config));
        }
 public ActionResult ProjectDetails(ProjectDetails_AdminPanelModels projectToEdit)
 {
     if (ModelState.IsValid)
     {
         db.Entry(projectToEdit.Project).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(projectToEdit));
 }
Esempio n. 7
0
        public bool FnUpdateSpotterDetail(MainDbContext db, List <OutstandingSpotterFeeViewModel> SpotterContractDetails, int ApprovalProcessDetailID, string RejectReason, string userMail)
        {
            try
            {
                if (string.IsNullOrEmpty(RejectReason))
                {
                    foreach (var data in SpotterContractDetails)
                    {
                        var spotterDtl = db.Spotter_Detail.Where(w => w.SpotterDetailId == data.SpotterDetailId).FirstOrDefault();

                        spotterDtl.ApprovedInd  = "A";
                        spotterDtl.ApprovedBy   = userMail;
                        spotterDtl.ApprovalDate = DateTime.Now;
                        spotterDtl.UpdatedBy    = userMail;
                        spotterDtl.UpdatedDate  = DateTime.Now;

                        db.Spotter_Detail.Add(spotterDtl);
                        db.Entry(spotterDtl).State = EntityState.Modified;
                    }
                }
                else
                {
                    foreach (var data in SpotterContractDetails)
                    {
                        var spotterDtl = db.Spotter_Detail.Where(w => w.SpotterDetailId == data.SpotterDetailId).FirstOrDefault();

                        spotterDtl.ApprovedInd     = "R";
                        spotterDtl.RejectedBy      = userMail;
                        spotterDtl.RejctedDate     = DateTime.Now;
                        spotterDtl.RejectionReason = RejectReason;
                        spotterDtl.UpdatedBy       = userMail;
                        spotterDtl.UpdatedDate     = DateTime.Now;

                        db.Spotter_Detail.Add(spotterDtl);
                        db.Entry(spotterDtl).State = EntityState.Modified;
                    }
                }
                var Id = db.SaveChanges();
                if (Id > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                glog.Error("FnUpdateSpotterDetail Exception: " + ex.Message + ex.InnerException);
                return(false);

                throw;
            }
        }
Esempio n. 8
0
        // Trang Thêm hóa đơn quảng cáo (được gọi khi thanh toán Online xong)
        public ActionResult CreateInvoice(OnlinePaymentModel model)
        {
            if (CurrentUser != null)
            {
                if (model.status == 1)
                {
                    if (model.transactionID.Contains("PACKAGE"))
                    {
                        var            adPackageId = long.Parse(model.transactionID.Substring(model.transactionID.IndexOf("ID") + 2));
                        PackageInvoice invoice     = new PackageInvoice()
                        {
                            Package       = db.Packages.FirstOrDefault(x => x.Id == adPackageId),
                            User          = CurrentUser,
                            Price         = (from c in db.AdPackages.Where(c => c.Id == adPackageId) select c.Price).FirstOrDefault(),
                            createdDate   = DateTime.Now,
                            transactionId = model.transactionID,
                            hashCode      = model.ticket,
                        };

                        db.PackageInvoices.Add(invoice);

                        // Thêm số lần đăng cho Store
                        var store = db.MerchantStores.Where(x => x.User.Id == CurrentUser.Id).FirstOrDefault();
                        store.Package         = store.Package + invoice.Package.Times;
                        db.Entry(store).State = EntityState.Modified;

                        db.SaveChanges();

                        return(RedirectToAction("PaymentComplete", "Package"));
                    }
                    else
                    {
                        var       adId        = long.Parse(model.transactionID.Substring(model.transactionID.IndexOf("ID") + 2));
                        var       createdDate = DateTime.Now;
                        AdInvoice invoice     = new AdInvoice()
                        {
                            AdPackage     = db.AdPackages.FirstOrDefault(x => x.Id == adId),
                            User          = CurrentUser,
                            Price         = (from c in db.AdPackages.Where(c => c.Id == adId) select c.Price).FirstOrDefault(),
                            createdDate   = createdDate,
                            ExpiredDate   = createdDate.AddDays((from c in db.AdPackages.Where(c => c.Id == adId) select c.Period).FirstOrDefault()),
                            Status        = false,
                            transactionId = model.transactionID,
                            hashCode      = model.ticket,
                        };
                        db.AdInvoices.Add(invoice);
                        db.SaveChanges();

                        return(RedirectToAction("AdManage", new { id = adId }));
                    }
                }
            }
            return(RedirectToAction("Index", "Package"));
        }
Esempio n. 9
0
        public bool FnUpdateContractSpotter(MainDbContext db, List <OutstandingSpotterFeeViewModel> SpotterContractDetails, int ApprovalProcessDetailID, string RejectReason, string userMail)
        {
            try
            {
                if (string.IsNullOrEmpty(RejectReason))
                {
                    foreach (var data in SpotterContractDetails)
                    {
                        var contractSpotter = db.Contract_Spotter.Where(w => w.ContractNumber == data.ContractNumber.Trim() && w.RolloverNumber == data.RolloverNumber && w.ItemNumber == data.ItemNumber).FirstOrDefault();
                        if (contractSpotter != null)
                        {
                            contractSpotter.ApprovedInd = "A";
                            contractSpotter.UpdatedBy   = userMail;
                            contractSpotter.UpdatedDate = DateTime.Now;

                            db.Contract_Spotter.Add(contractSpotter);
                            db.Entry(contractSpotter).State = EntityState.Modified;
                        }
                    }
                }
                else
                {
                    foreach (var data in SpotterContractDetails)
                    {
                        var contractSpotter = db.Contract_Spotter.Where(w => w.ContractNumber == data.ContractNumber.Trim() && w.RolloverNumber == data.RolloverNumber && w.ItemNumber == data.ItemNumber).FirstOrDefault();
                        if (contractSpotter != null)
                        {
                            contractSpotter.ApprovedInd = "P";
                            contractSpotter.UpdatedBy   = userMail;
                            contractSpotter.UpdatedDate = DateTime.Now;

                            db.Contract_Spotter.Add(contractSpotter);
                            db.Entry(contractSpotter).State = EntityState.Modified;
                        }
                    }
                }
                var Id = db.SaveChanges();
                if (Id > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                glog.Error("FnUpdateContractSpotter Exception: " + ex.Message + ex.InnerException);
                return(false);

                throw;
            }
        }
 //[HttpPost]
 //[ValidateAntiForgeryToken]
 public ActionResult Block(long?id)
 {
     if (ModelState.IsValid)
     {
         var product = db.Products.Find(id);
         product.isDisabled      = true;
         db.Entry(product).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View());
 }
 public ActionResult Edit([Bind(Include = "UserTypeId,UserType,EditedBy,EditedOn,StatusId", Exclude = "AddedBy,AddedOn")] UserTypes userTypes)
 {
     if (ModelState.IsValid)
     {
         db.Entry(userTypes).State = EntityState.Modified;
         db.Entry(userTypes).Property(uco => uco.AddedBy).IsModified = false;
         db.Entry(userTypes).Property(uco => uco.AddedOn).IsModified = false;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(userTypes));
 }
Esempio n. 12
0
 public ActionResult Edit([Bind(Include = "PrintCostId,Name,Width,Height,MonoCostPerPage,ColorCostPerPage,IsActive,EditedBy,EditedOn,StatusId", Exclude = "AddedBy,AddedOn")] PrintCosts printCosts)
 {
     if (ModelState.IsValid)
     {
         db.Entry(printCosts).State = EntityState.Modified;
         db.Entry(printCosts).Property(uco => uco.AddedBy).IsModified = false;
         db.Entry(printCosts).Property(uco => uco.AddedOn).IsModified = false;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(printCosts));
 }
 public ActionResult Edit([Bind(Include = "TxnId,UserId,TxnTypeId,TxnAmount,TxnDateTime,TxnBalance,TxnRefJobId,TxnStatus,EditedBy,EditedOn,StatusId", Exclude = "AddedBy,AddedOn")] UserTxns userTxns)
 {
     if (ModelState.IsValid)
     {
         db.Entry(userTxns).State = EntityState.Modified;
         db.Entry(userTxns).Property(uco => uco.AddedBy).IsModified = false;
         db.Entry(userTxns).Property(uco => uco.AddedOn).IsModified = false;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(userTxns));
 }
 public ActionResult Edit([Bind(Include = "JobId,UserId,DocId,DocName,DocTypeId,DocExt,DocFileNameOnServer,DocFilePath,DocTotalPages,PrintcostId,MonoPages,ColorPages,IsColor,IsDuplex,IsCollate,UnitCost,MonoUnitcost,ColorUnitcost,UnitItem,JobRemarks,PagesFrom,PagesTo,NumCopies,TotalPageCount,TotalPageCost,CreditUsed,JobError,JobErrorRemarks,PrinterName,PrinterPath,JobStatusId,EditedBy,EditedOn,StatusId", Exclude = "AddedBy,AddedOn")] PrintJobs printJobs)
 {
     if (ModelState.IsValid)
     {
         db.Entry(printJobs).State = EntityState.Modified;
         db.Entry(printJobs).Property(uco => uco.AddedBy).IsModified = false;
         db.Entry(printJobs).Property(uco => uco.AddedOn).IsModified = false;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(printJobs));
 }
        public virtual ActionResult SaveOperatorChoise(OperatorChoiseDto operChoiseDto)
        {
            // 01.09.2017 добавлена проверка на наличие тревожных сообщений на данном объекте
            // получить данные от клиента
            if (operChoiseDto == null)
            {
                return(Json(new { Success = false, Message = "НЕ УДАЛОСЬ ОБРАБОТАТЬ ЗАПРОС" }));
            }

            // если данные корректны, то изменить статус сообщения на обработанное и сохранить выбор оператора
            // 1) изменить запись в таблице Event
            // 2) TODO: добавить ссылку на информацию [новая таблица], когда произошло обновление записи
            if (ModelState.IsValid)
            {
                // занести действия пользователя в БД
                var ev = db.DvHeadEvents.Find(operChoiseDto.EventId);

                // установить оператора
                // ev. = operChoiseDto.OperatorEmail; TODO Добавить оператора

                // установить выбор оператора
                ev.ContinueActivity = operChoiseDto.Choise;

                // объект перестал быть тревожным
                ev.Alarm = 0;

                // установить статус обработки события
                ev.IsProcess = true;

                // TODO инициировать дальнейшие действия - позвонить в ЧОП, записать в БД
                // TODO обновить интерфейс оператора - страницу на стороне оператора
                db.Entry(ev).State = EntityState.Modified;
                db.SaveChanges(); // TODO проверки на соединение, и наличие записи

                // TODO проверить наличие тревожных сообщений на центральном контроллере DV-HEAD OMEGA по id
                // var tsCount = db.DvHeads.Find(operChoiseDto.HeadId).// Where(e => e.)
                // var tsCount = db.DvHeads.Where(head => head.Id == operChoiseDto.HeadId )
                var tsCount = db.DvHeadEvents.Where(eve => eve.Idhead == operChoiseDto.HeadId && eve.Alarm > 0).Count();
                // объект перестал быть тревожным
                if (tsCount == 0)
                {
                    // нашли необходимый DV-HEAD OMEGA
                    var dvHead = db.DvHeads.Find(operChoiseDto.HeadId);
                    // сделали нетревожным
                    dvHead.Alarm           = 0;
                    db.Entry(dvHead).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }

            return(Json(new { Success = true, Message = "Тревожное сообщение обработано" }));
        }
Esempio n. 16
0
        public void StartDraft()
        {
            var cardIds     = _draft.CubeDraftCards.Select(c => c.CardId).ToArray();
            var cardObjects = _db.Cards.Include("CardSet").Where(c => cardIds.Contains(c.Id)).ToArray();
            var cards       = cardIds.Select(c => cardObjects.Single(co => co.Id == c)).Shuffle().ToArray();

            var players = _draft.CubeDraftPlayers.Where(p => p.Confirmed).ToList();

            if (players.Count < 2 || players.Count > 10)
            {
                throw new InvalidOperationException("Invalid # of players. Players must be between 2 and 10");
            }

            if (players.Count * 45 > cards.Length)
            {
                throw new InvalidOperationException("Pool is not large enough for all players");
            }

            int position     = 1;
            int packPosition = -1;

            foreach (var player in players.Shuffle())
            {
                Players.Add(
                    new Drafter(
                        _draft,
                        player,
                        position,
                        new DraftCollection(
                            new[]
                {
                    new Pack(cards.Skip(++packPosition * 15).Take(15).ToArray(), "Cube Draft"),
                    new Pack(cards.Skip(++packPosition * 15).Take(15).ToArray(), "Cube Draft"),
                    new Pack(cards.Skip(++packPosition * 15).Take(15).ToArray(), "Cube Draft")
                }
                            )
                        )
                    );

                player.Position         = position;
                _db.Entry(player).State = EntityState.Modified;
                position++;
            }

            _draft.Status           = CubeDraftStatus.Drafting;
            _db.Entry(_draft).State = EntityState.Modified;
            _db.SaveChanges();

            _hubContext.Clients.Group(String.Format("draft/{0}/clients", _draft.Id)).draftStarted();
        }
        public ActionResult Confirm(long?id)
        {
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));

            if (ModelState.IsValid)
            {
                var store = db.MerchantStores.Find(id);
                UserManager.AddToRoles(store.User.Id, "Merchant");
                store.isDisabled      = true;
                db.Entry(store).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View());
        }
Esempio n. 18
0
        public ActionResult Edit([Bind(Include = "UserId,FName,LName,UserEmail,UserPass,UserTypeId,UserCode,UserPhone,UStatusId,EditedBy,EditedOn,StatusId", Exclude = "AddedBy,AddedOn")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                var encryptedPassword = CustomEnrypt.Encrypt(users.UserPass);
                users.UserPass = encryptedPassword;
                db.Entry(users).Property(uco => uco.AddedBy).IsModified = false;
                db.Entry(users).Property(uco => uco.AddedOn).IsModified = false;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(users));
        }
Esempio n. 19
0
        public ActionResult Edit(Notices notices)
        {
            var    db           = new MainDbContext();
            string timeToday    = DateTime.Now.ToString("h:mm:ss tt");
            string dateToday    = DateTime.Now.ToString("dd/M/yyyy");
            string new_item     = Request.Form["new_item"];
            string check_public = Request.Form["check_public"];

            if (ModelState.IsValid)
            {
                notices.Time_Edited = timeToday;
                notices.Date_Edited = dateToday;
                notices.Details     = new_item;
                notices.Time_Posted = time_posted;
                notices.Date_Posted = date_posted;
                if (check_public != null)
                {
                    notices.Public = "YES";
                }
                else
                {
                    notices.Public = "NO";
                }

                db.Entry(notices).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(notices));
        }
 // PUT api/<controller>/5
 public void Put(string id, [FromBody] News news)
 {
     try
     {
         if (ModelState.IsValid)
         {
             news.EditTime        = DateTime.Now;
             db.Entry(news).State = EntityState.Modified;
             db.Entry(news).Property(m => m.CreateTime).IsModified = false;
             db.SaveChanges();
         }
     }
     catch
     {
     }
 }
Esempio n. 21
0
        public async Task <IActionResult> PutFlight(int id, Flight flight)
        {
            if (id != flight.FlightId)
            {
                return(BadRequest());
            }

            _context.Entry(flight).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FlightExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok());
        }
Esempio n. 22
0
        public async Task <List <Indicator> > GetIndicators(List <string> indicatorIds)
        {
            var indicators = new List <Indicator>();

            foreach (var indicatorId in indicatorIds)
            {
                // Get indicator
                var indicator = await _mainDbContext.Indicators.FirstOrDefaultAsync(x => x.IndicatorId == indicatorId);

                // Indicator not found
                if (indicator == null)
                {
                    throw new NotFoundException(string.Format(IndicatorDependencyMessage.IndicatorDependencyNotFound, indicatorId));
                }

                // Detach
                _mainDbContext.Entry(indicator).State = EntityState.Detached;

                // Add
                indicators.Add(indicator);
            }

            // Return
            return(indicators);
        }
Esempio n. 23
0
        public async Task <IActionResult> PutColour(int id, Colour colour)
        {
            if (id != colour.Id)
            {
                return(BadRequest());
            }

            _context.Entry(colour).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ColourExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> PutCategory([FromRoute] long id, [FromBody] Category category)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != category.CategoryId)
            {
                return(BadRequest());
            }

            _context.Entry(category).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 25
0
        public async Task <IActionResult> PutOrganizasyonLider([FromRoute] int id, [FromBody] OrganizasyonLider organizasyonLider)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            _context.Entry(organizasyonLider).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!OrganizasyonLiderExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 26
0
        public async Task <IActionResult> PutGift(int id, Gift gift)
        {
            if (id != gift.GiftNumber)
            {
                return(BadRequest());
            }

            _context.Entry(gift).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GiftExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 27
0
        public ActionResult EditPage(Truck list)
        {
            var    db        = new MainDbContext();
            string timeToday = DateTime.Now.ToString("h:mm:ss tt");
            string dateToday = DateTime.Now.ToString("M/dd/yyyy");


            if (ModelState.IsValid)
            {
                list.Time_Edited     = timeToday;
                list.Date_Edited     = dateToday;
                list.DispatchExt     = list.DispatchExt;
                list.TruckID         = list.TruckID;
                list.CurrentLocation = list.CurrentLocation;
                list.CurrentStatus   = list.CurrentStatus;
                list.Time_Posted     = time_posted;
                list.Date_Posted     = date_posted;



                db.Entry(list).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Viewpage", "User"));
            }
            return(View(list));
        }
Esempio n. 28
0
        public async Task <ActionResult <Post> > DeletePost(long id, DeletePostForm deletePostForm)
        {
            var post = await _context.Posts.FindAsync(id);

            if (post == null ||
                post.AccessToken == null ||
                (post.AccessToken != null && deletePostForm.AccessToken != post.AccessToken))
            {
                return(NotFound());
            }
            post.IsDeleted             = true;
            _context.Entry(post).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PostExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(NoContent());
        }
Esempio n. 29
0
        public async Task <IActionResult> PutStudent([FromRoute] int id, [FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != student.StudentId)
            {
                return(BadRequest());
            }

            _context.Entry(student).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 30
0
        public ActionResult TaskDetails(TaskDetailsModels taskToEdit)
        {
            if (ModelState.IsValid)
            {
                var taskFromDB = db.Tasks.Find(taskToEdit.ID);
                //var task = new Task
                //{
                //    ID = taskToEdit.ID,
                //    Name = taskToEdit.Name,
                //    Description = taskToEdit.Description,
                //    Status = (Task.StatusE)taskToEdit.Status,
                //    Reporter = db.Users.Find(taskToEdit.ReporterId),
                //    DevAssignee = db.Users.Find(taskToEdit.DevAssigneeId),
                //    POAssignee = db.Users.Find(taskToEdit.POAssigneeId),
                //    Project = taskFromDB.Project,
                //    Comments = taskFromDB.Comments,
                //    Worklogs = taskFromDB.Worklogs
                //};

                taskFromDB.Name        = taskToEdit.Name;
                taskFromDB.Description = taskToEdit.Description;
                taskFromDB.DevAssignee = db.Users.Find(taskToEdit.DevAssigneeId);
                taskFromDB.POAssignee  = db.Users.Find(taskToEdit.POAssigneeId);
                taskFromDB.Status      = (Task.StatusE)taskToEdit.Status;

                db.Entry(taskFromDB).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("TaskDetails", new { Id = taskToEdit.ID }));
            }
            return(View(taskToEdit));
        }
Esempio n. 31
0
        public ActionResult EditProfile(FDRModel model)
        {
            if (ModelState.IsValid)
            {
                using (var db = new MainDbContext())
                {
                    string firstname = User.Identity.Name;

                    //Get Doctor
                    var FdrModel = db.FDR.FirstOrDefault(u => u.FirstName.Equals(firstname));
                    FdrModel.HospName = model.FDR.HospName;
                    FdrModel.EmployeeId = model.FDR.EmployeeId;
                    FdrModel.LicenseNo = model.FDR.LicenseNo;
                    FdrModel.Specialization = model.FDR.Specialization;
                    FdrModel.FirstName = model.FDR.FirstName;
                    FdrModel.MiddleName = model.FDR.MiddleName;
                    FdrModel.LastName = model.FDR.LastName;
                    FdrModel.Email = model.FDR.Email;
                    FdrModel.DateBirth = model.FDR.DateBirth;
                    FdrModel.Sex = model.FDR.Sex;
                    FdrModel.SecQuestion = model.FDR.SecQuestion;
                    FdrModel.SecAnswer = model.FDR.SecAnswer;

                    db.Entry(FdrModel).State = EntityState.Modified;

                    // Get the Address
                    var searchKeyAdd = db.FDR.Select(u => u.Key_Address);
                    var materializeAddKey = searchKeyAdd.ToList();
                    var KeyAdd = materializeAddKey[0];
                    var AddModel = db.Address.FirstOrDefault(u => u.Id.Equals(KeyAdd));

                    AddModel.City = model.Address.City;
                    AddModel.Province = model.Address.Province;
                    AddModel.Zipcode = model.Address.Zipcode;
                    AddModel.AddressType = model.Address.AddressType;

                    db.Entry(AddModel).State = EntityState.Modified;

                    // Get the Contact
                    var searchKeyCon = db.FDR.Select(u => u.Key_Contact);
                    var materializeConKey = searchKeyCon.ToList();
                    var KeyCon = materializeConKey[0];
                    var ConModel = db.Contact.FirstOrDefault(u => u.Id.Equals(KeyCon));

                    ConModel.MobileNo = model.Contact.MobileNo;
                    ConModel.PhoneNo = model.Contact.PhoneNo;

                    db.Entry(ConModel).State = EntityState.Modified;

                    // Get the Users
                    var searchUserKey = db.FDR.Select(u => u.Key_Users);
                    var materializeUserKey = searchUserKey.ToList();
                    var KeyUser = materializeUserKey[0];
                    var UsersModel = db.Users.FirstOrDefault(u => u.Id.Equals(KeyUser));

                    var encryptedPassword = CustomEnrypt.Encrypt(model.Users.Password);
                    UsersModel.Username = model.Users.Username;
                    UsersModel.Password = encryptedPassword;

                    db.Entry(UsersModel).State = EntityState.Modified;

                    db.SaveChanges();

                    var identity = new ClaimsIdentity(new[] {
                           new Claim(ClaimTypes.Name, FdrModel.FirstName),
                           new Claim(ClaimTypes.Role, "FDR")
                           }, "ApplicationCookie");

                    var ctx = Request.GetOwinContext();

                    var authManager = ctx.Authentication;

                    authManager.SignIn(identity);

                    return RedirectToAction("Index", "FDR");
                }

            }

            return View(model);
        }