private void ValidateGalleryImage(GalleryImage imageIn, GalleryImage imageOut) { Assert.False(string.IsNullOrEmpty(imageOut.ProvisioningState)); if (imageIn.Tags != null) { foreach (KeyValuePair <string, string> kvp in imageIn.Tags) { Assert.Equal(kvp.Value, imageOut.Tags[kvp.Key]); } } Assert.Equal(imageIn.Identifier.Publisher, imageOut.Identifier.Publisher); Assert.Equal(imageIn.Identifier.Offer, imageOut.Identifier.Offer); Assert.Equal(imageIn.Identifier.Sku, imageOut.Identifier.Sku); Assert.Equal(imageIn.Location, imageOut.Location); Assert.Equal(imageIn.OsState, imageOut.OsState); Assert.Equal(imageIn.OsType, imageOut.OsType); if (!string.IsNullOrEmpty(imageIn.Description)) { Assert.Equal(imageIn.Description, imageOut.Description); } }
/// <summary>View a single image in the subreddit.</summary> /// <param name="imageId">The image id.</param> /// <param name="subreddit">A valid subreddit name. Example: pics, gaming</param> /// <exception cref="T:System.ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> /// <exception cref="T:Imgur.API.ImgurException">Thrown when an error is found in a response from an Imgur endpoint.</exception> /// <exception cref="T:Imgur.API.MashapeException">Thrown when an error is found in a response from a Mashape endpoint.</exception> /// <returns></returns> public async Task <IGalleryImage> GetSubredditImageAsync( string imageId, string subreddit) { if (string.IsNullOrWhiteSpace(imageId)) { throw new ArgumentNullException(nameof(imageId)); } if (string.IsNullOrWhiteSpace(subreddit)) { throw new ArgumentNullException(nameof(subreddit)); } string url = string.Format("gallery/r/{0}/{1}", (object)subreddit, (object)imageId); IGalleryImage galleryImage; using (HttpRequestMessage request = this.RequestBuilder.CreateRequest(HttpMethod.Get, url)) { GalleryImage image = await this.SendRequestAsync <GalleryImage>(request).ConfigureAwait(false); galleryImage = (IGalleryImage)image; } return(galleryImage); }
/// <summary>View a single item in a gallery tag.</summary> /// <param name="galleryItemId">The gallery item id.</param> /// <param name="tag">The name of the tag.</param> /// <exception cref="T:System.ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> /// <exception cref="T:Imgur.API.ImgurException">Thrown when an error is found in a response from an Imgur endpoint.</exception> /// <exception cref="T:Imgur.API.MashapeException">Thrown when an error is found in a response from a Mashape endpoint.</exception> /// <returns></returns> public async Task <IGalleryItem> GetGalleryTagImageAsync( string galleryItemId, string tag) { if (string.IsNullOrWhiteSpace(galleryItemId)) { throw new ArgumentNullException(nameof(galleryItemId)); } if (string.IsNullOrWhiteSpace(tag)) { throw new ArgumentNullException(nameof(tag)); } string url = string.Format("gallery/t/{0}/{1}", (object)tag, (object)galleryItemId); IGalleryItem galleryItem; using (HttpRequestMessage request = this.RequestBuilder.CreateRequest(HttpMethod.Get, url)) { GalleryImage image = await this.SendRequestAsync <GalleryImage>(request).ConfigureAwait(false); galleryItem = (IGalleryItem)image; } return(galleryItem); }
// Load Pictures void LoadPictures() { using (var userStore = IsolatedStorageFile.GetUserStoreForApplication()) { var fileNames = userStore.GetFileNames("*.jpg"); if (!fileNames.Any()) { MessageBox.Show("There are no pictures in the gallery!"); return; } foreach (var fileName in fileNames) { using (var stream = userStore.OpenFile(fileName, FileMode.Open)) { GalleryImage newGalleryImage = new GalleryImage() { ImagePath = stream.Name }; galleryImages.Add(newGalleryImage); } } } }
public void RenderPartialViewWithCorrectModel_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; galleryServiceMock.Setup(x => x.AddComment(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Guid>())); var image = new GalleryImage(); galleryServiceMock.Setup(x => x.GetGalleryImageById(It.IsAny <Guid>())).Returns(image); var model = new GalleryItemViewModel(); mappingServiceMock.Setup(x => x.Map <GalleryItemViewModel>(image)).Returns(model); var userModel = new User(); userServiceMock.Setup(x => x.GetById(It.IsAny <string>())).Returns(userModel); // Act & Assert controller.WithCallTo(x => x.Comment(Guid.NewGuid(), model)) .ShouldRenderPartialView("_CommentBoxPartial") .WithModel <GalleryItemViewModel>(x => x == model); }
public IActionResult Index() { byte[] imageData = null; GalleryImage galleryImage = null; if (Request.Form.Files.Count > 0) { IFormFile imageFile = Request.Form.Files["Image"]; using (var reader = new BinaryReader(imageFile.OpenReadStream())) { imageData = reader.ReadBytes((int)imageFile.Length); } } var identityUser = _dbContext.Users.First(u => u.Email == HttpContext.User.Identity.Name); if (imageData != null) { galleryImage = new GalleryImage() { Image = imageData, Owner = identityUser }; } if (identityUser.GalleryImages == null) { identityUser.GalleryImages = new List <GalleryImage>(); } identityUser.GalleryImages.Add(galleryImage); _dbContext.Users.Update(identityUser); _dbContext.SaveChanges(); return(RedirectToAction("Index", new { userid = identityUser.Id })); }
private void BindImage() { if (!UseCompactMode) { return; } if (itemId == -1) { return; } imageLink = new Literal(); GalleryImage galleryImage = new GalleryImage(ModuleId, itemId); imageLink.Text = "<a onclick=\"window.open(this.href,'_blank');return false;\" " + " title=\"" + Server.HtmlEncode(GalleryResources.GalleryWebImageAltText).HtmlEscapeQuotes() + "\" href=\"" + imageBaseUrl + Page.ResolveUrl(fullSizeBaseUrl + galleryImage.ImageFile) + "\" ><img src=\"" + Page.ResolveUrl(webSizeBaseUrl + galleryImage.WebImageFile) + "\" alt=\"" + Server.HtmlEncode(GalleryResources.GalleryWebImageAltText).HtmlEscapeQuotes() + "\" /></a>"; pnlGallery.Controls.Clear(); pnlGallery.Controls.Add(imageLink); lblCaption.Text = Page.Server.HtmlEncode(galleryImage.Caption); lblDescription.Text = galleryImage.Description; if ((config.ShowTechnicalData) && (galleryImage.MetaDataXml.Length > 0)) { xmlMeta.DocumentContent = galleryImage.MetaDataXml; string xslPath = HttpContext.Current.Server.MapPath(WebUtils.GetApplicationRoot() + "/ImageGallery/GalleryMetaData.xsl"); xmlMeta.TransformSource = xslPath; } }
public ActionResult Upload(int?tsize, bool?tisWidth) { var file = Request.Files[0]; if (file == null) { throw new Exception("No File"); } using (var image = Image.FromStream(file.InputStream)) { GalleryImage galleryImage; if (tsize.HasValue && tisWidth.HasValue) { galleryImage = new GalleryImage(image, file.FileName, tsize.Value, tisWidth.Value); } else { galleryImage = new GalleryImage(image, file.FileName); } DbSession.SaveOrUpdate(galleryImage); return(Json(galleryImage)); } }
public async Task <IActionResult> SaveSnapshot() { if (!User.Identity.IsAuthenticated) { return(RedirectToAction(nameof(HomeController.Start), "Home")); } bool saved = false; var user = await _userManager.GetUserAsync(HttpContext.User); string image = Request.Form["datatype"].ToString(); var databaseimage = new GalleryImage { Title = user.FirstName, Url = image.ToString(), Created = DateTime.Now }; _context.Add(databaseimage); await _context.SaveChangesAsync(); saved = true; return(Json(saved ? "Your Snapshot stored in Gallery, you can see it there with your First Name on it" : "image not saved")); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { var imgArray = new List<GalleryImage>(); var gallery = new Gallery(); var fontAwsome = new TTF.fontawesome_webfont(); gallery.GalleryContainer.style.fontFamily = fontAwsome; gallery.LeftContainer.innerText = "\xf060"; gallery.RightContainer.innerText = "\xf061"; var img1 = new GalleryImage(); var img2 = new GalleryImage(); var img3 = new GalleryImage(); var img4 = new GalleryImage(); var img5 = new GalleryImage(); var img6 = new GalleryImage(); img1.GalleryImage.innerText = "Hello 1"; img2.GalleryImage.innerText = "Hello 2"; img3.GalleryImage.innerText = "Hello 3"; img4.GalleryImage.innerText = "Hello 4"; img5.GalleryImage.innerText = "Hello 5"; img6.GalleryImage.innerText = "Hello 6"; imgArray.Add(img1); imgArray.Add(img2); imgArray.Add(img3); imgArray.Add(img4); imgArray.Add(img5); imgArray.Add(img6); img1.AttachTo(gallery.Holder); img2.AttachTo(gallery.Holder); img3.AttachTo(gallery.Holder); img4.AttachTo(gallery.Holder); img5.AttachTo(gallery.Holder); img6.AttachTo(gallery.Holder); gallery.AttachToDocument(); gallery.RightContainer.css.hover.style.color = "#606060"; gallery.LeftContainer.css.hover.style.color = "#606060"; foreach (var i in imgArray) { new IStyle(i.GalleryImage) { width = "10em", transition = "width linear 300ms", Opacity = 1 }; } var counterL = 0; var counterR = imgArray.Count - 1; gallery.LeftContainer.onclick += async delegate { Console.WriteLine("Counter L" + counterL); Console.WriteLine("Counter R" + counterL); var temp = imgArray[counterR]; var newTemp = new GalleryImage(); newTemp.GalleryImage.innerText = "Helloo" + counterL; new IStyle(newTemp.GalleryImage) { width = "0em", transition = "width linear 300ms", Opacity = 1 }; gallery.Holder.insertBefore(newTemp.AsNode(), imgArray[counterL].AsNode()); Native.window.requestAnimationFrame += delegate { temp.GalleryImage.style.width = "0px"; newTemp.GalleryImage.style.width = "10em"; }; imgArray[counterR] = newTemp; await 305; temp.Orphanize(); counterR--; counterL--; if (counterL > imgArray.Count-1) { counterL = 0; } if (counterR > imgArray.Count - 1) { counterR = 0; } if (counterR < 0) { counterR = imgArray.Count - 1; } if (counterL < 0) { counterL = imgArray.Count - 1; } }; gallery.RightContainer.onclick += async delegate { Console.WriteLine("Right click" + counterR); var temp = imgArray[counterL]; var newTemp = new GalleryImage(); newTemp.GalleryImage.innerText = "Helloo" + counterR; new IStyle(newTemp.GalleryImage) { width = "0em", transition = "width linear 300ms", Opacity = 1 }; newTemp.AttachTo(gallery.Holder); Native.window.requestAnimationFrame += delegate { temp.GalleryImage.style.width = "0px"; newTemp.GalleryImage.style.width = "10em"; }; await 305; temp.Orphanize(); imgArray[counterL] = newTemp; counterL++; counterR++; if (counterL > imgArray.Count - 1) { counterL = 0; } if (counterR > imgArray.Count - 1) { counterR = 0; } if (counterR < 0) { counterR = imgArray.Count - 1; } if (counterL < 0) { counterL = imgArray.Count - 1; } }; }
private static void IndexItem(GalleryImage galleryImage) { if (WebConfigSettings.DisableSearchIndex) { return; } SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings(); if ((siteSettings == null) || (galleryImage == null)) { return; } Guid galleryFeatureGuid = new Guid("d572f6b4-d0ed-465d-ad60-60433893b401"); ModuleDefinition galleryFeature = new ModuleDefinition(galleryFeatureGuid); Module module = new Module(galleryImage.ModuleId); // get list of pages where this module is published List <PageModule> pageModules = PageModule.GetPageModulesByModule(galleryImage.ModuleId); foreach (PageModule pageModule in pageModules) { PageSettings pageSettings = new PageSettings( siteSettings.SiteId, pageModule.PageId); //don't index pending/unpublished pages if (pageSettings.IsPending) { continue; } mojoPortal.SearchIndex.IndexItem indexItem = new mojoPortal.SearchIndex.IndexItem(); indexItem.SiteId = siteSettings.SiteId; indexItem.PageId = pageSettings.PageId; indexItem.PageName = pageSettings.PageName; indexItem.ViewRoles = pageSettings.AuthorizedRoles; indexItem.ModuleViewRoles = module.ViewRoles; indexItem.FeatureId = galleryFeatureGuid.ToString(); indexItem.FeatureName = galleryFeature.FeatureName; indexItem.FeatureResourceFile = galleryFeature.ResourceFile; indexItem.CreatedUtc = galleryImage.UploadDate; indexItem.LastModUtc = galleryImage.UploadDate; indexItem.ItemId = galleryImage.ItemId; indexItem.ModuleId = galleryImage.ModuleId; indexItem.QueryStringAddendum = "&ItemID" + galleryImage.ModuleId.ToString() + "=" + galleryImage.ItemId.ToString(); indexItem.ModuleTitle = module.ModuleTitle; indexItem.Title = galleryImage.Caption; indexItem.Content = galleryImage.Description; indexItem.PublishBeginDate = pageModule.PublishBeginDate; indexItem.PublishEndDate = pageModule.PublishEndDate; mojoPortal.SearchIndex.IndexHelper.RebuildIndex(indexItem); if (debugLog) { log.Debug("Indexed " + galleryImage.Caption); } } }
public async Task GalleryImageVersion_CRUD_Tests() { EnsureClientsInitialized(LocationEastUs2); string rgName = Recording.GenerateAssetName(ResourceGroupPrefix); VirtualMachine vm = null; string imageName = Recording.GenerateAssetName("psTestSourceImage"); vm = await CreateCRPImage(rgName, imageName); Assert.False(string.IsNullOrEmpty(sourceImageId)); Trace.TraceInformation(string.Format("Created the source image id: {0}", sourceImageId)); string galleryName = Recording.GenerateAssetName(GalleryNamePrefix); Gallery gallery = GetTestInputGallery(); await WaitForCompletionAsync(await GalleriesOperations.StartCreateOrUpdateAsync(rgName, galleryName, gallery)); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); string galleryImageName = Recording.GenerateAssetName(GalleryImageNamePrefix); GalleryImage inputGalleryImage = GetTestInputGalleryImage(); await WaitForCompletionAsync((await GalleryImagesOperations.StartCreateOrUpdateAsync(rgName, galleryName, galleryImageName, inputGalleryImage))); Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName, galleryName)); string galleryImageVersionName = "1.0.0"; GalleryImageVersion inputImageVersion = GetTestInputGalleryImageVersion(sourceImageId); await WaitForCompletionAsync(await GalleryImageVersionsOperations.StartCreateOrUpdateAsync(rgName, galleryName, galleryImageName, galleryImageVersionName, inputImageVersion)); Trace.TraceInformation(string.Format("Created the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); GalleryImageVersion imageVersionFromGet = await GalleryImageVersionsOperations.GetAsync(rgName, galleryName, galleryImageName, galleryImageVersionName); Assert.NotNull(imageVersionFromGet); ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet); imageVersionFromGet = await GalleryImageVersionsOperations.GetAsync(rgName, galleryName, galleryImageName, galleryImageVersionName, ReplicationStatusTypes.ReplicationStatus); Assert.AreEqual(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.StorageAccountType); Assert.AreEqual(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType); Assert.NotNull(imageVersionFromGet.ReplicationStatus); Assert.NotNull(imageVersionFromGet.ReplicationStatus.Summary); inputImageVersion.PublishingProfile.EndOfLifeDate = Recording.UtcNow.AddDays(100); await WaitForCompletionAsync(await GalleryImageVersionsOperations.StartCreateOrUpdateAsync(rgName, galleryName, galleryImageName, galleryImageVersionName, inputImageVersion)); Trace.TraceInformation(string.Format("Updated the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); imageVersionFromGet = await GalleryImageVersionsOperations.GetAsync(rgName, galleryName, galleryImageName, galleryImageVersionName); Assert.NotNull(imageVersionFromGet); ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet); Trace.TraceInformation("Listing the gallery image versions"); List <GalleryImageVersion> listGalleryImageVersionsResult = await(GalleryImageVersionsOperations. ListByGalleryImageAsync(rgName, galleryName, galleryImageName)).ToEnumerableAsync(); Assert.IsTrue(listGalleryImageVersionsResult.Count() == 1); //Assert.Single(listGalleryImageVersionsResult); //Assert.Null(listGalleryImageVersionsResult.NextPageLink); await WaitForCompletionAsync(await GalleryImageVersionsOperations.StartDeleteAsync(rgName, galleryName, galleryImageName, galleryImageVersionName)); listGalleryImageVersionsResult = await(GalleryImageVersionsOperations. ListByGalleryImageAsync(rgName, galleryName, galleryImageName)).ToEnumerableAsync(); //Assert.Null(listGalleryImageVersionsResult.NextPageLink); Trace.TraceInformation(string.Format("Deleted the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); this.WaitMinutes(5); await WaitForCompletionAsync(await ImagesOperations.StartDeleteAsync(rgName, imageName)); Trace.TraceInformation("Deleted the CRP image."); await WaitForCompletionAsync(await VirtualMachinesOperations.StartDeleteAsync(rgName, vm.Name)); Trace.TraceInformation("Deleted the virtual machine."); await WaitForCompletionAsync(await GalleryImagesOperations.StartDeleteAsync(rgName, galleryName, galleryImageName)); Trace.TraceInformation("Deleted the gallery image."); WaitSeconds(100); await WaitForCompletionAsync(await GalleriesOperations.StartDeleteAsync(rgName, galleryName)); WaitSeconds(100); Trace.TraceInformation("Deleted the gallery."); }
public ActionResult Edit(PostViewModel model, string ReturnUrl) { ActionResult action; try { if (!base.ModelState.IsValid) { String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception)); base.ModelState.AddModelError("", messages); return(base.View(model)); } else if (!_postService.FindBy((Post x) => x.ProductCode.Equals(model.ProductCode) && x.Id != model.Id, true).IsAny <Post>()) { Post byId = this._postService.GetById(model.Id, isCache: false); string titleNonAccent = model.Title.NonAccent(); IEnumerable <MenuLink> bySeoUrl = this._menuLinkService.GetListSeoUrl(titleNonAccent, isCache: false); model.SeoUrl = model.Title.NonAccent(); if (bySeoUrl.Any <MenuLink>((MenuLink x) => x.Id != model.Id)) { PostViewModel postViewModel = model; postViewModel.SeoUrl = string.Concat(postViewModel.SeoUrl, "-", bySeoUrl.Count <MenuLink>()); } //string str1 = titleNonAccent; //if (str1.Length > 250) //{ // str1 = Utils.Utils.SplitWords(250, str1); //} string folderName = string.Format("{0:ddMMyyyy}", DateTime.UtcNow); if (model.Image != null && model.Image.ContentLength > 0) { string fileExtension = Path.GetExtension(model.Image.FileName); string fileName1 = titleNonAccent.FileNameFormat(fileExtension); string fileName2 = titleNonAccent.FileNameFormat(fileExtension); string fileName3 = titleNonAccent.FileNameFormat(fileExtension); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName1, ImageSize.WithBigSize, ImageSize.HeightBigSize, false); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName2, ImageSize.WithMediumSize, ImageSize.HeightMediumSize, false); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName3, ImageSize.WithSmallSize, ImageSize.HeightSmallSize, false); model.ImageBigSize = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName1); model.ImageMediumSize = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName2); model.ImageSmallSize = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName3); } int?menuId = model.MenuId; int i = 0; if ((menuId.GetValueOrDefault() > i ? menuId.HasValue : false)) { IMenuLinkService menuLinkService = this._menuLinkService; menuId = model.MenuId; MenuLink menuLink = menuLinkService.GetById(menuId.Value, isCache: false); model.VirtualCatUrl = menuLink.VirtualSeoUrl; model.VirtualCategoryId = menuLink.VirtualId; } //GalleryImage HttpFileCollectionBase files = base.Request.Files; List <GalleryImage> lstGalleryImages = new List <GalleryImage>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string[] allKeys = files.AllKeys; for (i = 0; i < (int)allKeys.Length; i++) { string str7 = allKeys[i]; if (num <= count) { if (!str7.Equals("Image")) { string str8 = str7.Replace("[]", ""); HttpPostedFileBase item = files[num]; if (item.ContentLength > 0) { string item1 = base.Request[str8]; GalleryImageViewModel galleryImageViewModel = new GalleryImageViewModel() { PostId = model.Id, AttributeValueId = int.Parse(str8) }; string fileName1 = string.Format("{0}-{1}.jpg", titleNonAccent, Guid.NewGuid()); string fileName2 = string.Format("{0}-{1}.jpg", titleNonAccent, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName1, ImageSize.WithBigSize, ImageSize.WithBigSize, false); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName2, ImageSize.WithThumbnailSize, ImageSize.HeightThumbnailSize, false); galleryImageViewModel.ImageThumbnail = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName2); galleryImageViewModel.ImagePath = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName1); galleryImageViewModel.OrderDisplay = num; galleryImageViewModel.Status = 1; galleryImageViewModel.Title = model.Title; galleryImageViewModel.Price = new double?(double.Parse(item1)); lstGalleryImages.Add(Mapper.Map <GalleryImage>(galleryImageViewModel)); } num++; } else { num++; } } } } if (lstGalleryImages.IsAny <GalleryImage>()) { byId.GalleryImages = lstGalleryImages; } //AttributeValue List <AttributeValue> lstAttributeValues = new List <AttributeValue>(); List <int> nums = new List <int>(); string item2 = base.Request["Values"]; if (!string.IsNullOrEmpty(item2)) { foreach (string list in item2.Split(new char[] { ',' }).ToList <string>()) { int num1 = int.Parse(list); nums.Add(num1); lstAttributeValues.Add(this._attributeValueService.GetById(num1, isCache: false)); } if (nums.IsAny <int>()) { ( from x in byId.AttributeValues where !nums.Contains(x.Id) select x).ToList <AttributeValue>().ForEach((AttributeValue att) => byId.AttributeValues.Remove(att)); } } byId.AttributeValues = lstAttributeValues; Post modelMap = Mapper.Map(model, byId); this._postService.Update(byId); //Update GalleryImage if (lstAttributeValues.IsAny <AttributeValue>()) { foreach (AttributeValue attributeValue in lstAttributeValues) { GalleryImage nullable = this._galleryService.Get((GalleryImage x) => x.AttributeValueId == attributeValue.Id && x.PostId == model.Id, false); if (nullable == null) { continue; } HttpRequestBase request = base.Request; i = attributeValue.Id; double num2 = double.Parse(request[i.ToString()]); nullable.Price = new double?(num2); this._galleryService.Update(nullable); } } //Update Localized foreach (var localized in model.Locales) { _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Title, localized.Title, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.ProductCode, localized.ProductCode, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.ShortDesc, localized.ShortDesc, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Description, localized.Description, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.TechInfo, localized.TechInfo, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.SeoUrl, localized.SeoUrl, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaTitle, localized.MetaTitle, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaKeywords, localized.MetaKeywords, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaDescription, localized.MetaDescription, localized.LanguageId); } base.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.Post))); if (!base.Url.IsLocalUrl(ReturnUrl) || ReturnUrl.Length <= 1 || !ReturnUrl.StartsWith("/") || ReturnUrl.StartsWith("//") || ReturnUrl.StartsWith("/\\")) { action = base.RedirectToAction("Index"); } else { action = this.Redirect(ReturnUrl); } } else { base.ModelState.AddModelError("", "Mã sản phẩm đã tồn tại."); action = base.View(model); } } catch (Exception ex) { base.ModelState.AddModelError("", ex.Message); ExtentionUtils.Log(string.Concat("Post.Edit: ", ex.Message)); return(base.View(model)); } return(action); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (ShouldProcess(this.Name, VerbsCommon.New)) { string resourceGroupName = this.ResourceGroupName; string galleryName = this.GalleryName; string galleryImageName = this.Name; GalleryImage galleryImage = new GalleryImage(); galleryImage.Location = this.Location; galleryImage.Identifier = new GalleryImageIdentifier(this.Publisher, this.Offer, this.Sku); galleryImage.OsState = this.OsState; galleryImage.OsType = this.OsType; if (this.IsParameterBound(c => c.Description)) { galleryImage.Description = this.Description; } if (this.IsParameterBound(c => c.Eula)) { galleryImage.Eula = this.Eula; } if (this.IsParameterBound(c => c.HyperVGeneration)) { galleryImage.HyperVGeneration = this.HyperVGeneration; } if (this.IsParameterBound(c => c.PrivacyStatementUri)) { galleryImage.PrivacyStatementUri = this.PrivacyStatementUri; } if (this.IsParameterBound(c => c.ReleaseNoteUri)) { galleryImage.ReleaseNoteUri = this.ReleaseNoteUri; } if (this.IsParameterBound(c => c.EndOfLifeDate)) { galleryImage.EndOfLifeDate = this.EndOfLifeDate; } if (this.IsParameterBound(c => c.Architecture)) { galleryImage.Architecture = this.Architecture; } if (this.IsParameterBound(c => c.Tag)) { galleryImage.Tags = this.Tag.Cast <DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value); } if (this.IsParameterBound(c => c.MinimumVCPU)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.VCPUs == null) { galleryImage.Recommended.VCPUs = new ResourceRange(); } galleryImage.Recommended.VCPUs.Min = this.MinimumVCPU; } if (this.IsParameterBound(c => c.MaximumVCPU)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.VCPUs == null) { galleryImage.Recommended.VCPUs = new ResourceRange(); } galleryImage.Recommended.VCPUs.Max = this.MaximumVCPU; } if (this.IsParameterBound(c => c.MinimumMemory)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.Memory == null) { galleryImage.Recommended.Memory = new ResourceRange(); } galleryImage.Recommended.Memory.Min = this.MinimumMemory; } if (this.IsParameterBound(c => c.MaximumMemory)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.Memory == null) { galleryImage.Recommended.Memory = new ResourceRange(); } galleryImage.Recommended.Memory.Max = this.MaximumMemory; } if (this.IsParameterBound(c => c.DisallowedDiskType)) { if (galleryImage.Disallowed == null) { galleryImage.Disallowed = new Disallowed(); } galleryImage.Disallowed.DiskTypes = this.DisallowedDiskType; } if (this.IsParameterBound(c => c.PurchasePlanName)) { if (galleryImage.PurchasePlan == null) { galleryImage.PurchasePlan = new ImagePurchasePlan(); } galleryImage.PurchasePlan.Name = this.PurchasePlanName; } if (this.IsParameterBound(c => c.PurchasePlanPublisher)) { if (galleryImage.PurchasePlan == null) { galleryImage.PurchasePlan = new ImagePurchasePlan(); } galleryImage.PurchasePlan.Publisher = this.PurchasePlanPublisher; } if (this.IsParameterBound(c => c.PurchasePlanProduct)) { if (galleryImage.PurchasePlan == null) { galleryImage.PurchasePlan = new ImagePurchasePlan(); } galleryImage.PurchasePlan.Product = this.PurchasePlanProduct; } if (this.IsParameterBound(c => c.Feature)) { galleryImage.Features = this.Feature; } var result = GalleryImagesClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImage); var psObject = new PSGalleryImage(); ComputeAutomationAutoMapperProfile.Mapper.Map <GalleryImage, PSGalleryImage>(result, psObject); WriteObject(psObject); } }); }
public async ValueTask <Response> CreateOrUpdateAsync(string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (galleryName == null) { throw new ArgumentNullException(nameof(galleryName)); } if (galleryImageName == null) { throw new ArgumentNullException(nameof(galleryImageName)); } if (galleryImage == null) { throw new ArgumentNullException(nameof(galleryImage)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, galleryName, galleryImageName, galleryImage); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 201: case 200: return(message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } }
public Response CreateOrUpdate(string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (galleryName == null) { throw new ArgumentNullException(nameof(galleryName)); } if (galleryImageName == null) { throw new ArgumentNullException(nameof(galleryImageName)); } if (galleryImage == null) { throw new ArgumentNullException(nameof(galleryImage)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, galleryName, galleryImageName, galleryImage); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 201: case 200: return(message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } }
private void ShowImage() { if (moduleId == -1) { return; } Gallery gallery = new Gallery(moduleId); DataTable dt = gallery.GetWebImageByPage(pageNumber); if (dt.Rows.Count > 0) { itemId = Convert.ToInt32(dt.Rows[0]["ItemID"]); totalPages = Convert.ToInt32(dt.Rows[0]["TotalPages"]); } showTechnicalData = WebUtils.ParseBoolFromHashtable( moduleSettings, "GalleryShowTechnicalDataSetting", false); if (itemId == -1) { return; } Literal topPageLinks = new Literal(); string pageUrl = SiteRoot + "/ImageGallery/GalleryBrowse.aspx?" + "pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&pagenumber="; topPageLinks.Text = UIHelper.GetPagerLinksWithPrevNext( pageUrl, 1, this.totalPages, this.pageNumber, "modulepager", "SelectedPage"); this.spnTopPager.Controls.Add(topPageLinks); GalleryImage galleryImage = new GalleryImage(moduleId, itemId); imageLink.Text = "<a onclick=\"window.open(this.href,'_blank');return false;\" href='" + ImageSiteRoot + fullSizeBaseUrl + galleryImage.ImageFile + "' ><img src='" + ImageSiteRoot + webSizeBaseUrl + galleryImage.WebImageFile + "' alt='" + Resources.GalleryResources.GalleryWebImageAltText + "' /></a>"; this.pnlGallery.Controls.Add(imageLink); this.lblCaption.Text = Server.HtmlEncode(galleryImage.Caption); this.lblDescription.Text = galleryImage.Description; if (showTechnicalData) { if (galleryImage.MetaDataXml.Length > 0) { xmlMeta.DocumentContent = galleryImage.MetaDataXml; string xslPath = System.Web.HttpContext.Current.Server.MapPath(SiteRoot + "/ImageGallery/GalleryMetaData.xsl"); xmlMeta.TransformSource = xslPath; } } }
public virtual GalleryImagesCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (galleryName == null) { throw new ArgumentNullException(nameof(galleryName)); } if (galleryImageName == null) { throw new ArgumentNullException(nameof(galleryImageName)); } if (galleryImage == null) { throw new ArgumentNullException(nameof(galleryImage)); } using var scope = _clientDiagnostics.CreateScope("GalleryImagesOperations.StartCreateOrUpdate"); scope.Start(); try { var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImage, cancellationToken); return(new GalleryImagesCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, galleryName, galleryImageName, galleryImage).Request, originalResponse)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Create or update a gallery Image Definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// created. /// </param> /// <param name='galleryImageName'> /// The name of the gallery Image Definition to be created or updated. The /// allowed characters are alphabets and numbers with dots, dashes, and periods /// allowed in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the create or update gallery image operation. /// </param> public static GalleryImage CreateOrUpdate(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage) { return(operations.CreateOrUpdateAsync(resourceGroupName, galleryName, galleryImageName, galleryImage).GetAwaiter().GetResult()); }
internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Compute/galleries/", false); uri.AppendPath(galleryName, true); uri.AppendPath("/images/", false); uri.AppendPath(galleryImageName, true); uri.AppendQuery("api-version", "2019-12-01", true); request.Uri = uri; request.Headers.Add("Content-Type", "application/json"); using var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(galleryImage); request.Content = content; return(message); }
/// <summary> /// Create or update a gallery Image Definition. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='galleryName'> /// The name of the Shared Image Gallery in which the Image Definition is to be /// created. /// </param> /// <param name='galleryImageName'> /// The name of the gallery Image Definition to be created or updated. The /// allowed characters are alphabets and numbers with dots, dashes, and periods /// allowed in the middle. The maximum length is 80 characters. /// </param> /// <param name='galleryImage'> /// Parameters supplied to the create or update gallery image operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <GalleryImage> CreateOrUpdateAsync(this IGalleryImagesOperations operations, string resourceGroupName, string galleryName, string galleryImageName, GalleryImage galleryImage, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, galleryName, galleryImageName, galleryImage, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
private void btnUpdate_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } GalleryImage galleryImage; if (moduleId > -1) { if (itemId > -1) { galleryImage = new GalleryImage(moduleId, itemId); } else { galleryImage = new GalleryImage(moduleId); } if (galleryImage.ModuleId != moduleId) { SiteUtils.RedirectToAccessDeniedPage(this); return; } Module module = GetModule(moduleId, Gallery.FeatureGuid); galleryImage.ModuleGuid = module.ModuleGuid; galleryImage.ContentChanged += new ContentChangedEventHandler(galleryImage_ContentChanged); int displayOrder; if (!Int32.TryParse(txtDisplayOrder.Text, out displayOrder)) { displayOrder = -1; } if (displayOrder > -1) { galleryImage.DisplayOrder = displayOrder; } galleryImage.WebImageHeight = config.WebSizeHeight; galleryImage.WebImageWidth = config.WebSizeWidth; galleryImage.ThumbNailHeight = config.ThumbnailHeight; galleryImage.ThumbNailWidth = config.ThumbnailWidth; galleryImage.Description = edDescription.Text; galleryImage.Caption = txtCaption.Text; galleryImage.UploadUser = Context.User.Identity.Name; SiteUser siteUser = SiteUtils.GetCurrentSiteUser(); if (siteUser != null) { galleryImage.UserGuid = siteUser.UserGuid; } // as long as javascript is available this code should never execute // because the standard file input ir replaced by javascript and the file upload happens // at the service url /ImageGallery/upload.ashx // this is fallback implementation if (uploader.HasFile) { string ext = Path.GetExtension(uploader.FileName); if (!SiteUtils.IsAllowedUploadBrowseFile(ext, ".jpg|.gif|.png|.jpeg")) { lblMessage.Text = GalleryResources.InvalidFile; return; } string newFileName = Path.GetFileName(uploader.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles); string newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName); if (galleryImage.ImageFile == newFileName) { // an existing gallery image delete the old one fileSystem.DeleteFile(newImagePath); } else { // this is a new galleryImage instance, make sure we don't use the same file name as any other instance int i = 1; while (fileSystem.FileExists(VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName))) { newFileName = i.ToInvariantString() + newFileName; i += 1; } } newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName); if (galleryImage.ItemId > -1) { //updating with a new image so delete the previous version GalleryHelper.DeleteImages(galleryImage, fileSystem, imageFolderPath); } //using (Stream s = flImage.FileContent) //{ // fileSystem.SaveFile(newImagePath, s, flImage.ContentType, true); //} using (Stream s = uploader.FileContent) { fileSystem.SaveFile(newImagePath, s, IOHelper.GetMimeType(Path.GetExtension(ext).ToLower()), true); } galleryImage.ImageFile = newFileName; galleryImage.WebImageFile = newFileName; galleryImage.ThumbnailFile = newFileName; galleryImage.Save(); GalleryHelper.ProcessImage(galleryImage, fileSystem, imageFolderPath, uploader.FileName, config.ResizeBackgroundColor); CurrentPage.UpdateLastModifiedTime(); CacheHelper.ClearModuleCache(moduleId); SiteUtils.QueueIndexing(); if (hdnReturnUrl.Value.Length > 0) { WebUtils.SetupRedirect(this, hdnReturnUrl.Value); return; } } else // not hasfile { //updating a previously uploaded image if (itemId > -1) { if (galleryImage.Save()) { CurrentPage.UpdateLastModifiedTime(); CacheHelper.ClearModuleCache(moduleId); SiteUtils.QueueIndexing(); if (newItem) { string thisUrl = SiteRoot + "/ImageGallery/EditImage.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&ItemID=" + galleryImage.ItemId.ToInvariantString(); WebUtils.SetupRedirect(this, thisUrl); return; } else { if (hdnReturnUrl.Value.Length > 0) { WebUtils.SetupRedirect(this, hdnReturnUrl.Value); return; } WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl()); } } } } } }
public void GalleryImageVersion_CRUD_Tests() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", galleryHomeLocation); EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); VirtualMachine vm = null; string imageName = ComputeManagementTestUtilities.GenerateName("psTestSourceImage"); try { string sourceImageId = ""; vm = CreateCRPImage(rgName, imageName, ref sourceImageId); Assert.False(string.IsNullOrEmpty(sourceImageId)); Trace.TraceInformation(string.Format("Created the source image id: {0}", sourceImageId)); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery gallery = GetTestInputGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix); GalleryImage inputGalleryImage = GetTestInputGalleryImage(); m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage); Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName, galleryName)); string galleryImageVersionName = "1.0.0"; GalleryImageVersion inputImageVersion = GetTestInputGalleryImageVersion(sourceImageId); m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName, galleryImageVersionName, inputImageVersion); Trace.TraceInformation(string.Format("Created the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); GalleryImageVersion imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName, galleryImageVersionName); Assert.NotNull(imageVersionFromGet); ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet); imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName, galleryImageVersionName, ReplicationStatusTypes.ReplicationStatus); Assert.Equal(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.StorageAccountType); Assert.Equal(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType); Assert.NotNull(imageVersionFromGet.ReplicationStatus); Assert.NotNull(imageVersionFromGet.ReplicationStatus.Summary); inputImageVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date; m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName, galleryImageVersionName, inputImageVersion); Trace.TraceInformation(string.Format("Updated the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName, galleryImageVersionName); Assert.NotNull(imageVersionFromGet); ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet); Trace.TraceInformation("Listing the gallery image versions"); IPage <GalleryImageVersion> listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions. ListByGalleryImage(rgName, galleryName, galleryImageName); Assert.Single(listGalleryImageVersionsResult); Assert.Null(listGalleryImageVersionsResult.NextPageLink); m_CrpClient.GalleryImageVersions.Delete(rgName, galleryName, galleryImageName, galleryImageVersionName); listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions. ListByGalleryImage(rgName, galleryName, galleryImageName); Assert.Empty(listGalleryImageVersionsResult); Assert.Null(listGalleryImageVersionsResult.NextPageLink); Trace.TraceInformation(string.Format("Deleted the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); ComputeManagementTestUtilities.WaitMinutes(5); m_CrpClient.Images.Delete(rgName, imageName); Trace.TraceInformation("Deleted the CRP image."); m_CrpClient.VirtualMachines.Delete(rgName, vm.Name); Trace.TraceInformation("Deleted the virtual machine."); m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName); Trace.TraceInformation("Deleted the gallery image."); m_CrpClient.Galleries.Delete(rgName, galleryName); Trace.TraceInformation("Deleted the gallery."); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); if (vm != null) { m_CrpClient.VirtualMachines.Delete(rgName, vm.Name); } m_CrpClient.Images.Delete(rgName, imageName); } } }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (ShouldProcess(this.Name, VerbsData.Update)) { string resourceGroupName; string galleryName; string galleryImageName; switch (this.ParameterSetName) { case "ResourceIdParameter": resourceGroupName = GetResourceGroupName(this.ResourceId); galleryName = GetResourceName(this.ResourceId, "Microsoft.Compute/Galleries", "Images"); galleryImageName = GetInstanceId(this.ResourceId, "Microsoft.Compute/Galleries", "Images"); break; case "ObjectParameter": resourceGroupName = GetResourceGroupName(this.InputObject.Id); galleryName = GetResourceName(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images"); galleryImageName = GetInstanceId(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images"); break; default: resourceGroupName = this.ResourceGroupName; galleryName = this.GalleryName; galleryImageName = this.Name; break; } var galleryImage = new GalleryImage(); if (this.ParameterSetName == "ObjectParameter") { ComputeAutomationAutoMapperProfile.Mapper.Map <PSGalleryImage, GalleryImage>(this.InputObject, galleryImage); } else { galleryImage = GalleryImagesClient.Get(resourceGroupName, galleryName, galleryImageName); } if (this.IsParameterBound(c => c.Description)) { galleryImage.Description = this.Description; } if (this.IsParameterBound(c => c.Eula)) { galleryImage.Eula = this.Eula; } if (this.IsParameterBound(c => c.PrivacyStatementUri)) { galleryImage.PrivacyStatementUri = this.PrivacyStatementUri; } if (this.IsParameterBound(c => c.ReleaseNoteUri)) { galleryImage.ReleaseNoteUri = this.ReleaseNoteUri; } if (this.IsParameterBound(c => c.EndOfLifeDate)) { galleryImage.EndOfLifeDate = this.EndOfLifeDate; } if (this.IsParameterBound(c => c.Tag)) { galleryImage.Tags = this.Tag.Cast <DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value); } if (this.IsParameterBound(c => c.MinimumVCPU)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.VCPUs == null) { galleryImage.Recommended.VCPUs = new ResourceRange(); } galleryImage.Recommended.VCPUs.Min = this.MinimumVCPU; } if (this.IsParameterBound(c => c.MaximumVCPU)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.VCPUs == null) { galleryImage.Recommended.VCPUs = new ResourceRange(); } galleryImage.Recommended.VCPUs.Max = this.MaximumVCPU; } if (this.IsParameterBound(c => c.MinimumMemory)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.Memory == null) { galleryImage.Recommended.Memory = new ResourceRange(); } galleryImage.Recommended.Memory.Min = this.MinimumMemory; } if (this.IsParameterBound(c => c.MaximumMemory)) { if (galleryImage.Recommended == null) { galleryImage.Recommended = new RecommendedMachineConfiguration(); } if (galleryImage.Recommended.Memory == null) { galleryImage.Recommended.Memory = new ResourceRange(); } galleryImage.Recommended.Memory.Max = this.MaximumMemory; } if (this.IsParameterBound(c => c.DisallowedDiskType)) { if (galleryImage.Disallowed == null) { galleryImage.Disallowed = new Disallowed(); } galleryImage.Disallowed.DiskTypes = this.DisallowedDiskType; } if (this.IsParameterBound(c => c.PurchasePlanName)) { if (galleryImage.PurchasePlan == null) { galleryImage.PurchasePlan = new ImagePurchasePlan(); } galleryImage.PurchasePlan.Name = this.PurchasePlanName; } if (this.IsParameterBound(c => c.PurchasePlanPublisher)) { if (galleryImage.PurchasePlan == null) { galleryImage.PurchasePlan = new ImagePurchasePlan(); } galleryImage.PurchasePlan.Publisher = this.PurchasePlanPublisher; } if (this.IsParameterBound(c => c.PurchasePlanProduct)) { if (galleryImage.PurchasePlan == null) { galleryImage.PurchasePlan = new ImagePurchasePlan(); } galleryImage.PurchasePlan.Product = this.PurchasePlanProduct; } var result = GalleryImagesClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImage); var psObject = new PSGalleryImage(); ComputeAutomationAutoMapperProfile.Mapper.Map <GalleryImage, PSGalleryImage>(result, psObject); WriteObject(psObject); } }); }
public void AddGalleryImage(GalleryImage galimg) { images.Add(galimg); }
// Edit // Get public IActionResult Edit(int id) { GalleryImage imageToEdit = _imageService.GetById(id); return(View(imageToEdit)); }
public void AddGalleryImage(GalleryImage galimg, ImageSource imageSource) { images.Add(galimg); imgS.Add(imageSource); }
public override void RebuildIndex( PageSettings pageSettings, string indexPath) { if (WebConfigSettings.DisableSearchIndex) { return; } if (pageSettings == null) { return; } //don't index pending/unpublished pages if (pageSettings.IsPending) { return; } log.Info("GalleryImageIndexBuilderProvider indexing page - " + pageSettings.PageName); try { Guid galleryFeatureGuid = new Guid("d572f6b4-d0ed-465d-ad60-60433893b401"); ModuleDefinition galleryFeature = new ModuleDefinition(galleryFeatureGuid); List <PageModule> pageModules = PageModule.GetPageModulesByPage(pageSettings.PageId); DataTable dataTable = GalleryImage.GetImagesByPage(pageSettings.SiteId, pageSettings.PageId); foreach (DataRow row in dataTable.Rows) { mojoPortal.SearchIndex.IndexItem indexItem = new mojoPortal.SearchIndex.IndexItem(); indexItem.SiteId = pageSettings.SiteId; indexItem.PageId = pageSettings.PageId; indexItem.PageName = pageSettings.PageName; indexItem.ViewRoles = pageSettings.AuthorizedRoles; indexItem.ModuleViewRoles = row["ViewRoles"].ToString(); if (pageSettings.UseUrl) { indexItem.ViewPage = pageSettings.Url.Replace("~/", string.Empty); indexItem.UseQueryStringParams = false; } indexItem.FeatureId = galleryFeatureGuid.ToString(); indexItem.FeatureName = galleryFeature.FeatureName; indexItem.FeatureResourceFile = galleryFeature.ResourceFile; // TODO: it would be good to check the module settings and if not // in compact mode use the GalleryBrowse.aspx page //indexItem.ViewPage = "GalleryBrowse.aspx"; indexItem.ItemId = Convert.ToInt32(row["ItemID"]); indexItem.ModuleId = Convert.ToInt32(row["ModuleID"]); indexItem.ModuleTitle = row["ModuleTitle"].ToString(); indexItem.Title = row["Caption"].ToString(); indexItem.Content = row["Description"].ToString(); indexItem.QueryStringAddendum = "&ItemID" + row["ModuleID"].ToString() + "=" + row["ItemID"].ToString(); indexItem.CreatedUtc = Convert.ToDateTime(row["UploadDate"]); indexItem.LastModUtc = indexItem.CreatedUtc; // lookup publish dates foreach (PageModule pageModule in pageModules) { if (indexItem.ModuleId == pageModule.ModuleId) { indexItem.PublishBeginDate = pageModule.PublishBeginDate; indexItem.PublishEndDate = pageModule.PublishEndDate; } } mojoPortal.SearchIndex.IndexHelper.RebuildIndex(indexItem, indexPath); if (debugLog) { log.Debug("Indexed " + indexItem.Title); } } } catch (System.Data.Common.DbException ex) { log.Error(ex); } }
public void ProcessRequest(HttpContext context) { base.Initialize(context); if (!UserCanEditModule(ModuleId, Gallery.FeatureGuid)) { log.Info("User has no edit permission so returning 404"); Response.StatusCode = 404; return; } if (CurrentSite == null) { log.Info("CurrentSite is null so returning 404"); Response.StatusCode = 404; return; } if (CurrentUser == null) { log.Info("CurrentUser is null so returning 404"); Response.StatusCode = 404; return; } if (FileSystem == null) { log.Info("FileSystem is null so returning 404"); Response.StatusCode = 404; return; } if (Request.Files.Count == 0) { log.Info("Posted File Count is zero so returning 404"); Response.StatusCode = 404; return; } if (Request.Files.Count > GalleryConfiguration.MaxFilesToUploadAtOnce) { log.Info("Posted File Count is higher than allowed so returning 404"); Response.StatusCode = 404; return; } module = GetModule(ModuleId, Gallery.FeatureGuid); if (module == null) { log.Info("Module is null so returning 404"); Response.StatusCode = 404; return; } itemId = WebUtils.ParseInt32FromQueryString("ItemID", itemId); //if (Request.Form.Count > 0) //{ // string submittedContent = Server.UrlDecode(Request.Form.ToString()); // this gets the full content of the post // log.Info("submitted data: " + submittedContent); //} Hashtable moduleSettings = ModuleSettings.GetModuleSettings(ModuleId); config = new GalleryConfiguration(moduleSettings); string imageFolderPath; string fullSizeImageFolderPath; if (WebConfigSettings.ImageGalleryUseMediaFolder) { imageFolderPath = "~/Data/Sites/" + CurrentSite.SiteId.ToInvariantString() + "/media/GalleryImages/" + ModuleId.ToInvariantString() + "/"; } else { imageFolderPath = "~/Data/Sites/" + CurrentSite.SiteId.ToInvariantString() + "/GalleryImages/" + ModuleId.ToInvariantString() + "/"; } fullSizeImageFolderPath = imageFolderPath + "FullSizeImages/"; string thumbnailPath = imageFolderPath + "Thumbnails/"; context.Response.ContentType = "text/plain";//"application/json"; var r = new System.Collections.Generic.List <UploadFilesResult>(); JavaScriptSerializer js = new JavaScriptSerializer(); for (int f = 0; f < Request.Files.Count; f++) { HttpPostedFile file = Request.Files[f]; string ext = Path.GetExtension(file.FileName); if (SiteUtils.IsAllowedUploadBrowseFile(ext, WebConfigSettings.ImageFileExtensions)) { GalleryImage galleryImage; if ((itemId > -1) && (Request.Files.Count == 1)) { galleryImage = new GalleryImage(ModuleId, itemId); } else { galleryImage = new GalleryImage(ModuleId); } galleryImage.ModuleGuid = module.ModuleGuid; galleryImage.WebImageHeight = config.WebSizeHeight; galleryImage.WebImageWidth = config.WebSizeWidth; galleryImage.ThumbNailHeight = config.ThumbnailHeight; galleryImage.ThumbNailWidth = config.ThumbnailWidth; galleryImage.UploadUser = CurrentUser.Name; galleryImage.UserGuid = CurrentUser.UserGuid; string newFileName = Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles); string newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName); if (galleryImage.ImageFile == newFileName) { // an existing gallery image delete the old one FileSystem.DeleteFile(newImagePath); } else { // this is a new galleryImage instance, make sure we don't use the same file name as any other instance int i = 1; while (FileSystem.FileExists(VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName))) { newFileName = i.ToInvariantString() + newFileName; i += 1; } } newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName); using (Stream s = file.InputStream) { FileSystem.SaveFile(newImagePath, s, file.ContentType, true); } galleryImage.ImageFile = newFileName; galleryImage.WebImageFile = newFileName; galleryImage.ThumbnailFile = newFileName; galleryImage.Save(); GalleryHelper.ProcessImage(galleryImage, FileSystem, imageFolderPath, file.FileName, config.ResizeBackgroundColor); r.Add(new UploadFilesResult() { Thumbnail_url = WebUtils.ResolveServerUrl(thumbnailPath + newFileName), Name = newFileName, Length = file.ContentLength, Type = file.ContentType, ReturnValue = galleryImage.ItemId.ToInvariantString() }); } } var uploadedFiles = new { files = r.ToArray() }; var jsonObj = js.Serialize(uploadedFiles); context.Response.Write(jsonObj.ToString()); }
void btnUpload_Click(object sender, EventArgs e) { // as long as javascript is available this code should never execute // because the standard file input ir replaced by javascript and the file upload happens // at the service url /ImageGallery/upload.ashx // this is fallback implementation Module module = GetModule(moduleId, Gallery.FeatureGuid); if (module == null) { SiteUtils.RedirectToAccessDeniedPage(this); return; } SiteUser siteUser = SiteUtils.GetCurrentSiteUser(); try { if (uploader.HasFile) { string ext = Path.GetExtension(uploader.FileName); if (SiteUtils.IsAllowedUploadBrowseFile(ext, ".jpg|.gif|.png|.jpeg")) { GalleryImage galleryImage = new GalleryImage(this.moduleId); galleryImage.ModuleGuid = module.ModuleGuid; galleryImage.WebImageHeight = config.WebSizeHeight; galleryImage.WebImageWidth = config.WebSizeWidth; galleryImage.ThumbNailHeight = config.ThumbnailHeight; galleryImage.ThumbNailWidth = config.ThumbnailWidth; galleryImage.UploadUser = Context.User.Identity.Name; if (siteUser != null) { galleryImage.UserGuid = siteUser.UserGuid; } //string newFileName = Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles); string newFileName = Path.GetFileName(uploader.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles); string newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName); if (galleryImage.ImageFile == newFileName) { // an existing gallery image delete the old one fileSystem.DeleteFile(newImagePath); } else { // this is a new galleryImage instance, make sure we don't use the same file name as any other instance int i = 1; while (fileSystem.FileExists(VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName))) { newFileName = i.ToInvariantString() + newFileName; i += 1; } } newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName); using (Stream s = uploader.FileContent) { //fileSystem.SaveFile(newImagePath, s, uploader.FileContentType, true); fileSystem.SaveFile(newImagePath, s, IOHelper.GetMimeType(Path.GetExtension(ext).ToLower()), true); } galleryImage.ImageFile = newFileName; galleryImage.WebImageFile = newFileName; galleryImage.ThumbnailFile = newFileName; galleryImage.Save(); GalleryHelper.ProcessImage(galleryImage, fileSystem, imageFolderPath, uploader.FileName, config.ResizeBackgroundColor); } } WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl()); } catch (UnauthorizedAccessException ex) { lblError.Text = ex.Message; } catch (ArgumentException ex) { lblError.Text = ex.Message; } }
public async Task <Boolean> CreateNewGallery(IFormCollection formdata) { try { Gallery gallery = new Gallery { GalleryType = formdata["GalleryType"], Title = formdata["GalleryTitle"] }; int i = 0; string GalleryTitle = formdata["GalleryTitle"]; string GalleryType = formdata["GalleryType"]; string Username = "******"; DateTime LastUpdateTime = DateTime.Now; // First we will Create a new Gallery and get the Id of that gallery int id = await CreateGalleryID(gallery); // Create the Gallery Path string GalleryPath = Path.Combine(_env.WebRootPath + $"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}Gallery{Path.DirectorySeparatorChar}", id.ToString()); // Path of gallery that will be stored in datatbase - No need to add full path string dbImageGalleryPath = Path.Combine($"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}Gallery{Path.DirectorySeparatorChar}", id.ToString()); // Create the Directory/Folder on Server to Store new Gallery Images CreateDirectory(GalleryPath); // Get all the files and file-details that were uploaded foreach (var file in formdata.Files) { if (file.Length > 0) { // Set the extension, file name and path of the folder and file var extension = Path.GetExtension(file.FileName); // make the file name unique by adding date time Stamp var filename = DateTime.Now.ToString("yymmssfff"); // Create the file path var path = Path.Combine(GalleryPath, filename) + extension; // Path of Image that will be stored in datatbase - No need to add full path var dbImagePath = Path.Combine(dbImageGalleryPath + $"{Path.DirectorySeparatorChar}", filename) + extension; string ImageCaption = formdata["ImageCaption[]"][i]; string Description = formdata["ImageDescription[]"][i]; string AlternateText = formdata["ImageAlt[]"][i]; // Create the Image Model Object and assin values to its properties GalleryImage Image = new GalleryImage(); Image.GalleryId = id; Image.ImageUrl = dbImagePath; Image.Caption = ImageCaption; Image.Description = Description; Image.AlternateText = AlternateText; // Add Images detail to Images Table await _db.GalleryImages.AddAsync(Image); // Copy the uploaded images to Server - Uploads folder // Using - Once file is copied then we will close the stream. using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } i = i + 1; } } gallery.LastUpdated = LastUpdateTime; gallery.Title = GalleryTitle; gallery.GalleryType = GalleryType; gallery.Username = Username; gallery.GalleryUrl = dbImageGalleryPath; _db.Galleries.Update(gallery); await _db.SaveChangesAsync(); return(true); } catch (System.Exception) { return(false); } }