Esempio n. 1
0
        //
        // GET: /Order/
        public virtual ActionResult Form(string id)
        {
            var model = new FormViewModel(ViewData.Model as BaseViewModel);
            var product1 = new ProductViewModel
                               {
                                   Title = "Karrbros Official Shirt",
                                   Price = 19.99,
                                   MaxOrderQuantity = 10,
                                   DescriptionLine1 = "50/50  Cotton Jerzee",
                                   DescriptionLine2 = "White Shirt - Blue/Orange Ink",
                                   AvailableSizes = new List<string> {"Small", "Medium", "Large", "X-Large"}
                               };
            var images = new List<ImageViewModel>();
            var image = new ImageViewModel
                            {
                                AltText = "Karrbros Official Shirt",
                                Path =string.Format("{0}/{1}/officialshirt.png", model.URLs.CDNOrders, id),
                                Title = "Karrbros Official Shirt"
                            };
            images.Add(image);
            product1.Images = images;
            model.Order.Products.Add(product1);
            model.Order.Title = "Karrbros Official";
            var crumb = new BreadCrumbViewModel { Display = "Order Search", Title = "order search", Url = "/Order/Search" };
            var crumb2 = new BreadCrumbViewModel { Display = model.Order.Title, Title = model.Order.Title, Url = "/Order/Form/" + model.Order.Id };
            model.BreadCrumbs.Add(crumb);
            model.BreadCrumbs.Add(crumb2);

               return View("Form", model);
        }
Esempio n. 2
0
 internal static void OpenExecuted(ImageViewModel source, ExecutedRoutedEventArgs e)
 {
     var dialog = new Microsoft.Win32.OpenFileDialog() { AddExtension = true };
     dialog.Filter = "Portable anymap format |*.pbm;*.pgm;*.ppm";
     bool? result = dialog.ShowDialog();
     if (result.HasValue && result.Value)
     {
         OpenExecutedInternal(source, dialog.FileName);
     }
     e.Handled = true;
 }
Esempio n. 3
0
 private Image ImageFromImageViewModel(ImageViewModel image)
 {
     return(image.Return(x => new Image()
     {
         Id = x.Id,
         Name = x.Name,
         //Data = new FileData()
         //{
         //    Id = x.Id,
         //    Data = x.Data
         //}
     }, null));
 }
        public async Task <ActionResult> Create(Employee employee, ImageViewModel imageVM)
        {
            if (ModelState.IsValid)
            {
                await _repo.CreateAsync(employee, imageVM);

                return(RedirectToAction("Details", new { id = employee.Id }));
            }
            else
            {
                return(View(employee));
            }
        }
Esempio n. 5
0
        public void ImageUpload(ImageViewModel model)
        {
            int imgId = 0;
            var file  = model.ImageFile;

            if (file != null)
            {
                //file.SaveAs(Server.MapPath("/UploadEmployeeImage" + file.FileName));
                BinaryReader reader = new BinaryReader(file.InputStream);
                ImageByte = reader.ReadBytes(file.ContentLength);
                ImageViewModel.bufferByte = ImageByte;
            }
        }
Esempio n. 6
0
 public CompanyEmployeeViewModel(CompanyEmployee employee)
 {
     Avatar        = new ImageViewModel(employee.Citizen.Entity.ImgUrl);
     ID            = employee.CitizenID;
     Name          = employee.Citizen.Entity.Name;
     Production    = (double?)employee.TodayProduction;
     Skill         = employee.GetWorkSkill();
     HP            = employee.TodayHP;
     MinHP         = employee.MinHP;
     JobContractID = employee.JobContractID;
     Salary        = (double)employee.Salary;
     TodaySalary   = (double?)employee.TodaySalary;
 }
Esempio n. 7
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var    parameter  = JsonConvert.DeserializeObject <Tuple <List <VKPhotoExtended>, int> >(e.Parameter.ToString());
            var    firstPhoto = parameter.Item1.First();
            string uniqueKey  = CoreHelper.GetImageViewModelKey(firstPhoto.ID, firstPhoto.OwnerID);

            vm = ServiceLocator.Current.GetInstance <KeyedViewModelLocator>()
                 .GetByKey(uniqueKey, () => new ImageViewModel(uniqueKey, parameter));
            vm.Activate();
            DataContext = vm;

            CoreHelper.UnlockOrientation();
        }
