public async Task Throw_When_ContestNameIsInvalidApi()
        {
            var options     = Utils.GetOptions(nameof(Throw_When_ContestNameIsInvalidApi));
            var userStore   = new Mock <IUserStore <User> >();
            var userManager = new Mock <UserManager <User> >(userStore.Object, null, null, null,
                                                             null, null, null, null, null);
            var contextAccessor      = new Mock <IHttpContextAccessor>();
            var userPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <User> >().Object;
            var signManager          = new Mock <SignInManager <User> >(userManager.Object, contextAccessor.Object, userPrincipalFactory, null, null, null, null).Object;
            var contestService       = new Mock <IContestService>();
            var userService          = new Mock <IUserService>();
            var userContestService   = new Mock <IUserContestService>();

            var newPhotoDTO = new Mock <NewPhotoDTO>().Object;

            newPhotoDTO.Title       = "New photo";
            newPhotoDTO.Description = "New photo descriptions";
            newPhotoDTO.PhotoUrl    = "www.newphoto.com";
            newPhotoDTO.Description = null;

            using (var actContext = new PhotoContestContext(options))
            {
                var sut = new PhotoService(actContext, contextAccessor.Object, contestService.Object, userService.Object, userManager.Object, signManager, userContestService.Object);
                await Assert.ThrowsExceptionAsync <ArgumentException>(() => sut.CreateApiAsync(newPhotoDTO));
            }
        }
示例#2
0
        public ActionResult PickCoverPhoto(FormCollection collection)
        {
            string id = collection["photoId"];

            if (id.IsNullOrWhiteSpace())
            {
                return(View("Error"));
            }
            int photoId = Int32.Parse(id);

            // Switching cover photos
            var userService  = new UserService(DbContext);
            var photoService = new PhotoService(DbContext);

            var oldPhotoId = userService.GetCoverPhoto(User.Identity.GetUserId());
            var oldPhoto   = photoService.GetPhotoById(oldPhotoId);

            if (oldPhoto != null)
            {
                oldPhoto.IsCurrentCoverPhoto = false;
            }
            photoService.GetPhotoById(photoId).IsCurrentCoverPhoto = true;
            DbContext.SaveChanges();

            return(RedirectToAction("Profile", "Home", new { id = User.Identity.GetUserId() }));
        }
示例#3
0
        private void BindPoster()
        {
            var posterId = string.IsNullOrEmpty(Request.QueryString["id"]) ? EmptyGuid : new Guid(Request.QueryString["id"]);

            if (posterId == EmptyGuid)
            {
                ShowError("There was an error with your request please go back and try again.");
                phMain.Visible = false;
                return;
            }

            hdnId.Value = posterId.ToString();

            var poster = posterService.GetPoster(posterId);

            var photoService = new PhotoService(Ioc.GetInstance <IPhotoRepository>());

            var photo = photoService.GetPhoto(poster.PhotoId);

            imgDisplayFull.ImageUrl = LinkBuilder.GetImageLinkByFileName(photo.FileName);

            ddlShow.SelectedValue = photo.ShowId.ToString();

            txtCreator.Text     = poster.Creator;
            txtLength.Text      = poster.Length.ToString();
            txtNotes.Text       = poster.Notes;
            txtNumber.Text      = poster.Number.ToString();
            txtReleaseDate.Text = poster.ReleaseDate != null?poster.ReleaseDate.Value.ToString("MM/dd/yyyy") : string.Empty;

            txtTechnique.Text       = poster.Technique;
            txtTitle.Text           = poster.Title;
            txtTotal.Text           = poster.Total.ToString();
            txtWidth.Text           = poster.Width.ToString();
            ddlStatus.SelectedValue = poster.Status.ToString();
        }
        private static List <Photo> GetVideos(IApiProvider apiProvider, PhotoListParameters photoListParameters)
        {
            var photoService = new PhotoService(apiProvider);
            var p            = photoListParameters;

            if (photoListParameters == null)
            {
                p = new PhotoListParameters();
            }

            p.IncludeUnpublished = false;
            p.PageOffset         = 1;
            p.Size  = 20;
            p.Video = true;

            var allPhotos = new List <Photo>();
            var completed = false;

            while (!completed)
            {
                var photos = photoService.GetList(p);
                allPhotos.AddRange(photos);
                completed = photos.Count < p.Size;
                p.PageOffset++;
            }
            return(allPhotos);
        }
        private void SetUpData()
        {
            this.targetService = new PhotoService();
            this.person = new Person();
            CrewmemberCollection crewMembers = new CrewmemberCollection();
            var personDetail = new PersonalDetail { CitizenshipCountryId = string.Empty, FirstName = string.Empty, LastName = string.Empty, MiddleName = string.Empty, Title = string.Empty, PreferredName = string.Empty, MaritalStatus = string.Empty, Nickname = string.Empty, Occupation = string.Empty, DocumentNumber = string.Empty, Suffix = string.Empty };
            crewMembers.Add(new Crewmember { CrewmemberId = string.Empty, CrewmemberTypeId = "1", SecurityPhotoAddress = string.Empty, ChargeId = string.Empty, EmployeeNo = string.Empty, LastEvent = string.Empty, PersonalDetail = personDetail });
            this.person.AssignCrewmembers(crewMembers);

            GuestCollection guests = new GuestCollection();

            var checkInDetail = new CheckInDetail
            {
                ApplicationId = string.Empty,
                LocationId = "1",
                LocationTypeId = "1",
                MachineName = "Machine",
                Station = "station",
                UserId = "user"
            };
            var cruiseDetail = new GuestCruiseDetail
            {
                BeaconId = string.Empty,
                CheckInDetail = checkInDetail,
                LoyaltyLevelTypeId = "1",
                ReservationId = "1",
                Stateroom = stateroom,
                ReservationStatusId = "0000089",
                StateroomCategoryTypeId = "3"
            };

            var guest = new Guest
            {
                GuestId = PersonId,
                PersonalDetail = personDetail,
                Age = 0,
                CruiseDetail = cruiseDetail,
                SecurityPhotoAddress = string.Empty,
            };

            guests.Add(guest);

            this.person.AssignGuests(guests);

            PortDebarkAuthorization pda = new PortDebarkAuthorization { PortId = "1", PersonId = "00001", CanDebarkAlone = true, IsActivePort = true, PortOrder = 1 };

            DebarkAuthorizedPersonCollection dapCollection = new DebarkAuthorizedPersonCollection();

            dapCollection.Add(new DebarkAuthorizedPerson { PersonTypeId = "2", Person = this.FilledPerson(), PersonId = PersonId, PersonType = PersonType.Guest });
            pda.AssignDebarkAuthorizedPersons(dapCollection);

            PortDebarkAuthorizationCollection portDebarkAuthorizations = new PortDebarkAuthorizationCollection();
            portDebarkAuthorizations.Add(pda);
            guest.AssignPortAuthorizations(portDebarkAuthorizations);
            guests.Add(guest);

            this.listOfPDA.Add(pda);

            person.AssignGuests(guests);
        }
