public virtual void SaveExpense(Model.Expense expense)
        {
            Guard.ArgumentNotNull(expense, "expense");

            this.ValidateFromRuleset(expense);

            exManager.Process(() =>
            {
                AExpenseEvents.Log.SaveExpenseStarted(expense.Id, expense.Title);
                ProcessInContext <object>((db) =>
                {
                    AExpenseEvents.Log.SaveExpenseInsertStarted(expense.Id, expense.Title);
                    var entity = expense.ToEntity();
                    db.Expenses.InsertOnSubmit(entity);

                    foreach (var detail in expense.Details)
                    {
                        var detailEntity = detail.ToEntity(expense);
                        db.ExpenseDetails.InsertOnSubmit(detailEntity);
                    }

                    this.retryPolicy.ExecuteAction(() => db.SubmitChanges());

                    AExpenseEvents.Log.SaveExpenseInsertFinished(expense.Id, expense.Title);
                    return(null);
                });

                UpdateCache(expense);
                AExpenseEvents.Log.SaveExpenseFinished(expense.Id, expense.Title);
            },
                              Constants.NotifyPolicy);
        }
        private void UpdateCache(Model.Expense expense)
        {
            if (cache.Contains(expense.Id.ToString()))
            {
                cache.Remove(expense.Id.ToString());
                AExpenseEvents.Log.SaveExpenseCacheRemoved(expense.Id, expense.Id.ToString());
            }

            // Update cache and get full populated expense
            // so we can also force the update by ApproverName and/or UserName
            expense = GetExpenseById(expense.Id);

            if (!string.IsNullOrEmpty(expense.ApproverName) &&
                cache.Contains(ApproverKey + expense.ApproverName))
            {
                cache.Remove(ApproverKey + expense.ApproverName);
                AExpenseEvents.Log.SaveExpenseCacheRemoved(expense.Id, ApproverKey + expense.ApproverName);
            }

            if (expense.User != null && !string.IsNullOrEmpty(expense.User.UserName) &&
                cache.Contains(UserKey + expense.User.UserName))
            {
                cache.Remove(UserKey + expense.User.UserName);
                AExpenseEvents.Log.SaveExpenseCacheRemoved(expense.Id, UserKey + expense.User.UserName);
            }

            AExpenseEvents.Log.SaveExpenseCacheUpdated(expense.Id);
        }
Ejemplo n.º 3
0
        public HttpResponseMessage PostExpense(ExpenseDto dto)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            var existingExpenseReport = Uow.ExpenseReports.Include(e => e.Employee).GetById(dto.ExpenseReportId);
            if (existingExpenseReport.Employee.UserId != User.Identity.Name)
            {
                // Trying to modify a record that does not belong to the user
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }

            var expense = new Model.Expense { ExpenseReport = existingExpenseReport };
            dto.UpdateEntity(expense);

            try
            {
                Uow.Expenses.Add(expense);
                Uow.Commit();
                dto.ExpenseId = expense.Id;
            }
            catch (Exception exp)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, exp.Message);
            }

            var response = Request.CreateResponse(HttpStatusCode.Created, dto);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = dto.ExpenseId }));
            return response;
        }