Esempio n. 8
0
        public async Task <ICollection <Image> > UploadImages([FromForm] ImageViewModel model)
        {
            ICollection <Image> images = new List <Image>();
            var files = model.Files;

            if (files != null && files.Any())
            {
                images = _imageRepository.Save(files, Consts.Folder.Product.Name());
                await _iProductRepository.AddImages(model.Id, images);
            }

            return(images);
        }
Esempio n. 9
0
        public ActionResult ViewImage(int id)
        {
            var imageTarget = this.Data.Images.GetById(id);

            if (imageTarget == null)
            {
                return(new HttpStatusCodeResult(400, "No record for this image in the database"));
            }

            var imgPreview = new ImageViewModel(imageTarget);

            return(this.View(imgPreview));
        }
Esempio n. 10
0
        public ImageViewModel GetImageById(int id)
        {
            Image          imageBind = _dataContext.Image.Where(i => i.ImageId == id).FirstOrDefault();
            ImageViewModel image     = new ImageViewModel()
            {
                ImageId  = imageBind.ImageId,
                Title    = imageBind.Title,
                Subtitle = imageBind.Subtitle,
                Url      = imageBind.Url
            };

            return(image);
        }
Esempio n. 11
0
 public CompositionViewModel(
     string name,
     int id,
     TemplateViewModel template,
     ImageViewModel background,
     ImageViewModel overlay)
 {
     Name       = name;
     Id         = id;
     Template   = template;
     Background = background;
     Overlay    = overlay;
 }
