public async Task GetGallery_not_mine_and_it_exist() { // Arrange var controller = new GalleryController(GalleryService.Object); controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[0].Id.ToString()); GalleryEntity newGallery = new GalleryEntity() { Id = Guid.NewGuid(), fk_owner = UserEntities[1].Id, Name = "TestName", owner = UserEntities[1] }; GalleryEntities.Add(newGallery); // Act ActionResult <GalleryDTO> response = await controller.GetGallery(newGallery.Id); // Assert Assert.IsInstanceOfType(response.Result, typeof(UnauthorizedResult)); var result = response.Result as UnauthorizedResult; Assert.AreEqual(401, result.StatusCode); GalleryEntities.Remove(newGallery); }
/// <summary> /// Initializes this instance. Derived classes can override this member to run their own initialization code. /// </summary> protected override void Initialize() { if (!GalleryController.IsInitialized) { GalleryController.InitializeGspApplication(); } if (!IsUserAuthorized) { WriteErrorResponse("You do not have authorization to perform the requested action.", 403); return; } // Normally you'd set these values from config values FileUploadPhysicalPath = Path.Combine(AppSetting.Instance.PhysicalApplicationPath, GlobalConstants.TempUploadDirectory); MaxUploadSize = GallerySettings.MaxUploadSize * 1024; AllowedExtensions = GallerySettings.AllowUnspecifiedMimeTypes ? ".*" : String.Join(",", Factory.LoadMimeTypes(GalleryId).Where(mt => mt.AllowAddToGallery).Select(mt => mt.Extension)); if (DestinationMediaAssetId > int.MinValue && !GallerySettings.AllowUnspecifiedMimeTypes) { // Always allow PNGs when user is replacing an existing image, since that's the format the tinyMCE image editor uses. AllowedExtensions += ",.png"; } }
public async Task PutGallery_mine_and_it_exist() { // Arrange var controller = new GalleryController(GalleryService.Object); controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[0].Id.ToString()); GalleryEntity newGalleryEntity = new GalleryEntity() { Id = Guid.NewGuid(), Name = "TestGalleryName", fk_owner = UserEntities[0].Id, owner = UserEntities[0] }; GalleryEntities.Add(newGalleryEntity); // Act GalleryPutDTO galleryPutDto = new GalleryPutDTO("UpdatedTestGalleryName"); ActionResult <GalleryDTO> response = await controller.PutGallery(newGalleryEntity.Id, galleryPutDto); // Assert Assert.IsInstanceOfType(response.Result, typeof(CreatedAtActionResult)); var result = response.Result as CreatedAtActionResult; Assert.AreEqual(201, result.StatusCode); Assert.IsNotNull(result.Value); Assert.IsInstanceOfType(result.Value, typeof(GalleryDTO)); GalleryDTO retrievedItem = result.Value as GalleryDTO; Assert.AreEqual(retrievedItem.Id, newGalleryEntity.Id); Assert.AreEqual(retrievedItem.Name, "UpdatedTestGalleryName"); GalleryEntities.Remove(newGalleryEntity); }
/// <summary> /// Initializes the <see cref="Gallery"/> class. /// </summary> static Gallery() { if (!GalleryController.IsInitialized) { GalleryController.InitializeGspApplication(); } }
public void ReturnHttpUnauthorized_WhenNoUserIsFound() { // Arrange var galleryServiceMock = new Mock <IGalleryImageService>(); var userServiceMock = new Mock <IUserService>(); var mappingServiceMock = new Mock <IMappingService>(); var utilsMock = new Mock <IUtilitiesService>(); var controller = new GalleryController(galleryServiceMock.Object, mappingServiceMock.Object, userServiceMock.Object, utilsMock.Object); var controllerContext = new Mock <ControllerContext>(); var user = new Mock <IPrincipal>(); user.Setup(p => p.IsInRole("admin")).Returns(true); user.SetupGet(x => x.Identity.Name).Returns("username"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(user.Object); controller.ControllerContext = controllerContext.Object; var image = new GalleryImage(); galleryServiceMock.Setup(x => x.GetGalleryImageById(It.IsAny <Guid>())).Returns(image); // Act & Assert controller.WithCallTo(x => x.LikeImage(Guid.NewGuid())) .ShouldGiveHttpStatus(401); }
public void LoadGalleryImageList() { if (galleryController == null) { galleryController = new GalleryController(); galleryController.CreateAndOpenGalley(patientId); } this.Dispatcher.Invoke(() => { listBox.Items.Clear(); galleryController.GetGalleryFilesList(patientId).ForEach((string path) => { byte[] array = File.ReadAllBytes(path); Image image = new Image(); image.Source = galleryController.ConvertToImage(array); ListBoxItem lbi = new ListBoxItem(); lbi.Width = 80; lbi.Height = 80; lbi.Content = image; listBox.Items.Add(lbi); }); }); }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the /// <see cref="T:System.Web.IHttpHandler"/> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to /// the intrinsic server objects (for example, Request, Response, Session, and Server) used to service /// HTTP requests.</param> public void ProcessRequest(HttpContext context) { try { if (!GalleryController.IsInitialized) { GalleryController.InitializeGspApplication(); } if (!IsUserAuthorized()) { throw new GallerySecurityException(); } SaveFileToServer(context); context.Response.ContentType = "text/plain"; context.Response.Write("Success"); } catch (GallerySecurityException ex) { HandleException(context, ex); context.Response.StatusCode = 403; context.Response.End(); } catch (Exception ex) { HandleException(context, ex); throw; } }
public override Task <bool> CreateOrUpdateImageAsync(Image image) { var imageCopy = Clone(image); return(Task.Run(async() => { var controller = new GalleryController(this.CosmosDbProvider, this.AzureStorageProvider, this.Logger); var actionResult = await InvokeControllerAction(async() => await controller.Store(imageCopy)); var statusCode = ExtractHttpStatusCode(actionResult); if (statusCode == HttpStatusCode.OK) { return true; } else if (statusCode == HttpStatusCode.NotFound) { return false; } if (!(statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.NotFound)) { throw new Exception($"Found unexpected error code: {statusCode}"); } return true; })); }
/// <summary> /// Initializes the request. /// </summary> /// <param name="context">The HTTP context.</param> /// <returns> /// Returns <c>true</c> when the method succeeds; otherwise <c>false</c>. /// </returns> public override bool InitializeRequest(HttpContext context) { bool isSuccessfullyInitialized = false; try { if (!GalleryController.IsInitialized) { GalleryController.InitializeGspApplication(); } if (InitializeVariables(context)) { isSuccessfullyInitialized = true; } else { _context.Response.StatusCode = 404; } return(base.InitializeRequest(context) & isSuccessfullyInitialized); } catch (System.Threading.ThreadAbortException) { throw; // We don't want these to fall into the generic catch because we don't want them logged. } catch (Exception ex) { AppEventController.LogError(ex); } return(isSuccessfullyInitialized); }
public override Task <bool> DeleteAllImagesAsync(string accountId) { return(Task.Run(async() => { var controller = new GalleryController(this.CosmosDbProvider, this.AzureStorageProvider, this.Logger); var actionResult = await InvokeControllerAction(async() => await controller.DeleteAllImages(accountId)); var statusCode = ExtractHttpStatusCode(actionResult); if (statusCode == HttpStatusCode.OK) { return true; } else if (statusCode == HttpStatusCode.NotFound) { return false; } if (!(statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.NotFound)) { throw new Exception($"Found unexpected error code: {statusCode}"); } return true; })); }
public async Task Detail() { // arrange var test_pk = 2; var mockGalleryRepository = new Mock <IGalleryRepository>(); mockGalleryRepository .Setup(x => x.GetGalleryEntries()) .Returns(Task.FromResult(GetTestSessions())); var mockTagRepository = new Mock <ITagRepository>(); mockTagRepository .Setup(x => x.GetTags()) .Returns(Task.FromResult(GetTestTags())); var controller = new GalleryController(mockGalleryRepository.Object, mockTagRepository.Object); // act var result = await controller.Detail(test_pk); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <GalleryEntry>( viewResult.ViewData.Model); Assert.Equal("The Combover", model.Title); Assert.Equal(test_pk, model.GalleryEntryID); }
public void SaveCode() { if (codeTex != null) { GalleryController.SaveImageToGallery(codeTex); } }
public async Task DeleteGallery_mine_and_it_exist() { // Arrange var controller = new GalleryController(GalleryService.Object); controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[0].Id.ToString()); GalleryEntity newGallery = new GalleryEntity() { Id = Guid.NewGuid(), fk_owner = UserEntities[0].Id, Name = "TestName", owner = UserEntities[0] }; GalleryEntities.Add(newGallery); // Act ActionResult response = await controller.DeleteGallery(newGallery.Id); // Assert Assert.IsInstanceOfType(response, typeof(NoContentResult)); var result = response as NoContentResult; Assert.AreEqual(204, result.StatusCode); GalleryService.Verify(repo => repo.DeleteGalleryAsync(It.IsAny <Guid>()), Times.Once()); GalleryEntities.Remove(newGallery); }
public async Task Index() { // arrange var mockGalleryRepository = new Mock <IGalleryRepository>(); mockGalleryRepository .Setup(x => x.GetGalleryEntries()) .Returns(Task.FromResult(GetTestSessions())); var mockTagRepository = new Mock <ITagRepository>(); mockTagRepository .Setup(x => x.GetTags()) .Returns(Task.FromResult(GetTestTags())); var controller = new GalleryController(mockGalleryRepository.Object, mockTagRepository.Object); // act var result = await controller.Index(null); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <IEnumerable <GalleryEntry> >( viewResult.ViewData.Model); Assert.Equal(2, model.Count()); }
public Entity.GalleryData GetInflatedMediaObject(int id) { try { IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(id); return(GalleryController.GetGalleryDataForMediaObject(mediaObject, (IAlbum)mediaObject.Parent, new Entity.GalleryDataLoadOptions { LoadMediaItems = true })); } catch (InvalidMediaObjectException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(String.Format("Could not find media object with ID = {0}", id)), ReasonPhrase = "Media Object Not Found" }); } catch (GallerySecurityException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (Exception ex) { AppEventController.LogError(ex); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = Utils.GetExStringContent(ex), ReasonPhrase = "Server Error" }); } }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> public void ProcessRequest(HttpContext context) { try { if (!GalleryController.IsInitialized) { GalleryController.InitializeGspApplication(); } if (InitializeVariables(context)) { string tvXml = GenerateTreeviewJson(); context.Response.ContentType = "text/json"; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); // Needed for IE 7 context.Response.Write(tvXml); } else { context.Response.End(); } } catch (System.Threading.ThreadAbortException) { throw; // We don't want these to fall into the generic catch because we don't want them logged. } catch (Exception ex) { AppEventController.LogError(ex); throw; } }
private void BindTemplateNameDropDownList() { var templateType = Enum <UiTemplateType> .Parse(ddlGalleryItem.SelectedValue); const string activeTmplSuffix = " <active>"; var tmplNames = (from a in GalleryController.GetUiTemplates() where a.TemplateType == templateType && a.GalleryId == GalleryId select new KeyValuePair <int, string>(a.UiTemplateId, a.RootAlbumIds.Any() ? a.Name + activeTmplSuffix : a.Name)); if (!tmplNames.Any()) { throw new WebException($"Could not find any UI templates in the data store having TemplateType='{templateType}'"); } var selectedIndex = 0; if (tmplNames.Any(kvp => !kvp.Value.EndsWith(activeTmplSuffix))) { // There is at least one tmpl that is active (as there always should be). Grab the index of the first one so we can select it in the dropdown selectedIndex = tmplNames.Select((v, i) => new { kvp = v, index = i }).First(item => item.kvp.Value.EndsWith(activeTmplSuffix)).index; } ddlTemplateName.DataTextField = "Value"; ddlTemplateName.DataValueField = "Key"; ddlTemplateName.DataSource = tmplNames; ddlTemplateName.DataBind(); ddlTemplateName.SelectedIndex = selectedIndex; }
public void CallAddNewImage_WhenParamsAreValid() { // Arrange var galleryServiceMock = new Mock <IGalleryImageService>(); var userServiceMock = new Mock <IUserService>(); var mappingServiceMock = new Mock <IMappingService>(); var utilsMock = new Mock <IUtilitiesService>(); var controller = new GalleryController(galleryServiceMock.Object, mappingServiceMock.Object, userServiceMock.Object, utilsMock.Object); var controllerContext = new Mock <ControllerContext>(); var user = new Mock <IPrincipal>(); user.Setup(p => p.IsInRole("admin")).Returns(true); user.SetupGet(x => x.Identity.Name).Returns("username"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(user.Object); controller.ControllerContext = controllerContext.Object; var model = new CreateImageViewModel(); // Act controller.Create(model); // Assert galleryServiceMock.Verify(x => x.AddNewImage(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Once); }
public AdminGalleryControllerTests() { var mockEnvironment = new Mock <IHostingEnvironment>(); mockEnvironment.Setup(m => m.WebRootPath).Returns(testRootDir); _controller = new GalleryController(mockEnvironment.Object); }
/// <summary> /// Initializes a new instance of the <see cref="Gallery"/> class. /// </summary> public Gallery() { // Ensure the app is initialized. This should have been done in the static constructor, but if anything went wrong // there, it may not be initialized, so we check again. if (!GalleryController.IsInitialized) { GalleryController.InitializeGspApplication(); } }
public static MainViewModel BuildMainView() { MainViewModel MVM = new MainViewModel(); MVM.Faqs = FAQsRoutines.GetTopFAQsForMAin(); MVM.Courses = CourseRoutine.GetTopCoursesForMAin(); MVM.Gallary = GalleryController.GetActiveGallary(); MVM.Instarctors = InstractorsRoutines.GetAll(); return(MVM); }
public void setGalleryId(int Id) { patientId = Id; if (galleryController == null) { galleryController = new GalleryController(); } galleryController.CreateAndOpenGalley(Id); LoadGalleryImageList(); }
/// <summary> /// Starts a synchronization on a background thread for the album specified in <paramref name="syncOptions" />. /// </summary> /// <param name="syncOptions">The synchronization options.</param> /// <param name="password">The password that allows remote access to the synchronization API.</param> private static void StartRemoteSync(SyncOptions syncOptions, string password) { IAlbum album = AlbumController.LoadAlbumInstance(syncOptions.AlbumIdToSynchronize); if (!ValidateRemoteSync(album, password)) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } Task.Factory.StartNew(() => GalleryController.BeginSync(syncOptions), TaskCreationOptions.LongRunning); }
public MediaItemsController(GalleryController galleryController, AlbumController albumController, GalleryObjectController galleryObjectController, FileStreamController streamController, HtmlController htmlController, UrlController urlController, UserController userController, ExceptionController exController, IAuthorizationService authorizationService) { _galleryController = galleryController; _albumController = albumController; _galleryObjectController = galleryObjectController; _streamController = streamController; _htmlController = htmlController; _urlController = urlController; _userController = userController; _exController = exController; _authorizationService = authorizationService; }
private void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); return; } }
/// <summary> /// Initialize a new instance of the ViewDrawRibbonGroupGallery class. /// </summary> /// <param name="ribbon">Reference to owning ribbon control.</param> /// <param name="ribbonGallery">Reference to source gallery.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public ViewDrawRibbonGroupGallery(KryptonRibbon ribbon, KryptonRibbonGroupGallery ribbonGallery, NeedPaintHandler needPaint) { Debug.Assert(ribbon != null); Debug.Assert(ribbonGallery != null); Debug.Assert(needPaint != null); // Remember incoming references _ribbon = ribbon; GroupGallery = ribbonGallery; _needPaint = needPaint; _currentSize = GroupGallery.ItemSizeCurrent; // Create the button view used in small setting CreateLargeButtonView(); // Hook into the gallery events GroupGallery.MouseEnterControl += OnMouseEnterControl; GroupGallery.MouseLeaveControl += OnMouseLeaveControl; // Associate this view with the source component (required for design time selection) Component = GroupGallery; if (_ribbon.InDesignMode) { // At design time we need to know when the user right clicks the gallery ContextClickController controller = new(); controller.ContextClick += OnContextClick; MouseController = controller; } // Create controller needed for handling focus and key tip actions _controller = new GalleryController(_ribbon, GroupGallery, this); SourceController = _controller; KeyController = _controller; // We need to rest visibility of the gallery for each layout cycle _ribbon.ViewRibbonManager.LayoutBefore += OnLayoutAction; _ribbon.ViewRibbonManager.LayoutAfter += OnLayoutAction; // Define back reference to view for the gallery definition GroupGallery.GalleryView = this; // Give paint delegate to gallery so its palette changes are redrawn GroupGallery.ViewPaintDelegate = needPaint; // Hook into changes in the ribbon custom definition GroupGallery.PropertyChanged += OnGalleryPropertyChanged; NULL_CONTROL_WIDTH = (int)(50 * FactorDpiX); _largeImagePadding = new Padding((int)(3 * FactorDpiX), (int)(2 * FactorDpiY), (int)(3 * FactorDpiX), (int)(3 * FactorDpiY)); }
private void BindTemplateNameDropDownList() { var templateType = Enum <UiTemplateType> .Parse(ddlGalleryItem.SelectedValue); var tmplNames = (from a in GalleryController.GetUiTemplates() where a.TemplateType == templateType && a.GalleryId == GalleryId select new KeyValuePair <int, string>(a.UiTemplateId, a.Name)); ddlTemplateName.DataTextField = "Value"; ddlTemplateName.DataValueField = "Key"; ddlTemplateName.DataSource = tmplNames; ddlTemplateName.DataBind(); }
/// <overloads> /// Synchronize the files in the media objects directory with the data store. /// </overloads> /// <summary> /// Invoke a synchronization having the specified options. It is initiated on a background thread and the current thread /// is immediately returned. /// </summary> /// <param name="syncOptions">An object containing settings for the synchronization.</param> /// <returns>An instance of <see cref="HttpResponseMessage" />.</returns> /// <exception cref="System.Web.Http.HttpResponseException">Thrown when the caller does not have permission to start a /// synchronization.</exception> public HttpResponseMessage StartSync(SyncOptions syncOptions) { try { #region Check user authorization if (!Utils.IsAuthenticated) { var url = Utils.GetUrl(PageId.login, "ReturnUrl={0}", Utils.UrlEncode(Utils.GetCurrentPageUrl(true))); throw new GallerySecurityException($"You are not logged in. <a href='{url}'>Log in</a>"); //throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } IAlbum album = AlbumController.LoadAlbumInstance(syncOptions.AlbumIdToSynchronize); if (!Utils.IsUserAuthorized(SecurityActions.Synchronize, RoleController.GetGalleryServerRolesForUser(), syncOptions.AlbumIdToSynchronize, album.GalleryId, false, album.IsVirtualAlbum)) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } #endregion syncOptions.SyncId = GetSyncId(); syncOptions.UserName = Utils.UserName; Task.Factory.StartNew(() => GalleryController.BeginSync(syncOptions), TaskCreationOptions.LongRunning); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Synchronization started...") }); } catch (GallerySecurityException ex) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent(ex.Message), ReasonPhrase = "Log In Required" }); } catch (Exception ex) { AppEventController.LogError(ex); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = Utils.GetExStringContent(ex), ReasonPhrase = "Server Error" }); } }
public void ReturnHttpNotFound_WhenNoSuchImageIsPresent() { // Arrange var galleryServiceMock = new Mock <IGalleryImageService>(); var userServiceMock = new Mock <IUserService>(); var mappingServiceMock = new Mock <IMappingService>(); var utilsMock = new Mock <IUtilitiesService>(); var controller = new GalleryController(galleryServiceMock.Object, mappingServiceMock.Object, userServiceMock.Object, utilsMock.Object); // Act & Assert controller.WithCallTo(x => x.PopulateModal(Guid.NewGuid())) .ShouldGiveHttpStatus(404); }
public void ReturnBadRequest_WhenImageIdIsMissing() { // Arrange var galleryServiceMock = new Mock <IGalleryImageService>(); var userServiceMock = new Mock <IUserService>(); var mappingServiceMock = new Mock <IMappingService>(); var utilsMock = new Mock <IUtilitiesService>(); var controller = new GalleryController(galleryServiceMock.Object, mappingServiceMock.Object, userServiceMock.Object, utilsMock.Object); // Act & Assert controller.WithCallTo(x => x.PopulateModal(null)) .ShouldGiveHttpStatus(400); }