private bool btnOkClicked() { //User clicked 'Delete images'. Delete the hi-res images for the selected albums and images. string[] selectedItems = RetrieveUserSelections(); if (selectedItems.Length == 0) { // No images were selected. Inform user and exit function. string msg = String.Format(CultureInfo.CurrentCulture, "<p class='gsp_msgwarning'><span class='gsp_bold'>{0} </span>{1}</p>", Resources.GalleryServerPro.Task_No_Objects_Selected_Hdr, Resources.GalleryServerPro.Task_No_Objects_Selected_Dtl); phMsg.Controls.Clear(); phMsg.Controls.Add(new System.Web.UI.LiteralControl(msg)); return(false); } try { HelperFunctions.BeginTransaction(); // Convert the string array of IDs to integers. Also assign whether each is an album or media object. // (Determined by the first character of each id's string: a=album; m=media object) foreach (string selectedItem in selectedItems) { int id = Convert.ToInt32(selectedItem.Substring(1), CultureInfo.InvariantCulture); char idType = Convert.ToChar(selectedItem.Substring(0, 1), CultureInfo.InvariantCulture); // 'a' or 'm' if (idType == 'm') { Image image; try { image = (Image)Factory.LoadMediaObjectInstance(id, GalleryObjectType.Image, true); } catch (InvalidMediaObjectException) { continue; // Image may have been deleted by someone else, so just skip it. } image.DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(image); } if (idType == 'a') { DeleteHiResImagesFromAlbum(Factory.LoadAlbumInstance(id, true, true)); } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(true); }
/// <summary> /// Find, or create if necessary, the album corresponding to the specified directory and set it as the /// child of the parentAlbum parameter. /// </summary> /// <param name="directory">The directory for which to obtain a matching album object.</param> /// <param name="parentAlbum">The album that contains the album at the specified directory.</param> /// <returns>Returns an album object corresponding to the specified directory and having the specified /// parent album.</returns> private IAlbum SynchronizeDirectory(DirectoryInfo directory, IAlbum parentAlbum) { #region Parameter validation if (directory == null) { throw new ArgumentNullException("directory"); } if (parentAlbum == null) { throw new ArgumentNullException("parentAlbum"); } if (directory.Parent.FullName != parentAlbum.FullPhysicalPathOnDisk.TrimEnd(new char[] { Path.DirectorySeparatorChar })) { throw new ArgumentException("Error in SynchronizeDirectory()."); } #endregion IAlbum childAlbum; if (this._albumsFromDataStore.TryGetValue(directory.FullName, out childAlbum)) { // Found the album. Update properties. childAlbum.IsSynchronized = true; childAlbum.IsPrivate = (parentAlbum.IsPrivate ? true : childAlbum.IsPrivate); // Only set to private if parent is private childAlbum.RegenerateThumbnailOnSave = this.OverwriteThumbnail; } else { // No album exists for this directory. Create a new one. childAlbum = Factory.CreateAlbumInstance(); childAlbum.Parent = parentAlbum; string directoryName = directory.Name; childAlbum.Title = directoryName; //childAlbum.ThumbnailMediaObjectId = 0; // not needed childAlbum.DirectoryName = directoryName; childAlbum.FullPhysicalPathOnDisk = Path.Combine(parentAlbum.FullPhysicalPathOnDisk, directoryName); childAlbum.IsPrivate = parentAlbum.IsPrivate; } if (childAlbum.IsNew || childAlbum.HasChanges) { HelperFunctions.UpdateAuditFields(childAlbum, this._userName); childAlbum.Save(); } // Commit the transaction to the database for every 100 media objects that are processed. if ((this._synchStatus.CurrentFileIndex - this._lastTransactionCommitFileIndex) >= 100) { HelperFunctions.CommitTransaction(); HelperFunctions.BeginTransaction(); this._lastTransactionCommitFileIndex = this._synchStatus.CurrentFileIndex; } return(childAlbum); }
private Message saveCaptions() { // Iterate through all the textboxes, saving any captions that have changed. // The media object IDs are stored in a hidden input tag. HtmlTextArea ta; HtmlInputHidden gc; IGalleryObject mo; string newTitle, previousTitle; Message msg = Message.None; int maxTitleLength = GalleryServerPro.Configuration.ConfigManager.GetGalleryServerProConfigSection().DataStore.MediaObjectTitleLength; if (!IsUserAuthorized(SecurityActions.EditMediaObject)) { return(msg); } try { HelperFunctions.BeginTransaction(); // Loop through each item in the repeater control. If an item is checked, extract the ID. foreach (RepeaterItem rptrItem in rptr.Items) { ta = (HtmlTextArea)rptrItem.Controls[1]; // The <TEXTAREA> tag gc = (HtmlInputHidden)rptrItem.Controls[3]; // The hidden <input> tag // Retrieve new title. Since the Value property of <TEXTAREA> HTML ENCODEs the text, // and we want to store the actual text, we must decode to get back to the original. newTitle = Util.HtmlDecode(ta.Value); mo = Factory.LoadMediaObjectInstance(Convert.ToInt32(gc.Value, CultureInfo.InvariantCulture)); previousTitle = mo.Title; mo.Title = Util.CleanHtmlTags(newTitle); if (mo.Title.Length > maxTitleLength) { // This caption exceeds the maximum allowed length. Set message ID so that user // can be notified. This caption will be truncated when saved to the databse. msg = Message.OneOrMoreCaptionsExceededMaxLength; } if (mo.Title != previousTitle) { GalleryObjectController.SaveGalleryObject(mo); } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(msg); }
private bool btnOkClicked() { // User clicked 'Delete selected objects'. string[] selectedItems = RetrieveUserSelections(); if (selectedItems.Length == 0) { // No objects were selected. Inform user and exit function. ucUserMessage.MessageTitle = Resources.GalleryServerPro.Task_No_Objects_Selected_Hdr; ucUserMessage.MessageDetail = Resources.GalleryServerPro.Task_No_Objects_Selected_Dtl; ucUserMessage.Visible = true; return(false); } if (!ValidateBeforeObjectDeletion(selectedItems)) { return(false); } try { HelperFunctions.BeginTransaction(); // Convert the string array of IDs to integers. Also assign whether each is an album or media object. // (Determined by the first character of each id's string: a=album; m=media object) foreach (string selectedItem in selectedItems) { int id = Convert.ToInt32(selectedItem.Substring(1), CultureInfo.InvariantCulture); char idType = Convert.ToChar(selectedItem.Substring(0, 1), CultureInfo.InvariantCulture); // 'a' or 'm' if (idType == 'm') { IGalleryObject go = Factory.LoadMediaObjectInstance(id); go.Delete(); } if (idType == 'a') { IAlbum go = Factory.LoadAlbumInstance(id, false); AlbumController.DeleteAlbum(go); } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(true); }
private void SaveCaptions() { // Iterate through all the textboxes, saving any captions that have changed. // The media object IDs are stored in a hidden input tag. HtmlTextArea ta; HtmlInputHidden gc; IGalleryObject mo; if (!IsUserAuthorized(SecurityActions.EditMediaObject)) { return; } try { HelperFunctions.BeginTransaction(); // Loop through each item in the repeater control. If an item is checked, extract the ID. foreach (RepeaterItem rptrItem in rptr.Items) { ta = (HtmlTextArea)rptrItem.Controls[1]; // The <TEXTAREA> tag gc = (HtmlInputHidden)rptrItem.Controls[3]; // The hidden <input> tag // Retrieve new title. Since the Value property of <TEXTAREA> HTML ENCODEs the text, // and we want to store the actual text, we must decode to get back to the original. string newTitle = Utils.HtmlDecode(ta.Value); try { mo = Factory.LoadMediaObjectInstance(Convert.ToInt32(gc.Value, CultureInfo.InvariantCulture), true); } catch (InvalidMediaObjectException) { continue; // Gallery object may have been deleted by someone else, so just skip it. } string previousTitle = mo.Title; mo.Title = Utils.CleanHtmlTags(newTitle, GalleryId); if (mo.Title != previousTitle) { GalleryObjectController.SaveGalleryObject(mo); } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); }
private int RotateImages() { // Rotate any images on the hard drive according to the user's wish. var returnValue = int.MinValue; var imagesToRotate = RetrieveUserSelections(); try { HelperFunctions.BeginTransaction(); foreach (var kvp in imagesToRotate) { IGalleryObject mo; try { mo = Factory.LoadMediaObjectInstance(kvp.Key, true); } catch (InvalidMediaObjectException) { continue; // Image may have been deleted by someone else, so just skip it. } IGalleryObjectMetadataItem metaOrientation; if (kvp.Value == MediaObjectRotation.Rotate0 && !mo.MetadataItems.TryGetMetadataItem(MetadataItemName.Orientation, out metaOrientation)) { continue; } mo.Rotation = kvp.Value; try { GalleryObjectController.SaveGalleryObject(mo); } catch (UnsupportedImageTypeException) { returnValue = (int)MessageType.CannotRotateInvalidImage; } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(returnValue); }
private void btnOkClicked() { object formFieldGalleryObjectIds = Request.Form["goIds"]; if ((formFieldGalleryObjectIds == null) || (String.IsNullOrEmpty(formFieldGalleryObjectIds.ToString()))) { // The hidden field will be empty when no changes have been made. Just return. return; } string strGoIds = formFieldGalleryObjectIds.ToString(); string[] goIds = strGoIds.Split(new char[] { ',' }); // User wants to persist the reordering changes to the data store. As the user has been dragging and dropping objects // in their new locations, server-side code has been keeping the CurrentSequences property synchronized with the order // of the objects in the user's browser. Now we want to loop through those objects and update the Sequence property // of each one according to it's position within the list. IGalleryObjectCollection galleryObjects = this.GetAlbum().GetChildGalleryObjects(true); int newSequence = 0; try { HelperFunctions.BeginTransaction(); foreach (string galleryObjectIdentifier in goIds) { // Parse the string into its 2 parts: (a) The first character is either "a" (for album) or "m" (for media object); // (b) The rest of the string is the ID for the album of media object. Ex: "a132" is an album with ID=132. GalleryObjectType galleryObjectType = (galleryObjectIdentifier.Substring(0, 1) == "a" ? GalleryObjectType.Album : GalleryObjectType.MediaObject); int galleryObjectId = Convert.ToInt32(galleryObjectIdentifier.Substring(1), CultureInfo.InvariantCulture); IGalleryObject matchingGalleryObject = galleryObjects.FindById(galleryObjectId, galleryObjectType); if ((matchingGalleryObject != null) && (matchingGalleryObject.Sequence != newSequence)) { matchingGalleryObject.Sequence = newSequence; GalleryObjectController.SaveGalleryObject(matchingGalleryObject); } newSequence++; } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); }
private Message saveCaptions() { // Iterate through all the textboxes, saving any captions that have changed. // The media object IDs are stored in a hidden input tag. HtmlInputText ta; HtmlTextArea tdesc; HtmlInputHidden gc; string previousTitle, previousDescription; Message msg = Message.None; if (!IsUserAuthorized(SecurityActions.EditMediaObject)) { return(msg); } try { HelperFunctions.BeginTransaction(); foreach (RepeaterItem rptrItem in rptr.Items) { ta = (HtmlInputText)rptrItem.Controls[1]; // The <input TEXT> tag tdesc = (HtmlTextArea)rptrItem.Controls[3]; // The <TEXTAREA> tag gc = (HtmlInputHidden)rptrItem.Controls[5]; // The hidden <input> tag SueetieMediaAlbum _sueetieMediaAlbum = SueetieMedia.GetSueetieMediaAlbum(CurrentSueetieGalleryID, Convert.ToInt32(gc.Value)); previousDescription = _sueetieMediaAlbum.AlbumDescription; previousTitle = _sueetieMediaAlbum.AlbumTitle; _sueetieMediaAlbum.AlbumTitle = Util.HtmlDecode(ta.Value); _sueetieMediaAlbum.AlbumDescription = tdesc.Value; if (_sueetieMediaAlbum.AlbumTitle != previousTitle || _sueetieMediaAlbum.AlbumDescription != previousDescription) { SueetieMedia.UpdateSueetieMediaAlbum(_sueetieMediaAlbum); } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); SueetieMedia.ClearSueetieMediaAlbumListCache(CurrentSueetieGalleryID); return(msg); }
private int RotateImages() { // Rotate any images on the hard drive according to the user's wish. int returnValue = int.MinValue; Dictionary <int, RotateFlipType> imagesToRotate = retrieveUserSelections(); try { HelperFunctions.BeginTransaction(); foreach (KeyValuePair <int, RotateFlipType> kvp in imagesToRotate) { IGalleryObject image; try { image = Factory.LoadMediaObjectInstance(kvp.Key, GalleryObjectType.Image, true); } catch (InvalidMediaObjectException) { continue; // Image may have been deleted by someone else, so just skip it. } image.Rotation = kvp.Value; try { GalleryObjectController.SaveGalleryObject(image); } catch (UnsupportedImageTypeException) { returnValue = (int)Message.CannotRotateInvalidImage; } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(returnValue); }
private void UpdateUserAlbumProfileSetting(bool enableUserAlbum) { HelperFunctions.BeginTransaction(); try { foreach (IUserAccount user in UserController.GetAllUsers()) { IUserProfile profile = ProfileController.GetProfile(user.UserName); profile.GetGalleryProfile(GalleryId).EnableUserAlbum = enableUserAlbum; ProfileController.SaveProfile(profile); } HelperFunctions.CommitTransaction(); HelperFunctions.PurgeCache(); } catch { HelperFunctions.RollbackTransaction(); throw; } }
private int rotateImages() { // Rotate any images on the hard drive according to the user's wish. int returnValue = int.MinValue; Dictionary <int, RotateFlipType> imagesToRotate = retrieveUserSelections(); try { HelperFunctions.BeginTransaction(); foreach (KeyValuePair <int, RotateFlipType> kvp in imagesToRotate) { IGalleryObject image = Factory.LoadImageInstance(kvp.Key); image.Rotation = kvp.Value; try { GalleryObjectController.SaveGalleryObject(image); } catch (UnsupportedImageTypeException) { returnValue = (int)Message.CannotRotateInvalidImage; } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(returnValue); }
/// <summary> /// Move or copy the objects. An exception is thrown if the user does not have the required permission or is /// trying to transfer an object to itself. /// </summary> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on /// user does not belong to a role that authorizes the moving or copying.</exception> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.CannotTransferAlbumToNestedDirectoryException"> /// Thrown when the user tries to move or copy an album to one of its children albums.</exception> private void TransferObjects() { #region Get list of objects to move or copy string[] galleryObjectIds = (string[])ViewState["ids"]; // Convert the string array of IDs to integers. Also assign whether each is an album or media object. // (Determined by the first character of each ids string: a=album; m=media object) int id; char idType; IGalleryObjectCollection objectsToMoveOrCopy = new GalleryObjectCollection(); for (int i = 0; i < galleryObjectIds.Length; i++) { id = Convert.ToInt32(galleryObjectIds[i].Substring(1), CultureInfo.InvariantCulture); idType = Convert.ToChar(galleryObjectIds[i].Substring(0, 1), CultureInfo.InvariantCulture); if (idType == 'a') { objectsToMoveOrCopy.Add(Factory.LoadAlbumInstance(id, false)); } else if (idType == 'm') { // Grab a reference to the media object through the base page's album instead of using Factory.LoadMediaObjectInstance(). // This causes the base page's album object to have an accurate state of the child objects so that when we assign the // thumbnail object later in this page life cycle, it works correctly. objectsToMoveOrCopy.Add(this.GetAlbum().GetChildGalleryObjects(GalleryObjectType.MediaObject).FindById(id, GalleryObjectType.MediaObject)); } else { throw new GalleryServerPro.ErrorHandler.CustomExceptions.WebException("Invalid object identifier in method transferObjects(). Expected: 'a' or 'm'. Found: " + idType.ToString()); } } #endregion #region Validate (throws exception if it doesn't validate) ValidateObjectsCanBeMovedOrCopied(objectsToMoveOrCopy); #endregion try { HelperFunctions.BeginTransaction(); #region Move or copy each object foreach (IGalleryObject galleryObject in objectsToMoveOrCopy) { IAlbum album = galleryObject as IAlbum; if (album == null) { if (this.TransType == TransferType.Move) { MoveMediaObject(galleryObject); } else { CopyMediaObject(galleryObject); } } else { if (this.TransType == TransferType.Move) { MoveAlbum(album); } else { CopyAlbum(album); } } } #endregion HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } }
/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating under full trust. In this case, /// the ComponentArt Upload control is used. The logic is nearly identical to that in AddUploadedFilesLessThanFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> /// <param name="files">The files to add to the gallery.</param> private void AddUploadedFilesForFullTrust(UploadedFileInfoCollection files) { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); UploadedFileInfo[] fileInfos = new UploadedFileInfo[files.Count]; files.CopyTo(fileInfos, 0); Array.Reverse(fileInfos); foreach (UploadedFileInfo file in fileInfos) { if (String.IsNullOrEmpty(file.FileName)) { continue; } if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. lock (file) { if (File.Exists(file.TempFileName)) { using (ZipUtility zip = new ZipUtility(Util.UserName, GetGalleryServerRolesForUser())) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.GetStream(), this.GetAlbum(), chkDiscardOriginalImage.Checked)); } } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } // Sueetie Modified - Add contents of ZIP file - All List <SueetieMediaObject> sueetieMediaObjects = SueetieMedia.GetSueetieMediaUpdateList(this.GetAlbumId()); int i = 0; foreach (SueetieMediaObject _sueetieMediaObject in sueetieMediaObjects) { int _moid = _sueetieMediaObject.MediaObjectID; IGalleryObject mo = Factory.LoadMediaObjectInstance(_moid); SueetieContent sueetieContent = new SueetieContent { SourceID = _sueetieMediaObject.MediaObjectID, ContentTypeID = MediaHelper.ConvertContentType(mo.MimeType.TypeCategory), ApplicationID = (int)SueetieApplications.Current.ApplicationID, UserID = _sueetieMediaObject.SueetieUserID, DateTimeCreated = mo.DateAdded, IsRestricted = mo.IsPrivate, Permalink = MediaHelper.SueetieMediaObjectUrl(_moid, this.GalleryId) }; // Add Sueetie-specific data to Sueetie_gs_MediaObject _sueetieMediaObject.ContentTypeID = MediaHelper.ConvertContentType(mo.MimeType.TypeCategory); _sueetieMediaObject.AlbumID = this.GetAlbum().Id; _sueetieMediaObject.InDownloadReport = false; SueetieMedia.CreateSueetieMediaObject(_sueetieMediaObject); SueetieCommon.AddSueetieContent(sueetieContent); i++; } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); lock (file) { if (File.Exists(file.TempFileName)) { file.SaveAs(filepath); } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } try { IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum()); GalleryObjectController.SaveGalleryObject(go); if ((chkDiscardOriginalImage.Checked) && (go is Business.Image)) { ((Business.Image)go).DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(go); } // Sueetie Modified - Add mediaobject to Sueetie_Content - Single File SueetieContent sueetieContent = new SueetieContent { SourceID = go.Id, ContentTypeID = MediaHelper.ConvertContentType(go.MimeType.TypeCategory), ApplicationID = (int)SueetieApplications.Current.ApplicationID, UserID = CurrentSueetieUserID, IsRestricted = this.GetAlbum().IsPrivate, Permalink = MediaHelper.SueetieMediaObjectUrl(go.Id, this.GalleryId) }; SueetieCommon.AddSueetieContent(sueetieContent); // Add Sueetie-specific data to Sueetie_gs_MediaObject SueetieMediaObject _sueetieMediaObject = new SueetieMediaObject(); _sueetieMediaObject.MediaObjectID = go.Id; _sueetieMediaObject.ContentTypeID = MediaHelper.ConvertContentType(go.MimeType.TypeCategory); _sueetieMediaObject.AlbumID = this.GetAlbum().Id; _sueetieMediaObject.InDownloadReport = false; SueetieMedia.CreateSueetieMediaObject(_sueetieMediaObject); SueetieMediaAlbum sueetieAlbum = SueetieMedia.GetSueetieMediaAlbum(this.GetAlbum().Id); if (CurrentSueetieGallery.IsLogged) { SueetieLogs.LogUserEntry((UserLogCategoryType)sueetieAlbum.AlbumMediaCategoryID, sueetieAlbum.ContentID, CurrentSueetieUserID); } } catch (UnsupportedMediaObjectTypeException ex) { try { File.Delete(filepath); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message)); } #endregion } } SueetieMedia.ClearMediaPhotoListCache(0); SueetieMedia.ClearSueetieMediaObjectListCache(this.CurrentSueetieGalleryID); HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Delete the uploaded temporary files, as by this time they have been saved to the destination directory. foreach (UploadedFileInfo file in files) { try { System.IO.File.Delete(file.TempFileName); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance } // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }
/// <summary> /// In certain cases, the web-based installer creates a text file in the App Data directory that is meant as a signal to this /// code that additional setup steps are required. If this file is found, carry out the additional actions. This file is /// created in the SetFlagForMembershipConfiguration() method of pages\install.ascx.cs. /// </summary> internal static void ProcessInstallerFile() { string filePath = Path.Combine(AppSetting.Instance.PhysicalApplicationPath, Path.Combine(GlobalConstants.AppDataDirectory, GlobalConstants.InstallerFileName)); if (!File.Exists(filePath)) { return; } string adminUserName; string adminPwd; string adminEmail; using (StreamReader sw = File.OpenText(filePath)) { adminUserName = sw.ReadLine(); adminPwd = sw.ReadLine(); adminEmail = sw.ReadLine(); } HelperFunctions.BeginTransaction(); #region Create the Sys Admin role. // Create the Sys Admin role. If it already exists, make sure it has AllowAdministerSite permission. string sysAdminRoleName = Resources.GalleryServerPro.Installer_Sys_Admin_Role_Name; if (!RoleController.RoleExists(sysAdminRoleName)) { RoleController.CreateRole(sysAdminRoleName); } IGalleryServerRole role = Factory.LoadGalleryServerRole(sysAdminRoleName); if (role == null) { role = Factory.CreateGalleryServerRoleInstance(sysAdminRoleName, true, true, true, true, true, true, true, true, true, true, false); role.RootAlbumIds.Add(Factory.LoadRootAlbumInstance().Id); role.Save(); } else { // Role already exists. Make sure it has Sys Admin permission. if (!role.AllowAdministerSite) { role.AllowAdministerSite = true; role.Save(); } } #endregion #region Create the Sys Admin user account. // Create the Sys Admin user account. Will throw an exception if the name is already in use. try { CreateUser(adminUserName, adminPwd, adminEmail); } catch (MembershipCreateUserException ex) { if (ex.StatusCode == MembershipCreateStatus.DuplicateUserName) { // The user already exists. Update the password and email address to our values. UserEntity user = GetUser(adminUserName, true); ChangePassword(user.UserName, GetPassword(user.UserName), adminPwd); user.Email = adminEmail; UpdateUser(user); } } // Add the Sys Admin user to the Sys Admin role. if (!RoleController.IsUserInRole(adminUserName, sysAdminRoleName)) { RoleController.AddUserToRole(adminUserName, sysAdminRoleName); } #endregion #region Create sample album and image if (!Config.GetCore().MediaObjectPathIsReadOnly) { DateTime currentTimestamp = DateTime.Now; IAlbum sampleAlbum = null; foreach (IAlbum album in Factory.LoadRootAlbumInstance().GetChildGalleryObjects(GalleryObjectType.Album)) { if (album.DirectoryName == "Samples") { sampleAlbum = album; break; } } if (sampleAlbum == null) { // Create sample album. sampleAlbum = Factory.CreateAlbumInstance(); sampleAlbum.Parent = Factory.LoadRootAlbumInstance(); sampleAlbum.Title = "Samples"; sampleAlbum.DirectoryName = "Samples"; sampleAlbum.Summary = "Welcome to Gallery Server Pro!"; sampleAlbum.CreatedByUserName = adminUserName; sampleAlbum.DateAdded = currentTimestamp; sampleAlbum.LastModifiedByUserName = adminUserName; sampleAlbum.DateLastModified = currentTimestamp; sampleAlbum.Save(); } // Look for sample image in sample album. IGalleryObject sampleImage = null; foreach (IGalleryObject image in sampleAlbum.GetChildGalleryObjects(GalleryObjectType.Image)) { if (image.Original.FileName == Constants.SAMPLE_IMAGE_FILENAME) { sampleImage = image; break; } } if (sampleImage == null) { // Sample image not found. Pull image from assembly, save to disk, and create a media object from it. string sampleDirPath = Path.Combine(AppSetting.Instance.MediaObjectPhysicalPath, sampleAlbum.DirectoryName); string sampleImageFilename = HelperFunctions.ValidateFileName(sampleDirPath, Constants.SAMPLE_IMAGE_FILENAME); string sampleImageFilepath = Path.Combine(sampleDirPath, sampleImageFilename); System.Reflection.Assembly asm = Assembly.GetExecutingAssembly(); using (Stream stream = asm.GetManifestResourceStream(String.Concat("GalleryServerPro.Web.gs.images.", Constants.SAMPLE_IMAGE_FILENAME))) { if (stream != null) { BinaryWriter bw = new BinaryWriter(File.Create(sampleImageFilepath)); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); bw.Write(buffer); bw.Flush(); bw.Close(); } } if (File.Exists(sampleImageFilepath)) { IGalleryObject image = Factory.CreateImageInstance(new FileInfo(sampleImageFilepath), sampleAlbum); image.Title = "Margaret, Skyler and Roger Martin (December 2008)"; image.CreatedByUserName = adminUserName; image.DateAdded = currentTimestamp; image.LastModifiedByUserName = adminUserName; image.DateLastModified = currentTimestamp; image.Save(); } } } #endregion HelperFunctions.CommitTransaction(); HelperFunctions.PurgeCache(); File.Delete(filePath); }
private Message saveCaptions() { // Iterate through all the textboxes, saving any captions that have changed. // The media object IDs are stored in a hidden input tag. HtmlInputText ta; HtmlTextArea tdesc; HtmlInputHidden gc; IGalleryObject mo; string newTitle, previousTitle, previousTags, previousDescription; Message msg = Message.None; if (!IsUserAuthorized(SecurityActions.EditMediaObject)) { return(msg); } try { HelperFunctions.BeginTransaction(); // Loop through each item in the repeater control. If an item is checked, extract the ID. foreach (RepeaterItem rptrItem in rptr.Items) { ta = (HtmlInputText)rptrItem.Controls[1]; // The <input TEXT> tag tdesc = (HtmlTextArea)rptrItem.Controls[3]; // The <TEXTAREA> tag gc = (HtmlInputHidden)rptrItem.Controls[5]; // The hidden <input> tag // Retrieve new title. Since the Value property of <TEXTAREA> HTML ENCODEs the text, // and we want to store the actual text, we must decode to get back to the original. newTitle = Util.HtmlDecode(ta.Value); mo = Factory.LoadMediaObjectInstance(Convert.ToInt32(gc.Value, CultureInfo.InvariantCulture), true); previousTitle = mo.Title; mo.Title = Util.RemoveHtmlTags(newTitle); if (mo.Title != previousTitle) { GalleryObjectController.SaveGalleryObject(mo); } SueetieMediaObject _sueetieMediaObject = SueetieMedia.GetSueetieMediaObject(CurrentSueetieGalleryID, mo.Id); previousDescription = _sueetieMediaObject.MediaObjectDescription; _sueetieMediaObject.MediaObjectDescription = tdesc.Value; if (_sueetieMediaObject.MediaObjectTitle != newTitle || _sueetieMediaObject.MediaObjectDescription != previousDescription) { SueetieMedia.UpdateSueetieMediaObject(_sueetieMediaObject); } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); SueetieMedia.ClearSueetieMediaObjectListCache(CurrentSueetieGalleryID); return(msg); }
private bool btnOkClicked() { // User clicked 'Delete selected objects'. string[] selectedItems = RetrieveUserSelections(); if (selectedItems.Length == 0) { // No objects were selected. Inform user and exit function. ucUserMessage.MessageTitle = Resources.GalleryServerPro.Task_No_Objects_Selected_Hdr; ucUserMessage.MessageDetail = Resources.GalleryServerPro.Task_No_Objects_Selected_Dtl; ucUserMessage.Visible = true; return(false); } if (!ValidateBeforeObjectDeletion(selectedItems)) { return(false); } try { HelperFunctions.BeginTransaction(); // Convert the string array of IDs to integers. Also assign whether each is an album or media object. // (Determined by the first character of each id's string: a=album; m=media object) foreach (string selectedItem in selectedItems) { int id = Convert.ToInt32(selectedItem.Substring(1), CultureInfo.InvariantCulture); char idType = Convert.ToChar(selectedItem.Substring(0, 1), CultureInfo.InvariantCulture); // 'a' or 'm' if (idType == 'm') { IGalleryObject go; try { go = Factory.LoadMediaObjectInstance(id); } catch (InvalidMediaObjectException) { continue; // Media object may have been deleted by someone else, so just skip it. } if (UserCanDeleteMediaObject) { if (chkDeleteDbRecordsOnly.Checked) { go.DeleteFromGallery(); } else { go.Delete(); } } } if (idType == 'a') { IAlbum album; try { album = AlbumController.LoadAlbumInstance(id, false); } catch (InvalidAlbumException) { continue; // Album may have been deleted by someone else, so just skip it. } if (UserCanDeleteChildAlbum) { AlbumController.DeleteAlbum(album, !chkDeleteDbRecordsOnly.Checked); } } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } HelperFunctions.PurgeCache(); return(true); }
/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating under full trust. In this case, /// the ComponentArt Upload control is used. The logic is nearly identical to that in AddUploadedFilesLessThanFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> /// <param name="files">The files to add to the gallery.</param> private void AddUploadedFilesForFullTrust(UploadedFileInfoCollection files) { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); UploadedFileInfo[] fileInfos = new UploadedFileInfo[files.Count]; files.CopyTo(fileInfos, 0); Array.Reverse(fileInfos); foreach (UploadedFileInfo file in fileInfos) { if (String.IsNullOrEmpty(file.FileName)) { continue; } if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. lock (file) { if (File.Exists(file.TempFileName)) { using (ZipUtility zip = new ZipUtility(Util.UserName, RoleController.GetGalleryServerRolesForUser())) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.GetStream(), this.GetAlbum(), chkDiscardOriginalImage.Checked)); } } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); #if DEBUG TechInfoSystems.TracingTools.Tools.MarkSpot(string.Format(CultureInfo.CurrentCulture, "Attempting to move file {0} to {1}...", file.FileName, filepath)); #endif lock (file) { if (File.Exists(file.TempFileName)) { file.SaveAs(filepath); } else { // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on // to the next one. this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg)); continue; // Skip to the next file. } } try { IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum()); GalleryObjectController.SaveGalleryObject(go); if ((chkDiscardOriginalImage.Checked) && (go is Business.Image)) { ((Business.Image)go).DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(go); } } catch (UnsupportedMediaObjectTypeException ex) { try { File.Delete(filepath); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message)); } #endregion } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Delete the uploaded temporary files, as by this time they have been saved to the destination directory. foreach (UploadedFileInfo file in files) { try { System.IO.File.Delete(file.TempFileName); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance } // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }
/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating at lesss than full trust. In this case, /// the ASP.NET FileUpload control is used. The logic is nearly identical to that in AddUploadedFilesForFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> private void AddUploadedFilesLessThanFullTrust() { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); for (int i = 0; i < 5; i++) { FileUpload file = (FileUpload)phUpload.FindControl("fuUpload" + i); if (!file.HasFile) { continue; } if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. // Extract the files from the zipped file. using (ZipUtility zip = new ZipUtility(Util.UserName, RoleController.GetGalleryServerRolesForUser())) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.FileContent, this.GetAlbum(), chkDiscardOriginalImage.Checked)); } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); #if DEBUG TechInfoSystems.TracingTools.Tools.MarkSpot(string.Format(CultureInfo.CurrentCulture, "Attempting to move file {0} to {1}...", file.FileName, filepath)); #endif file.SaveAs(filepath); try { IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum()); GalleryObjectController.SaveGalleryObject(go); if ((chkDiscardOriginalImage.Checked) && (go is Business.Image)) { ((Business.Image)go).DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(go); } } catch (UnsupportedMediaObjectTypeException ex) { try { File.Delete(filepath); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message)); } #endregion } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }
/// <summary> /// Find, or create if necessary, the album corresponding to the specified directory and set it as the /// child of the parentAlbum parameter. /// </summary> /// <param name="directory">The directory for which to obtain a matching album object.</param> /// <param name="parentAlbum">The album that contains the album at the specified directory.</param> /// <returns>Returns an album object corresponding to the specified directory and having the specified /// parent album.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="directory" /> or <paramref name="parentAlbum" /> is null.</exception> /// <exception cref="ArgumentException">Thrown when </exception> /// <exception cref="ArgumentException">Thrown when the full directory path of the parent of <paramref name="directory" /> does not match the /// directory path of <paramref name="parentAlbum" />.</exception> private IAlbum SynchronizeDirectory(DirectoryInfo directory, IAlbum parentAlbum) { #region Parameter validation if (directory == null) { throw new ArgumentNullException("directory"); } if (parentAlbum == null) { throw new ArgumentNullException("parentAlbum"); } if (!directory.Parent.FullName.Equals(parentAlbum.FullPhysicalPathOnDisk.TrimEnd(new char[] { Path.DirectorySeparatorChar }), StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException(String.Format("Error in SynchronizeDirectory(). directory.Parent.FullName='{0}'; parentAlbum.FullPhysicalPathOnDisk='{1}'", directory.Parent.FullName, parentAlbum.FullPhysicalPathOnDisk.TrimEnd(new char[] { Path.DirectorySeparatorChar }))); } #endregion var childAlbum = (IAlbum)parentAlbum.GetChildGalleryObjects(GalleryObjectType.Album) .FirstOrDefault(a => a.FullPhysicalPathOnDisk == directory.FullName); if (childAlbum != null) { // Found the album. Update properties. childAlbum.IsPrivate = (parentAlbum.IsPrivate ? true : childAlbum.IsPrivate); // Only set to private if parent is private childAlbum.RegenerateThumbnailOnSave = RebuildThumbnail; } else { // No album exists for this directory. Create a new one. childAlbum = Factory.CreateEmptyAlbumInstance(parentAlbum.GalleryId); childAlbum.Parent = parentAlbum; string directoryName = directory.Name; childAlbum.Title = directoryName; //childAlbum.ThumbnailMediaObjectId = 0; // not needed childAlbum.DirectoryName = directoryName; childAlbum.FullPhysicalPathOnDisk = Path.Combine(parentAlbum.FullPhysicalPathOnDisk, directoryName); childAlbum.IsPrivate = parentAlbum.IsPrivate; } childAlbum.IsSynchronized = true; if (childAlbum.IsNew || childAlbum.HasChanges) { HelperFunctions.UpdateAuditFields(childAlbum, UserName); childAlbum.Save(); } // Commit the transaction to the database for every 100 media objects that are processed. if ((_synchStatus.CurrentFileIndex - _lastTransactionCommitFileIndex) >= 100) { HelperFunctions.CommitTransaction(); HelperFunctions.BeginTransaction(); _lastTransactionCommitFileIndex = _synchStatus.CurrentFileIndex; } return(childAlbum); }
/// <summary> /// Adds the uploaded files to the gallery. This method is called when the application is operating at lesss than full trust. In this case, /// the ASP.NET FileUpload control is used. The logic is nearly identical to that in AddUploadedFilesForFullTrust - the only /// differences are syntax differences arising from the different file upload control. /// </summary> private void AddUploadedFilesLessThanFullTrust() { // Clear the list of hash keys so we're starting with a fresh load from the data store. try { MediaObjectHashKeys.Clear(); string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk; HelperFunctions.BeginTransaction(); for (int i = 0; i < 5; i++) { FileUpload file = (FileUpload)phUpload.FindControl("fuUpload" + i); if (!file.HasFile) { continue; } if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked)) { #region Extract the files from the zipped file. // Extract the files from the zipped file. using (ZipUtility zip = new ZipUtility(Util.UserName, GetGalleryServerRolesForUser())) { this._skippedFiles.AddRange(zip.ExtractZipFile(file.FileContent, this.GetAlbum(), chkDiscardOriginalImage.Checked)); } #endregion } else { #region Add the file string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName); string filepath = Path.Combine(albumPhysicalPath, filename); file.SaveAs(filepath); try { IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum()); // Sueetie Modified - Fix Blank Title on individual uploads if (go.Title.Trim().Length == 0) { go.Title = go.Original.FileName; } GalleryObjectController.SaveGalleryObject(go); if ((chkDiscardOriginalImage.Checked) && (go is Business.Image)) { ((Business.Image)go).DeleteHiResImage(); GalleryObjectController.SaveGalleryObject(go); } // Sueetie Modified - Add mediaobject to Sueetie_Content - Single File SueetieContent sueetieContent = new SueetieContent { SourceID = go.Id, ContentTypeID = MediaHelper.ConvertContentType(go.MimeType.TypeCategory), ApplicationID = (int)SueetieApplications.Current.ApplicationID, UserID = CurrentSueetieUserID, IsRestricted = this.GetAlbum().IsPrivate, Permalink = MediaHelper.SueetieMediaObjectUrl(go.Id, this.GalleryId) }; SueetieCommon.AddSueetieContent(sueetieContent); // Add Sueetie-specific data to Sueetie_gs_MediaObject SueetieMediaObject _sueetieMediaObject = new SueetieMediaObject(); _sueetieMediaObject.MediaObjectID = go.Id; _sueetieMediaObject.ContentTypeID = MediaHelper.ConvertContentType(go.MimeType.TypeCategory); _sueetieMediaObject.AlbumID = this.GetAlbum().Id; _sueetieMediaObject.InDownloadReport = false; SueetieMedia.CreateSueetieMediaObject(_sueetieMediaObject); SueetieMediaAlbum sueetieAlbum = SueetieMedia.GetSueetieMediaAlbum(this.GetAlbum().Id); if (CurrentSueetieGallery.IsLogged) { SueetieLogs.LogUserEntry((UserLogCategoryType)sueetieAlbum.AlbumMediaCategoryID, sueetieAlbum.ContentID, CurrentSueetieUserID); } SueetieMedia.ClearMediaPhotoListCache(0); SueetieMedia.ClearSueetieMediaObjectListCache(this.CurrentSueetieGalleryID); } catch (UnsupportedMediaObjectTypeException ex) { try { File.Delete(filepath); } catch (UnauthorizedAccessException) { } // Ignore an error; the file will end up getting deleted during cleanup maintenance this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message)); } #endregion } } HelperFunctions.CommitTransaction(); } catch { HelperFunctions.RollbackTransaction(); throw; } finally { // Clear the list of hash keys to free up memory. MediaObjectHashKeys.Clear(); HelperFunctions.PurgeCache(); } }