示例#6
0
        public ActionResult Index(long photoID)
        {
            PhotoViewModel model = new PhotoViewModel();

            model.Photo = PhotoRepository.Single(p => p.ID == photoID, p => p.Site, p => p.Tags);

            if (model.Photo == null)
            {
                return(new HttpNotFoundResult(string.Format("Photo {0} was not found", photoID)));
            }

            model.Photo.AvailableTags = PhotoService.GetUnusedTagNames(photoID);

            model.PhotoDate  = model.Photo.Captured.ToString("MMM dd, yyyy");
            model.PhotoTime  = model.Photo.Captured.ToString("h:mm:ss tt");
            model.SiteCoords = string.Format("{0}, {1}", model.Photo.Site.Latitude, model.Photo.Site.Longitude);

            model.DroughtMonitorData         = LoadDMData(DMDataType.COUNTY, model.Photo.Captured, model.Photo.Site.CountyFips);
            model.DroughtMonitorData.PhotoID = photoID;

            model.WaterData         = LoadWaterData(model.Photo.Site.Latitude, model.Photo.Site.Longitude, model.Photo.Captured);
            model.WaterData.PhotoID = photoID;

            model.UserCollections = LoadUserCollections(photoID);

            return(View(model));
        }
        public async Task GetPhotoTest()
        {
            var Photos = new List <Photo>
            {
                new Photo()
                {
                    Id = 1, PostId = 1, PhotoUrl = "https://2krota.ru/wp-content/uploads/2019/02/0_i-1.jpg"
                },
                new Photo()
                {
                    Id = 2, PostId = 2, PhotoUrl = "https://avatanplus.com/files/photos/mid/5898cefd5798715a14e88daf.jpg"
                },
            };

            var fakeRepositoryMock = new Mock <IPhotoRepository>();

            fakeRepositoryMock.Setup(x => x.GetAll()).ReturnsAsync(Photos);


            var PhotoService = new PhotoService(fakeRepositoryMock.Object);

            var resultPhotos = await PhotoService.GetPhotos();

            Assert.Collection(resultPhotos, Photo => { Assert.Equal(1, Photo.PostId); },
                              Photo => { Assert.Equal("https://avatanplus.com/files/photos/mid/5898cefd5798715a14e88daf.jpg", Photo.PhotoUrl); });
        }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!SaveData())
        {
            return;
        }

        if (ResizePhotoStatistic.IsRun == false)
        {
            ResizePhotoStatistic.Init();
            ResizePhotoStatistic.IsRun = true;
            linkCancel.Visible         = true;
            OutDiv.Visible             = true;
            btnSave.Visible            = false;
            try
            {
                //todo rewrite
                ResizePhotoStatistic.Count = PhotoService.GetCountPhotos(0, PhotoType.Product);

                var tr = new Thread(Resize);
                ResizePhotoStatistic.ThreadImport = tr;
                tr.Start();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
                lError.Text    = ex.Message;
                lError.Visible = true;
            }
        }
    }
        public void ReturnAllPhotosFromDbSetWrapperFilteredByUserId_WhenUserIdIsProvided()
        {
            // Arrange
            string userId = "test id";

            var dbSetWrapperMock = new Mock <IEfDbSetWrapper <Photo> >();
            IQueryable <Photo> expectedPhotos = new List <Photo>()
            {
                new Photo()
                {
                    UserId = userId
                },
                new Photo()
            }.Where(x => x.UserId == userId)
            .AsQueryable();

            dbSetWrapperMock.Setup(x => x.All).Returns(expectedPhotos);

            PhotoService service = new PhotoService(dbSetWrapperMock.Object);

            // Act
            IQueryable <Photo> actualPhotos = service.GetAllByUserId(userId);

            // Assert
            CollectionAssert.AreEqual(expectedPhotos, actualPhotos);
        }
示例#10
0
        private List <Domain.Photo> GetPhotos(IApiProvider apiProvider)
        {
            List <Domain.Photo> result       = new List <Domain.Photo>();
            IPhotoService       photoService = new PhotoService(apiProvider);

            bool done = false;
            int  page = 1;

            while (!done)
            {
                List <Domain.Photo> photos = photoService.GetList(new PhotoListParameters
                {
                    IncludeUnpublished = false,
                    Size       = 100,
                    PageOffset = page++
                });

                if (photos.Count > 0)
                {
                    result.AddRange(photos);
                }
                if (photos.Count < 100)
                {
                    done = true;
                }
            }

            return(result);
        }
