public async Task <ActionResult> Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ExpenseRecord expenseRecord = db.ExpenseRecords.Find(id);

            if (expenseRecord == null)
            {
                return(HttpNotFound());
            }
            else
            {
                try
                {
                    //--- Delete all attachments for the current expense record
                    if (await DeleteAttachmentFilesAsync(expenseRecord.ExpenseAttachments.Select(x => x.ExpenseAttachmentName)))
                    {
                        //--- Delete current expense record and it will delete also the related attachment records
                        db.ExpenseRecords.Remove(expenseRecord);
                        db.SaveChanges();
                    }
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    SetVariables2ViewBag(expenseRecord);
                    this.ModelState.AddModelError("ExpenseDescription", ex.GetBaseException().Message);
                    return(View("Edit", expenseRecord));
                }
            }
        }
Exemple #2
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,UserAccountId,Description,Amount,Date")] ExpenseRecord expenseRecord)
        {
            if (id != expenseRecord.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(expenseRecord);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ExpenseRecordExists(expenseRecord.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserAccountId"] = new SelectList(_context.Set <UserAccount>(), "Id", "Id", expenseRecord.UserAccountId);
            return(View(expenseRecord));
        }
Exemple #3
0
        public IActionResult Put([FromBody] ExpenseRecord record)
        {
            // Exercise 4
            // TODO

            throw new NotImplementedException();
        }
        public async Task <int> SaveAsync(ExpenseRecord entity)
        {
            string commandText = DapperExtensions.InsertQuery(typeof(ExpenseRecord).Name, entity);

            using (var db = new MySqlConnection(_option.Value.ConnectionString))
            {
                db.Open();
                return(await db.ExecuteScalarAsync <int>(commandText, entity, null));
            }
        }
Exemple #5
0
        public async Task <bool> InsertExpenseRecord(ExpenseRecord expenseRecord)
        {
            var result = await _expenseRecordRepository.SaveAsync(expenseRecord);

            if (result > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #6
0
        public async Task Insert_ExpenseRecord()
        {
            var expenseRecord = new ExpenseRecord()
            {
                Amount = 100, Deleted = 0, ExpenseTime = DateTime.Parse("2019-11-10"), UserId = 1
            };

            _expenseRecordRepository.Setup(x => x.SaveAsync(It.IsAny <ExpenseRecord>())).Returns(Task.FromResult(1));
            _balanceService = new BalanceService(_balanceRepository.Object, _expenseRecordRepository.Object);
            var actual = await _balanceService.InsertExpenseRecord(expenseRecord);

            Assert.True(actual);
        }
Exemple #7
0
 ActionResult GetModel(int id, out ExpenseRecord model)
 {
     using (var db = new ExpenseDBEntities())
     {
         model = db.ExpenseRecords.Where(x => x.ExpenseRecordId == id).FirstOrDefault();
         if (model == null)
         {
             return(View("CustomError", null, "This record does not exist."));
         }
         //if (HttpContext.User.IsInRole("Employee") && model.RequesterUserId != HttpContext.User.Identity.Name)
         //    return View("CustomError", null, "This user does not have permission to perform this action.");
     }
     return(null);
 }
 public static ExpenseRecordType Load(ExpenseRecord expData)
 {
     return new ExpenseRecordType()
     {
         Amount = expData.Amount,
         CatId = expData.CategoriesId,
         Description = expData.Description,
         Id = expData.id,
         ExpDate = expData.ExpDate,
         OwnerId = expData.OwnerId,
         PersonalCatId = expData.PersonalCategoryId,
         Posted = expData.Posted
     };
 }
        private void SetViewBagSelectLists(string userId, ExpenseRecord expenseRecord = null)
        {
            IEnumerable <ExpenseType> expenseTypes = db.ExpenseTypes.Where(x => x.UserId == userId).OrderBy(x => x.Title);

            if (expenseRecord == null)
            {
                ViewBag.ExpenseTypeID   = new SelectList(expenseTypes, "ID", "Title");
                ViewBag.ExpenseEntityID = new SelectList(db.ExpenseEntities.Where(x => x.UserId == userId && x.ExpenseTypeID == expenseTypes.FirstOrDefault().ID).OrderByDescending(x => x.ID), "ID", "ExpenseEntityName");
            }
            else
            {
                ViewBag.ExpenseTypeID   = new SelectList(expenseTypes, "ID", "Title", expenseRecord.ExpenseTypeID);
                ViewBag.ExpenseEntityID = new SelectList(db.ExpenseEntities.Where(x => x.UserId == userId && x.ExpenseTypeID == expenseRecord.ExpenseTypeID).OrderByDescending(x => x.ID), "ID", "ExpenseEntityName", expenseRecord.ExpenseEntityID);
            }
        }
Exemple #10
0
        public async Task <IActionResult> Create([Bind("Id,Description,Amount,Date")] ExpenseRecord expenseRecord)
        {
            if (ModelState.IsValid)
            {
                var user = (from account in _context.UserAccount
                            where account.Email.Equals(User.Identity.Name)
                            select account).FirstOrDefault();
                expenseRecord.UserAccountId = user.Id;
                _context.Add(expenseRecord);
                await _context.SaveChangesAsync();

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

            return(View(expenseRecord));
        }
 public IActionResult Post([FromBody] ExpenseRecord record)
 {
     try
     {
         this.repository.Create(record);
         return(this.Created($"api/expenses/{record.Id}", null));
     }
     catch (ArgumentNullException)
     {
         return(this.BadRequest());
     }
     catch (InvalidOperationException)
     {
         return(this.StatusCode((int)HttpStatusCode.Conflict));
     }
 }
 public IActionResult Put([FromBody] ExpenseRecord record)
 {
     try
     {
         this.repository.Update(record);
         return(this.NoContent());
     }
     catch (ArgumentNullException)
     {
         return(this.BadRequest());
     }
     catch (InvalidOperationException)
     {
         return(this.NotFound());
     }
 }
        public async Task <bool> DeleteAsync(ExpenseRecord entity)
        {
            using (var db = new MySqlConnection(_option.Value.ConnectionString))
            {
                db.Open();
                var res = await db.ExecuteAsync("delete from ");

                if (res > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #14
0
        public void ThrowsInvalidOperationExceptionWhenTryingToAddRecordThatAlreadyExists()
        {
            var subject   = new ExpenseRepository();
            var newRecord = new ExpenseRecord
            {
                Id     = Guid.Parse("00000000-0000-0000-0000-000000000005"),
                Name   = "Anakin Skywalker",
                Reason = ExpenseReason.Hotel,
                Amount = 20m,
                Text   = "Cheap hotel in Mom's guest room.",
                Date   = 6.October(2016)
            };

            subject
            .Invoking(x => x.Create(newRecord))
            .ShouldThrow <InvalidOperationException>()
            .WithMessage($"An expense record with ID {newRecord.Id} already exists in the database!");
        }
        private void SetVariables2ViewBag(ExpenseRecord expenseRecord = null)
        {
            //--- Get current user
            string userId = User.Identity.GetUserId();

            //--- Set User ID
            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();
            ViewBag.UserID = utils.Encrypt(userId);

            //--- Set attachmentUploadWebAPIUrl
            string webAPIUri = utils.GetAppSetting("EL_EXPENSE_LOG_WEB_API_URI");
            Uri    uri       = new Uri(new Uri(webAPIUri), "/api/attachment/upload");

            ViewBag.AttachmentUploadWebAPIUrl = uri.ToString();

            //--- Set Lists
            SetViewBagSelectLists(userId, expenseRecord);
        }
Exemple #16
0
        public void ThrowsInvalidOperationExceptionWhenTryingToUpdateRecordThatDoesNotExist()
        {
            var subject       = new ExpenseRepository();
            var updatedRecord = new ExpenseRecord
            {
                Id     = Guid.Parse("00000000-0000-0000-0000-000000000006"),
                Date   = 12.October(2016),
                Name   = "Anakin Skywalker",
                Reason = ExpenseReason.Taxi,
                Text   = "Taxi to Tatooine, visiting Mom",
                Amount = 12.5m
            };

            subject
            .Invoking(x => x.Update(updatedRecord))
            .ShouldThrow <InvalidOperationException>()
            .WithMessage($"An expense record with ID {updatedRecord.Id} does not exist in the database!");
        }
        public ActionResult Edit(int?id, string expenseTypeIDFilter, string expenseEntityIDFilter, string fromDateFilter, string toDateFilter, string descriptionSearchFilter, string sortOrder)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ExpenseRecord expenseRecord = db.ExpenseRecords.Find(id);

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

            //--- Set current filter selections into ViewBag
            SetFilter2ViewBag(expenseTypeIDFilter, expenseEntityIDFilter, fromDateFilter, toDateFilter, descriptionSearchFilter, sortOrder);

            SetVariables2ViewBag(expenseRecord);

            return(View(expenseRecord));
        }
Exemple #18
0
        public void CanUpdateRecord()
        {
            var subject       = new ExpenseRepository();
            var updatedRecord = new ExpenseRecord
            {
                Id     = Guid.Parse("00000000-0000-0000-0000-000000000001"),
                Date   = 12.October(2016),
                Name   = "Anakin Skywalker",
                Reason = ExpenseReason.Taxi,
                Text   = "Taxi to Tatooine, visiting Mom",
                Amount = 12.5m
            };

            subject
            .Invoking(x => x.Update(updatedRecord))
            .ShouldNotThrow();
            subject
            .FindById(updatedRecord.Id)
            .ShouldBeEquivalentTo(updatedRecord);
        }
Exemple #19
0
        public ActionResult Reject(ExpenseRecord model)
        {
            var expense = new ExpenseRecord();

            using (var db = new ExpenseDBEntities())
            {
                expense = db.ExpenseRecords.Where(x => x.ExpenseRecordId == model.ExpenseRecordId).FirstOrDefault();
            }
            expense.ApprovalStatusId       = 2;
            expense.ApproverComment        = "Looks good";
            expense.ApproverId             = HttpContext.User.Identity.Name;
            expense.ApprovedOrRejectedDate = DateTime.Now;
            using (var db = new ExpenseDBEntities())
            {
                db.Entry(expense).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            ModelState.Clear();
            return(RedirectToAction("Index"));
        }
Exemple #20
0
        public void CanAddRecord()
        {
            var subject   = new ExpenseRepository();
            var newRecord = new ExpenseRecord
            {
                Id     = Guid.Parse("00000000-0000-0000-0000-000000000006"),
                Name   = "Anakin Skywalker",
                Reason = ExpenseReason.Hotel,
                Amount = 20m,
                Text   = "Cheap hotel in Mom's guest room.",
                Date   = 6.October(2016)
            };

            subject
            .Invoking(x => x.Create(newRecord))
            .ShouldNotThrow();
            subject
            .FindById(newRecord.Id)
            .ShouldBeEquivalentTo(newRecord);
        }
Exemple #21
0
        public ActionResult Add(ExpenseRecord model)
        {
            var fileName = Path.GetFileNameWithoutExtension(model.ReceiptImageFile.FileName);
            var extn     = Path.GetExtension(model.ReceiptImageFile.FileName);

            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extn;

            model.ReceiptImagePath = "~/Image/" + fileName;
            model.ReceiptImageFile.SaveAs(Path.Combine(Server.MapPath("~/Image"), fileName));
            model.ApprovalStatusId = (byte)ApprovalStatus.Submitted;
            model.RequesterUserId  = HttpContext.User.Identity.Name;
            model.SubmittedDate    = DateTime.Now;

            using (var db = new ExpenseDBEntities())
            {
                db.ExpenseRecords.Add(model);
                db.SaveChanges();
            }
            ModelState.Clear();
            return(RedirectToAction("Index"));
        }
        public async Task <ActionResult> Create([Bind(Include = "ExpenseRecordID,ExpenseTypeID,ExpenseEntityID,ExpenseDate,ExpensePrice,ExpenseDescription,selectFiles,attachmentsJson")] ExpenseRecord expenseRecord)
        {
            string userId = User.Identity.GetUserId();

            if (ModelState.IsValid)
            {
                try
                {
                    string uploadAttachmentTaskResult = await InsertAttachmentRecordsAsync(expenseRecord.ExpenseRecordID);

                    await Task.Factory.StartNew(() =>
                    {
                        expenseRecord.ExpenseLogDate = DateTime.Now;
                        expenseRecord.UserId         = userId;
                        db.ExpenseRecords.Add(expenseRecord);
                        db.SaveChanges();
                    });

                    if (!String.IsNullOrEmpty(uploadAttachmentTaskResult))
                    {
                        throw new Exception($"Some of the attachments were not uploaded. {uploadAttachmentTaskResult}");
                    }


                    //--- redirect to Index page and pass the filter
                    return(RedirectToAction("Index", IndexViewRouteValues()));
                }
                catch (Exception ex1)
                {
                    ViewData["message"] = ex1.Message;
                    ViewData["trace"]   = ex1.StackTrace;
                    return(View("ErrorDescr"));
                }
            }

            SetViewBagSelectLists(userId, expenseRecord);

            return(View(expenseRecord));
        }