public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var modelName = bindingContext.ModelName; // Try to fetch the value of the argument by name var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); if (valueProviderResult == ValueProviderResult.None) { return(Task.CompletedTask); } bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); var value = valueProviderResult.FirstValue; try { bindingContext.Result = ModelBindingResult.Success(DateTimeContext.Parse(value)); } catch (ArgumentException e) { bindingContext.ModelState.TryAddModelError(modelName, e.Message); } return(Task.CompletedTask); }
public ActionResult DateChanger() { var model = new DateTimeContext { Current = UserService.DateTime.Date }; return(View(model)); }
/// <summary> /// Add new movie /// </summary> /// <param name="movies"></param> /// <returns></returns> public static bool AddMovie(Movies movies) { using (var context = new DateTimeContext()) { context.Attach(movies).State = EntityState.Added; return(context.SaveChanges() == 1); } }
public void MovieConnectionTest() { using (var context = new DateTimeContext()) { var movies = context.Movies.ToList(); Assert.IsTrue(movies.Count > 0 && movies.FirstOrDefault().Title == "Aliens extended"); } }
/// <summary> /// Get all available movies /// </summary> /// <returns></returns> public static async Task <List <Movies> > GetMovies() { return(await Task.Run(async() => { using (var context = new DateTimeContext()) { return await context.Movies.AsNoTracking().ToListAsync(); } })); }
public void DateChanger_WithPost_ReturnsViewResult() { var controller = SystemUnderTest(); var model = new DateTimeContext(); var current = DateTime.Now.AddDays(1); model.Current = current; var result = controller.DateChanger(model); Assert.IsNotNull(result, "ViewResult should not be null."); mockUserService.VerifySet(d => d.DateTime = current); }
public void Now_ShouldReturnDateTimeNow() { var startDateTime = DateTime.Now; Thread.Sleep(1); var now = new DateTimeContext().Now; Thread.Sleep(1); var endDateTime = DateTime.Now; Assert.IsTrue(now > startDateTime && now < endDateTime); }
public void UtcNow_ShouldReturnDateTimeUtcNow() { var startDateTime = DateTime.UtcNow; Thread.Sleep(1); var utcNow = new DateTimeContext().UtcNow; Thread.Sleep(1); var endDateTime = DateTime.UtcNow; Assert.IsTrue(utcNow > startDateTime && utcNow < endDateTime); }
public void GetFirstMovieValidateHoursMinutes() { using (var context = new DateTimeContext()) { var firstMovie = context.Movies.FirstOrDefault(); var movieTitle = firstMovie.Title; var duration = firstMovie.Duration.Value; var hours = duration.Hours; var minutes = duration.Minutes; Assert.AreEqual(hours, 3); Assert.AreEqual(minutes, 30); Console.WriteLine($"{movieTitle} is {hours} hours {minutes} minutes long"); } }
public EndBalance Calculate(List <Filter> filters) { if (filters == null) { return(null); } var startFilter = filters.FindStartDateFilter(nameof(TransactionDisplay.CreatedTime)); var endFilter = filters.FindEndDateFilter(nameof(TransactionDisplay.CreatedTime)); if (startFilter == null || endFilter == null) { return(null); } var transactionsAmount = Context.Transactions .ApplyTableRequestIQueryable <Transaction, TransactionDisplay, long>(CreateTableRequest(filters)) .Select(x => x.Amount) .ToList(); var startDate = DateTimeContext.Parse(startFilter.Value.ToString()); var endDate = DateTimeContext.Parse(endFilter.Value.ToString()); var totalExpenses = transactionsAmount.Where(x => x < 0).Sum(); var totalIncome = transactionsAmount.Where(x => x > 0).Sum(); var balanceOnStartDate = Context.Transactions.Where(x => x.CreatedTime <= startDate).Sum(x => x.Amount); var balanceOnEndDate = Context.Transactions.Where(x => x.CreatedTime <= endDate).Sum(x => x.Amount); var availableBalance = Context.Transactions.Sum(x => x.Amount); var filterByProjectStr = filters.SingleFilterOrDefault(nameof(TransactionDisplay.ProjectId))?.Value?.ToString(); var filterByProject = filterByProjectStr != null?long.Parse(filterByProjectStr) as long? : null; return(new EndBalance { BalanceOnStartDate = balanceOnStartDate, BalanceOnEndDate = balanceOnEndDate, AvailableBalance = availableBalance, TotalExpenses = totalExpenses, TotalIncome = totalIncome, TotalAmount = totalExpenses + totalIncome, StartDate = startDate, EndDate = endDate, ProjectsBalances = CalculateProjectsBalances(startDate, endDate, filterByProject) }); }
public ActionResult DateChanger(DateTimeContext model) { if (ModelState.IsValid) { if (model.Current.Date.Equals(UserService.DateTime.Date)) { AddWarningMessage("Date not been updated. Select a new date and Submit"); return(View(model)); } UserService.DateTime = model.Current; AddInformationMessage("Date updated Successfully"); return(RedirectToAction("DateChanger")); } AddErrorMessage("The date entered was not recognised. The date entered must be in the form DD/MM/YYYY"); return(View(model)); }
public DateTimeContext Apply(TextBox textBox, DateTime?value, FormatSpecifier[] formatSpecifiers, out int start, out int length) { // No value or no text selected then prevent increment if (!value.HasValue || string.IsNullOrWhiteSpace(textBox.SelectedText)) { start = -1; length = -1; return(null); } string text = textBox.SelectedText.TrimEnd(); if (!Regex.IsMatch(text, "^[0-9]*$")) { start = -1; length = -1; return(null); } start = textBox.SelectionStart; length = text.Length; int numberOfPreviousNumbers = 0; for (int i = 0; i < textBox.Text.Length; i++) { if (i == start) // Found start index { break; } if (char.IsDigit(textBox.Text[i])) { continue; } numberOfPreviousNumbers++; // Must have encountered as seperator. Inc } FormatSpecifier formatSpecifier = formatSpecifiers.FirstOrDefault(x => x.Index == numberOfPreviousNumbers); DateTimeContext dateTimeContext = new DateTimeContext(formatSpecifier); return(dateTimeContext); }
public void DateChanger_WithPost_ReturnsViewResultError() { var controller = SystemUnderTest(); var model = new DateTimeContext(); var current = DateTime.Now; model.Current = current; controller.ModelState.AddModelError("key", @"date field error message"); // set an invalid model state var result = controller.DateChanger(model); Assert.IsNotNull(result, "ViewResult should not be null."); var values = controller.ModelState[""].Errors[0]; Assert.AreEqual("The date entered was not recognised. The date entered must be in the form DD/MM/YYYY", values.ErrorMessage); mockUserService.VerifySet(dv => dv.DateTime = current, Times.Never()); }
protected override Expression GetFilterExpression(ParameterExpression param, Filter filter) { var field = filter.Path.CreatePropertyExpression(param); ConstantExpression value = Expression.Constant(DateTimeContext.Parse(filter.Value.ToString())); DateTime?date = value.Value as DateTime?; if (date == null) { return(null); } DateTime currentDate = ((DateTime)date).Date; DateTime nextDate = currentDate.AddDays(1); switch (filter.Operator) { case FilterOperator.Equal: case FilterOperator.Contains: return(Expression.AndAlso( Expression.GreaterThanOrEqual(field, Expression.Constant(currentDate)), Expression.LessThan(field, Expression.Constant(nextDate)))); case FilterOperator.GreaterThan: return(Expression.GreaterThan(field, Expression.Constant(currentDate))); case FilterOperator.GreaterThanOrEqual: return(Expression.GreaterThanOrEqual(field, Expression.Constant(currentDate))); case FilterOperator.LessThan: return(Expression.LessThan(field, Expression.Constant(nextDate))); case FilterOperator.LessThanOrEqual: return(Expression.LessThanOrEqual(field, Expression.Constant(nextDate))); default: throw new SwitchExpressionValueException(filter.Operator); } }
public void DateChanger_WithPost_ReturnsViewResultWarning() { var controller = SystemUnderTest(); var model = new DateTimeContext(); var current = DateTime.Now; model.Current = current; var result = controller.DateChanger(model); Assert.IsNotNull(result, "ViewResult should not be null."); Assert.IsTrue(((ViewResult)result).TempData.Count == 1); var values = ((ViewResult)result).TempData.Values; var e = values.GetEnumerator(); e.MoveNext(); var d = (Dictionary <string, List <string> >)e.Current; Assert.AreEqual("Date not been updated. Select a new date and Submit", d[""][0]); mockUserService.VerifySet(dv => dv.DateTime = current, Times.Never()); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SeedManager seedManager, MigrationManager migrationManager) { var stopwatch = Stopwatch.StartNew(); try { loggerFactory.AddSerilog(); Log.Logger().Information("Application is starting..."); Log.Logger().Information("Configuration:"); ConfigurationProvider.GetType().GetProperties().ToList().ForEach(prop => { Log.Logger().Information("[{name}] = '{value}'", prop.Name, prop.GetValue(ConfigurationProvider)); }); DateTimeContext.Initialize(ConfigurationProvider.TimeZone); Log.Logger().Information("Configure EF Mappings..."); MappingConfig.RegisterMappings(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); //todo IS incorrect page diesnt exist yet!! app.UseHsts(); app.UseHttpsRedirection(); } app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")) }); app.UseSession(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute(name: "Area", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute(name: "Area2", template: "{area:exists}/{controller=Home}/{action=Index}/{isReadonly?}"); routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute(name: "default2", template: "{controller=Home}/{action=Index}/{isReadonly?}"); }); //migrationManager.EnsureCreated(ConfigurationProvider); //migrationManager.ApplyMigrations(ConfigurationProvider); seedManager.Seed(ConfigurationProvider); } catch (Exception e) { Log.Logger().Error(e, "Application failed to start"); throw; } finally { stopwatch.Stop(); Log.Logger().Information("Startup time: {Seconds}s", stopwatch.Elapsed.Seconds); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BasicSeedManager seedManager, MigrationManager migrationManager) { var stopwatch = Stopwatch.StartNew(); try { loggerFactory.AddSerilog(); Log.Logger().Information("Application is starting..."); Log.Logger().Information("Configuration:"); ConfigurationProvider.GetType().GetProperties().ToList().ForEach(prop => { Log.Logger().Information("[{name}] = '{value}'", prop.Name, prop.GetValue(ConfigurationProvider)); }); DateTimeContext.Initialize(ConfigurationProvider.TimeZone); Log.Logger().Information("Configure EF Mappings..."); MappingConfig.RegisterMappings(); Log.Logger().Information("Configure Jwt Bearer Authentication..."); app.ConfigJwtBearerMiddleware(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Default}/{action=Index}/{id?}"); routes.MapRoute( name: "admin", template: "{*url}", defaults: new { controller = "Default", action = "Index" } ); }); //app.Use(async (context, next) => //{ // await next(); // if (context.Response.StatusCode == 404 && // !Path.HasExtension(context.Request.Path.Value) && // !context.Request.Path.Value.StartsWith("/api/")) // { // context.Request.Path = "/index.html"; // await next(); // } //}); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); migrationManager.ApplyMigrations(ConfigurationProvider); //seedManager.Seed(); } else { app.UseExceptionHandler("/error"); } } catch (Exception e) { Log.Logger().Error(e, "Application failed to start"); throw; } finally { stopwatch.Stop(); Log.Logger().Information("Startup time: {Seconds}s", stopwatch.Elapsed.Seconds); } }