Esempio n. 12
0
 internal static void SaveExecuted(ImageViewModel source, ExecutedRoutedEventArgs e)
 {
     try
     {
         source.SaveImage();
     }
     catch (Exception ex)
     {
         MessageBox.Show("Can't save the file. " + ex.Message, "Error", MessageBoxButton.OK);
         return;
     }
     e.Handled = true;
 }
        public IActionResult Upload([FromForm] ImageViewModel imageViewModel)
        {
            try
            {
                var request = _uploadFileRepository.Upload(imageViewModel);

                return(Ok(request.Result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 14
0
        public ImageViewModel Get_Delete_PhotoAlbumImage(string img_path, Controller ctrl)
        {
            ImageViewModel photo = new ImageViewModel();

            if (!String.IsNullOrEmpty(img_path))
            {
                string filename = img_path.Split('/')[1];
                photo      = DataLayer.get_photoInalbum_by_path(filename);
                photo.page = ctrl.TempData["page"] == null ? 1 : Int32.Parse(ctrl.TempData["page"].ToString());
            }

            return(photo);
        }
Esempio n. 15
0
 internal static void SaveExecuted(ImageViewModel source, ExecutedRoutedEventArgs e)
 {
     try
     {
         source.SaveImage();
     }
     catch (Exception ex)
     {
         MessageBox.Show("Can't save the file. " + ex.Message, "Error", MessageBoxButton.OK);
         return;
     }
     e.Handled = true;
 }
        // GET: Images/Create
        public ActionResult Create(int albumID, string albumName)
        {
            ViewBag.albumId   = albumID;
            ViewBag.albumName = albumName;

            var albums = GetAllAlbums();

            var model = new ImageViewModel();

            model.Albums = GetSelectListItems(albums);

            return(View(model));
        }
Esempio n. 17
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            await StatusBarProvider.TryExecuteAsync(async statusBar => await statusBar.HideAsync());

            Guid key = (Guid)e.Parameter;

            ClientRepository repository = new ClientRepository();
            IClient          client     = repository.FindRemote(key);

            if (client == null)
            {
                client = repository.FindLocal();
            }

            if (client == null)
            {
                throw Ensure.Exception.ArgumentOutOfRange("parameter", "Unnable to find a client with key '{0}'.", key);
            }

            DataContext = new ImageViewModel(client);

            ViewModel.PropertyChanged   += OnViewModelPropertyChanged;
            ViewModel.DownloadCompleted += m =>
            {
                ShowError(string.Empty);
                ImageList.SelectedIndex = ViewModel.Images.Count - 1;
            };
            ViewModel.DownloadFailed += type =>
            {
                switch (type)
                {
                case DownloadImageCommand.FailType.ClientError:
                    ShowError("Downloading failed");
                    break;

                case DownloadImageCommand.FailType.Cancelled:
                    ShowError("Downloading cancelled");
                    break;

                default:
                    ShowError("Unknown error while downloading the image");
                    Debug.Fail($"Missing switch for {type}.");
                    break;
                }
            };
            ViewModel.SaveCompleted += () => ShowInfo("Saved");
            ViewModel.SaveFailed    += () => ShowError("Something went wrong saving the image");
            ViewModel.CheckStatus.Execute(null);
        }
Esempio n. 18
0
        public async Task <ActionResult> UploadFileAsync(IFormFile file)
        {
            try
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                string container   = _configuration.GetSection("ImageContainerPath").Value;
                string userId      = User.Claims.FirstOrDefault(p => p.Type == ClaimTypes.NameIdentifier)?.Value;
                string folderName  = Path.Combine(container, userId);
                string uploadPath  = Path.Combine(webRootPath, folderName);

                string fileName = $"{DateTime.UtcNow.ToVietnamDateTime().Ticks.ToString()}_{Guid.NewGuid().ToString().Replace("-", "")}{Path.GetExtension(file.FileName)}";

                if (file.Length > 0)
                {
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    using (var fileStream = new FileStream(Path.Combine(uploadPath, fileName), FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
                var requestHost = Request.Host;
                var scheme      = Request.Scheme;
                var port        = requestHost.Port.GetValueOrDefault();
                var url         = new UriBuilder();
                url.Scheme = scheme;
                url.Host   = requestHost.Host;

                if (port != 0)
                {
                    url.Port = port;
                }
                url.Path += Path.Combine(folderName, fileName);

                var imageInformation = new ImageViewModel()
                {
                    UID    = userId,
                    Name   = file.FileName,
                    URL    = url.ToString(),
                    Status = "done"
                };

                return(Ok(BaseResponse <ImageViewModel> .PrepareDataSuccess(imageInformation)));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex));
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Generates image width attributes as html by given image view model for object that is image.
        /// </summary>
        /// <param name="helper">The helper.</param>
        /// <param name="model">The image view model.</param>
        /// <returns>The generated image width attribute as html content.</returns>
        public static string GetWidthAttributeForImage(this HtmlHelper helper, ImageViewModel model)
        {
            CustomSizeModel customSize      = model.CustomSize;
            IDataItem       dataItem        = model.Item.DataItem;
            string          thumbnailName   = model.ThumbnailName;
            int?            thumbnailWidth  = model.ThumbnailWidth;
            int?            thumbnailHeight = model.ThumbnailHeight;

            var html  = string.Empty;
            var image = dataItem as Image;

            if (image != null)
            {
                double height         = image.Height;
                double width          = image.Width;
                double originalHeight = height;
                double originalWidth  = width;

                double widthToHeightRatio = originalWidth / originalHeight;

                if (customSize != null && thumbnailName == null)
                {
                    if (customSize.Width.HasValue && customSize.Method.Equals(CropCropArguments, StringComparison.InvariantCultureIgnoreCase))
                    {
                        width = customSize.Width.Value;
                    }
                    else if (customSize.MaxWidth.HasValue && customSize.Method.Equals(ResizeFitToAreaArguments, StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (image.Height > customSize.MaxHeight.Value)
                        {
                            width = Math.Round(widthToHeightRatio * customSize.MaxHeight.Value);
                        }
                        else if (image.Width > customSize.MaxWidth.Value || image.IsVectorGraphics())
                        {
                            width = customSize.MaxWidth.Value;
                        }
                    }
                }
                else if (thumbnailName != null && thumbnailWidth.HasValue)
                {
                    width = thumbnailWidth.Value;
                }

                if (width > 0)
                {
                    html = string.Format(@"width={0}", width);
                }
            }

            return(html);
        }
        public async Task <IActionResult> AddImageForMedicine(int medicineId)
        {
            if (Request.HasFormContentType)
            {
                var form = Request.Form;
                foreach (var formFile in form.Files)
                {
                    var medicine = await _repo.GetMedicineAsync(medicineId);

                    var model = new ImageViewModel();

                    var file         = formFile;
                    var uploadResult = new ImageUploadResult();

                    if (file.Length > 0)
                    {
                        using (var stream = file.OpenReadStream())
                        {
                            var uploadParams = new ImageUploadParams()
                            {
                                File           = new FileDescription(file.Name, stream),
                                Transformation = new Transformation().Width(500).Height(500).Crop("fill")
                            };

                            uploadResult = _cloudinary.Upload(uploadParams);
                        }
                    }

                    model.Url      = uploadResult.Uri.ToString();
                    model.PublicId = uploadResult.PublicId;

                    var image = _mapper.Map <Image>(model);
                    image.MedicineId = medicineId;

                    if (!medicine.Images.Any(x => x.IsMain))
                    {
                        image.IsMain = true;
                    }

                    medicine.Images.Add(image);

                    if (await _repo.SaveAllAsync())
                    {
                        var imageToReturn = _mapper.Map <ImageViewModel>(image);
                        return(CreatedAtRoute("GetImage", new { id = image.Id }, imageToReturn));
                    }
                }
            }

            return(BadRequest("Could not add image"));
        }
Esempio n. 21
0
        public List <ImageViewModel> GetViewImages()
        {
            List <ImageViewModel> images = new List <ImageViewModel>();

            foreach (var image in _album.Images)
            {
                ImageViewModel img = new ImageViewModel();
                img.Uri = image.Uri;

                images.Add(img);
            }

            return(images);
        }
Esempio n. 22
0
        public void TestCurrentAndComments()
        {
            var s         = new TestImageService();
            var viewModel = new MainViewModel(s);

            var current = new ImageViewModel(new Image {
                Id = "101"
            });

            viewModel.ChangeCurrent.Execute(current);

            Assert.AreEqual(current, viewModel.Current);
            Assert.AreEqual("101", viewModel.Current.Comments[0].Model.Id);
        }
Esempio n. 23
0
        public ActionResult DeleteImages()
        {
            DirectoryInfo                uploadedImagesDirectory = new DirectoryInfo(Server.MapPath("~/UploadedImages/"));
            ICollection <Image>          allImages = db.ImagesTable.ToList();
            ICollection <ImageViewModel> allImageViewModels;

            allImageViewModels = ImageViewModel.mapImagesToImageViewModels(allImages, uploadedImagesDirectory);
            if (TempData["Deleted"] != null)
            {
                ViewBag.DeletedImages = TempData["Deleted"].ToString();
            }

            return(View(allImageViewModels));
        }
Esempio n. 24
0
        public ActionResult RequestImage(ImageViewModel model)
        {
            try
            {
                _bus.GetEndpoint(_settings.ImageTrackingServiceAddress)
                    .Send(new RequestImageCommand(new Uri(model.SourceAddress)));

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
Esempio n. 25
0
        private ImageViewModel GetImageViewModel(List <Image> relatedImages)
        {
            var image = new ImageViewModel();

            if (relatedImages.Any())
            {
                var relatedImage = relatedImages.First();
                image.Id       = relatedImage.Id;
                image.ImageUrl = relatedImage.MediaUrl;
                image.AltText  = relatedImage.AlternativeText;
            }

            return(image);
        }
Esempio n. 26
0
        public ActionResult RequestImage(ImageViewModel model)
        {
            try
            {
                _bus.GetEndpoint(_settings.ImageTrackingServiceAddress)
                .Send(new RequestImageCommand(new Uri(model.SourceAddress)));

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 27
0
        //GET: Images/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ImageViewModel image = _imageService.GetById((int)id);

            if (image == null)
            {
                return(HttpNotFound());
            }
            return(View(image));
        }
Esempio n. 28
0
        public void LoadImage_IncorrectPath_ArgumentException()
        {
            // arrange
            var path = @"incorrectPath";
            var ivm  = new ImageViewModel(mboxMock);

            ivm.ImagePath = path;

            // act
            ivm.LoadImageCommand.Execute(null);

            // assert
            //exception
        }
Esempio n. 29
0
        public async void ChangeAvatar_IfUploadImage_ReturnNotNull()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <BlogDbContext>()
                          .UseInMemoryDatabase(databaseName: "SomeDatabase")
                          .Options;
            var context         = new BlogDbContext(options);
            var mockUserManager = new Mock <FakeUserManager>();

            var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, "1"),
            }));

            var userApp = new ApplicationUser()
            {
                Id = "1", UserName = "******", Email = "*****@*****.**"
            };

            mockUserManager
            .Setup(_ => _.GetUserAsync(user))
            .ReturnsAsync(userApp);
            var unit = new UnitOfWork(context);

            var fileMock = new Mock <IFormFile>();
            var content  = "Hello World from a Fake File";
            var fileName = "test.pdf";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);

            var controller = new AccountController(mockUserManager.Object, unit);
            var file       = fileMock.Object;
            var image      = new ImageViewModel()
            {
                AvatarImage = file
            };

            //Act
            var result = await controller.ChangeAvatar(image);

            //Assert
            Assert.IsType <IActionResult>(result);
        }
Esempio n. 30
0
 public static void GenerateThumbnail(ImageViewModel target, DataOperationUnit dataOpUnit = null)
 {
     try
     {
         while (!InternalGenerateThumbnail(target, dataOpUnit))
         {
             Thread.Sleep(500);
         }
     }
     catch (FileNotFoundException)
     {
         s_logger.Warn($"Abort thumbnail generating. File not found:{target.AbsoluteMasterPath}");
     }
 }
Esempio n. 31
0
        public static List <Task> GenerateRemakeThumbnailTasks(IEnumerable <PageViewModel> pages)
        {
            List <Task> tasks = new List <Task>();

            foreach (var page in pages)
            {
                ImageViewModel image = page.Image;
                tasks.Add(new Task(() => Delete.ThumbnailDeleting.DeleteThumbnail(image)));
                tasks.Add(new Task(() => ThumbnailGenerating.GenerateThumbnail(image)));
                tasks.Add(new Task(() => s_logger.Info($"Remade Thumbnail imageId:{image.ID}")));
            }

            return(tasks);
        }
Esempio n. 32
0
        public ActionResult Edit(ImageViewModel imageViewModel)
        {
            try {
                if (ModelState.IsValid)
                {
                    ContentImage img = new ContentImage(imageViewModel.ModuleID);
                    img.SaveChanges(imageViewModel);
                }

                return(RedirectToAction("edit", "pages", new { id = imageViewModel.PageID }));
            } catch {
                return(View(imageViewModel));
            }
        }
Esempio n. 33
0
        private void CopyFile(ImageViewModel image, Guid bookId)
        {
            var    sourceFilename        = Path.Combine(_importLibraryDirectory, image.RelativeMasterPath);
            string newRelativeMasterPath = GenerateNewRelativeMasterPath(image, bookId);
            var    destFilename          = Path.Combine(Configuration.ApplicationConfiguration.WorkingDirectory, newRelativeMasterPath);
            var    destDirectory         = Path.GetDirectoryName(destFilename);

            if (!Directory.Exists(destDirectory))
            {
                Directory.CreateDirectory(destDirectory);
            }

            File.Copy(sourceFilename, destFilename);
        }
Esempio n. 34
0
        public ActionResult ImageEditor(ImageViewModel model)
        {
            if (GetCommand <SaveImageDataCommand>().ExecuteCommand(model))
            {
                var result = GetCommand <GetImageCommand>().ExecuteCommand(model.Id.ToGuidOrDefault());
                return(Json(new WireJson {
                    Success = result != null, Data = result
                }));
            }

            return(Json(new WireJson {
                Success = false
            }));
        }
Esempio n. 35
0
 internal static void OpenExecutedInternal(ImageViewModel source, string path)
 {
     try
     {
         source.ReplaceImage(path);
     }
     catch (MalformedFileException)
     {
         MessageBox.Show("Provided file is not a valid image.", "Invalid file", MessageBoxButton.OK);
     }
     catch (SystemException ex)
     {
         MessageBox.Show("Can't open the file. " + ex.Message, "File Error", MessageBoxButton.OK);
     }
 }
Esempio n. 36
0
        private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            var fb = new Facebook.FacebookClient(App.AccessToken);
            var result = await fb.GetTaskAsync("fql",
                new
                {
                    //q = "SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)"
                    //q = "SELECT aid FROM album WHERE (owner=1383951117)"
                    q = "SELECT src_big,src_small,target_id FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject='') OR pid IN (SELECT pid FROM photo WHERE aid IN (SELECT aid FROM album WHERE (owner='1383951117') AND type!='profile')) and place_id in (SELECT page_id FROM place WHERE distance(latitude, longitude, '41.878700', '-87.636620') < '50000')"
                });
            //System.Threading.Thread.Sleep(4000);
            System.Diagnostics.Debug.WriteLine("Result: " + result.ToString());
            JObject ob = JObject.Parse(result.ToString());
            JArray data = (JArray)ob["data"];
            int i;
            List<Uri> small=new List<Uri>();       
            List<Uri> big = new List<Uri>();
            for(i=0;i<data.Count;i++)
            {
                JObject a=(JObject)data[i];
                JValue b = (JValue)a["src_big"];
                big.Add(new Uri(b.Value.ToString()));
                b = (JValue)a["src_small"];
                small.Add(new Uri(b.Value.ToString()));
            }

            my_popup_cs.IsOpen = false;

            var GroupedURLs = new List<ImageViewModel>();
            for (int j = 0; j < small.Count; j++)
            {
                var objImageViewModel = new ImageViewModel();
                if (small.ElementAtOrDefault(j) != null)
                {
                    objImageViewModel.First = big[j];
                    objImageViewModel.big = big[j];
                }

                GroupedURLs.Add(objImageViewModel);
            }

            ic.ItemsSource = GroupedURLs;
        }
Esempio n. 37
0
        internal static void SaveAsExecuted(ImageViewModel source, ExecutedRoutedEventArgs e)
        {
            var dialog = new Microsoft.Win32.SaveFileDialog() { AddExtension = true };
            dialog.Filter = "Portable bitmap format|*.pbm|Portable graymap format|*.pgm|Portable pixmap format|*.ppm";
            bool? result = dialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                try
                {
                    source.SaveImage(dialog.FileName, (PNMFormat)(dialog.FilterIndex));
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Can't save the file\n" + ex.Message, "Error", MessageBoxButton.OK);
                    return;
                }
            }

            e.Handled = true;
        }
Esempio n. 38
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            var URLs = new List<Uri> 
            {
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative),
                new Uri("/Delhi.png",UriKind.Relative)   
            };

            my_popup_cs.IsOpen = false;

            var GroupedURLs = new List<ImageViewModel>();
            for (int i = 0; i < URLs.Count; i++)
            {
                var objImageViewModel = new ImageViewModel();
                if (URLs.ElementAtOrDefault(i) != null)
                {
                    objImageViewModel.First = URLs[i];
                    objImageViewModel.name = URLs[i].ToString();
                }

                GroupedURLs.Add(objImageViewModel);
            }

            ic.ItemsSource = GroupedURLs;


        }
