public void CanRemoveAndAddImagesExternally() { const string basePath = @"C:\"; var allFiles = new[] { "image.png", "some.gif" } .Select(f => basePath + f); var fsMock = new Mock <IFileSystem>(); fsMock.Setup(fs => fs.GetFiles(basePath)).Returns(allFiles); var imagesVM = new ImagesViewModel(fsMock.Object) { CurrentFolder = basePath }; imagesVM.SelectedIndex = 0; Assert.Equal(allFiles, imagesVM.Images); imagesVM.RemoveImage(allFiles.ElementAt(1)); Assert.Equal(allFiles.Where(p => p != allFiles.ElementAt(1)), imagesVM.Images); imagesVM.InsertImage(allFiles.ElementAt(1)); Assert.Equal(allFiles, imagesVM.Images); }
public async Task <ActionResult> Index(Guid?selectedTag) { var vm = new ImagesViewModel { Message = TempData["Message"]?.ToString() }; var api = CreateTrainingApi(); vm.Tags = await GetTagSelectList(api, selectedTag); if (!selectedTag.HasValue) { return(View(vm)); } var images = await api.GetTaggedImagesAsync(ProjectId, tagIds : new List <string> { selectedTag.Value.ToString() }); foreach (var image in images) { vm.Images.Add(new ImagesViewModel.Image { Url = image.ThumbnailUri }); } return(View(vm)); }
public ActionResult Images(int?amountToShow) { using (UnitOfWorkManager.NewUnitOfWork()) { if (amountToShow == null) { amountToShow = 5; } var cacheKey = string.Concat("Images", UsersRole.Id, amountToShow); var viewModel = _cacheService.Get <ImagesViewModel>(cacheKey); if (viewModel == null) { var images = _imageService.GetAll(); // create the view model viewModel = new ImagesViewModel { Images = images, }; _cacheService.Set(cacheKey, viewModel, CacheTimes.FiveMinute); } return(PartialView(viewModel)); } }
public IActionResult PostImage(ICollection <IFormFile> files, ImagesViewModel model) { bool useDatabaseStorage = model.SaveToDb; try { foreach (IFormFile file in files) { if (file.Length > 0) { MemoryStream ms = new MemoryStream(); file.CopyTo(ms); byte[] imageInBytes = ms.ToArray(); string type = file.ContentType; if (type != "image/bmp" && type != "image/png" && type != "image/jpeg" && type != "image/gif") { throw new Exception(_localizer["The selected format is not supported."]); } if (useDatabaseStorage) { // working solution - savig images to the DB Image dbImageEntity = new Image(); dbImageEntity.Name = file.FileName; dbImageEntity.ImageData = new ImageData() { Data = imageInBytes }; dbImageEntity.InDb = true; // indicate that the image is strored in the database _databaseContext.Images.Add(dbImageEntity); _databaseContext.SaveChanges(); } else { SaveImageToFilesystem(imageInBytes, file.FileName); } TempData["Success"] = true; } else { throw new InvalidImageFormatException(_localizer["The selected file is not a image or contains no data."]); } } } catch (InvalidImageFormatException ex) { TempData["ErrorMessage"] = ex.Message; } catch (Exception ex) { TempData["ErrorMessage"] = _localizer["There was an error during image upload."] + ex.Message + ((ex.InnerException != null) ? ex.InnerException.Message : ""); } return(RedirectToAction("Index")); }
public async Task <IActionResult> Index() { try { if (storageConfig.AccountKey == string.Empty || storageConfig.AccountName == string.Empty) { return(BadRequest("sorry, can't retrieve your azure storage details from appsettings.js, make sure that you add azure storage details there")); } if (storageConfig.ImageContainer == string.Empty) { return(BadRequest("Please provide a name for your image container in the azure blob storage")); } List <string> imageUrls = await StorageHelper.GetImagelUrls(storageConfig); var imagesViewModel = new ImagesViewModel(); imagesViewModel.ImageUrls = imageUrls; return(View(imagesViewModel)); } catch (Exception exception) { return(View()); } }
public void TastStateConditions() { var catsStorage = new CatsStorage(); var catsData = new CatsData(); var vm = new ImagesViewModel(catsStorage, catsData); vm.Init(null); Assert.AreEqual(vm.CurrentState, State.NoData); vm.Init(null); catsData.TokenCource = new CancellationTokenSource(); vm.Init(null); Assert.AreEqual(vm.CurrentState, State.Loading); catsData.TokenCource.Cancel(); catsData.TokenCource = null; Assert.AreEqual(vm.CurrentState, State.Error); catsData.Cats = new List <ImageModel> { new ImageModel(0, String.Empty, String.Empty, String.Empty) }; vm.Init(null); Assert.AreEqual(vm.CurrentState, State.Normal); }
public void AddToFavoriteTest() { var catsStorage = new CatsStorage(); var catsData = new CatsData(); catsStorage.Cats = new List <ImageModel> { new ImageModel(27, String.Empty, String.Empty, String.Empty), new ImageModel(37, String.Empty, String.Empty, String.Empty), }; var vm = new ImagesViewModel(catsStorage, catsData); vm.Init(null); Assert.IsTrue(vm.FavoriteCommand.CanExecute(catsStorage.Cats.First())); vm.FavoriteCommand.Execute(catsStorage.Cats.First()); Assert.IsTrue(vm.Cats.First().IsFavorite); Assert.IsFalse(vm.Cats.Last().IsFavorite); Assert.IsTrue(catsStorage.Cats.First().IsFavorite); Assert.IsFalse(catsStorage.Cats.Last().IsFavorite); Assert.AreEqual(catsStorage.CatsFavoritesIds.Count, 1); Assert.AreEqual(catsStorage.CatsFavoritesIds.First(), catsStorage.Cats.First().Id); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); IUnityContainer container = new UnityContainer(); var customXmlRW = new DataBase(@"C:\Users\stefan\Desktop\db.xml"); // Register ViewModels var loginViewModel = new LoginViewModel(customXmlRW); container.RegisterInstance <LoginViewModel>(loginViewModel); var showImagesViewModel = new ImagesViewModel(); container.RegisterType <ImagesViewModel>(); var addImageViewModel = new AddImageViewModel(); container.RegisterType <AddImageViewModel>(); var accountDetailsViewModel = new AccountDetailsViewModel(); container.RegisterType <AccountDetailsViewModel>(); var contentViewModel = new ContentViewModel(container, customXmlRW); container.RegisterInstance <ContentViewModel>(contentViewModel); var mainWindowViewModel = new MainWindowViewModel(container); container.RegisterInstance <MainWindowViewModel>(mainWindowViewModel); var mainWindow = container.Resolve <MainWindow>(); mainWindow.DataContext = container.Resolve <MainWindowViewModel>(); Application.Current.MainWindow = mainWindow; Application.Current.MainWindow.Show(); }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.Main); var viewModel = new ImagesViewModel(new AstrobinService()); images = await viewModel.GetTasksAsync(); imageUrls = viewModel.GetImageIds(images); _adapter = new ImageResultsAdapter(this, images, imageUrls); SetContentView(Resource.Layout.Main); _recyclerView = FindViewById <RecyclerView>(Resource.Id.imageOfTheDayRecycler); _recyclerView.SetAdapter(_adapter); _layoutManager = new LinearLayoutManager(this); _recyclerView.SetLayoutManager(_layoutManager); textMessage = FindViewById <TextView>(Resource.Id.message); BottomNavigationView navigation = FindViewById <BottomNavigationView>(Resource.Id.navigation); navigation.SetOnNavigationItemSelectedListener(this); }
public void ThereAreFavoritesInStorageTest() { var catsStorage = new CatsStorage(); var catsData = new CatsData(); catsStorage.Cats = new List <ImageModel> { new ImageModel(27, String.Empty, String.Empty, String.Empty), new ImageModel(37, String.Empty, String.Empty, String.Empty), }; var vm = new ImagesViewModel(catsStorage, catsData); vm.Init(null); Assert.IsFalse(vm.Cats.Any(model => model.IsFavorite)); catsStorage.CatsFavoritesIds = new List <int> { catsStorage.Cats.First().Id }; vm.Init(null); Assert.AreEqual(1, vm.Cats.Count(model => model.IsFavorite)); }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } using (var database = new BlogDbContext()) { var image = database.Images.Where(i => i.Id == id).First(); if (!IsUserAuthorizedToEdit(image)) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } if (image == null) { return(HttpNotFound()); } var model = new ImagesViewModel(); model.Id = image.Id; model.Title = image.Title; model.Contents = image.Contents; model.Description = image.Description; model.AlbumId = image.AlbumId; model.Albums = database.Albums.OrderBy(a => a.Name).ToList(); model.Tags = string.Join(", ", image.Tags.Select(t => t.Name)); return(View(model)); } }
public IActionResult Search(ImagesViewModel model) { var pictureDetailsList = HttpContext.Session.GetObject <List <PictureDetailsDto> >("PictureDetailsList"); if (pictureDetailsList == null) { return(PartialView("_TableImages", new List <PictureDto>())); } else { var result = pictureDetailsList.Where(i => (String.IsNullOrWhiteSpace(model.Search.cropped_picture) ? true : i.cropped_picture == model.Search.cropped_picture) && (String.IsNullOrWhiteSpace(model.Search.author) ? true : i.author == model.Search.author) && (String.IsNullOrWhiteSpace(model.Search.camera) ? true : i.camera == model.Search.camera) && (String.IsNullOrWhiteSpace(model.Search.tags) ? true : i.tags == model.Search.tags) && (String.IsNullOrWhiteSpace(model.Search.id) ? true : i.id == model.Search.id) && (String.IsNullOrWhiteSpace(model.Search.full_picture) ? true : i.full_picture == model.Search.full_picture)); if (result != null) { return(PartialView("_TableImages", result.Select(r => new PictureDto() { id = r.id, cropped_picture = r.cropped_picture }).ToList())); } return(PartialView("_TableImages", new List <PictureDto>())); } }
public IActionResult AddImages(ImagesViewModel img) { if (ModelState.IsValid) { string uniqueFileName = null; Console.WriteLine(img.Photo); if (img.Photo != null) { Console.WriteLine("ab"); string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "img/PG"); Console.WriteLine(uploadsFolder); uniqueFileName = Guid.NewGuid().ToString() + "_" + img.Photo.FileName; Console.WriteLine(uniqueFileName); string FilePath = Path.Combine(uploadsFolder, uniqueFileName); Console.WriteLine(FilePath); img.Photo.CopyTo(new FileStream(FilePath, FileMode.Create)); } //ApplicationUser usr = await GetCurrentUserAsync(); var Email = HttpContext.User.Identity.Name; Images newImg = new Images { Email = Email, PhotoPath = uniqueFileName }; _context.Add(newImg); _context.SaveChanges(); } return(View(img)); }
public bool RemoveImage(ImagesViewModel image) { if (!ModelState.IsValid) { return(false); } return(_imagesSessionService.Remove(image)); }
// GET: Admin/Images public ActionResult Images() { ImagesViewModel viewModel = new ImagesViewModel(); viewModel.Images = _image.GetAll().ToList(); return(View(viewModel)); }
public async Task CanRenameImages() { const string basePath = @"C:\"; const string oldFilePath = basePath + "image.png"; const string newFileName = "other_image"; var invalidFileNames = new[] { @"image\ima", "im/age", "imag\n", "imag\t" }; var promptedFileName = newFileName; const string newFilePath = basePath + newFileName + ".png"; var allFiles = new[] { oldFilePath }; var allFilesResulting = new[] { newFilePath }; var notifiesUserOfError = false; var fsMock = new Mock <IFileSystem>(); fsMock.Setup(fs => fs.GetFiles(basePath)).Returns(allFiles); fsMock.Setup(fs => fs.Move(oldFilePath, newFilePath)).Verifiable(); fsMock.Setup(fs => fs.FileExists(oldFilePath)).Returns(true); var imagesVM = new ImagesViewModel(fsMock.Object) { CurrentFolder = basePath }; imagesVM.RenameImage.Where(a => a != null) .Subscribe(a => a.Act()); Assert.Equal(allFiles, imagesVM.Images); imagesVM.PromptForNewFileName.RegisterHandler(ic => ic.SetOutput(promptedFileName)); imagesVM.NotifyUserOfError.RegisterHandler(ic => { notifiesUserOfError = true; ic.SetOutput(Unit.Default); }); await imagesVM.RenameImage.Execute(); fsMock.Verify(fs => fs.Move(oldFilePath, newFilePath)); await Task.Delay(1); Assert.Equal(allFilesResulting, imagesVM.Images); foreach (var invalidFileName in invalidFileNames) { promptedFileName = invalidFileName; await imagesVM.RenameImage.Execute(); Assert.Equal(allFilesResulting, imagesVM.Images); } Assert.True(notifiesUserOfError); }
public ActionResult Create() { using (var database = new BlogDbContext()) { var model = new ImagesViewModel(); model.Albums = database.Albums.OrderBy(a => a.Name).ToList(); return(View(model)); } }
public async Task <IActionResult> Images() { var response = await _dogClient.GetBreedImages(); var model = new ImagesViewModel(); model.Dogs = response.Message; return(View(model)); }
public ActionResult ManageImages() { DatabaseService service = new DatabaseService(); ImagesViewModel model = new ImagesViewModel(); model.Images = service.GetImages(Request.QueryString["albumId"]); return(View(model)); }
public IActionResult Index() { var connectionString = _configuration.GetConnectionString("ConStr"); var repo = new ImagesRepository(connectionString); var vm = new ImagesViewModel() { Images = repo.GetImages() }; return(View(vm)); }
private void OnLogin() { User.Validate("login"); if (User.IsValid) { var user = UserService.GetUser(User); var storeWindow = new StoreWindow(); var imageVM = new ImagesViewModel(); imageVM.ImageModels = ImageService.GetImageModels(user); storeWindow.DataContext = new StoreViewModel(user, imageVM); CloseAction(); storeWindow.Show(); } }
public ContentViewModel(IUnityContainer container, DataBase db) { _container = container; _dataBase = db; _ImagesViewModel = _container.Resolve <ImagesViewModel>(); _addImageViewModel = _container.Resolve <AddImageViewModel>(); _accountDetailsViewModel = _container.Resolve <AccountDetailsViewModel>(); CurrentContentViewModel = _ImagesViewModel; NavCommand = new Command <string>(OnNav); }
public ActionResult PatientImagesCreate(ImagesViewModel imagesViewModel, string name, IEnumerable <HttpPostedFileBase> files, FormCollection coll) { try { if (ModelState.IsValid) { if (files != null) { List <HttpPostedFileBase> list = files.ToList(); if (list[0] != null) { imagesViewModel.PatientID = getCurrentPatientID(); string imageCategoryName = imageRepository.getIMageCategoryNameByID(imagesViewModel.ImageCategoryID); ImagesDrawing ob = new ImagesDrawing(); ob.PatientImageSaver(System.Drawing.Image.FromStream(list[0].InputStream), Server.MapPath(@"~/Content/Images/") + imageCategoryName, @"../../Content/Images/" + imageCategoryName, imagesViewModel); return(RedirectToAction("patientImagesList", new { patientID = imagesViewModel.PatientID })); } } else { ViewBag.patientID = imagesViewModel.PatientID; return(View()); } } else { ViewBag.patientID = imagesViewModel.PatientID; ImageCreateViewModel imageCreateViewModel = new ImageCreateViewModel(); imageCreateViewModel.imageCategoryList = imageRepository.getImagesCategoryList(); imageCreateViewModel.appointmentList = appointmentRepository.getPatientAppountmentList(imagesViewModel.PatientID); return(View(imageCreateViewModel)); } return(RedirectToAction("patientImagesList", new { patientID = imagesViewModel.PatientID })); } catch { ViewBag.patientID = imagesViewModel.PatientID; ImageCreateViewModel imageCreateViewModel = new ImageCreateViewModel(); imageCreateViewModel.imageCategoryList = imageRepository.getImagesCategoryList(); imageCreateViewModel.appointmentList = appointmentRepository.getPatientAppountmentList(imagesViewModel.PatientID); return(View(imageCreateViewModel)); } }
public async Task <IActionResult> RemoveImage(ImagesViewModel file) { var dto = new FileToDatabaseDto() { Id = file.ImageId, }; var image = await _spaceshipService.RemoveImage(dto); if (image == null) { return(RedirectToAction(nameof(Index))); } return(RedirectToAction(nameof(Index))); }
public async Task <ImagesViewModel> UpdatePage() { try { ImagesViewModel model = new ImagesViewModel(); model.ImagesFromDatabase = await _dbHelper.GetAllImages(); return(model); } catch { ImagesViewModel model = new ImagesViewModel(); model.ImagesFromDatabase = null; return(model); } }
public async Task <IActionResult> Images(int?page) { var user = await GetCurrentUserAsync(); if (user != null) { var role = await _userManager.GetRolesAsync(user); TempData["userRole"] = role[0]; string res = string.Empty; if (!string.IsNullOrEmpty(HttpContext.Request.Query["resturant"])) { res = HttpContext.Request.Query["resturant"].ToString(); } ViewBag.rid = res; var dummy = _context.RestaurantDetail.FirstOrDefault(a => a.id == Convert.ToInt32(res)); ViewBag.Rname = dummy.restaurantName; List <ImageDetail> imageDetail = new List <ImageDetail>(); var _imageDetails = _context.ImageDetail.Where(a => a.restaurantId == Convert.ToInt32(res)).ToList(); foreach (var imgs in _imageDetails) { imgs.RestaurantName = dummy.restaurantName; imageDetail.Add(imgs); } var dummyItems = imageDetail; var pager = new PageImages(dummyItems.Count(), page); var viewModel = new ImagesViewModel { Items = dummyItems.Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize), PageImageitems = pager }; return(View(viewModel)); } else { return(RedirectToAction("QuickRegister", "Account")); } }
public ActionResult PatientImagesEdit(ImagesViewModel patientImageViewModel) { try { if (ModelState.IsValid) { bool check = patientRepository.updatePatinetImage(patientImageViewModel); } else { return(View()); } return(RedirectToAction("patientImagesList", new { patientID = patientImageViewModel.PatientID })); } catch { return(View()); } }
public ProductViewModel(ProductDataModel product) { _product = product; if (!_product.Stores.Contains(0)) { _product.Stores.Add(0); // Default store ID } DataVM = new DataViewModel(product); LinksVM = new LinksViewModel(product); DiscountsVM = new DiscountsViewModel(product); OffersVM = new OffersViewModel(product); ImagesVM = new ImagesViewModel(product); LoadCommand = new CommandHandler(o => Load()); SaveCommand = new CommandHandler(o => Save()); RemoveCommand = new CommandHandler(o => RemoveItem(o)); BackCommand = new CommandHandler(o => BackTo()); }
public ActionResult Images() { var viewModel = new ImagesViewModel(); var webRootPath = Server.MapPath("~"); var localFilePrefix = $"{webRootPath}images"; var filter = Request.Params["filter"]; var sortBy = Request.Params["sortBy"]; var files = string.IsNullOrEmpty(filter) ? Directory.GetFiles(localFilePrefix) : Directory.GetFiles(localFilePrefix, filter); foreach (var filePath in files) { var fileModel = new FileModel { Name = Path.GetFileName(filePath) }; var fileInfo = new FileInfo(filePath); fileModel.CreationDateUTC = fileInfo.CreationTimeUtc; fileModel.CreationDateUTC = fileInfo.CreationTimeUtc.AddHours(-6); // Daylight savings fileModel.ImageUrl = $"/images/{fileModel.Name}"; fileModel.SizeInBytes = fileInfo.Length; viewModel.Images.Add(fileModel); if (viewModel.Images.Count >= 100) { break; // like a "Take()" but not really. } } if (sortBy == "size") { viewModel.Images = viewModel.Images.OrderByDescending(item => item.SizeInBytes).ToList(); } else if (sortBy == "date") { viewModel.Images = viewModel.Images.OrderByDescending(item => item.CreationDateUTC).ToList(); } viewModel.NextCleanup = (int)FileUtility.NextCleanupDuration; return(View(viewModel)); }
private void SetImageTags(Images image, ImagesViewModel model, BlogDbContext database) { var tagsString = model.Tags.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(t => t.ToLower()).Distinct(); image.Tags.Clear(); foreach (var tagString in tagsString) { Tag tag = database.Tags.FirstOrDefault(t => t.Name.Equals(tagString)); if (tag == null) { tag = new Tag() { Name = tagString }; database.Tags.Add(tag); } image.Tags.Add(tag); } }
private ImagesViewModel GetImageForDate(int? year, int? month, int? day) { var viewModel = new ImagesViewModel(); if (!year.HasValue)//default { year = DateTime.Now.Year; month = DateTime.Now.Month; viewModel.Images = _blogPostDao.GetImagesForMonth(new DateTime(year.Value, month.Value, 1)); viewModel.DateForImages = DateTime.Now; viewModel.DisplayDateString = string.Format("{0}/{1}", year.Value, month.Value); } else { if (!month.HasValue)//year/ { month = 1; viewModel.DateForImages = new DateTime(year.Value, month.Value, 1); viewModel.Images = _blogPostDao.GetImagesForMonth(viewModel.DateForImages); viewModel.DisplayDateString = string.Format("{0}/{1}", year.Value, month.Value); } else if (day.HasValue)//year/month/day { viewModel.DateForImages = new DateTime(year.Value, month.Value, day.Value); viewModel.Images = _blogPostDao.GetImagesForMonth(viewModel.DateForImages); viewModel.DisplayDateString = string.Format("{0}/{1}/{2}", year.Value, month.Value, day.Value); } else // year/month { viewModel.DateForImages = new DateTime(year.Value, month.Value, 1); viewModel.Images = _blogPostDao.GetImagesForMonth(viewModel.DateForImages); viewModel.DisplayDateString = string.Format("{0}/{1}", year.Value, month.Value); } } return viewModel; }