public ViewResult Index(int pageId = 1) { var entries = Services.Entry.GetList().OrderByDescending(e => e.DateCreated); IEnumerable<Entry> mainEntryList; PageList mainPageList = null; if (Services.Config.Current.IsPagingEnabled) { IEnumerable<Entry> list = entries; if (!Services.User.Current.IsAdmin) list = entries.Where(x => x.IsPublished ?? true); int amount = list.Count(); list = PaggingQuery<Entry>.ToPageList(list, Services.Config.Current.PageAmount, pageId); mainEntryList = list; mainPageList = new PageList(pageId, amount, Services.Config.Current.PageAmount); } else { mainEntryList = entries; } var model = new IndexModel() { Entries = mainEntryList.Select(EntrySummaryModelAdapter.Convert), Pagging = mainPageList }; return View(model); }
public ActionResult Index(string id) { if (!_tilgangsKontroll.ErGyldigMatchId(id)) { var currentMatch = _currentMatchProvider.GetMatchId(); if (currentMatch != Guid.Empty) { id = currentMatch.ToString(); } else { return RedirectTilForsiden("Ugyldig id for match i url. Sjekk linken."); } } var indexModel = new IndexModel { TillatNyttLag = _settings.TillatOpprettNyttLag, TillatNySpiller = _settings.TillatOpprettNySpiller, MatchId = id, KlientUrl = _settings.TestklientUrl }; return View(indexModel); }
/// <summary> /// The Index Page /// </summary> /// <returns>An <see cref="ActionResult"/> containing the view data.</returns> public ActionResult Index() { IndexModel model = new IndexModel(); model.PageOptions = new PageOptions(); model.Response = DataStore.GetData(model.PageOptions); return View(model); }
/************** SIDE PANEL **************/ public ActionResult ReadMore(bool readmore) { IndexModel model = new IndexModel(); model = DefaultIndex(model); model.panel = 2; model.why = readmore; return View("Index", model); }
public ActionResult Index(string q) { var entries = Services.Entry.GetList(); var results = entries .Where(e => e.Title.IndexOf(q, StringComparison.OrdinalIgnoreCase) >= 0) .Select(e => new SearchResultModel { Slug = e.Slug, Title = e.Title, Date = e.DateCreated.ToDateString()}); var model = new IndexModel { Results = results, QueryText = q }; return View(model); }
/// <summary> /// Adds a subject to the DataStore object. /// </summary> /// <returns>An <see cref="ActionResult"/> containing the updated view data.</returns> public ActionResult AddToSubjectTable() { IndexModel model = new IndexModel(); TestSubject subject = new TestSubject() { Email = Request.QueryString["Email"], FirstName = Request.QueryString["FirstName"], LastName = Request.QueryString["LastName"], Password = Request.QueryString["Password"] }; DataStore.AddSubject(subject); return UpdateSubjectTable(); }
public ActionResult SendMessage(IndexModel model) { if (ModelState.IsValid) { return RedirectToAction("Index", "Home"); } else { model = DefaultIndex(model); model.panel = 2; return View("Index", model); } }
public async Task<ActionResult> Index() { var blogContext = new BlogContext(); var filter = new BsonDocument(); var sort = Builders<Models.Post>.Sort.Descending("CreatedAtUtc"); var recentPosts = await blogContext.Posts.Find(filter).Sort(sort).Limit(10).ToListAsync(); var model = new IndexModel { RecentPosts =recentPosts }; return View(model); }
private IndexModel DefaultIndex(IndexModel model) { using(db_informaticsEntities _db = new db_informaticsEntities()){ model.panel = 1; model.branchList = _db.branch_information.OrderBy(x => x.branch).ToList(); int branch_id = model.branchList[0].branch_id; List<branch_course> branch_courses = _db.branch_course.Where(x => x.branch_id == branch_id).ToList(); model.courseList = new List<course_information>(); foreach(var i in branch_courses){ course_information temp = _db.course_information.Find(i.course_id); model.courseList.Add(temp); } return model; } }
public void Index_WithModel_ShouldReturnViewWithSpecifiedBalanceDate() { var balanceDate = DateTime.Today.AddDays(1); var accountBalances = new List<AccountBalance>(); _getAccountBalancesCommand.Expect(x => x.Execute(balanceDate)).Return(accountBalances); var model = new IndexModel() { Date = balanceDate }; var controller = GetController(); var result = (ViewResult)controller.Index(model); var viewModel = (IndexModel)result.Model; Assert.That(viewModel.Date, Is.EqualTo(balanceDate)); Assert.That(viewModel.AccountBalances, Is.SameAs(accountBalances)); }
public IndexModule(IStatisticsManager statisticsManager, IPoolManager poolManager, IAlgorithmManager algorithmManager) { var model = new IndexModel { Pools = poolManager.GetAllAsReadOnly(), Algorithms = algorithmManager.GetAllAsReadOnly(), Statistics = statisticsManager }; Get["/"] = _ => { // include common data required by layout. ViewBag.Header = "Welcome"; // return our view return View["index", model]; }; }
public ActionResult Index(IndexModel model) { if (!ModelState.IsValid) return View(); var from = new MailAddress(model.SenderEmail, model.SenderName); var to = new MailAddress(Services.Config.Current.ContactForm.RecipientEmail, Services.Config.Current.ContactForm.RecipientName); var mailMessage = new MailMessage(from, to) { Subject = Services.Config.Current.ContactForm.Subject, Body = model.Message, IsBodyHtml = false }; Services.Message.SendEmail(mailMessage); return RedirectToAction("Confirm"); }
public ViewResult Index() { var entries = Services.Entry.GetList(); var model = new IndexModel { Entries = entries .OrderByDescending(e => e.DateCreated) .Select(e => new EntrySummaryModel { Key = e.Slug, Title = e.Title, Date = e.DateCreated.ToDateString(), PrettyDate = e.DateCreated.ToPrettyDate() }) }; return View(model); }
public ActionResult Index(int page = 0,int rows = 10) { using (var s = sf.OpenSession()) { WebSessionContext.Bind(s); var query = this.ResolveQuery<AcademicApplicationQuery>(); var count = query.CountRecords(); var total = (int)Math.Ceiling((float)count / (float)rows); if (page == 0) page = 1; int pageIndex = Convert.ToInt32(page) - 1; var results = query.GetApplicants().Take(rows).Skip(pageIndex * rows) .Select(c => new AcademicApplicationRecords { FirstName = c.FirstName, LatestStatus = c.LatestStatus, ReferenceNumber = c.ReferenceNumber, OtherName = c.OtherName, SessionCode = c.SessionCode }).ToList(); var indexModel = new IndexModel { Page = page, Total = total, Rows = count, Records = results }; indexModel.CalculatePaging(); WebSessionContext.Unbind(sf); s.Close(); return View(indexModel); } }
public ActionResult Index() { var currentCulture = CultureHelper.GetCurrentCulture(); var languages = new Collection<LanguageModel>(); foreach (var culture in CultureHelper.GetImplementedCultures()) { languages.Add(new LanguageModel { Name = culture.NativeName, CultureName = culture.Name }); } var model = new IndexModel { Username = PrincipalHelper.GetUsername(), AvailableLanguages = languages, CurrentLanguageNameIso = currentCulture.TwoLetterISOLanguageName, CurrentLanguageName = currentCulture.NativeName, CurrentLanguageTextDirection = currentCulture.TextInfo.IsRightToLeft ? "rtl" : "ltr" }; return View(model); }
public ActionResult Index() { try { IndexModel model = new IndexModel(); IEnumerable <DokmeeCabinet> dokmeeCabinets = _dokmeeService.GetCurrentUserCabinet(User.Identity.GetUserId()); model.Cabinets = _mapper.Map <IEnumerable <Cabinet> >(dokmeeCabinets); return(View(model)); } catch (InvalideUsernameException ex) { return(RedirectToAction("Logoff", "Account")); } catch (InvalidePasswordException ex) { return(RedirectToAction("Logoff", "Account")); } catch (Exception ex) { throw; } }
public async Task <ActionResult> Index() { var blogContext = new BlogContext(); var recentPosts = await blogContext.Posts.Find(x => true) .SortByDescending(x => x.CreatedAtUtc) .Limit(10) .ToListAsync(); var tags = await blogContext.Posts.Aggregate() .Project(x => new { _id = x.Id, Tags = x.Tags }) .Unwind(x => x.Tags) .Group <TagProjection>("{ _id: '$Tags', Count: { $sum: 1 } }") .ToListAsync(); var model = new IndexModel { RecentPosts = recentPosts, Tags = tags }; return(View(model)); }
public async Task OnGetAsync() { // Arrange var deviceFlowCode = new DeviceFlowCodes { UserCode = $"{Guid.NewGuid()}" }; var deviceFlowCodes = new Mock <DbSet <DeviceFlowCodes> >(); deviceFlowCodes.Setup(x => x.FindAsync(deviceFlowCode.UserCode)).ReturnsAsync(deviceFlowCode); var context = new Mock <IPersistedGrantDbContext>(); context.Setup(x => x.DeviceFlowCodes).Returns(deviceFlowCodes.Object); var index = new IndexModel(context.Object); // Act var get = await index.OnGetAsync(deviceFlowCode.UserCode).ConfigureAwait(false); // Assert deviceFlowCodes.Verify(x => x.FindAsync(deviceFlowCode.UserCode), Times.Once); Assert.Equal(deviceFlowCode, index.DeviceFlowCode); Assert.IsType <PageResult>(get); }
public async Task OnGetAsync() { // Arrange var client = new Client { Id = Random.Next() }; var clients = new Mock <DbSet <Client> >(); clients.Setup(x => x.FindAsync(client.Id)).ReturnsAsync(client); var context = new Mock <IConfigurationDbContext>(); context.Setup(x => x.Clients).Returns(clients.Object); var index = new IndexModel(context.Object); // Act var get = await index.OnGetAsync(client.Id).ConfigureAwait(false); // Assert clients.Verify(x => x.FindAsync(client.Id), Times.Once); Assert.Equal(client, index.Client); Assert.IsType <PageResult>(get); }
public IActionResult Index(int?id) { if (id != null) { var result = new IndexModel { CategoryId = id, Categories = context.Categories, Products = context.Products.Where(x => x.CategoryId == id).OrderByDescending(x => x.Id).Take(6) }; return(View(result)); } var items = new IndexModel { Products = context.Products.OrderByDescending(x => x.Id).Take(6 * 1), Categories = context.Categories }; return(View(items)); }
public async Task OnGetAsync() { // Arrange var apiResource = new ApiResource { Id = Random.Next() }; var apiResources = new Mock <DbSet <ApiResource> >(); apiResources.Setup(x => x.FindAsync(apiResource.Id)).ReturnsAsync(apiResource); var context = new Mock <IConfigurationDbContext>(); context.Setup(x => x.ApiResources).Returns(apiResources.Object); var index = new IndexModel(context.Object); // Act var get = await index.OnGetAsync(apiResource.Id).ConfigureAwait(false); // Assert apiResources.Verify(x => x.FindAsync(apiResource.Id), Times.Once); Assert.Equal(apiResource, index.ApiResource); Assert.IsType <PageResult>(get); }
public DetailsViewModel SearchFile(Uri link) { string templink = link.OriginalString; templink = templink.Replace("watch?", ""); templink = templink.Replace("=", "/"); var youTube = YouTube.Default; // starting point for YouTube actions var video = youTube.GetVideo(templink); // gets a Video object with info about the video var currentPath = Directory.GetCurrentDirectory(); DetailsViewModel details = new DetailsViewModel() { FullName = video.FullName, Link = new Uri(templink, UriKind.Absolute), Resolution = video.Resolution, FilePath = currentPath + @"\wwwroot\Downloads\" + video.FullName }; IndexModel indexModel = new IndexModel(fileProvider); indexModel.OnGetDownloadPhysical(details.FilePath); details.IndexModel = indexModel; if (FileType.Mp4.ToString() == video.Format.ToString()) { details.Format = FileType.Mp4; } else { details.Format = FileType.Mp3; } return(details); }
public async Task <IActionResult> SendVerificationEmail(IndexModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); var email = user.Email; StatusMessage = "Verification email sent. Please check your email."; return(RedirectToAction(nameof(Index))); }
public IActionResult Index() { var status = GatewayHelper.GetRedirectedIps(); var builder = ImmutableArray.CreateBuilder <DeviceWitStatus>(); foreach (var device in ConfigHelper.Instance.Devices.OrderBy(d => d.Name)) { builder.Add(new DeviceWitStatus(device, status.ContainsKey(device.Ip))); } var currentIp = Request.HttpContext.Connection.RemoteIpAddress.ToString(); if (!currentIp.Contains(":")) { builder.Add(new DeviceWitStatus(new Device($"This device ({currentIp})", currentIp), status.ContainsKey(currentIp))); } var model = new IndexModel(builder.ToImmutable(), GatewayHelper.GetCurrentIp()); return(View(model)); }
public async Task LoadAsync(BaseViewModel model, List <IndexModel> additionalIndexModels = null) { using (Profiler.StepStatic("Create Ministry Models")) { var ministries = await Repository.GetMinistriesAsync(); List <string> uncachedPostKeys = IndexModel.GetTopPostKeys(ministries).ToList(); uncachedPostKeys.AddRange(IndexModel.GetFeaturePostKeys(ministries)); if (additionalIndexModels != null) { var additionalIndexes = additionalIndexModels.Select(m => m.Index); uncachedPostKeys.AddRange(IndexModel.GetTopPostKeys(additionalIndexes)); uncachedPostKeys.AddRange(IndexModel.GetFeaturePostKeys(additionalIndexes)); } IEnumerable <Post> loadedPosts = await Repository.GetPostsAsync(uncachedPostKeys); foreach (var ministry in ministries) { var ministryModel = new IndexModel(ministry); ministryModel.SetTopPost(loadedPosts); ministryModel.SetFeaturePost(loadedPosts); model.Ministries.Add(ministryModel); } if (additionalIndexModels != null) { foreach (var indexModel in additionalIndexModels) { indexModel.SetTopPost(loadedPosts); indexModel.SetFeaturePost(loadedPosts); } } } model.ResourceLinks = await Repository.GetResourceLinksAsync(); var homeSettings = await Repository.GetHomeAsync(); model.WebcastingLive = !string.IsNullOrEmpty(homeSettings?.LiveWebcastM3uPlaylist); }
public ActionResult Index() { IndexModel model = new IndexModel(); var Msg = TempData["Saved"] as string; if (Msg != null && Msg == "true") { model.HasSavedMessage = true; } else { model.HasSavedMessage = false; } Msg = TempData["Changed"] as string; if (Msg != null && Msg == "true") { model.HasChangedMessage = true; } else { model.HasChangedMessage = false; } Msg = TempData["Delete"] as string; if (Msg != null && Msg == "true") { model.HasDeleteMessage = true; } else { model.HasDeleteMessage = false; } model.Holidays = _holService.GetAll().ToPagedList(model.Page, model.PageSize); return(View(model)); }
public async Task <IActionResult> Upload(IndexModel model) { // Do some additional checks if (ModelState.IsValid) { if (model.NewFile.FileName.Length > 256) { ModelState.AddModelError(nameof(IndexModel.NewFile), "File name must be max 256 characters"); } else if ((model.NewFile.ContentType?.Length ?? 0) > 128) { ModelState.AddModelError(nameof(IndexModel.NewFile), "Content type of file must be max 128 characters"); } else if (model.NewFile.Length > 1 * 1024 * 1024) { ModelState.AddModelError(nameof(IndexModel.NewFile), "File max size 1 MB"); } } if (ModelState.IsValid) { try { await _fileService.UploadFileAsync(model.NewFile, User, HttpContext.RequestAborted); return(RedirectToAction(nameof(Index))); } catch (SpaceUnavailableException e) { ModelState.AddModelError(nameof(IndexModel.NewFile), e.Message); } } // Re-hydrate the Files collection model.Files = await _fileService.GetFilesAsync(User, HttpContext.RequestAborted); return(View(nameof(Index), model)); }
public PartialViewResult FaireSimulation(ApplicationModel application, SessionModel session, FormCollection data) { //modele de l'action IndexModel model = new IndexModel() { Application = application }; FeuilleSalaire feuilleSalaire = null; Exception exception = null; TryUpdateModel(model, data); if (!ModelState.IsValid) { return(PartialView("Erreurs", Static.GetErreursForModel(ModelState))); } try { feuilleSalaire = application.pamMetier.GetSalaire(data["Application.Employes"], model.HeuresTravaillees, (int)model.joursTravaillees); } catch (Exception ex) { exception = ex; } //erreur ? if (exception != null) { return(PartialView("Erreurs", Static.GetErreursForException(exception))); } session.Simulation = new Simulation() { FeuilleSalaire = feuilleSalaire, HeuresTravaillees = model.HeuresTravaillees, JoursTravaillees = (int)model.joursTravaillees, Num = session.NumNextSimulation++ }; //on affiche la feuille de salaire return(PartialView("simulation", feuilleSalaire)); }
public async Task <IActionResult> NextPage(int?page) { User logg = await this.userManager.GetUserAsync(base.User); IList <Auction> list = await this.context.Auctions.Include(t => t.owner).Where(t => t.state == "OPEN").OrderByDescending(t => t.openDate).ToListAsync(); int auctionsCount = list.Count; var winu = this.context.Users.Join(context.Auctions, user => user, win => win.winner, (user, win) => new { UserName = user.UserName, auctionId = win.Id } ).ToList(); var winner = new List <KeyValuePair <int, string> >(); foreach (var a in winu) { await Console.Out.WriteAsync(a.UserName); winner.Add(new KeyValuePair <int, string>(a.auctionId, a.UserName)); } IndexModel auction = new IndexModel() { loggedInUser = logg, currentPage = (int)page, pageNumbers = (int)Math.Ceiling(auctionsCount / 12.0), auctionsList = list.ToPagedList((int)page, 12), winners = winner }; return(PartialView("List", auction)); }
public ActionResult New(Weenie model) { ActionResult result = HandlePostback(model); if (result != null) { return(result); } result = ValidateWeenie(model); if (result != null) { return(result); } model.CleanDeletedAndEmptyProperties(); model.LastModified = DateTime.Now; model.ModifiedBy = GetUserName(); try { SandboxContentProviderHost.CurrentProvider.CreateWeenie(GetUserToken(), model); IndexModel indexModel = new IndexModel(); indexModel.SuccessMessages.Add("Weenie " + model.WeenieId.ToString() + " successfully created."); CurrentIndexModel = indexModel; return(RedirectToAction("Sandbox")); } catch (Exception ex) { model.ErrorMessages.Add("Error saving weenie in the API"); model.Exception = ex; } return(View(model)); }
public ActionResult Index() { if ((Session["UserLogin"] == null) || (Session["UserLogin"] != null && Session["UserLogin"].ToString() != "admin")) { return(HttpNotFound()); } ViewBag.UserLogin = Session["UserLogin"].ToString(); var model = new IndexModel(UserController.Users); if (UserController.Users.Count < 2) { model.IsDatabaseInitialized = false; } if (TempData["InitializationUsersSuccess"] != null) { ViewBag.InitializationUsersSuccess = true; } if (TempData["AdminCannotBeDeleted"] != null) { ViewBag.AdminCannotBeDeleted = true; } if (TempData["DeleteUserSuccess"] != null) { ViewBag.DeleteUserSuccess = true; } if (TempData["DeleteUserNotFound"] != null) { ViewBag.DeleteUserNotFound = true; } if (TempData["InitializationAlreadyDone"] != null) { ViewBag.InitializationAlreadyDone = true; } return(View(model)); }
public async Task <ViewResult> Index() { // choose versions ReleaseVersion[] versions = await this.GetReleaseVersionsAsync(); ReleaseVersion stableVersion = versions.LastOrDefault(version => !version.IsBeta && !version.IsForDevs); ReleaseVersion stableVersionForDevs = versions.LastOrDefault(version => !version.IsBeta && version.IsForDevs); ReleaseVersion betaVersion = versions.LastOrDefault(version => version.IsBeta && !version.IsForDevs); ReleaseVersion betaVersionForDevs = versions.LastOrDefault(version => version.IsBeta && version.IsForDevs); // render view IndexVersionModel stableVersionModel = stableVersion != null ? new IndexVersionModel(stableVersion.Version.ToString(), stableVersion.Release.Body, stableVersion.Asset.DownloadUrl, stableVersionForDevs?.Asset.DownloadUrl) : new IndexVersionModel("unknown", "", "https://github.com/Pathoschild/SMAPI/releases", null); // just in case something goes wrong) IndexVersionModel betaVersionModel = betaVersion != null && this.SiteConfig.BetaEnabled ? new IndexVersionModel(betaVersion.Version.ToString(), betaVersion.Release.Body, betaVersion.Asset.DownloadUrl, betaVersionForDevs?.Asset.DownloadUrl) : null; // render view var model = new IndexModel(stableVersionModel, betaVersionModel, this.SiteConfig.BetaBlurb); return(this.View(model)); }
public IActionResult Index(IndexModel indexModel) { if (indexModel.SearchingString == null) { var bikes = _repo.GetProducts(); var bikesCard = bikes.Select(b => _mapper.Map <BikeCardViewModel>(b)); var model = new IndexModel() { SearchingString = indexModel.SearchingString, bikesList = bikesCard }; return(View(model)); } var searchBikes = _repo.GetProducts(indexModel.SearchingString); var searchModel = new IndexModel() { SearchingString = indexModel.SearchingString, bikesList = searchBikes.Select(b => _mapper.Map <BikeCardViewModel>(b)) }; return(View(searchModel)); }
public void OnGetWithOwnerName() { var repository = Substitute.For <IOwnerRepository>(); var owners = new Owners(); owners.Initialise(new List <DomainModel.Owner> { new DomainModel.Owner { Name = "John" } }); repository.GetAllOwners().Returns(owners); var indexModel = new IndexModel(repository); Assert.IsNotNull(indexModel); indexModel.OnGet("John"); Assert.IsNotNull(indexModel.Owner); Assert.IsNull(indexModel.Owners); Assert.AreEqual("John", indexModel.Owner.Name); Assert.AreEqual(string.Empty, indexModel.Message); repository.Received(1).GetAllOwners(); }
public async Task <IActionResult> Index(string id) { var user = await _userManager.FindByIdAsync(id); if (User.Identity.IsAuthenticated && id == null) { user = await _userManager.GetUserAsync(User); } var tracks = _context.Tracks.Where(t => t.AuthorId == user.Id).ToList(); tracks.Reverse(); var model = new IndexModel { User = user, Tracks = tracks }; ViewData["summaryChart"] = GeneratePieChart(tracks); return(View(model)); }
public async static Task GetHubMessagesWriteDocumentsTask(EventHubClient eventHubClient, SearchServiceClient searchServiceClient, string partition, DateTime fromTime, CancellationToken cancellation) { var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, fromTime); while (true) { var listToSend = new List <IndexModel>(); Console.WriteLine("Waiting for data from partition: {0}", partition); EventData eventData = await eventHubReceiver.ReceiveAsync(); if (eventData == null) { continue; } string data = Encoding.UTF8.GetString(eventData.GetBytes()); listToSend.Add(IndexModel.NewIndexModel(data)); Console.WriteLine(string.Format("Message received. Partition: {0} Data: '{1}'", partition, data)); // Write the documents to the index IndexUtils.UploadDcuments(searchServiceClient, listToSend, Constants.IndexName); } }
public async Task OnGetAsync_InvalidModel() { // Arrange var persistedGrant = new PersistedGrant { Key = $"{Guid.NewGuid()}" }; var persistedGrants = new Mock <DbSet <PersistedGrant> >(); persistedGrants.Setup(x => x.FindAsync(persistedGrant.Key)).ReturnsAsync(persistedGrant); var context = new Mock <IPersistedGrantDbContext>(); context.Setup(x => x.PersistedGrants).Returns(persistedGrants.Object); var key = $"{Guid.NewGuid()}"; var index = new IndexModel(context.Object); // Act var get = await index.OnGetAsync(key).ConfigureAwait(false); // Assert persistedGrants.Verify(x => x.FindAsync(key), Times.Once); Assert.Null(index.PersistedGrant); Assert.IsType <NotFoundResult>(get); }
public async Task OnPostDownload_ShouldDownload_ZeroByteFile() { // Arrange var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase("InMemoryDb"); var mockAppDbContext = new Mock <ApplicationDbContext>(optionsBuilder.Options); var expectedAssignments = ApplicationDbContext.GetSeedingAssignments(); var expectedAssignment = expectedAssignments.First(x => x.Id == 1); mockAppDbContext.Setup( db => db.GetAssignmentsAsync()).Returns(Task.FromResult(expectedAssignments)); mockAppDbContext.Setup( db => db.GetAssignmentById(It.IsAny <int>())).Returns(Task.FromResult(expectedAssignment)); var pageModel = new IndexModel(mockAppDbContext.Object); // Act var fileStreamResult = await pageModel.OnPostDownload(1, "AssignmentSpecification"); // Assert Assert.Equal(0, fileStreamResult.FileStream.Length); }
public ActionResult Index(int?page) { var model = new IndexModel(); var user = _db.Employees.FirstOrDefault(x => x.Email == User.Identity.Name); var empInfo = _db.Employees.FirstOrDefault(x => x.Email == User.Identity.Name); var meetings = empInfo?.MeetingEmployees.Where(x => x.Employee_Id == empInfo.Id).Select(x => x.Meeting) .ToList(); //var notes = empInfo?.Notes.ToList(); var guests = empInfo?.EmployeeGuests.Where(x => x.Employee_Id == empInfo.Id).Select(x => x.Guest).ToList(); if (empInfo != null) { model = new IndexModel() { Employee = empInfo, Meetings = meetings, Guests = guests, //Notes = notes }; } return(View(model)); }
public async Task OnGetAsync_InvalidId() { // Arrange var client = new Client { Id = Random.Next() }; var clients = new Mock <DbSet <Client> >(); clients.Setup(x => x.FindAsync(client.Id)).ReturnsAsync(client); var context = new Mock <IConfigurationDbContext>(); context.Setup(x => x.Clients).Returns(clients.Object); const int id = 0; var index = new IndexModel(context.Object); // Act var get = await index.OnGetAsync(id).ConfigureAwait(false); // Assert clients.Verify(x => x.FindAsync(id), Times.Never); Assert.Null(index.Client); Assert.IsType <NotFoundResult>(get); }
public async Task OnGet_PopulatesThePageModel() { var userView = new UserView(new ApplicationUser { Id = Guid.Empty, Email = "*****@*****.**", GivenName = "Sample", FamilyName = "User" }); var mockUserService = new Mock <IUserService>(); mockUserService.Setup(l => l.GetCurrentUserAsync()) .ReturnsAsync(userView) .Verifiable(); var pageModel = new IndexModel(mockUserService.Object); var result = await pageModel.OnGetAsync().ConfigureAwait(false); result.Should().BeOfType <PageResult>(); pageModel.CurrentUser.Email.Should().Be(userView.Email); pageModel.CurrentUser.DisplayName.Should().Be(userView.DisplayName); }
public async Task TestRazorPage_CorrectlyProcessesKeywords(string keywords, string[] splitKeywords, string[] results) { var mockService = new Mock <IGoogleSearchService>(); var page = new IndexModel(mockService.Object); page.Keywords = keywords; page.URL = "http://www.google.com"; var request = new GoogleSearchRequest { Keywords = splitKeywords, NumberOfResults = 0, UrlToFind = "http://www.google.com" }; mockService .Setup(x => x.GetSearchResults(It.Is <GoogleSearchRequest>(r => new GoogleSearchRequestComparer().Equals(r, request)))) .ReturnsAsync(results); await page.OnPostAsync(); Assert.AreEqual(results, page.SearchResults); mockService.VerifyAll(); }
public async Task <IActionResult> Index() { var model = new IndexModel("https://www.getsircl.com"); var pages = context.ContentDocuments .AsNoTracking() .Where(d => d.DeletedOnUtc == null && d.PublishedOnUtc != null && d.Path != null && d.Type.Name.EndsWith("Page")) .OrderBy(d => d.Path).ThenBy(d => d.Id); var securedPaths = await context.ContentSecuredPaths.ToListAsync(); foreach (var page in pages) { if (securedPaths.Any(sp => page.Path.StartsWith(sp.Path))) { continue; } model.Urls.Add(new SitemapUrl(page.Path, page.ModifiedOnUtc)); } return(View(model)); }
public async System.Threading.Tasks.Task <ActionResult> DeleteEmployee(string id) { var model = new IndexModel(); model.employee = await ApiService.GetEmployee(id); if (model.employee != null) { try { model.employees = await ApiService.DeleteEmployeesAsync(id); return(RedirectToAction("Index")); } catch { ViewBag.enrror = "Khong the xoa duoc!"; return(RedirectToAction("Index")); } } return(RedirectToAction("Index")); // var model = new IndexModel(); }
// // GET: /Manage/Index public async Task <ActionResult> Index(ManageMessageId?message) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Ваш пароль изменен." : message == ManageMessageId.SetPasswordSuccess ? "Пароль задан." : message == ManageMessageId.SetTwoFactorSuccess ? "Настроен поставщик двухфакторной проверки подлинности." : message == ManageMessageId.Error ? "Произошла ошибка." : message == ManageMessageId.AddPhoneSuccess ? "Ваш номер телефона добавлен." : message == ManageMessageId.RemovePhoneSuccess ? "Ваш номер телефона удален." : ""; var userId = User.Identity.GetUserId(); var model = new IndexModel { HasPassword = HasPassword(), PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), Logins = await UserManager.GetLoginsAsync(userId), BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) }; return(View(model)); }
public IndexModel Index(IndexModel model) { return new IndexModel(); }
/// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public SqlServerIndexModelAnnotations([NotNull] IndexModel index) { Check.NotNull(index, nameof(index)); _index = index; }
public virtual ActionResult Index() { var model = new IndexModel() { DetailsModel = new JavaScriptSerializer().Serialize(new DetailsModel()) }; return View(model); }
public IndexModel Index(IndexModel model) { return model; }
public ActionResult Index(IndexModel model, string returnUrl) { if (ModelState.IsValid ) { return RedirectToLocal(returnUrl); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "A ocurrido un error. Volver a intentar."); return View(model); }
public ActionResult Index() { IndexModel model = new IndexModel(); model = DefaultIndex(model); return View(model); }
public ActionResult Apply(IndexModel model) { if(ModelState.IsValid){ using(db_informaticsEntities _db = new db_informaticsEntities()){ applicant_information tbl = new applicant_information(); tbl.branch_id = model.apply.branch_id; tbl.course_id = model.apply.course_id; tbl.prefix = model.apply.gender; if(tbl.prefix.Equals("Mr.")){ tbl.gender = "Male"; } else{ tbl.gender = "Female"; } tbl.firstname = model.apply.firstname; tbl.middlename = model.apply.middlename; tbl.lastname = model.apply.lastname; tbl.telephone = model.apply.telephone; tbl.mobile = model.apply.mobile; tbl.email = model.apply.email; tbl.address = model.apply.address; tbl.hea = model.apply.hea; tbl.lsa = model.apply.lsa; tbl.sa = model.apply.sa; _db.applicant_information.Add(tbl); _db.SaveChanges(); return RedirectToAction("Index"); } } else{ model = DefaultIndex(model); model.panel = 3; return View("Index", model); } }
/// <summary> /// Gets the updated table view. /// </summary> /// <returns>An <see cref="ActionResult"/> containing the updated view data.</returns> public ActionResult UpdateSubjectTable() { PageOptions options = new PageOptions(Request.QueryString["SortBy"], Request.QueryString["PageNumber"]); IndexModel model = new IndexModel(); model.Response = DataStore.GetData(options); model.PageOptions = options; return View("SubjectTable", model); }
public ActionResult Index() { var model = new IndexModel(); return View("~/Views/RestCore/Index.cshtml", model); }
private ActionResult RedirectTilForsiden(string melding, bool erFeilmelding = true) { var indexModel = new IndexModel { TillatNyttLag = _settings.TillatOpprettNyttLag, TillatNySpiller = _settings.TillatOpprettNySpiller, Melding = melding, ErFeilmelding = erFeilmelding, KlientUrl = _settings.TestklientUrl }; return View("Index", indexModel); }