示例#11
0
        public void AddPhoto_PassValidData_CallsAddAndSaves()
        {
            var photoBll   = new UserPhotoBLL();
            var unitOfWork = new Mock <IPhotoUnitOfWork>();

            var userProfile = new UserProfile
            {
                Photos = new List <UserPhoto> {
                    new UserPhoto()
                }
            };

            unitOfWork.Setup(u => u.UserRepository.Get(It.IsAny <string>()))
            .Returns(userProfile);
            unitOfWork.Setup(u => u.UserRepository.Find(It.IsAny <Expression <Func <UserProfile, bool> > >()))
            .Returns(new List <UserProfile> {
                new UserProfile()
            });
            unitOfWork.Setup(u => u.Photos.Add(It.IsAny <UserPhoto>()))
            .Callback <UserPhoto>(t => userProfile.Photos.Add(t));


            // Act

            var photoService = new PhotoService(unitOfWork.Object);

            photoService.AddPhoto(photoBll);

            // Assert

            unitOfWork.Verify(u => u.Photos.Add(It.IsAny <UserPhoto>()), Times.Once());
            unitOfWork.Verify(u => u.SaveAsync(), Times.Once());
            Assert.IsTrue(userProfile.Photos.Count == 2);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _galleryModule = Module as GalleryModule;
            if (_galleryModule == null)
            {
                _galleryModule = _moduleLoader.GetModuleFromClassName("CMS.Modules.Gallery.GalleryModule") as GalleryModule;
            }
            _albumService = _galleryModule.GetAlbumService();
            _photoService = _galleryModule.GetPhotoService();

            if (Module != null)
            {
                btnCancel.Attributes.Add("onclick",
                                         String.Format("document.location.href='AdminGallery.aspx{0}'",
                                                       GetBaseQueryString()));
                btnMassImport.Click += btnMassImport_Click;

                if (Request.QueryString["AlbumId"] == null)
                {
                    return;
                }

                int albumId = Int32.Parse(Request.QueryString["AlbumId"]);

                if (albumId == 0 || albumId == -1)
                {
                    return;
                }

                _album = _albumService.GetAlbumById(albumId);

                if (!IsPostBack)
                {
                    BindAlbum();
                }

                btnDelete.Visible = true;
                btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');");

                if (!IsPostBack)
                {
                    DisplayFastImportPanel();
                }

                if (_album.Id > 0)
                {
                    FileUploaderAJAXPhotos.Visible = true;
                }
                else
                {
                    FileUploaderAJAXPhotos.Visible = false;
                }
                Session["GalleryPath"] = _galleryModule.PathBuilder.GetAlbumVirtualDirectory(_album.Id);
            }

            if (FileUploaderAJAXPhotos.IsPosting && Session["GalleryPath"] != null)
            {
                FileHelper.ManageAjaxPost(FileUploaderAJAXPhotos, 2000, Session["GalleryPath"] + "\\ToImport", HttpPostedFileAJAX.fileType.image, false, false);
            }
        }
        public List <PhotoService> GetUnpopular()
        {
            serviceList = new List <PhotoService>();
            using (var connection = new SqlConnection(mainconn))
            {
                connection.Open();
                string sql = "SELECT" +
                             " Seveces.SName," +
                             " SUM((Seveces.Price * Order_Services.NumbCopies)) as price" +
                             " FROM Order_Services INNER JOIN Orders on Order_Services.orderID = Orders.OrderId" +
                             " INNER JOIN Seveces on Seveces.serviceId = Order_Services.serviceID" +
                             " GROUP BY Seveces.SName order by price; ";

                using (var commant = new SqlCommand(sql, connection))
                {
                    using (var reader = commant.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var serv = new PhotoService();
                            serv.Name  = reader["SName"].ToString();
                            serv.Price = Convert.ToDecimal(reader["price"]);
                            serviceList.Add(serv);
                        }
                    }
                    connection.Close();
                }
            }
            return(serviceList);
        }
示例#14
0
        public ActionResult Delete(int?id)
        {
            var photoService     = new PhotoService(myDbContext);
            var eventService     = new EventService(myDbContext);
            var eventListService = new EventListService(myDbContext);
            var userService      = new UserService(myDbContext);

            if (id.HasValue)
            {
                var realID = id.Value;
                var e      = eventService.GetEvent(realID);

                EventViewModel eventViewModel = new EventViewModel();

                eventViewModel.Id          = e.Id;
                eventViewModel.name        = e.Name;
                eventViewModel.Creator     = userService.GetUser(User.Identity.GetUserId());
                eventViewModel.description = e.Description;
                eventViewModel.SignupStart = e.SignupStart;
                eventViewModel.SignupEnd   = e.SignupEnd;
                eventViewModel.StartTime   = e.StartTime;
                eventViewModel.EndTime     = e.EndTime;
                eventViewModel.MaxCapacity = e.MaxCapacity;
                eventViewModel.photoPath   = e.Photo.Path;

                return(View(eventViewModel));
            }
            else
            {
                return(View("Error"));
            }
        }
示例#15
0
 public async Task DeleteTest()
 {
     var fakeRepository = Mock.Of <IPhotoRepository>();
     var PhotoService   = new PhotoService(fakeRepository);
     int PhotoId        = 1;
     await PhotoService.Delete(PhotoId);
 }
示例#16
0
        private bool LoadVehicleFromEditScreen(POJAZDY editVehicle)
        {
            editVehicle.Kolor = textBox62.TextOrDefault();

            var parse = int.TryParse(textBox61.Text, out int przebieg);

            if (!parse)
            {
                return(false);
            }
            editVehicle.Przebieg = przebieg;

            parse = float.TryParse(textBox60.Text, out float zaGodz);
            if (!parse)
            {
                return(false);
            }
            editVehicle.ZaGodz = zaGodz;

            editVehicle.Sprawny = (sbyte)(checkBox7.Checked == true ? 1 : 0);

            editVehicle.Opis = richTextBox1.TextOrDefault();

            if (_lastLoadImage != null && editVehicle.ZDJECIA.Count == 0)
            {
                editVehicle.ZDJECIA.Add(new ZDJECIA()
                {
                    Zdjecie = PhotoService.ImageToByteArray(_lastLoadImage), POJAZDY_idPojazd = editVehicle.idPojazd
                });
            }

            return(true);
        }