Esempio n. 39
0
        public override void OnApplyTemplate() {
            //csCommon.Resources.FloatingStyles fs = new FloatingStyles();
            //var ct = fs.FindName("SimpleFloatingStyle") as ControlTemplate;

            base.OnApplyTemplate();
            if (DesignerProperties.GetIsInDesignMode(this)) return;

            AppStateSettings.Instance.FullScreenFloatingElementChanged += InstanceFullScreenFloatingElementChanged;


            if (_fe.Style != null) {
                SetBinding(StyleProperty,
                    new Binding {
                        Source = _fe,
                        Path = new PropertyPath("Style"),
                        Mode = BindingMode.TwoWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                    });
            }

            //this.Style = this.FindResource("SimpleContainer") as Style;

            _svi.BorderThickness = new Thickness(0, 0, 0, 0);

            _svi.SingleInputRotationMode = (_fe.RotateWithFinger)
                ? SingleInputRotationMode.Default
                : SingleInputRotationMode.Disabled;

            _svi.ContainerManipulationDelta += _svi_ScatterManipulationDelta;


            _fe.ScatterViewItem = _svi;

            if (!_fe.ShowShadow) {
                SurfaceShadowChrome ssc;
                ssc = _svi.Template.FindName("shadow", _svi) as SurfaceShadowChrome;
                _svi.BorderBrush = null;
                _svi.Background = null;
                if (ssc != null) ssc.Visibility = Visibility.Hidden;
            }

            var closeButton = GetTemplateChild("PART_Close") as Button;
            if (closeButton != null)
                closeButton.Click += CloseButtonClick;

            _partAssociation = GetTemplateChild("PART_Association") as Line;
            _partContent = GetTemplateChild("PART_Content") as Grid;
            _partPreview = GetTemplateChild("PART_Preview") as FrameworkElement;
            _partStream = GetTemplateChild("PART_Stream") as SurfaceButton;
            _cpView = GetTemplateChild("cpView") as FrameworkElement;
            if (_fe == null) return;
            DataContext = _fe;

            _fe.CloseRequest += FeCloseRequest;
            _fe.ResetRequest += _fe_ResetRequest;


            _svi.SetBinding(WidthProperty,
                new Binding {Source = _fe, Path = new PropertyPath("Width"), Mode = BindingMode.Default});
            _svi.SetBinding(HeightProperty,
                new Binding {Source = _fe, Path = new PropertyPath("Height"), Mode = BindingMode.Default});

            _resize = GetTemplateChild("bResize") as Border;
            if (_resize != null) {
                SetResize(_resize);
            }

            UpdateAssociatedLine();

            var resizeBack = GetTemplateChild("bResize1") as Border;
            if (resizeBack != null) {
                SetResize(resizeBack);
            }

            _cc = GetTemplateChild("cpView") as ContentControl;

            // check for document, if not exist use ModelInstance
            if (_fe.Document != null) {
                IDocument vm = null;
                _fe.ConnectChannel = _fe.Document.Channel;
                _fe.ConnectMessage = _fe.Document.ToString();
                switch (_fe.Document.FileType) {
                    case FileTypes.image:
                        vm = new ImageViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.imageFolder:
                        vm = new ImageFolderViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.xps:
                        vm = new XpsViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.video:
                        vm = new VideoViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.web:
                        vm = new WebViewModel {Doc = _fe.Document};
                        break;
                    case FileTypes.html:
                        vm = new HtmlViewModel {Doc = _fe.Document};
                        break;
                }
                if (vm != null) {
                    var b = ViewLocator.LocateForModel(vm, null, null) as FrameworkElement;
                    if (b != null) {
                        b.Width = double.NaN;
                        b.Height = double.NaN;
                        b.HorizontalAlignment = HorizontalAlignment.Stretch;
                        b.VerticalAlignment = VerticalAlignment.Stretch;
                        ViewModelBinder.Bind(vm, b, null);
                        if (_cc != null) _cc.Content = b;
                    }
                }
            }
            else if (_fe.ModelInstance != null) {
                try {
                    var b = ViewLocator.LocateForModel(_fe.ModelInstance, null, null) as FrameworkElement;
                    if (b != null) {
                        b.HorizontalAlignment = HorizontalAlignment.Stretch;
                        b.VerticalAlignment = VerticalAlignment.Stretch;
                        ViewModelBinder.Bind(_fe.ModelInstance, b, null);
                        if (_cc != null) _cc.Content = b;
                    }
                }
                catch (Exception e) {
                    Logger.Log("Floating Container", "Error adding floating element", e.Message, Logger.Level.Error);
                }
            }

            UpdateBackInstance();

            if (_fe.DockingStyle == DockingStyles.None)
                if (_partPreview != null) _partPreview.Visibility = Visibility.Collapsed;

            _svi.PreviewTouchDown += (e, s) => {
                if (_svi.TouchesOver.Count() == 4) {
                    SwitchFullscreen();
                    s.Handled = true;
                    _svi.ReleaseAllTouchCaptures();
                }
                //return;
                // FIXME TODO: Unreachable code
//                if (!InteractiveSurface.PrimarySurfaceDevice.IsFingerRecognitionSupported)
//                    return;
//
//
//                _touchDown = DateTime.Now;
//                if (s.TouchDevice.GetIsFingerRecognized()) {
//                    _fe.OriginalOrientation = s.Device.GetOrientation(this);
//                    //double angle = s.TouchDevice.GetOrientation(Application.Current.MainWindow);
//                    //_reverse = (angle < 180);
//                }
//
//                if (!s.TouchDevice.GetIsFingerRecognized() &&
//                    !s.TouchDevice.GetIsTagRecognized()) {
//                    if (!string.IsNullOrEmpty(_fe.ConnectChannel) &&
//                        DateTime.Now > _lastBlobEvent.AddSeconds(1)) {
//                        AppStateSettings.Instance.Imb.SendMessage(_fe.ConnectChannel,
//                            _fe.ConnectMessage);
//                        s.Handled = true;
//                        _lastBlobEvent = DateTime.Now;
//                    }
//                }


                //Console.WriteLine(d.ToString());
            };
            //_svi.PreviewTouchUp += (e, s) =>
            //            {
            //              if (!_fe.Large && _touchDown.AddMilliseconds(300) > DateTime.Now && _fe.LastContainerPosition!=null)
            //              {
            //                ResetLastPosition();
            //              }
            //            };

            _svi.PreviewMouseDown += (e, s) => { _touchDown = DateTime.Now; };
            _svi.PreviewMouseUp += (e, s) => {
                if (!_fe.Large && _touchDown.AddMilliseconds(300) > DateTime.Now &&
                    _fe.LastContainerPosition != null) {
                    ResetLastPosition();
                }
            };

            if (_fe.IsFullScreen) {
                FrameworkElement fe = Application.Current.MainWindow;
                _svi.Center = new Point(fe.Width/2, fe.Height/2);
                _svi.Width = fe.Width;
                _svi.Height = fe.Height;
                _svi.Opacity = _fe.OpacityNormal;
            }

            if (_partStream != null) {
                _partStream.Click += _partStream_Click;
            }

            //b.HorizontalAlignment = HorizontalAlignment.Stretch;
            //b.VerticalAlignment = VerticalAlignment.Stretch;
        }