Ejemplo n.º 4
0
        public void CanGetExpenseForApprovalFromCache()
        { 

            Guid expenseIdToSave = Guid.NewGuid();
            Assert.IsNull(util.DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
            var stubUser = new User { UserName = "******" };
            var stubManager = "the manager";
            var expenseToSave = new Model.Expense
                                    {
                                        Id = expenseIdToSave,
                                        Date = new DateTime(1900, 01, 01),
                                        Title = "Title",
                                        Description = "Description",
                                        Total = 1.0,
                                        ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                                        CostCenter = "CostCenter",
                                        Approved = false,
                                        User = stubUser,
                                      
                                        ApproverName = stubManager
                                    };

            var repository = new ExpenseRepository(TestDatabaseConnectionString, TimeSpan.MaxValue);
            repository.SaveExpense(expenseToSave);

            var expToApprove = repository.GetExpensesForApproval(stubManager);

            DatabaseHelper.BypassRepositoryAndDeleteExpense(TestDatabaseConnectionString, expenseToSave.Id);

            expToApprove = repository.GetExpensesForApproval(stubManager);

            Assert.AreEqual(1, expToApprove.Count());

            Assert.AreEqual(expenseIdToSave, expToApprove.First().Id);
        }
        public virtual void SaveExpense(Model.Expense expense)
        {
            Guard.ArgumentNotNull(expense, "expense");

            this.ValidateFromRuleset(expense);

            exManager.Process(() =>
            {
                ProcessInContext <object>((db) => {
                    var entity = expense.ToEntity();
                    db.Expenses.InsertOnSubmit(entity);

                    foreach (var detail in expense.Details)
                    {
                        var detailEntity = detail.ToEntity(expense);
                        db.ExpenseDetails.InsertOnSubmit(detailEntity);
                    }

                    db.SubmitChanges();
                    return(null);
                });

                UpdateCache(expense);
            },
                              Constants.NotifyPolicy);
        }
Ejemplo n.º 6
0
        public void CanInterceptAndTraceWithValidApprover()
        {
            var newExpense = new Model.Expense();

            newExpense.Id                  = testGuid;
            newExpense.Title               = "testing title";
            newExpense.CostCenter          = "testing cost center";
            newExpense.ReimbursementMethod = ReimbursementMethod.DirectDeposit;
            newExpense.User                = new Model.User()
            {
                FullName = "test user", UserName = "******"
            };
            newExpense.Date         = System.DateTime.Today;
            newExpense.ApproverName = "ADATUM\\mary";
            newExpense.Details.Add(new Model.ExpenseItem()
            {
                Description = "test item", Amount = 10, Id = Guid.NewGuid()
            });

            var repository = container.Resolve <IExpenseRepository>();

            repository.SaveExpense(newExpense);

            Log log = DatabaseHelper.GetFirstLog(LoggingDatabaseConnectionString);

            Assert.IsNotNull(log);
            Assert.AreEqual("Call Logging", log.Title);
        }
        public void CanInterceptAndTraceWithValidApprover()
        {
            var newExpense = new Model.Expense();

            newExpense.Id                  = testGuid;
            newExpense.Title               = "testing title";
            newExpense.CostCenter          = "testing cost center";
            newExpense.ReimbursementMethod = ReimbursementMethod.DirectDeposit;
            newExpense.User                = new Model.User()
            {
                FullName = "test user", UserName = "******"
            };
            newExpense.Date         = System.DateTime.Today;
            newExpense.ApproverName = "ADATUM\\mary";
            newExpense.Details.Add(new Model.ExpenseItem()
            {
                Description = "test item", Amount = 10, Id = Guid.NewGuid()
            });

            var repository = new ExpenseRepository(TestDatabaseConnectionString);

            repository.SaveExpense(newExpense);

            var events = listener.EventsWritten;

            Assert.IsNotNull(events);
            Assert.AreEqual(6, events.Count);
        }
 public static void CreateExpense(string databaseConnectionString, Model.Expense expense)
 {
     using (var db = new ExpensesDataContext(databaseConnectionString))
     {
         db.Expenses.InsertOnSubmit(expense.ToEntity());
         db.SubmitChanges();
     }
 }
Ejemplo n.º 9
0
        public static List <Model.Expense> ReadCsv(Attachment attachment)
        {
            var expenseList = new List <Model.Expense>();

            if (attachment.ContentType == FileDownloadInfo.ContentType)
            {
                FileDownloadInfo downloadInfo = (attachment.Content as JObject).ToObject <FileDownloadInfo>();
                var filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Files/");

                filePath += attachment.Name + DateTime.Now.Millisecond; // just to avoid name collision with other users
                if (downloadInfo != null)
                {
                    using (WebClient myWebClient = new WebClient())
                    {
                        // Download the Web resource and save it into the current filesystem folder.
                        myWebClient.DownloadFile(downloadInfo.DownloadUrl, filePath);
                    }
                    if (File.Exists(filePath))
                    {
                        using (TextFieldParser parser = new TextFieldParser(filePath))
                        {
                            bool isFirstRow = true;
                            parser.TextFieldType = FieldType.Delimited;
                            parser.SetDelimiters(",");
                            while (!parser.EndOfData)
                            {
                                string[] fields = parser.ReadFields();

                                if (isFirstRow)
                                {
                                    isFirstRow = false;
                                    continue;
                                }
                                try
                                {
                                    var expense = new Model.Expense()
                                    {
                                        SerialNumber = Convert.ToDouble(fields[0]),
                                        ReportName   = fields[1],
                                        Date         = DateTime.Parse(fields[2]),
                                        Description  = fields[3],
                                        Currency     = Currency.Rupee,
                                        TotalAmount  = Convert.ToDecimal(fields[4])
                                    };
                                    expenseList.Add(expense);
                                }
                                catch (Exception ex)
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
            }
            return(expenseList);
        }
        // Showcase imperative validation from config rules just before saving
        private void ValidateFromRuleset(Model.Expense expense)
        {
            var validator             = this.ValidatorFactory.CreateValidator <Model.Expense>("ExpenseRuleset");
            ValidationResults results = validator.Validate(expense);

            if (!results.IsValid)
            {
                throw new NotifyException(results.First().Message);
            }
        }
Ejemplo n.º 11
0
        public void AddExpenseLogsActivity()
        {
            using (var subscription = obsListener.LogToSqlDatabase("Activity", TracingDatabaseConnectionString))
            {
                var repository = new ExpenseRepository(TestDatabaseConnectionString, TimeSpan.MinValue);

                Guid expenseIdToSave = Guid.NewGuid();
                Assert.IsNull(DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
                var stubUser = new User {
                    UserName = "******"
                };
                var stubManager   = "the manager";
                var expenseToSave = new Model.Expense
                {
                    Id                  = expenseIdToSave,
                    Date                = new DateTime(1900, 01, 01),
                    Title               = "Title",
                    Description         = "Description",
                    Total               = 1.0,
                    ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                    CostCenter          = "CostCenter",
                    Approved            = false,
                    User                = stubUser,

                    ApproverName = stubManager
                };

                repository.SaveExpense(expenseToSave);
                subscription.Sink.FlushAsync().Wait();

                var logEntries = DatabaseHelper.GetAllLogEntries(TracingDatabaseConnectionString);

                Assert.AreEqual(6, logEntries.Count());

                var SaveExpenseStartedEntry = logEntries.SingleOrDefault(e => e.EventId == 290);
                Assert.IsNotNull(SaveExpenseStartedEntry);
                StringAssert.Contains(SaveExpenseStartedEntry.Payload, expenseToSave.Id.ToString());

                var SaveExpenseInsertStartedEntry = logEntries.SingleOrDefault(e => e.EventId == 295);
                Assert.IsNotNull(SaveExpenseInsertStartedEntry);
                StringAssert.Contains(SaveExpenseInsertStartedEntry.Payload, expenseToSave.Id.ToString());

                var SaveExpenseInsertFinishedEntry = logEntries.SingleOrDefault(e => e.EventId == 294);
                Assert.IsNotNull(SaveExpenseInsertFinishedEntry);
                StringAssert.Contains(SaveExpenseInsertFinishedEntry.Payload, expenseToSave.Id.ToString());

                var SaveExpenseCacheUpdatedEntry = logEntries.SingleOrDefault(e => e.EventId == 292);
                Assert.IsNotNull(SaveExpenseCacheUpdatedEntry);

                var SaveExpenseFinishedEntry = logEntries.SingleOrDefault(e => e.EventId == 291);
                Assert.IsNotNull(SaveExpenseFinishedEntry);
                StringAssert.Contains(SaveExpenseFinishedEntry.Payload, expenseToSave.Id.ToString());
            }
        }
Ejemplo n.º 12
0
        public void UpdatingAnExpenseUpdatesTheCache()
        {
            //Creation of expense
            Guid expenseIdToSave = Guid.NewGuid();

            Assert.IsNull(util.DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
            var stubUser = new User {
                UserName = "******"
            };
            var stubManager   = "the manager";
            var expenseToSave = new Model.Expense
            {
                Id                  = expenseIdToSave,
                Date                = new DateTime(1900, 01, 01),
                Title               = "Title",
                Description         = "Description",
                Total               = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter          = "CostCenter",
                Approved            = false,
                User                = stubUser,

                ApproverName = stubManager
            };

            //Get the repository with the highest cache expiration
            var repository = new ExpenseRepository(TestDatabaseConnectionString, TimeSpan.MaxValue);

            //Save expense
            repository.SaveExpense(expenseToSave);

            //Get expense (it also caches the expense)
            var savedExpense = repository.GetExpenseById(expenseIdToSave);

            //basic Assertion
            Assert.IsNotNull(savedExpense);

            //Approve the expense
            savedExpense.Approved = true;

            Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity(Thread.CurrentPrincipal.Identity, new Claim[] { new Claim(ClaimTypes.Role, "Manager") }));
            repository.UpdateApproved(savedExpense);

            //Delete expense in db so we make sure we will get expense from cache.
            DatabaseHelper.BypassRepositoryAndDeleteExpense(TestDatabaseConnectionString, savedExpense.Id);

            //Get expense (from cache) and verify new description
            var cachedExpense = repository.GetExpenseById(expenseIdToSave);

            //Assert
            Assert.IsNotNull(cachedExpense);
            Assert.IsTrue(cachedExpense.Approved);
        }
Ejemplo n.º 13
0
        public bool InsertExpense(Model.Expense expense)
        {
            try
            {
                expense.CreationTime = DateTime.Now;
                Instance.Connection.Insert(expense);
            }
            catch (SQLiteException ex)
            {
                Log.Info("SQLiteEx", ex.Message);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 14
0
 public static bool AddExpense(Model.Expense e)
 {
     foreach (Model.Expense expense in Expenses)
     {
         if (e.ID < expense.ID)
         {
             e.ID = expense.ID;
         }
         if (e.ID == expense.ID)
         {
             e.ID++;
         }
     }
     Expenses.Add(e);
     return(true);
 }
Ejemplo n.º 15
0
        public bool UpdateExpense(Model.Expense expense)
        {
            try
            {
                expense.UpdateTime = DateTime.Now;

                Instance.Connection.Query <Model.Expense>(
                    "UPDATE Expense set Name=?, Value=?, Time=?, UpdateTime=?, ExpenseSourceID=?, ExpenseStateId=?, AssetId=?",
                    expense.Name, expense.Value, expense.Time, expense.UpdateTime, expense.ExpenseSourceId, expense.ExpenseStateId, expense.AssetId);

                return(true);
            }
            catch (SQLiteException ex)
            {
                Log.Info("SQLiteEx", ex.Message);

                return(false);
            }
        }
        public void UpdateApproved(Model.Expense expense)
        {
            Guard.ArgumentNotNull(expense, "expense");

            Model.Expense udpatedExpense = ProcessInContext((db) =>
            {
                var exp = db.Expenses.SingleOrDefault(e => e.Id == expense.Id);
                if (exp == null)
                {
                    return(null);
                }

                exp.Approved = expense.Approved;
                db.SubmitChanges();
                return(exp.ToModel());
            });

            UpdateCache(udpatedExpense);

            Logger.Write(string.Format(CultureInfo.CurrentCulture, "The expense '{0}' for user '{1}' was approved by user '{2}'.", udpatedExpense.Title, udpatedExpense.User.UserName, udpatedExpense.ApproverName), Constants.ExpenseOperationsCategory);
        }
        public void CanInterceptAndTraceWithValidApprover()
        {
            var newExpense = new Model.Expense();
            newExpense.Id = testGuid;
            newExpense.Title = "testing title";
            newExpense.CostCenter = "testing cost center";
            newExpense.ReimbursementMethod = ReimbursementMethod.DirectDeposit;
            newExpense.User = new Model.User() { FullName = "test user", UserName = "******" };
            newExpense.Date = System.DateTime.Today;
            newExpense.ApproverName = "ADATUM\\mary";
            newExpense.Details.Add(new Model.ExpenseItem() { Description = "test item", Amount = 10, Id = Guid.NewGuid() });

            var repository = container.Resolve<IExpenseRepository>();

            repository.SaveExpense(newExpense);

            Log log = DatabaseHelper.GetFirstLog(LoggingDatabaseConnectionString);

            Assert.IsNotNull(log);
            Assert.AreEqual("Call Logging", log.Title);
        }
        public void CanInterceptAndTraceWithValidApprover()
        {
            var newExpense = new Model.Expense();
            newExpense.Id = testGuid;
            newExpense.Title = "testing title";
            newExpense.CostCenter = "testing cost center";
            newExpense.ReimbursementMethod = ReimbursementMethod.DirectDeposit;
            newExpense.User = new Model.User() { FullName = "test user", UserName = "******" };
            newExpense.Date = System.DateTime.Today;
            newExpense.ApproverName = "ADATUM\\mary";
            newExpense.Details.Add(new Model.ExpenseItem() { Description = "test item", Amount = 10, Id = Guid.NewGuid() });

            var repository = new ExpenseRepository(TestDatabaseConnectionString);

            repository.SaveExpense(newExpense);

            var events = listener.EventsWritten;

            Assert.IsNotNull(events);
            Assert.AreEqual(6, events.Count);
        }
Ejemplo n.º 19
0
        public void GetExpenseForApprovalAreGoneAfterCacheExpires()
        {
            Guid expenseIdToSave = Guid.NewGuid();

            Assert.IsNull(util.DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
            var stubUser = new User {
                UserName = "******"
            };
            var stubManager   = "the manager";
            var expenseToSave = new Model.Expense
            {
                Id                  = expenseIdToSave,
                Date                = new DateTime(1900, 01, 01),
                Title               = "Title",
                Description         = "Description",
                Total               = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter          = "CostCenter",
                Approved            = false,
                User                = stubUser,

                ApproverName = stubManager
            };

            var repository = new ExpenseRepository(TestDatabaseConnectionString, new TimeSpan(0, 0, 2));

            repository.SaveExpense(expenseToSave);

            var expToApprove = repository.GetExpensesForApproval(stubManager);

            DatabaseHelper.BypassRepositoryAndDeleteExpense(TestDatabaseConnectionString, expenseToSave.Id);

            Thread.Sleep(3000);

            expToApprove = repository.GetExpensesForApproval(stubManager);

            Assert.AreEqual(0, expToApprove.Count());
        }
Ejemplo n.º 20
0
        public void CanGetExpenseByIdFromCache()
        {
            Guid expenseIdToSave = Guid.NewGuid();

            Assert.IsNull(util.DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
            var stubUser = new User {
                UserName = "******"
            };
            var stubManager   = "the manager";
            var expenseToSave = new Model.Expense
            {
                Id                  = expenseIdToSave,
                Date                = new DateTime(1900, 01, 01),
                Title               = "Title",
                Description         = "new expense",
                Total               = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter          = "CostCenter",
                Approved            = true,
                User                = stubUser,

                ApproverName = stubManager
            };

            var repository = new ExpenseRepository(TestDatabaseConnectionString, new TimeSpan(1, 0, 0));

            repository.SaveExpense(expenseToSave);

            var expense = repository.GetExpenseById(expenseToSave.Id);

            DatabaseHelper.BypassRepositoryAndDeleteExpense(TestDatabaseConnectionString, expenseToSave.Id);

            expense = repository.GetExpenseById(expenseToSave.Id);

            Assert.IsNotNull(expense);

            Assert.AreEqual("new expense", expense.Description);
        }
        public Model.Expense GetExpenseById(Guid expenseId)
        {
            Model.Expense result = cache.GetData(expenseId.ToString()) as Model.Expense;

            if (result == null)
            {
                result = ProcessInContext((db) =>
                {
                    var entity = (from e in db.Expenses
                                  where e.Id == expenseId
                                  select e).SingleOrDefault();

                    return(entity.ToModel());
                });

                if (result != null)
                {
                    cache.Add(expenseId.ToString(), result, CacheItemPriority.Normal, null, GetExpiration());
                }
            }

            return(result);
        }
        public void UpdateApproved(Model.Expense expense)
        {
            Guard.ArgumentNotNull(expense, "expense");

            Model.Expense udpatedExpense = ProcessInContext((db) =>
            {
                var exp = db.Expenses.SingleOrDefault(e => e.Id == expense.Id);
                if (exp == null)
                {
                    return(null);
                }

                exp.Approved = expense.Approved;
                return(this.retryPolicy.ExecuteAction(() =>
                {
                    db.SubmitChanges();
                    return exp.ToModel();
                }));
            });

            UpdateCache(udpatedExpense);
            AExpenseEvents.Log.ExpenseApproved(udpatedExpense.Title, udpatedExpense.User.UserName, udpatedExpense.ApproverName);
        }
        public Model.Expense GetExpenseById(Guid expenseId)
        {
            Model.Expense result = cache.Get(expenseId.ToString()) as Model.Expense;

            if (result == null)
            {
                result = ProcessInContext((db) =>
                {
                    var entity = (from e in db.Expenses
                                  where e.Id == expenseId
                                  select e).SingleOrDefault();

                    return(this.retryPolicy.ExecuteAction <Model.Expense>(() => entity.ToModel()));
                });

                if (result != null)
                {
                    cache.Add(expenseId.ToString(), result, GetExpiration());
                }
            }

            return(result);
        }
Ejemplo n.º 24
0
        public static DataAccessLayer.Expense ToEntity(this Model.Expense model)
        {
            if (model == null)
            {
                return(null);
            }

            var expense = new DataAccessLayer.Expense
            {
                Id                  = model.Id,
                Approved            = model.Approved,
                CostCenter          = model.CostCenter,
                Date                = model.Date,
                ReimbursementMethod = Enum.GetName(typeof(ReimbursementMethod), model.ReimbursementMethod),
                Title               = model.Title,
                UserName            = model.User.UserName,
                Approver            = model.ApproverName,
                Amount              = Convert.ToDecimal(model.Total),
                Description         = model.Description
            };

            return(expense);
        }
Ejemplo n.º 25
0
        public HttpResponseMessage PostExpense(ExpenseDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            var existingExpenseReport = Uow.ExpenseReports.Include(e => e.Employee).GetById(dto.ExpenseReportId);

            if (existingExpenseReport.Employee.UserId != User.Identity.Name)
            {
                // Trying to modify a record that does not belong to the user
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            var expense = new Model.Expense {
                ExpenseReport = existingExpenseReport
            };

            dto.UpdateEntity(expense);

            try
            {
                Uow.Expenses.Add(expense);
                Uow.Commit();
                dto.ExpenseId = expense.Id;
            }
            catch (Exception exp)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, exp.Message));
            }

            var response = Request.CreateResponse(HttpStatusCode.Created, dto);

            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = dto.ExpenseId }));
            return(response);
        }
        public void GetAllExpensesUsingBootstrapper()
        {
            var expected = new Model.Expense
            {
                Id                  = testGuid,
                Date                = new DateTime(1900, 01, 01),
                Title               = "Title",
                Description         = "Description",
                Total               = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter          = "CostCenter",
                Approved            = true,
                User                = new User {
                    UserName = "******"
                },
                ApproverName = "approver name"
            };

            DatabaseHelper.CreateExpense(TestDatabaseConnectionString, expected);

            var repository = container.Resolve <IExpenseRepository>();
            var expenses   = repository.GetAllExpenses();

            Assert.IsNotNull(expenses);
            var actual = expenses.ToList().Where(e => e.Id == expected.Id).FirstOrDefault();

            Assert.IsNotNull(actual);
            Assert.AreEqual(expected.Total, actual.Total);
            Assert.AreEqual(expected.Approved, actual.Approved);
            Assert.AreEqual(expected.CostCenter, actual.CostCenter);
            Assert.AreEqual(expected.Date, actual.Date);
            Assert.AreEqual(expected.Description, actual.Description);
            Assert.AreEqual(expected.Id, actual.Id);
            Assert.AreEqual(expected.ReimbursementMethod, actual.ReimbursementMethod);
            Assert.AreEqual(expected.Title, actual.Title);
            Assert.AreEqual(expected.User.UserName, actual.User.UserName);
        }
Ejemplo n.º 27
0
 public static void DeleteExpense(Pages.Views.ExpensesView e)
 {
     Model.Expense expense = SearchExpense(e.Name);
     Expenses.Remove(expense);
 }
        public void AddExpenseLogsActivity()
        {
            using(var subscription = obsListener.LogToSqlDatabase("Activity", TracingDatabaseConnectionString))
            {
                var repository = new ExpenseRepository(TestDatabaseConnectionString, TimeSpan.MinValue);

                Guid expenseIdToSave = Guid.NewGuid();
                Assert.IsNull(DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
                var stubUser = new User { UserName = "******" };
                var stubManager = "the manager";
                var expenseToSave = new Model.Expense
                                        {
                                            Id = expenseIdToSave,
                                            Date = new DateTime(1900, 01, 01),
                                            Title = "Title",
                                            Description = "Description",
                                            Total = 1.0,
                                            ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                                            CostCenter = "CostCenter",
                                            Approved = false,
                                            User = stubUser,
                                      
                                            ApproverName = stubManager
                                        };

                repository.SaveExpense(expenseToSave);
                subscription.Sink.FlushAsync().Wait();

                var logEntries = DatabaseHelper.GetAllLogEntries(TracingDatabaseConnectionString);

                Assert.AreEqual(6, logEntries.Count());
                
                var SaveExpenseStartedEntry = logEntries.SingleOrDefault(e=> e.EventId == 290);
                Assert.IsNotNull(SaveExpenseStartedEntry);
                StringAssert.Contains(SaveExpenseStartedEntry.Payload, expenseToSave.Id.ToString());

                var SaveExpenseInsertStartedEntry = logEntries.SingleOrDefault(e=> e.EventId == 295);
                Assert.IsNotNull(SaveExpenseInsertStartedEntry);
                StringAssert.Contains(SaveExpenseInsertStartedEntry.Payload, expenseToSave.Id.ToString());

                var SaveExpenseInsertFinishedEntry = logEntries.SingleOrDefault(e=> e.EventId == 294);
                Assert.IsNotNull(SaveExpenseInsertFinishedEntry);
                StringAssert.Contains(SaveExpenseInsertFinishedEntry.Payload, expenseToSave.Id.ToString());

                var SaveExpenseCacheUpdatedEntry = logEntries.SingleOrDefault(e=> e.EventId == 292);
                Assert.IsNotNull(SaveExpenseCacheUpdatedEntry);

                var SaveExpenseFinishedEntry = logEntries.SingleOrDefault(e => e.EventId == 291);
                Assert.IsNotNull(SaveExpenseFinishedEntry);
                StringAssert.Contains(SaveExpenseFinishedEntry.Payload, expenseToSave.Id.ToString());
            }
        }
Ejemplo n.º 29
0
        public static void ConnectAndSync()
        {
            #region Users
            Model.User Miki = new Model.User
            {
                ID               = 1,
                Name             = "Herperger Miklós",
                Nickname         = "Professzor úr",
                Username         = "******",
                Password         = "******",
                Phone            = "+36-30-123-4567",
                Email            = "*****@*****.**",
                CreditCardNumber = "123456789"
            };
            Model.User Krisz = new Model.User
            {
                ID               = 2,
                Name             = "Sipos Krisztián",
                Nickname         = "Doktor úr",
                Username         = "******",
                Password         = "******",
                Phone            = "+36-30-989-4774",
                Email            = "*****@*****.**",
                CreditCardNumber = "123456789"
            };
            Model.User Kapitány = new Model.User
            {
                ID               = 3,
                Name             = "Tüttő Lajos",
                Nickname         = "Kapitány",
                Username         = "******",
                Password         = "******",
                Phone            = "+36-30-123-4567",
                Email            = "*****@*****.**",
                CreditCardNumber = "123456789"
            };
            Model.User Roli = new Model.User
            {
                ID               = 4,
                Name             = "Roli de Milyen",
                Nickname         = "Roli",
                Username         = "******",
                Password         = "******",
                Phone            = "+36-30-822-8258",
                Email            = "*****@*****.**",
                CreditCardNumber = "123456789"
            };
            Model.User Andi = new Model.User
            {
                ID               = 5,
                Name             = "Pesti Andrea Zita",
                Nickname         = "Andi",
                Username         = "******",
                Password         = "******",
                Phone            = "+36-30-123-4567",
                Email            = "*****@*****.**",
                CreditCardNumber = "123456789"
            };
            Model.User asdf = new Model.User
            {
                ID               = 6,
                Name             = "asdf",
                Nickname         = "asdf",
                Username         = "******",
                Password         = "******",
                Phone            = "+36-30-123-4567",
                Email            = "*****@*****.**",
                CreditCardNumber = "11773470-00551962-00000000"
            };
            Users.Add(Miki);
            Users.Add(Krisz);
            Users.Add(Kapitány);
            Users.Add(Roli);
            Users.Add(Andi);
            Users.Add(asdf);
            #endregion

            #region Expenses
            Model.Expense Sör = new Model.Expense
            {
                ID            = 1,
                Amount        = 1200,
                ApartmentCost = false,
                CreationTime  = DateTime.Now,
                Description   = "esti sörözés",
                ExpenseMonth  = DateTime.Now,
                From          = Krisz,
                To            = Miki,
                Name          = "GarázsHétfő",
                Paid          = true,
                SharingType   = Model.Expense.eSharingType.Common
            };
            Model.Expense VízMiki = new Model.Expense
            {
                ID            = 2,
                Amount        = 2000,
                ApartmentCost = true,
                CreationTime  = DateTime.Now,
                Description   = "-",
                ExpenseMonth  = DateTime.Now,
                From          = Krisz,
                To            = Miki,
                Name          = "Havi víz / fő",
                Paid          = false,
                SharingType   = Model.Expense.eSharingType.Common
            };
            Model.Expense VízRoli = new Model.Expense
            {
                ID            = 3,
                Amount        = 2000,
                ApartmentCost = true,
                CreationTime  = DateTime.Now,
                Description   = "-",
                ExpenseMonth  = DateTime.Now,
                From          = Krisz,
                To            = Roli,
                Name          = "Havi víz / fő",
                Paid          = false,
                SharingType   = Model.Expense.eSharingType.Common
            };
            Model.Expense VízKapitány = new Model.Expense
            {
                ID            = 4,
                Amount        = 2000,
                ApartmentCost = true,
                CreationTime  = DateTime.Now,
                Description   = "-",
                ExpenseMonth  = DateTime.Now,
                From          = Krisz,
                To            = Kapitány,
                Name          = "Havi víz / fő",
                Paid          = false,
                SharingType   = Model.Expense.eSharingType.Common
            };
            Model.Expense VízAndi = new Model.Expense
            {
                ID            = 5,
                Amount        = 2000,
                ApartmentCost = true,
                CreationTime  = DateTime.Now,
                Description   = "-",
                ExpenseMonth  = DateTime.Now,
                From          = Krisz,
                To            = Andi,
                Name          = "Havi víz / fő",
                Paid          = false,
                SharingType   = Model.Expense.eSharingType.Common
            };
            Expenses.Add(Sör);
            Expenses.Add(VízAndi);
            Expenses.Add(VízKapitány);
            Expenses.Add(VízMiki);
            Expenses.Add(VízRoli);
            #endregion

            #region Tasks

            Model.Task Konyhatakarítás = new Model.Task
            {
                ID                      = 1,
                From                    = Andi,
                TaskStatus              = Model.Task.eStatus.Open,
                To                      = Krisz,
                CreationDate            = DateTime.Now.AddDays(-5),
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Waiting_for_reply,
                AcceptanceMessage       = "",
                Description             = "Légyszi mosogasd el a tányérokat!",
                RequestedCompletionDate = DateTime.Now.AddDays(3),
            };
            Model.Task Fürdőtakarítás = new Model.Task
            {
                ID                      = 2,
                From                    = Andi,
                TaskStatus              = Model.Task.eStatus.Open,
                To                      = Roli,
                CreationDate            = DateTime.Now.AddDays(-3),
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Waiting_for_reply,
                AcceptanceMessage       = "",
                Description             = "Haj van a fürdőkádban",
                RequestedCompletionDate = DateTime.Now.AddDays(5),
            };
            Model.Task Menedzsmentprogi = new Model.Task
            {
                ID                      = 3,
                From                    = Krisz,
                TaskStatus              = Model.Task.eStatus.Open,
                To                      = Miki,
                CreationDate            = DateTime.Now,
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Waiting_for_reply,
                AcceptanceMessage       = "",
                Description             = "Észrevettem egy hibát, ki kell javítani, majd dumáljuk meg, hogy mi lenne a legjobb megoldás",
                RequestedCompletionDate = DateTime.Now.AddDays(5),
            };
            Model.Task AsdfAd = new Model.Task
            {
                ID                      = 4,
                From                    = asdf,
                TaskStatus              = Model.Task.eStatus.Open,
                To                      = Krisz,
                CreationDate            = DateTime.Now,
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Waiting_for_reply,
                AcceptanceMessage       = "",
                Description             = "Asdf ad feladat",
                RequestedCompletionDate = DateTime.Now.AddDays(5),
            };
            Model.Task AsdfKap = new Model.Task
            {
                ID                      = 5,
                From                    = Krisz,
                TaskStatus              = Model.Task.eStatus.Open,
                To                      = asdf,
                CreationDate            = DateTime.Now,
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Waiting_for_reply,
                AcceptanceMessage       = "",
                Description             = "Asdf kap feladat",
                RequestedCompletionDate = DateTime.Now.AddDays(5),
            };
            Model.Task AsdfAdKap = new Model.Task
            {
                ID                      = 6,
                From                    = asdf,
                TaskStatus              = Model.Task.eStatus.Open,
                To                      = asdf,
                CreationDate            = DateTime.Now,
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Waiting_for_reply,
                AcceptanceMessage       = "",
                Description             = "Asdf ad magának feladat",
                RequestedCompletionDate = DateTime.Now.AddDays(5),
            };
            Model.Task AsdfEldogad = new Model.Task
            {
                ID                      = 7,
                From                    = asdf,
                TaskStatus              = Model.Task.eStatus.Acceptence,
                To                      = Krisz,
                CreationDate            = DateTime.Now,
                AcceptanceProperty      = Model.Task.eAcceptanceProperty.Accepted_with_conditions,
                AcceptanceMessage       = "de akkor legyen sör",
                Description             = "Asdf el kell fogadjon feladat feltételt",
                RequestedCompletionDate = DateTime.Now.AddDays(5),
            };
            Tasks.Add(Konyhatakarítás);
            Tasks.Add(Fürdőtakarítás);
            Tasks.Add(Menedzsmentprogi);
            Tasks.Add(AsdfAd);
            Tasks.Add(AsdfKap);
            Tasks.Add(AsdfAdKap);
            Tasks.Add(AsdfEldogad);
            #endregion

            #region MonthlyFees

            Model.MonthlyFees Víz = new Model.MonthlyFees
            {
                ID           = 1,
                FeeType      = Model.MonthlyFees.eFeeType.Water,
                Amount       = 9570,
                CreationDate = DateTime.Now
            };
            Model.MonthlyFees Gáz = new Model.MonthlyFees
            {
                ID           = 2,
                FeeType      = Model.MonthlyFees.eFeeType.Gas,
                Amount       = 10000,
                CreationDate = DateTime.Now
            };
            Model.MonthlyFees Net = new Model.MonthlyFees
            {
                ID           = 3,
                FeeType      = Model.MonthlyFees.eFeeType.Internet,
                Amount       = 4600,
                CreationDate = DateTime.Now
            };
            Model.MonthlyFees Villany = new Model.MonthlyFees
            {
                ID           = 4,
                FeeType      = Model.MonthlyFees.eFeeType.Electricity,
                Amount       = 12000,
                CreationDate = DateTime.Now
            };
            MonthlyFees.Add(Víz);
            MonthlyFees.Add(Gáz);
            MonthlyFees.Add(Net);
            MonthlyFees.Add(Villany);
            #endregion
        }
Ejemplo n.º 30
0
        public void UpdatingAnExpenseUpdatesTheCache()
        {
            //Creation of expense
            Guid expenseIdToSave = Guid.NewGuid();
            Assert.IsNull(util.DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
            var stubUser = new User { UserName = "******" };
            var stubManager = "the manager";
            var expenseToSave = new Model.Expense
            {
                Id = expenseIdToSave,
                Date = new DateTime(1900, 01, 01),
                Title = "Title",
                Description = "Description",
                Total = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter = "CostCenter",
                Approved = false,
                User = stubUser,

                ApproverName = stubManager
            };

            //Get the repository with the highest cache expiration
            var repository = new ExpenseRepository(TestDatabaseConnectionString, TimeSpan.MaxValue);

            //Save expense
            repository.SaveExpense(expenseToSave);

            //Get expense (it also caches the expense)
            var savedExpense = repository.GetExpenseById(expenseIdToSave);

            //basic Assertion
            Assert.IsNotNull(savedExpense);
            
            //Approve the expense
            savedExpense.Approved = true;

            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("test"), new string[] { "Manager" });
            repository.UpdateApproved(savedExpense);

            //Delete expense in db so we make sure we will get expense from cache.
            DatabaseHelper.BypassRepositoryAndDeleteExpense(TestDatabaseConnectionString, savedExpense.Id);

            //Get expense (from cache) and verify new description
            var cachedExpense = repository.GetExpenseById(expenseIdToSave);

            //Assert
            Assert.IsNotNull(cachedExpense);
            Assert.IsTrue(cachedExpense.Approved);
        }
Ejemplo n.º 31
0
        public void GetExpenseByIdIsGoneAfterCacheExpires()
        {

            Guid expenseIdToSave = Guid.NewGuid();
            Assert.IsNull(util.DatabaseHelper.GetExpenseById(TestDatabaseConnectionString, expenseIdToSave));
            var stubUser = new User { UserName = "******" };
            var stubManager = "the manager";
            var expenseToSave = new Model.Expense
            {
                Id = expenseIdToSave,
                Date = new DateTime(1900, 01, 01),
                Title = "Title",
                Description = "Description",
                Total = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter = "CostCenter",
                Approved = true,
                User = stubUser,

                ApproverName = stubManager
            };

            var repository = new ExpenseRepository(TestDatabaseConnectionString, new TimeSpan(0, 0, 2));
            repository.SaveExpense(expenseToSave);

            var expense = repository.GetExpenseById(expenseToSave.Id);

            DatabaseHelper.BypassRepositoryAndDeleteExpense(TestDatabaseConnectionString, expenseToSave.Id);

            Thread.Sleep(3000);

            expense = repository.GetExpenseById(expenseToSave.Id);

            Assert.IsNull(expense);

        }
Ejemplo n.º 32
0
        public static DataAccessLayer.ExpenseDetail ToEntity(this Model.ExpenseItem model, Model.Expense expense)
        {
            if (model == null || expense == null)
            {
                return(null);
            }

            var expenseItem = new DataAccessLayer.ExpenseDetail
            {
                Id          = model.Id,
                Description = model.Description,
                Amount      = Convert.ToDecimal(model.Amount),
                ExpenseId   = expense.Id
            };

            return(expenseItem);
        }
        public void GetAllExpensesUsingBootstrapper()
        {
            var expected = new Model.Expense
            {
                Id = testGuid,
                Date = new DateTime(1900, 01, 01),
                Title = "Title",
                Description = "Description",
                Total = 1.0,
                ReimbursementMethod = ReimbursementMethod.DirectDeposit,
                CostCenter = "CostCenter",
                Approved = true,
                User = new User { UserName = "******" },
                ApproverName = "approver name"
            };
            DatabaseHelper.CreateExpense(TestDatabaseConnectionString, expected);

            var repository = container.Resolve<IExpenseRepository>();
            var expenses = repository.GetAllExpenses();

            Assert.IsNotNull(expenses);
            var actual = expenses.ToList().Where(e => e.Id == expected.Id).FirstOrDefault();
            Assert.IsNotNull(actual);
            Assert.AreEqual(expected.Total, actual.Total);
            Assert.AreEqual(expected.Approved, actual.Approved);
            Assert.AreEqual(expected.CostCenter, actual.CostCenter);
            Assert.AreEqual(expected.Date, actual.Date);
            Assert.AreEqual(expected.Description, actual.Description);
            Assert.AreEqual(expected.Id, actual.Id);
            Assert.AreEqual(expected.ReimbursementMethod, actual.ReimbursementMethod);
            Assert.AreEqual(expected.Title, actual.Title);
            Assert.AreEqual(expected.User.UserName, actual.User.UserName);
        }
Ejemplo n.º 34
0
 public ExpensesView(Model.Expense e)
 {
     ReferenceExpense = e;
 }