示例#17
0
        protected void btnResizePhoto_Click(object sender, EventArgs e)
        {
            if (CommonStatistic.IsRun)
            {
                return;
            }

            CommonStatistic.Init();
            CommonStatistic.CurrentProcess     = Request.Url.PathAndQuery;
            CommonStatistic.CurrentProcessName = Request.Url.PathAndQuery;
            CommonStatistic.IsRun          = true;
            CommonStatistic.CurrentProcess = Request.Url.PathAndQuery;
            linkCancel.Visible             = true;
            OutDiv.Visible  = true;
            btnSave.Visible = false;
            try
            {
                CommonStatistic.TotalRow = PhotoService.GetCountPhotos(0, PhotoType.Product);
                CommonStatistic.StartNew(Resize);
                //CommonStatistic.ThreadImport = new Thread(Resize) { IsBackground = true };
                //CommonStatistic.ThreadImport.Start();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
                lError.Text    = ex.Message;
                lError.Visible = true;
            }
        }
示例#18
0
        public async Task TestUploadPhotoAsyncWithSomeMetadata()
        {
            var metadata = new Dictionary <string, string>
            {
                { Constants.Height, "3024" },
                { Constants.Width, "4032" },
                { Constants.DateTaken, "2020-07-22 13:45:26" },
            };
            var mockProperties = new Mock <IBlobResult>();

            mockProperties.Setup(p => p.Metadata).Returns(metadata);
            mockProperties.Setup(p => p.ContentType).Returns("");

            _mockBlobService.Setup(b => b.UploadPhotoAsync(It.IsAny <IFormFile>(), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(mockProperties.Object);

            var file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.txt");

            var photoService = new PhotoService(_mockBlobService.Object, _mockPhotoRepository.Object, _mockConfigurationService.Object);

            var result = (await photoService.UploadOriginalsAsync(new List <FormFile> {
                file
            }, PhotoType.Activity, Helpers.UserId)).FirstOrDefault();

            var timezone     = TimeZoneInfo.Local;
            var expectedDate = TimeZoneInfo.ConvertTimeToUtc(new DateTime(2020, 7, 22, 13, 45, 26, DateTimeKind.Unspecified), timezone);

            result.Filename.Should().Be("original.txt");
            result.Location.Should().BeNull();
            result.Height.Should().Be(3024);
            result.Width.Should().Be(4032);
            result.DateTaken.Should().Be(expectedDate);
        }
示例#19
0
        protected void Resize()
        {
            foreach (var photo in PhotoService.GetNamePhotos(0, PhotoType.Product, true))
            {
                try
                {
                    var originalPath = FoldersHelper.GetImageProductPathAbsolut(ProductImageType.Original, photo);
                    if (!File.Exists(originalPath))
                    {
                        var bigPath = FoldersHelper.GetImageProductPathAbsolut(ProductImageType.Big, photo);
                        if (File.Exists(bigPath))
                        {
                            File.Copy(bigPath, originalPath);
                        }
                    }

                    if (File.Exists(originalPath))
                    {
                        using (var image = ImageFromFile(originalPath))
                        {
                            FileHelpers.SaveProductImageUseCompress(photo, image, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex);
                    CommonStatistic.TotalErrorRow++;
                }
                CommonStatistic.RowPosition++;
            }

            CommonStatistic.IsRun = false;
        }
示例#20
0
        public ActionResult SiteDashboard(long siteID)
        {
            // Make sure the siteID belongs to a CameraSite
            if (CollectionRepository.Find(c => c.Site.ID == siteID && c.Type == CollectionType.SITE).FirstOrDefault() == null)
            {
                return(RedirectToAction("SiteList", "Home", null));
            }
            else
            {
                SiteDashboardViewModel model = new SiteDashboardViewModel();

                model.CollectionViewModel = GetCollectionViewModel(siteID, -1);
                model.Years = GetSiteYearSummary(siteID);
                model.Tags  = PhotoService.GetPopularTagsForSite(siteID);

                //Photo Frequency
                model.PhotoFrequency           = GetPhotoFrequencyData(siteID);
                model.PhotoFrequency.SiteName  = model.CollectionViewModel.Collection.Site.Name;
                model.PhotoFrequency.StartDate = model.CollectionViewModel.SiteDetails.First;

                Photo    lastPhoto     = PhotoRepository.Find(p => p.Site.ID == siteID).OrderBy(p => p.Captured).Last();
                DateTime lastPhotoDate = lastPhoto.Captured;

                model.DroughtMonitorData         = LoadDMData(DMDataType.COUNTY, lastPhotoDate, model.CollectionViewModel.Collection.Site.CountyFips);
                model.DroughtMonitorData.PhotoID = lastPhoto.ID;

                model.WaterData         = LoadWaterData(model.CollectionViewModel.Collection.Site.Latitude, model.CollectionViewModel.Collection.Site.Longitude, lastPhotoDate);
                model.WaterData.PhotoID = lastPhoto.ID;

                return(View(model));
            }
        }
示例#21
0
    protected void Resize()
    {
        try
        {
            var photos = PhotoService.GetNamePhotos(0, PhotoType.Product);
            foreach (var photo in photos)
            {
                var path = FoldersHelper.GetImageProductPathAbsolut(ProductImageType.Original, photo);
                if (File.Exists(path))
                {
                    using (var image = ImageFromFile(path))
                    {
                        FileHelpers.SaveProductImageUseCompress(path, image, true);
                    }
                }

                ResizePhotoStatistic.Index++;
            }

            ResizePhotoStatistic.IsRun = false;
            ResizePhotoStatistic.ThreadImport.Abort();
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }
    }
示例#22
0
    private int CreateMenuItem()
    {
        ValidateData();

        var mItem = new AdvMenuItem
        {
            MenuItemName     = txtName.Text,
            MenuItemParentID = string.IsNullOrEmpty(hParent.Value) ? 0 : Convert.ToInt32(hParent.Value),
            MenuItemUrlPath  = txtUrl.Text,
            Enabled          = ckbEnabled.Checked,
            Blank            = ckbBlank.Checked,
            SortOrder        = Convert.ToInt32(txtSortOrder.Text),
            MenuItemUrlType  = (EMenuItemUrlType)Convert.ToInt32(rblLinkType.SelectedValue),
            ShowMode         = (EMenuItemShowMode)Convert.ToInt32(ddlShowMode.SelectedValue)
        };

        if (_type == MenuService.EMenuType.Top)
        {
            CacheManager.RemoveByPattern(CacheNames.GetMainMenuCacheObjectName());
            CacheManager.RemoveByPattern(CacheNames.GetMainMenuAuthCacheObjectName());
        }
        else if (_type == MenuService.EMenuType.Bottom)
        {
            var cacheName = CacheNames.GetBottomMenuCacheObjectName();
            if (CacheManager.Contains(cacheName))
            {
                CacheManager.Remove(cacheName);
            }

            var cacheAuthName = CacheNames.GetBottomMenuAuthCacheObjectName();
            if (CacheManager.Contains(cacheAuthName))
            {
                CacheManager.Remove(cacheAuthName);
            }
        }
        mItem.MenuItemID = MenuService.AddMenuItem(mItem, _type);
        _menuItemId      = mItem.MenuItemID;
        if (IconFileUpload.HasFile)
        {
            using (IconFileUpload.FileContent)
            {
                var tempName = PhotoService.AddPhoto(new Photo(0, _menuItemId, PhotoType.MenuIcon)
                {
                    OriginName = IconFileUpload.FileName
                });
                if (!string.IsNullOrWhiteSpace(tempName))
                {
                    IconFileUpload.SaveAs(FoldersHelper.GetPathAbsolut(FolderType.MenuIcons, tempName));
                }
            }
        }
        else
        {
            mItem.MenuItemIcon = string.Empty;
        }

        MenuService.UpdateMenuItem(mItem, _type);

        return(mItem.MenuItemID);
    }
示例#23
0
        public ActionResult photo()
        {
            PhotoService        photserv   = new PhotoService();
            IEnumerable <photo> listephoto = photserv.GetMany();

            return(View(listephoto));
        }
示例#24
0
        public void RemoveComment_ShouldRemoveCommentFromPhotoAndCallUpdatePhoto()
        {
            _photoRepo = new Mock <IPhotoRepo>();
            _userRepo  = new Mock <IUserRepo>();
            _userRepo.Setup(c => c.Users).Returns(_users);
            var comment = new Comment()
            {
                Id = 1, UserId = "1"
            };
            var photo = new Photo()
            {
                Id = 1, Comments = new List <Comment>()
                {
                    comment
                }
            };
            var options = new DbContextOptionsBuilder <AppDbContext>()
                          .UseInMemoryDatabase(databaseName: "ImageAlbumDb")
                          .Options;

            using (var context = new AppDbContext(options))
            {
                _photoService = new PhotoService(context, _photoRepo.Object, _userRepo.Object);

                _photoService.RemoveComment(photo, comment);

                Assert.AreEqual(0, photo.Comments.Count());
                _photoRepo.Verify(c => c.UpdatePhoto(photo), Times.Once());
            }
        }
示例#25
0
        public async Task Throw_When_InvalidIdOfPhoto()
        {
            var options = Utils.GetOptions(nameof(Throw_When_InvalidIdOfPhoto));

            var userStore   = new Mock <IUserStore <User> >();
            var userManager = new Mock <UserManager <User> >(userStore.Object, null, null, null,
                                                             null, null, null, null, null);
            var contextAccessor      = new Mock <IHttpContextAccessor>();
            var userPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <User> >().Object;
            var signManager          = new Mock <SignInManager <User> >(userManager.Object, contextAccessor.Object, userPrincipalFactory, null, null, null, null).Object;
            var contestService       = new Mock <IContestService>();
            var userService          = new Mock <IUserService>();
            var userContestService   = new Mock <IUserContestService>();

            using (var arrContext = new PhotoContestContext(options))
            {
                await arrContext.Contests.AddRangeAsync(Utils.SeedContests());

                await arrContext.Categories.AddRangeAsync(Utils.SeedCategories());

                await arrContext.Photos.AddRangeAsync(Utils.SeedPhotos());

                await arrContext.Statuses.AddRangeAsync(Utils.SeedStatuses());

                await arrContext.Users.AddRangeAsync(Utils.SeedUsers());

                await arrContext.SaveChangesAsync();
            };
            using (var actContext = new PhotoContestContext(options))
            {
                var sut = new PhotoService(actContext, contextAccessor.Object, contestService.Object, userService.Object, userManager.Object, signManager, userContestService.Object);
                await Assert.ThrowsExceptionAsync <ArgumentException>(() => sut.GetAsync(Guid.Parse("3c1996fe-f204-42b7-9ea9-03a7196968e8")));
            }
        }
示例#26
0
        public void AddAndModify_ReturnNull_Withwid()
        {
            var service = new PhotoService();
            var dto     = new photoActionDTO()
            {
                wid            = 36,
                beginDate      = "2015-09-01",
                endDate        = DateTime.Now.AddDays(5).ToString(),
                actContent     = "test20151",
                brief          = "jianjie",
                isAllowSharing = true
            };

            service.Add(dto);
            Assert.IsTrue(dto.id > 0);

            photoActionDTO model = service.GetModel(dto.id);

            Assert.AreEqual(dto.wid, model.wid);

            dto.brief = "test间接";
            service.Modify(dto);
            Assert.IsNotNull(dto);

            model = service.GetModel(dto.id);
            Assert.AreEqual(dto.brief, model.brief);
        }
示例#27
0
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (grid.UpdatedRow != null)
        {
            int sortOrder = 0;
            if (int.TryParse(grid.UpdatedRow["PhotoSortOrder"], out sortOrder))
            {
                var ph = new Photo(Convert.ToInt32(grid.UpdatedRow["ID"]), ProductID, PhotoType.Product)
                {
                    Description    = grid.UpdatedRow["Description"],
                    PhotoSortOrder = sortOrder
                };

                PhotoService.UpdateProductPhoto(ph);
                if (grid.UpdatedRow["Main"] == "True")
                {
                    PhotoService.SetProductMainPhoto(Convert.ToInt32(grid.UpdatedRow["ID"]));
                    MainPhotoUpdate(this, new EventArgs());
                }
            }
        }


        DataTable data = _paging.PageItems;

        while (data.Rows.Count < 1 && _paging.CurrentPageIndex > 1)
        {
            _paging.CurrentPageIndex--;
            data = _paging.PageItems;
        }

        var clmn = new DataColumn("IsSelected", typeof(bool))
        {
            DefaultValue = _inverseSelection
        };

        data.Columns.Add(clmn);
        if ((_selectionFilter != null) && (_selectionFilter.Values != null))
        {
            for (int i = 0; i <= data.Rows.Count - 1; i++)
            {
                int intIndex = i;
                if (Array.Exists(_selectionFilter.Values, c => c == data.Rows[intIndex]["ID"].ToString()))
                {
                    data.Rows[i]["IsSelected"] = !_inverseSelection;
                }
            }
        }

        if (data.Rows.Count < 1)
        {
            goToPage.Visible = false;
        }

        grid.DataSource = data;
        grid.DataBind();

        pageNumberer.PageCount = _paging.PageCount;
        lblFound.Text          = _paging.TotalRowsCount.ToString();
    }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
            User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;

            int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
            int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
            string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
            string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();

            IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);

            string[] splitIds = selectedProfilePictureIds.Split(',');
            List<int> selectedProfilePictures = new List<int>();

            foreach (string id in splitIds) {
                if (id != string.Empty) {
                    selectedProfilePictures.Add(Int32.Parse(id));
                }
            }

            return new PhotosModel() {
                UserId = myUserId,
                ProfilePictureURL = myProfilePictureURL,
                Photos = myPhotos,
                SelectedPhotos = selectedProfilePictures
            };
        }
示例#29
0
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!fuIcon.HasFile)
            {
                return;
            }
            if (!FileHelpers.CheckFileExtension(fuIcon.FileName, FileHelpers.eAdvantShopFileTypes.Image))
            {
                OnErr(new ErrorEventArgs {
                    Message = Resource.Admin_ErrorMessage_WrongImageExtension
                });
                return;
            }
            PhotoService.DeletePhotos(PaymentMethodID, PhotoType.Payment);
            var tempName = PhotoService.AddPhoto(new Photo(0, PaymentMethodID, PhotoType.Payment)
            {
                OriginName = fuIcon.FileName
            });

            if (string.IsNullOrWhiteSpace(tempName))
            {
                return;
            }
            using (System.Drawing.Image image = System.Drawing.Image.FromStream(fuIcon.FileContent))
            {
                FileHelpers.SaveResizePhotoFile(FoldersHelper.GetPathAbsolut(FolderType.PaymentLogo, tempName), SettingsPictureSize.PaymentIconWidth, SettingsPictureSize.PaymentIconHeight, image);
            }
            imgIcon.ImageUrl = FoldersHelper.GetPath(FolderType.PaymentLogo, tempName, true);
            imgIcon.Visible  = true;
        }