Esempio n. 40
0
 protected void OnImageStateChanged(ImageViewModel image, StateChangedEventArgs e)
 {
     switch ( e.NewState )
     {
         case ImageState.Original:
             CalculateAverages();
             PositionCurrentItem();
             break;
         case ImageState.ReadyForCorrection:
             if ( image.AutoCorrect.CanExecute( null ) )
             {
                 image.AutoCorrect.Execute( null );
             }
             break;
         case ImageState.Corrected:
             CalculateAverages();
             PositionCurrentItem();
             if ( Images.CurrentPosition < _images.Count - 1 )
             {
                 Images.MoveCurrentToNext();
             }
             break;
     }
 }
Esempio n. 41
0
 protected void AddImage(ImageViewModel image)
 {
     image.StateChanged += image_StateChanged;
     _images.Add( image );
     if ( _images.Count == 1 )
     {
         Images.MoveCurrentToFirst();
     }
 }
        private void RefreshImage(ImageViewModel Image)
        {
            if (Image == null)
                return;

            var BitmapSource = this.Invoke<BitmapSource>(new Func<BitmapDecoder, BitmapSource>(CreateBitmapSource), Image.BitmapDecoder);
            Image.Source = BitmapSource;
            switch (this.ZoomType)
            {
                case ZoomType.BestFit:
                case ZoomType.FitWidth:
                case ZoomType.FitHeight:
                    this._ZoomPercent = Image.Zoom;
                    break;
            }
        }
Esempio n. 43
0
        public ActionResult UploadImage(ImageViewModel model)
        {
            var validImageTypes = new string[]{"image/gif","image/jpeg","image/pjpeg","image/png"};
            if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
            {
                ModelState.AddModelError("ImageUpload", "This field is required");
            }
            else if (!validImageTypes.Contains(model.ImageUpload.ContentType))
            {
                ModelState.AddModelError("ImageUpload", "Please choose a valid image file.");
            }
            if (ModelState.IsValid)
            {
                if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
                {
                    var baseDir = "~/Content/Images/" + model.category;
                    var imagePath = Path.Combine(Server.MapPath(baseDir), model.ImageUpload.FileName);
                    model.ImageUpload.SaveAs(imagePath);
                }
                
                return RedirectToAction("Index");
            }


            return View(model);
        }
        private void UpdateImageForRelease(ReleaseData releaseData, ImageViewModel selectedItem)
        {
            string extension = Path.GetExtension(selectedItem.DiscogsImage.Uri);
            string mimeType = MimeHelper.GetMimeTypeForExtension(extension);
            DatabaseImage image = new DatabaseImage()
            {
                Description = "Auto import from Discogs",
                Extension = extension,
                IsMain = true,
                MimeType = mimeType,
                Type = ImageType.FrontCover
            };

            releaseData.Release.Images.Add(image);
            releaseData.Release.DateModified = DateTime.Now;
            this.CollectionManager.ImageHandler.StoreImage(image, selectedItem.Data);
            ThumbnailGenerator.UpdateReleaseThumbnail(releaseData.Release, this.CollectionManager.ImageHandler);
            this.CollectionManager.Save(releaseData.Release);

            this.CollectionManager.Operations.WriteTags(releaseData.Release);
        }
        public ActionResult ViewImage(int id)
        {
            var imageTarget = this.Data.Images.GetById(id);
            if (imageTarget == null)
            {
                return new HttpStatusCodeResult(400, "No record for this image in the database");
            }

            var imgPreview = new ImageViewModel(imageTarget);

            return this.View(imgPreview);
        }
        private bool ChooseReleasePicture(ReleaseData releaseData, int releaseNumber)
        {
            List<ImageViewModel> images = new List<ImageViewModel>();
            foreach (ImageItem imageItem in releaseData.Images)
            {
                ImageViewModel imageViewModel = new ImageViewModel(imageItem);
                images.Add(imageViewModel);
            }

            string title = "Choose image for release " + releaseNumber + "/" + this.totalReleases + " - " + releaseData.Release.JoinedAlbumArtists + " - " + releaseData.Release.Title;

            bool pickResult = false;

            this.waitWindow.Dispatcher.Invoke(() =>
            {
                ImagePicker picker = new ImagePicker(title, images);
                if (picker.ShowDialog() == true)
                {
                    ImageViewModel selectedItem = (ImageViewModel)picker.SelectedItem;
                    this.UpdateImageForRelease(releaseData, selectedItem);
                    pickResult = true;
                }
                else if (picker.IsSkipped)
                {
                    pickResult = true;
                }
                else
                {
                    pickResult = false;
                }
            });

            return pickResult;
        }
Esempio n. 47
0
 protected void RemoveImage(ImageViewModel image)
 {
     image.StateChanged -= image_StateChanged;
 }