示例#30
0
        private void btnUpload_Click(object sender, EventArgs e)
        {
            HttpPostedFile postedFile = this.filUpload.PostedFile;

            if (postedFile.ContentLength > 0)
            {
                _photo.Title     = txtTitle.Text;
                _photo.FileName  = PhotoService.CreateServerFilename(postedFile.FileName);
                _photo.Size      = postedFile.ContentLength;
                _photo.CreatedBy = (User)this.User.Identity;
                _photo.Section   = base.Section;
                _photo.Album     = _albumService.GetAlbumById(_albumId);

                // Save the file
                try
                {
                    _photoService.SavePhoto(_photo, postedFile.InputStream);

                    if (_photoId <= 0 && this._photo.Id > 0)
                    {
                        // This appears to be a new file. Store the id of the file in the viewstate
                        // so the file can be deleted if the user decides to cancel.
                        ViewState["tempPhotoId"] = _photo.Id;
                    }
                    BindPhoto();
                }
                catch (Exception ex)
                {
                    // Something went wrong
                    ShowError("Error saving the file: " + ex.Message);
                }
            }
        }
示例#31
0
        public HttpResponseMessage Upload(long selectedCollectionID)
        {
            // Get a reference to the file that our jQuery sent.  Even with multiple files, they will all be their own request and be the 0 index
            HttpPostedFile file = HttpContext.Current.Request.Files[0];

            var temp = Path.Combine(PathManager.GetUserCollectionPath(), "Temp");

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

            User  user  = UserRepository.First(u => u.ProviderID == this.User.Identity.Name);
            Photo photo = PhotoService.ProcessUserPhoto(file.InputStream, Guid.NewGuid().ToString(), user, selectedCollectionID);

            // Now we need to wire up a response so that the calling script understands what happened
            HttpContext.Current.Response.ContentType = "text/plain";
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var result     = new { name = file.FileName, id = photo.ID };

            HttpContext.Current.Response.Write(serializer.Serialize(result));
            HttpContext.Current.Response.StatusCode = 200;

            // For compatibility with IE's "done" event we need to return a result as well as setting the context.response
            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
示例#32
0
 public static void DeleteCarousel(int id)
 {
     SQLDataAccess.ExecuteNonQuery("[CMS].[sp_DeleteCarousel]", CommandType.StoredProcedure, new SqlParameter {
         ParameterName = "@CarouselID", Value = id
     });
     PhotoService.DeletePhotos(id, PhotoType.Carousel);
 }
        public override bool ApplyChanges()
        {
            // Make sure that all is set up
            EnsureChildControls();

            // Update the web part
            VisualEmbed webPart = (VisualEmbed)WebPartToEdit;
            if (webPart != null)
            {
                // Get the token for the photo first
                if (Videos != null)
                {
                    IPhotoService photoService = new PhotoService(Utilities.ApiProvider);
                    Domain.Photo photo = photoService.Get(Convert.ToInt32(Videos.SelectedValue), false);

                    webPart.PhotoId = Videos.SelectedValue;
                    webPart.PhotoToken = photo.Token;
                }
            }

            return true;
        }
示例#34
0
        static void Main()
        {
            var locationService = new LocationService();
            var locations = locationService.GetAll();

            var location = locationService.GetById(locations[0].Id);

            var hotelService = new HotelService();
            var hotel = hotelService.GetById(location.Hotels[0].Id);

            var roomService = new RoomService();
            var room = roomService.GetById(hotel.Rooms[0].Id);

            var photoService = new PhotoService();

            // Delete any existing photos
            foreach (var p in room.Photos)
            {
                photoService.Delete(p.Id);
            }

            Console.WriteLine("Adding photo to: {0}", room.Name);

            var photo = new Photo
            {
                Title = "A view of the room", Description = "A beautiful room with wonderful views of the neighbours walls", RoomId = room.Id
            };

            const string roomPhoto = @"Pictures\roomview.jpg";
            const string roomPhoto2 = @"Pictures\roomview_2.jpg";

            photo.Data = ReadPhotoData(roomPhoto);
            photoService.Insert(photo);

            photo.Data = ReadPhotoData(roomPhoto2);
            photoService.Update(photo);
        }
示例#35
0
        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();

                // * Make the query
                PhotoListParameters listParameters = new PhotoListParameters
                {
                    AlbumId = null,
                    IncludeUnpublished = false,
                    Size = _count
                };

                if (!String.IsNullOrEmpty(_albumInfo))
                {
                    string[] albumParams = _albumInfo.Split('|');
                    listParameters.AlbumId = Convert.ToInt32(albumParams[0]);
                    listParameters.Token = albumParams[1];
                }

                switch (_order)
                {
                    case "CreatedAscending":
                    case "PublishedAscending":
                    case "UploadedAscending":
                    case "ViewsAscending":
                        listParameters.Order = GenericSort.Ascending;
                        break;

                    default:
                        listParameters.Order = GenericSort.Descending;
                        break;
                }

                switch (_order)
                {
                    case "CreatedAscending":
                    case "CreatedDescending":
                        listParameters.OrderBy = PhotoListSort.Created;
                        break;

                    case "UploadedAscending":
                    case "UploadedDescending":
                        listParameters.OrderBy = PhotoListSort.Uploaded;
                        break;

                    case "ViewsAscending":
                    case "ViewsDescending":
                        listParameters.OrderBy = PhotoListSort.Views;
                        break;

                    default:
                        listParameters.OrderBy = PhotoListSort.Published;
                        break;
                }

                if ((_tags != null) && (_tags.Count > 0))
                {
                    listParameters.TagMode = (_tagMode == "All" ? PhotoTagMode.And : PhotoTagMode.Any);
                    listParameters.Tags = _tags;
                }

                this.Controls.Add(new LiteralControl("<ul class=\"visual-list\">"));

                IApiProvider apiProvider = Utilities.ApiProvider;
                if (apiProvider != null)
                {
                    IPhotoService photoService = new PhotoService(apiProvider);
                    List<Domain.Photo> photos = photoService.GetList(listParameters);

                    string protocol = Configuration.HttpSecure ? "https://" : "http://";

                    foreach (Domain.Photo photo in photos)
                    {
                        PhotoBlock size = Utilities.GetVideoSize(photo, Size);
                        string pid = "photo" + photo.PhotoId.ToString();
                        string showVideoCall;

                        // Figure out exact code to put in
                        string token = _tokenFreeEmebds ? "" : photo.Token;
                        if (_clickToPlay)
                        {
                            showVideoCall = "showVideo('" + pid + "','" + Utilities.EmbedCode(photo.PhotoId.Value.ToString(), token, size.Width.Value, null, true).Replace("\"", "&#34;").Replace("'", "\\'") + "'); return false;";
                        }
                        else
                        {
                            showVideoCall = "showVideo('" + Utilities.EmbedCode(photo.PhotoId.Value.ToString(), token, 640, null, false).Replace("\"", "&#34;").Replace("'", "\\'") + "'); return false;";
                        }
                        this.Controls.Add(new LiteralControl("<li>"));
                        this.Controls.Add(new LiteralControl("<div class=\"visual-list-image\"><a href=\"#\" id=\"" + pid + "\" onclick=\"" + showVideoCall + "\"><img src=\"" + protocol + Configuration.Domain + size.Download + "\" /></a></div>"));
                        this.Controls.Add(new LiteralControl("<div class=\"visual-list-meta\">"));
                        this.Controls.Add(new LiteralControl(photo.Title));
                        this.Controls.Add(new LiteralControl("<p>" + photo.ContentText + "</p>"));
                        this.Controls.Add(new LiteralControl("<div class=\"visual-list-date\">" + photo.OriginalDateDate + "</div>"));
                        if (photo.ViewCount != null) this.Controls.Add(new LiteralControl("<div class=\"visual-list-views\">" + photo.ViewCount.Value.ToString() + " views</div>"));
                        this.Controls.Add(new LiteralControl("</div>"));
                        this.Controls.Add(new LiteralControl("</li>"));
                    }
                }

                this.Controls.Add(new LiteralControl("</ul>"));
                if (_clickToPlay)
                {
                    this.Controls.Add(new LiteralControl("<script src=\"/_layouts/23video/23video.js\"></script>"));
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
        private List<Domain.Photo> GetPhotos(IApiProvider apiProvider)
        {
            List<Domain.Photo> result = new List<Domain.Photo>();
            IPhotoService photoService = new PhotoService(apiProvider);

            bool done = false;
            int page = 1;
            while (!done)
            {
                List<Domain.Photo> photos = photoService.GetList(new PhotoListParameters
                {
                    IncludeUnpublished = false,
                    Size = 100,
                    PageOffset = page++
                });

                if (photos.Count > 0)
                    result.AddRange(photos);
                if (photos.Count < 100)
                    done = true;
            }

            return result;
        }
示例#37
0
 public PhotoController(PhotoService photoService, MongoDatabase database)
 {
     _photService = photoService;
     _database = database;
 }
        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();

                // * Make the query
                PhotoListParameters listParameters = new PhotoListParameters
                {
                    AlbumId = null,
                    IncludeUnpublished = false,
                    Size = _count
                };

                if (!String.IsNullOrEmpty(_albumId)) listParameters.AlbumId = Convert.ToInt32(_albumId);

                switch (_order)
                {
                    case "CreatedAscending":
                    case "PublishedAscending":
                    case "UploadedAscending":
                    case "ViewsAscending":
                        listParameters.Order = GenericSort.Ascending;
                        break;

                    default:
                        listParameters.Order = GenericSort.Descending;
                        break;
                }

                switch (_order)
                {
                    case "CreatedAscending":
                    case "CreatedDescending":
                        listParameters.OrderBy = PhotoListSort.Created;
                        break;

                    case "UploadedAscending":
                    case "UploadedDescending":
                        listParameters.OrderBy = PhotoListSort.Uploaded;
                        break;

                    case "ViewsAscending":
                    case "ViewsDescending":
                        listParameters.OrderBy = PhotoListSort.Views;
                        break;

                    default:
                        listParameters.OrderBy = PhotoListSort.Published;
                        break;
                }

                if ((_tags != null) && (_tags.Count > 0))
                {
                    listParameters.TagMode = (_tagMode == "All" ? PhotoTagMode.And : PhotoTagMode.Any);
                    listParameters.Tags = _tags;
                }

                this.Controls.Add(new LiteralControl("<table class=\"visual-grid\">"));

                IApiProvider apiProvider = Utilities.ApiProvider;
                if (apiProvider != null)
                {
                    IPhotoService photoService = new PhotoService(apiProvider);
                    List<Domain.Photo> photos = photoService.GetList(listParameters);

                    int rowNumber = 0;
                    int rowCount = (int)Math.Ceiling((decimal)photos.Count / (decimal)_rowCount);
                    int colNumber = 0;

                    foreach (Domain.Photo photo in photos)
                    {
                        string showVideoCall = "showVideo('" + Utilities.EmbedCode(photo.PhotoId.Value.ToString(), photo.Token, 640, null).Replace("\"", "&#34;").Replace("'", "\\'") + "'); return false;";

                        if (colNumber == 0) this.Controls.Add(new LiteralControl("<tr" + (rowNumber + 1 == rowCount ? " class=\"last\"" : "") + ">"));

                        this.Controls.Add(new LiteralControl("<td onclick=\"" + showVideoCall + "\"" + ((colNumber == _rowCount - 1) ? " class=\"last\"" : "") + ">"));
                        this.Controls.Add(new LiteralControl("<div class=\"visual-grid-image\"><img src=\"http://" + Configuration.Domain + photo.Small.Download + "\" /></div>"));
                        this.Controls.Add(new LiteralControl("<div class=\"visual-grid-meta\">"));
                        this.Controls.Add(new LiteralControl("<a href=\"#\" onclick=\"" + showVideoCall + "\">" + photo.Title + "</a>"));
                        this.Controls.Add(new LiteralControl("<p>" + photo.ContentText + "</p>"));
                        this.Controls.Add(new LiteralControl("<div class=\"visual-grid-date\">" + photo.OriginalDateDate + "</div>"));
                        if (photo.ViewCount != null) this.Controls.Add(new LiteralControl("<div class=\"visual-grid-views\">" + photo.ViewCount.Value.ToString() + " views</div>"));
                        this.Controls.Add(new LiteralControl("</div>"));
                        this.Controls.Add(new LiteralControl("</td>"));

                        colNumber++;
                        if (colNumber == _rowCount)
                        {
                            this.Controls.Add(new LiteralControl("</tr>"));
                            colNumber = 0;
                            rowNumber++;
                        }
                    }

                    if (colNumber > 0)
                    {
                        while (colNumber < _rowCount)
                        {
                            this.Controls.Add(new LiteralControl("<td class=\"visual-grid-empty\">&nbsp;</td>"));
                            colNumber++;
                        }

                        this.Controls.Add(new LiteralControl("</tr>"));
                    }
                }

                this.Controls.Add(new LiteralControl("</table>"));
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }