private static AlbumDto ConfigureAlbumTable(int galleryId, GspContext ctx) { // Create the root album if necessary. var rootAlbumDto = (from a in ctx.Albums where a.FKGalleryId == galleryId && a.AlbumParentId == 0 select a).FirstOrDefault(); if (rootAlbumDto == null) { rootAlbumDto = new AlbumDto { FKGalleryId = galleryId, AlbumParentId = 0, Title = "All albums", DirectoryName = String.Empty, Summary = "Welcome to Gallery Server Pro!", ThumbnailMediaObjectId = 0, Seq = 0, DateAdded = DateTime.Now, CreatedBy = "System", LastModifiedBy = "System", DateLastModified = DateTime.Now, OwnedBy = String.Empty, OwnerRoleName = String.Empty, IsPrivate = false }; ctx.Albums.Add(rootAlbumDto); ctx.SaveChanges(); } return(rootAlbumDto); }
/// <summary> /// Gets the data schema version of the database. May return null. Examples: "2.3.3421", "2.4.1" /// </summary> /// <returns>Returns a <see cref="string"/> containing the database version.</returns> internal static string GetDataSchemaVersionString() { using (GspContext ctx = new GspContext()) { return((from a in ctx.AppSettings where a.SettingName == "DataSchemaVersion" select a.SettingValue).FirstOrDefault()); } }
private static void ConfigureMimeTypeGalleryTable(int galleryId, GspContext ctx) { // Create a new set of gallery MIME types (do nothing if already present). bool mimeTypeGalleryTableHasRecords = ((from mtg in ctx.MimeTypeGalleries where mtg.FKGalleryId == galleryId select mtg).Count() > 0); string sql = @" INSERT INTO [gs_MimeTypeGallery] (FKGalleryId, FKMimeTypeId, IsEnabled) SELECT @GalleryId, mt.MimeTypeId, 0 FROM [gs_MimeType] mt WHERE mt.MimeTypeId NOT IN (SELECT mtg.FKMimeTypeId FROM [gs_MimeTypeGallery] mtg WHERE mtg.FKGalleryId = {0}); ".Replace("@GalleryId", galleryId.ToString(CultureInfo.InvariantCulture)); ctx.Database.ExecuteSqlCommand(sql, galleryId); if (!mimeTypeGalleryTableHasRecords) { // The gs_MimeTypeGallery table was empty when we started. We inserted records in the previous SQL, and now we want // to enable the .jpg and .jpeg file types. (By default, users can upload these types in a gallery.) sql = @" UPDATE [gs_MimeTypeGallery] SET IsEnabled = 1 WHERE FKGalleryId = {0} AND FKMimeTypeId IN (SELECT MimeTypeId FROM [gs_MimeType] WHERE FileExtension IN ('.jpg', '.jpeg'));"; ctx.Database.ExecuteSqlCommand(sql, galleryId); } }
private static void ConfigureSyncTable(int galleryId, GspContext ctx) { var syncDto = ctx.Synchronizes.Find(galleryId); if (syncDto == null) { // No sync record exists. Create one. syncDto = new SynchronizeDto { FKGalleryId = galleryId, SynchId = String.Empty, SynchState = 1, TotalFiles = 0, CurrentFileIndex = 0 }; ctx.Synchronizes.Add(syncDto); } else { // Update the existing sync record to default values. syncDto.SynchId = String.Empty; syncDto.SynchState = 1; syncDto.TotalFiles = 0; syncDto.CurrentFileIndex = 0; } ctx.SaveChanges(); }
private static AlbumDto ConfigureAlbumTable(int galleryId, GspContext ctx) { // Create the root album if necessary. var rootAlbumDto = (from a in ctx.Albums where a.FKGalleryId == galleryId && a.AlbumParentId == 0 select a).FirstOrDefault(); if (rootAlbumDto == null) { rootAlbumDto = new AlbumDto { FKGalleryId = galleryId, AlbumParentId = 0, Title = "All albums", DirectoryName = String.Empty, Summary = "Welcome to Gallery Server Pro!", ThumbnailMediaObjectId = 0, Seq = 0, DateAdded = DateTime.Now, CreatedBy = "System", LastModifiedBy = "System", DateLastModified = DateTime.Now, OwnedBy = String.Empty, OwnerRoleName = String.Empty, IsPrivate = false }; ctx.Albums.Add(rootAlbumDto); ctx.SaveChanges(); } return rootAlbumDto; }
private static void ConfigureRoleAlbumTable(int rootAlbumId, GspContext ctx) { // For each role with AllowAdministerSite permission, add a corresponding record in gs_Role_Album giving it // access to the root album. string sql = String.Format(CultureInfo.InvariantCulture, @" INSERT INTO [gs_Role_Album] (FKRoleName, FKAlbumId) SELECT R.RoleName, {0} FROM [gs_Role] R LEFT JOIN [gs_Role_Album] RA ON R.RoleName = RA.FKRoleName WHERE R.AllowAdministerSite = 1 AND RA.FKRoleName IS NULL; ", rootAlbumId); ctx.Database.ExecuteSqlCommand(sql); }
private static void ConfigureGallerySettingsTable(int galleryId, GspContext ctx) { // Create a new set of gallery settings by copying the template settings (do nothing if already present). string sql = @" INSERT INTO [gs_GallerySetting] (FKGalleryId, IsTemplate, SettingName, SettingValue) SELECT @GalleryId, 0, t.SettingName, t.SettingValue FROM [gs_GallerySetting] t WHERE t.IsTemplate = 1 AND t.SettingName NOT IN (SELECT g.SettingName FROM [gs_GallerySetting] g WHERE g.FKGalleryId = {0}); ".Replace("@GalleryId", galleryId.ToString(CultureInfo.InvariantCulture)); ctx.Database.ExecuteSqlCommand(sql, galleryId); }
private static void ConfigureGallerySettingsTable(int galleryId, GspContext ctx) { // Create a new set of gallery settings by copying the template settings (do nothing if already present). string sql = @" INSERT INTO [gs_GallerySetting] (FKGalleryId, IsTemplate, SettingName, SettingValue) SELECT @GalleryId, 0, t.SettingName, t.SettingValue FROM [gs_GallerySetting] t WHERE t.IsTemplate = 1 AND t.SettingName NOT IN (SELECT g.SettingName FROM [gs_GallerySetting] g WHERE g.FKGalleryId = {0}); ".Replace("@GalleryId", galleryId.ToString(CultureInfo.InvariantCulture)); ctx.Database.ExecuteSqlCommand(sql, galleryId); }
private static void ConfigureGalleryTable(int galleryId, GspContext ctx) { // Insert a gallery record (do nothing if already present). var galleryDto = ctx.Galleries.Find(galleryId); if (galleryDto == null) { try { Create(galleryId); } catch (SqlCeException ex) { // Log error but otherwise swallow, since the reason for the error could be that the gallery was // just created by another thread. ErrorHandler.Error.Record(ex); } } }
/// <summary> /// Configure the gallery with the specified <paramref name="galleryId"/> by verifying that a default set of /// records exist in the supporting tables (gs_Album, gs_GallerySetting, gs_MimeTypeGallery, gs_Synchronize, gs_Role_Album). /// No changes are made to the file system as part of this operation. This method does not overwrite existing data, but it /// does insert missing data. This function can be used during application initialization to validate the data integrity for /// a gallery. For example, if the user has added a record to the MIME types or template gallery settings tables, this method /// will ensure that the new records are associated with the gallery identified in <paramref name="galleryId"/>. /// </summary> /// <param name="galleryId">The ID of the gallery to configure.</param> internal static void Configure(int galleryId) { using (GspContext ctx = new GspContext()) { // Step 1: Insert a gallery record (do nothing if already present). ConfigureGalleryTable(galleryId, ctx); // Step 2: Create a new set of gallery settings by copying the template settings (do nothing if already present). ConfigureGallerySettingsTable(galleryId, ctx); // Step 3: Create a new set of gallery MIME types (do nothing if already present). ConfigureMimeTypeGalleryTable(galleryId, ctx); // Step 4: Create the root album if necessary. AlbumDto rootAlbumDto = ConfigureAlbumTable(galleryId, ctx); // Step 5: For each role with AllowAdministerSite permission, add a corresponding record in gs_Role_Album giving it // access to the root album. ConfigureRoleAlbumTable(rootAlbumDto.AlbumId, ctx); // Step 6: Update the sync table. ConfigureSyncTable(galleryId, ctx); } }
/// <summary> /// Configure the gallery with the specified <paramref name="galleryId"/> by verifying that a default set of /// records exist in the supporting tables (gs_Album, gs_GallerySetting, gs_MimeTypeGallery, gs_Synchronize, gs_Role_Album). /// No changes are made to the file system as part of this operation. This method does not overwrite existing data, but it /// does insert missing data. This function can be used during application initialization to validate the data integrity for /// a gallery. For example, if the user has added a record to the MIME types or template gallery settings tables, this method /// will ensure that the new records are associated with the gallery identified in <paramref name="galleryId"/>. /// </summary> /// <param name="galleryId">The ID of the gallery to configure.</param> internal static void Configure(int galleryId) { using (GspContext ctx = new GspContext()) { // Step 1: Insert a gallery record (do nothing if already present). ConfigureGalleryTable(galleryId, ctx); // Step 2: Create a new set of gallery settings by copying the template settings (do nothing if already present). ConfigureGallerySettingsTable(galleryId, ctx); // Step 3: Create a new set of gallery MIME types (do nothing if already present). ConfigureMimeTypeGalleryTable(galleryId, ctx); // Step 4: Create the root album if necessary. AlbumDto rootAlbumDto = ConfigureAlbumTable(galleryId, ctx); // Step 5: For each role with AllowAdministerSite permission, add a corresponding record in gs_Role_Album giving it // access to the root album. ConfigureRoleAlbumTable(rootAlbumDto.AlbumId, ctx); // Step 6: Update the sync table. ConfigureSyncTable(galleryId, ctx); } }
/// <summary> /// Persist the current gallery settings to the data store. /// </summary> /// <param name="gallerySettings">An instance of <see cref="IGallerySettings"/> to persist to the data store.</param> /// <exception cref="ArgumentNullException">Thrown when <paramref name="gallerySettings" /> is null.</exception> /// public override void GallerySetting_Save(IGallerySettings gallerySettings) { if (gallerySettings == null) throw new ArgumentNullException("gallerySettings"); Type gsType = gallerySettings.GetType(); string boolType = typeof(bool).ToString(); string intType = typeof(int).ToString(); string stringType = typeof(string).ToString(); string stringArrayType = typeof(string[]).ToString(); string floatType = typeof(float).ToString(); string dateTimeType = typeof(DateTime).ToString(); string usersType = typeof(IUserAccountCollection).ToString(); string metadataDefType = typeof(IMetadataDefinitionCollection).ToString(); using (GspContext ctx = new GspContext()) { ctx.GallerySettings.Load(); foreach (PropertyInfo prop in gsType.GetProperties()) { if ((prop == null) || (prop.PropertyType.FullName == null)) { continue; } string propValue; if (prop.PropertyType.FullName.Equals(boolType)) { propValue = Convert.ToBoolean(prop.GetValue(gallerySettings, null), CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(intType)) { propValue = Convert.ToInt32(prop.GetValue(gallerySettings, null), CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(stringType)) { propValue = Convert.ToString(prop.GetValue(gallerySettings, null), CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(stringArrayType)) { propValue = String.Join(",", (string[])prop.GetValue(gallerySettings, null)); } else if (prop.PropertyType.FullName.Equals(floatType)) { propValue = Convert.ToSingle(prop.GetValue(gallerySettings, null), CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(dateTimeType)) { propValue = Convert.ToDateTime(prop.GetValue(gallerySettings, null), CultureInfo.InvariantCulture).ToString("O", CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(usersType)) { propValue = String.Join(",", ((IUserAccountCollection)prop.GetValue(gallerySettings, null)).GetUserNames()); } else if (prop.PropertyType.FullName.Equals(metadataDefType)) { propValue = ((IMetadataDefinitionCollection)prop.GetValue(gallerySettings, null)).Serialize(); } else { propValue = prop.GetValue(gallerySettings, null).ToString(); } // Find the gallery setting in the DB and update it. PropertyInfo propLocal = prop; var gallerySettingDto = (from i in ctx.GallerySettings.Local where i.FKGalleryId == gallerySettings.GalleryId && i.SettingName == propLocal.Name select i).FirstOrDefault(); if (gallerySettingDto != null) { gallerySettingDto.SettingValue = propValue; } } ctx.SaveChanges(); } }
/// <summary> /// Persist each each metadata item that has HasChanges = true to the data store. If all items are marked for updating /// (mediaObject.RegenerateMetadataOnSave = true), then all metadata items are deleted from the data store and then inserted based /// on the current metadata items. If one or more items has HasChanges = false, then each item with HasChanges = true is /// processed according to the following rules: (1) If the metadata value is null or an empty string, it is deleted from the /// data store and removed from the MetadataItems collection. (2) If the item's MediaObjectMetadataId = int.MinValue, the /// item is assumed to be new and is inserted. (3) Any item not falling into the previous two categories, but HasChanges = true, /// is assumed to be pre-existing and an update stored procedure is executed. /// </summary> /// <param name="mediaObject">The media object for which to update metadata items in the data store.</param> /// <param name="ctx">A database context.</param> private static void UpdateMetadataItems(IGalleryObject mediaObject, GspContext ctx) { if (mediaObject.ExtractMetadataOnSave) { // User wants to replace all metadata items. Delete them all from the data store, then insert the ones we have. DeleteMetadataItems(mediaObject, ctx); InsertMetadataItems(mediaObject, ctx); } else { IGalleryObjectMetadataItemCollection metadataItemsToSave = mediaObject.MetadataItems.GetItemsToSave(); if (metadataItemsToSave.Count == 0) { return; // Nothing to save } // There is at least one item to persist to the data store. foreach (IGalleryObjectMetadataItem metaDataItem in metadataItemsToSave) { if (String.IsNullOrEmpty(metaDataItem.Value)) { // There is no value, so let's delete this item. DeleteMetadataItem(metaDataItem, ctx); // Remove it from the collection. mediaObject.MetadataItems.Remove(metaDataItem); } else if (metaDataItem.MediaObjectMetadataId == int.MinValue) { // Insert the item. MediaObjectMetadataDto mDto = new MediaObjectMetadataDto { FKMediaObjectId = mediaObject.Id, MetadataNameIdentifier = (int)metaDataItem.MetadataItemName, Description = metaDataItem.Description, Value = metaDataItem.Value }; ctx.MediaObjectMetadatas.Add(mDto); // Note: The newly assigned ID is not assigned back to metaDataItem.MediaObjectMetadataId, but that should be // OK because we'll be reloading the items from the DB after the save. } else { // Update the item. MediaObjectMetadataDto mDto = ctx.MediaObjectMetadatas.Find(metaDataItem.MediaObjectMetadataId); if (mDto != null) { mDto.MetadataNameIdentifier = (int)metaDataItem.MetadataItemName; mDto.Description = metaDataItem.Description; mDto.Value = metaDataItem.Value; } } } } }
/// <summary> /// Retrieve the most recent synchronization information from the data store. /// </summary> /// <param name="galleryId">The gallery ID.</param> /// <param name="factory">An instance of <see cref="IFactory"/>. It is used to instantiate a <see cref="ISynchronizationStatus"/> object.</param> /// <returns> /// Returns an <see cref="ISynchronizationStatus"/> object with the most recent synchronization information from the data store. /// </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="factory" /> is null.</exception> public override ISynchronizationStatus Synchronize_RetrieveStatus(int galleryId, IFactory factory) { if (factory == null) throw new ArgumentNullException("factory"); ISynchronizationStatus updatedSynchStatus = null; using (GspContext ctx = new GspContext()) { SynchronizeDto sDto = ctx.Synchronizes.Find(galleryId); if (sDto != null) { SynchronizationState synchState = (SynchronizationState)Enum.Parse(typeof(SynchronizationState), sDto.SynchState.ToString(CultureInfo.InvariantCulture)); updatedSynchStatus = factory.CreateSynchronizationStatus(galleryId, sDto.SynchId, synchState, sDto.TotalFiles, String.Empty, sDto.CurrentFileIndex, String.Empty); } } if (updatedSynchStatus == null) { // The gs_Synchronize table didn't have a record for this gallery. Configure the gallery, which will // insert the missing record, then call this method again. IGallery gallery = Gallery_GetGalleries(factory.CreateGalleryCollection()).FindById(galleryId); if (gallery != null) { gallery.Configure(); } else { throw new ErrorHandler.CustomExceptions.InvalidGalleryException(galleryId); } return Synchronize_RetrieveStatus(galleryId, factory); } return updatedSynchStatus; }
private static void DeleteMetadataItems(IGalleryObject mediaObject, GspContext ctx) { foreach (MediaObjectMetadataDto mDto in (from m in ctx.MediaObjectMetadatas where m.FKMediaObjectId == mediaObject.Id select m)) { ctx.MediaObjectMetadatas.Remove(mDto); } }
/// <summary> /// Persist the specified gallery to the data store. Return the ID of the gallery. /// </summary> /// <param name="gallery">An instance of <see cref="IGallery"/> to persist to the data store.</param> /// <returns> /// Return the ID of the gallery. If this is a new gallery and a new ID has been /// assigned, then this value has also been assigned to the <see cref="IGallery.GalleryId"/> property. /// </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="gallery" /> is null.</exception> /// public override int Gallery_Save(IGallery gallery) { if (gallery == null) throw new ArgumentNullException("gallery"); using (GspContext ctx = new GspContext()) { if (gallery.IsNew) { GalleryDto galleryDto = new GalleryDto { Description = gallery.Description, DateAdded = gallery.CreationDate }; ctx.Galleries.Add(galleryDto); ctx.SaveChanges(); // Assign newly created gallery ID. gallery.GalleryId = galleryDto.GalleryId; } else { var galleryDto = ctx.Galleries.Find(gallery.GalleryId); if (galleryDto != null) { galleryDto.Description = gallery.Description; ctx.SaveChanges(); } else { throw new DataException(String.Format(CultureInfo.CurrentCulture, "Cannot save gallery: No existing gallery with Gallery ID {0} was found in the database.", gallery.GalleryId)); } } } return gallery.GalleryId; }
/// <summary> /// Gets the data schema version of the database. May return null. Examples: "2.3.3421", "2.4.1" /// </summary> /// <returns>Returns a <see cref="string"/> containing the database version.</returns> internal static string GetDataSchemaVersionString() { using (GspContext ctx = new GspContext()) { return (from a in ctx.AppSettings where a.SettingName == "DataSchemaVersion" select a.SettingValue).FirstOrDefault(); } }
/// <summary> /// Permanently delete all errors from the data store that are system-wide (that is, not associated with a specific gallery) and also /// those errors belonging to the specified <paramref name="galleryId"/>. /// </summary> /// <param name="galleryId">The gallery ID.</param> public override void AppError_ClearLog(int galleryId) { using (GspContext ctx = new GspContext()) { var aeDtos = (from ae in ctx.AppErrors where ae.FKGalleryId == galleryId || ae.FKGalleryId == int.MinValue select ae); foreach (var aeDto in aeDtos) { ctx.AppErrors.Remove(aeDto); } ctx.SaveChanges(); } }
/// <summary> /// Delete the application error from the data store. /// </summary> /// <param name="appErrorId">The value that uniquely identifies this application error (<see cref="IAppError.AppErrorId"/>).</param> public override void AppError_Delete(int appErrorId) { using (GspContext ctx = new GspContext()) { AppErrorDto aeDto = (from ae in ctx.AppErrors where ae.AppErrorId == appErrorId select ae).FirstOrDefault(); if (aeDto != null) { ctx.AppErrors.Remove(aeDto); ctx.SaveChanges(); } } }
/// <summary> /// Return a collection representing the child media objects contained within the album specified by /// <paramref name="albumId"/> parameter. If no matching objects are found in the data store, an empty collection is returned. /// </summary> /// <param name="albumId">The ID that uniquely identifies the desired album.</param> /// <returns> /// Returns a collection of all media objects directly within the album represented by <paramref name="albumId"/>. /// </returns> public override IEnumerable<MediaObjectDto> Album_GetChildMediaObjectsById(int albumId) { using (GspContext ctx = new GspContext()) { return (from mo in ctx.MediaObjects where mo.FKAlbumId == albumId select mo).ToList(); } }
/// <summary> /// Persist the specified album to the data store. Return the ID of the album. /// </summary> /// <param name="album">An instance of <see cref="IAlbum"/> to persist to the data store.</param> /// <returns> /// Return the ID of the album. If this is a new album and a new ID has been /// assigned, then this value has also been assigned to the ID property of the object. /// </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception> public override int Album_Save(IAlbum album) { if (album == null) throw new ArgumentNullException("album"); using (GspContext ctx = new GspContext()) { if (album.IsNew) { AlbumDto aDto = new AlbumDto { FKGalleryId = album.GalleryId, AlbumParentId = album.Parent.Id, Title = album.Title, DirectoryName = album.DirectoryName, Summary = album.Summary, ThumbnailMediaObjectId = album.Thumbnail.MediaObjectId, Seq = album.Sequence, DateStart = (album.DateStart > DateTime.MinValue ? album.DateStart : (DateTime?)null), DateEnd = (album.DateEnd > DateTime.MinValue ? album.DateEnd : (DateTime?)null), CreatedBy = album.CreatedByUserName, DateAdded = album.DateAdded, LastModifiedBy = album.LastModifiedByUserName, DateLastModified = album.DateLastModified, OwnedBy = album.OwnerUserName, OwnerRoleName = album.OwnerRoleName, IsPrivate = album.IsPrivate }; ctx.Albums.Add(aDto); ctx.SaveChanges(); if (album.Id != aDto.AlbumId) album.Id = aDto.AlbumId; // Return newly created album ID. return aDto.AlbumId; } else { AlbumDto aDto = ctx.Albums.Find(album.Id); if (aDto != null) { aDto.FKGalleryId = album.GalleryId; aDto.AlbumParentId = album.Parent.Id; aDto.Title = album.Title; aDto.DirectoryName = album.DirectoryName; aDto.Summary = album.Summary; aDto.ThumbnailMediaObjectId = album.ThumbnailMediaObjectId; aDto.Seq = album.Sequence; aDto.DateStart = (album.DateStart > DateTime.MinValue ? album.DateStart : (DateTime?)null); aDto.DateEnd = (album.DateEnd > DateTime.MinValue ? album.DateEnd : (DateTime?)null); aDto.LastModifiedBy = album.LastModifiedByUserName; aDto.DateLastModified = album.DateLastModified; aDto.OwnedBy = album.OwnerUserName; aDto.OwnerRoleName = album.OwnerRoleName; aDto.IsPrivate = album.IsPrivate; ctx.SaveChanges(); } return album.Id; } } }
/// <summary> /// Return a collection of album IDs that are immediate children of the album represented by <paramref name="albumId"/>. /// If no matching objects are found in the data store, an empty collection is returned. /// </summary> /// <param name="albumId">The ID that uniquely identifies the album for which to return the child albums /// contained within.</param> /// <returns> /// Returns a collection of all album IDs directly within the album represented by <paramref name="albumId"/>. /// </returns> public override IEnumerable<int> Album_GetChildAlbumIdsById(int albumId) { using (GspContext ctx = new GspContext()) { return (from a in ctx.Albums where a.AlbumParentId == albumId select a.AlbumId).ToList(); } }
/// <summary> /// Return the album for the specified <paramref name="albumId"/>. Returns null if no matching object /// is found in the data store. /// </summary> /// <param name="albumId">The ID that uniquely identifies the desired album.</param> /// <returns> /// Returns an instance of <see cref="AlbumDto"/>, or null if no matching object is found. /// </returns> public override AlbumDto Album_GetAlbumById(int albumId) { using (GspContext ctx = new GspContext()) { return ctx.Albums.Find(albumId); } }
/// <summary> /// Verify various tables have required records. For example, the album table must have a root album for each gallery, the gallery /// settings table must have a set of gallery settings, the MIME type gallery table must have a set of MIME types for each /// gallery, and the synch table has a record for each gallery and its values are reset to default values. Also propogate any new /// gallery settings or MIME types to all galleries. This function works by iterating through each gallery and calling the /// CreateGallery routine. /// </summary> private static void ValidateDataIntegrity() { using (GspContext ctx = new GspContext()) { foreach (GalleryDto gallery in (from g in ctx.Galleries where g.GalleryId > int.MinValue select g)) { Gallery.Configure(gallery.GalleryId); } } }
/// <summary> /// Permanently delete the specified gallery from the data store, including all related records. This action cannot /// be undone. /// </summary> /// <param name="gallery">The <see cref="IGallery"/> to delete from the data store.</param> public override void Gallery_Delete(IGallery gallery) { using (GspContext ctx = new GspContext()) { // Delete gallery. Cascade delete rules in DB will delete related records. GalleryDto galleryDto = (from g in ctx.Galleries where g.GalleryId == gallery.GalleryId select g).FirstOrDefault(); if (galleryDto != null) { ctx.Galleries.Remove(galleryDto); ctx.SaveChanges(); } } }
/// <summary> /// Save the list of root album IDs to the data store. The table gs_Role_Album contains one record for each role/album /// relationship. This procedure adds and deletes records as needed. /// </summary> /// <param name="role">The gallery server role containing the list of root Album IDs to persist to the data store.</param> private static void PersistRoleAlbumRelationshipsToDataStore(IGalleryServerRole role) { // Step 1: Copy the list of root album IDs to a new list. We'll be removing items from the list as we process them, // so we don't want to mess with the actual list attached to the object. List<int> roleAlbumRelationshipsToPersist = new List<int>(); foreach (int albumId in role.RootAlbumIds) { roleAlbumRelationshipsToPersist.Add(albumId); } using (GspContext ctx = new GspContext()) { // Step 2: Get a list of all root album IDs in the data store for this role. List<int> roleAlbumRelationshipsToDelete = new List<int>(); foreach (int albumId in (from ra in ctx.RoleAlbums where ra.FKRoleName == role.RoleName select ra.FKAlbumId)) { // Step 3: Iterate through each role/album relationship that is stored in the data store. If it is in our list, then // remove it from the list (see step 5 why). If not, the user must have unchecked it so add it to a list of // relationships to be deleted. if (roleAlbumRelationshipsToPersist.Contains(albumId)) { roleAlbumRelationshipsToPersist.Remove(albumId); } else { roleAlbumRelationshipsToDelete.Add(albumId); } } // Step 4: Delete the records we accumulated in our list. var roleAlbumDtos = from ra in ctx.RoleAlbums where roleAlbumRelationshipsToDelete.Contains(ra.FKAlbumId) select ra; foreach (RoleAlbumDto roleAlbumDto in roleAlbumDtos) { ctx.RoleAlbums.Remove(roleAlbumDto); } // Step 5: Any items still left in the roleAlbumRelationshipsToPersist list must be new ones checked by the user. Add them. foreach (int albumid in roleAlbumRelationshipsToPersist) { ctx.RoleAlbums.Add(new RoleAlbumDto { FKAlbumId = albumid, FKRoleName = role.RoleName }); } ctx.SaveChanges(); } }
/// <summary> /// Fill the <paramref name="emptyCollection"/> with all the galleries in the current application. The return value is the same reference /// as the parameter. The template gallery is not included (that is, the one where the gallery ID = <see cref="Int32.MinValue"/>. /// </summary> /// <param name="emptyCollection">An empty <see cref="IGalleryCollection"/> object to populate with the list of galleries in the current /// application. This parameter is required because the library that implements this interface does not have /// the ability to directly instantiate any object that implements <see cref="IGalleryCollection"/>.</param> /// <returns> /// Returns an <see cref="IGalleryCollection"/> representing the galleries in the current application. The returned object is the /// same object in memory as the <paramref name="emptyCollection"/> parameter. /// </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="emptyCollection" /> is null.</exception> /// public override IGalleryCollection Gallery_GetGalleries(IGalleryCollection emptyCollection) { if (emptyCollection == null) throw new ArgumentNullException("emptyCollection"); if (emptyCollection.Count > 0) { emptyCollection.Clear(); } using (GspContext ctx = new GspContext()) { var galleries = from i in ctx.Galleries where i.GalleryId > int.MinValue select i; foreach (GalleryDto gallery in galleries) { IGallery g = emptyCollection.CreateEmptyGalleryInstance(); g.GalleryId = gallery.GalleryId; g.Description = gallery.Description; g.CreationDate = gallery.DateAdded; g.Albums = FlattenGallery(gallery.GalleryId); emptyCollection.Add(g); } } return emptyCollection; }
/// <summary> /// Persist the specified application error to the data store. Return the ID of the error. /// </summary> /// <param name="appError">The application error to persist to the data store.</param> /// <returns> /// Return the ID of the error. If this is a new error object and a new ID has been /// assigned, then this value has also been assigned to the ID property of the object. /// </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="appError" /> is null.</exception> public override int AppError_Save(IAppError appError) { if (appError == null) throw new ArgumentNullException("appError"); AppErrorDto aeDto = new AppErrorDto { FKGalleryId = appError.GalleryId, TimeStamp = appError.Timestamp, ExceptionType = appError.ExceptionType, Message = appError.Message, Source = appError.Source, TargetSite = appError.TargetSite, StackTrace = appError.StackTrace, ExceptionData = ErrorHandler.Error.Serialize(appError.ExceptionData), InnerExType = appError.InnerExType, InnerExMessage = appError.InnerExMessage, InnerExSource = appError.InnerExSource, InnerExTargetSite = appError.InnerExTargetSite, InnerExStackTrace = appError.InnerExStackTrace, InnerExData = ErrorHandler.Error.Serialize(appError.InnerExData), Url = appError.Url, FormVariables = ErrorHandler.Error.Serialize(appError.FormVariables), Cookies = ErrorHandler.Error.Serialize(appError.Cookies), SessionVariables = ErrorHandler.Error.Serialize(appError.SessionVariables), ServerVariables = ErrorHandler.Error.Serialize(appError.ServerVariables) }; using (GspContext ctx = new GspContext()) { ctx.AppErrors.Add(aeDto); ctx.SaveChanges(); appError.AppErrorId = aeDto.AppErrorId; return appError.AppErrorId; } }
/// <summary> /// Insert all metadata items from the data store for the specified media object. Assumes no existing metadata record exists /// that matches the MediaObjectMetadataId value of each metadata item. Each metadata item is inserted and the newly /// assigned MediaObjectMetadataId value is assigned to the item's MediaObjectMetadataId property. /// </summary> /// <param name="mediaObject">The media object for which to insert all metadata items to the data store.</param> /// <param name="ctx">A database context.</param> private static void InsertMetadataItems(IGalleryObject mediaObject, GspContext ctx) { // Insert meta data items, if any, into MediaObjectMetadata table. if (mediaObject.MetadataItems.Count > 0) { foreach (IGalleryObjectMetadataItem metaDataItem in mediaObject.MetadataItems) { MediaObjectMetadataDto mDto = new MediaObjectMetadataDto { FKMediaObjectId = mediaObject.Id, MetadataNameIdentifier = (int)metaDataItem.MetadataItemName, Description = metaDataItem.Description, Value = metaDataItem.Value }; ctx.MediaObjectMetadatas.Add(mDto); // Note: The newly assigned ID is not assigned back to metaDataItem.MediaObjectMetadataId, but that should be // OK because we'll be reloading the items from the DB after the save. } } }
/// <summary> /// Return a collection representing the application settings in the data store. /// If no records are found in the data store, an empty collection is returned. /// </summary> /// <returns> /// Returns a collection containing the application settings in the data store. /// </returns> public override IEnumerable<AppSettingDto> AppSetting_GetAppSettings() { using (GspContext ctx = new GspContext()) { return ctx.AppSettings.ToList(); } }
/// <summary> /// Flatten the gallery into a dictionary of album IDs (key) and the flattened list of all albums each album /// contains (value). /// </summary> /// <param name="galleryId">The gallery ID.</param> /// <returns>An instance of Dictionary<int, List<int>>.</returns> private static Dictionary<int, List<int>> FlattenGallery(int galleryId) { Dictionary<int, List<int>> flatIds = new Dictionary<int, List<int>>(); ILookup<int, AlbumTuple> albums; using (GspContext ctx = new GspContext()) { albums = (from a in ctx.Albums where a.FKGalleryId == galleryId select new AlbumTuple { AlbumId = a.AlbumId, AlbumParentId = a.AlbumParentId }).ToLookup(a => a.AlbumParentId, v => v); } const int rootAlbumParentId = 0; // Get a reference to the root album AlbumTuple rootAlbum = albums[rootAlbumParentId].First(); // Add the root album to our flat list and set up the child list flatIds.Add(rootAlbum.AlbumId, new List<int> { rootAlbum.AlbumId }); // Now add the children of the root album foreach (AlbumTuple albumTuple in albums[rootAlbum.AlbumId]) { FlattenAlbum(albumTuple, albums, flatIds, new List<int> { rootAlbum.AlbumId }); } return flatIds; }
/// <summary> /// Persist the current application settings to the data store. /// </summary> /// <param name="appSetting">An instance of <see cref="IAppSetting"/> to persist to the data store.</param> /// <exception cref="ArgumentNullException">Thrown when <paramref name="appSetting" /> is null.</exception> public override void AppSetting_Save(IAppSetting appSetting) { if (appSetting == null) throw new ArgumentNullException("appSetting"); Type asType = appSetting.GetType(); // Specify the list of properties we want to save. string[] propertiesToSave = new[] { "MediaObjectDownloadBufferSize", "EncryptMediaObjectUrlOnClient", "EncryptionKey", "JQueryScriptPath", "JQueryUiScriptPath", "MembershipProviderName", "RoleProviderName", "ProductKey", "EnableCache", "AllowGalleryAdminToManageUsersAndRoles", "AllowGalleryAdminToViewAllUsersAndRoles", "MaxNumberErrorItems" }; string boolType = typeof(bool).ToString(); string intType = typeof(int).ToString(); string stringType = typeof(string).ToString(); using (GspContext ctx = new GspContext()) { ctx.AppSettings.Load(); foreach (PropertyInfo prop in asType.GetProperties()) { if ((prop == null) || (prop.PropertyType.FullName == null)) { continue; } if (Array.IndexOf(propertiesToSave, prop.Name) >= 0) { // This is one of the properties we want to save. string propValue; if (prop.PropertyType.FullName.Equals(boolType)) { propValue = Convert.ToBoolean(prop.GetValue(appSetting, null), CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(intType)) { propValue = Convert.ToInt32(prop.GetValue(appSetting, null), CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(stringType)) { propValue = Convert.ToString(prop.GetValue(appSetting, null), CultureInfo.InvariantCulture); } else { propValue = prop.GetValue(appSetting, null).ToString(); } // Find the app setting in the DB and update it. var appSettingDto = (from i in ctx.AppSettings.Local where i.SettingName == prop.Name select i).FirstOrDefault(); if (appSettingDto != null) { appSettingDto.SettingValue = propValue; } else { throw new DataException(String.Format(CultureInfo.CurrentCulture, "Cannot update application setting. No record was found in gs_AppSetting with SettingName='{0}'.", prop.Name)); } } } ctx.SaveChanges(); } }
/// <summary> /// Delete the specified metadata item from the data store. No error occurs if the record does not exist in the data store. /// </summary> /// <param name="metaDataItem">The metadata item to delete from the data store.</param> /// <param name="ctx">A database context.</param> private static void DeleteMetadataItem(IGalleryObjectMetadataItem metaDataItem, GspContext ctx) { MediaObjectMetadataDto mDto = ctx.MediaObjectMetadatas.Find(metaDataItem.MediaObjectMetadataId); if (mDto != null) { ctx.MediaObjectMetadatas.Remove(mDto); } }
/// <summary> /// Persist the current gallery control settings to the data store. /// </summary> /// <param name="galleryControlSettings">An instance of <see cref="IGalleryControlSettings"/> to persist to the data store.</param> public override void GalleryControlSetting_Save(IGalleryControlSettings galleryControlSettings) { using (GspContext ctx = new GspContext()) { string[] propertiesToExclude = new[] { "GalleryControlSettingId", "ControlId" }; Type gsType = galleryControlSettings.GetType(); string viewModeType = typeof(ViewMode).ToString(); string boolType = typeof(bool).ToString(); string boolNullableType = typeof(bool?).ToString(); string intType = typeof(int).ToString(); string intNullableType = typeof(int?).ToString(); string stringType = typeof(string).ToString(); ctx.GalleryControlSettings.Load(); foreach (PropertyInfo prop in gsType.GetProperties()) { if (Array.IndexOf(propertiesToExclude, prop.Name) >= 0) { continue; // Skip this one. } // Get a reference to the database record (won't exist for new items). string propName = prop.Name; GalleryControlSettingDto gcsDto = (from g in ctx.GalleryControlSettings.Local where g.ControlId == galleryControlSettings.ControlId && g.SettingName == propName select g).FirstOrDefault(); object objPropValue = prop.GetValue(galleryControlSettings, null); if (objPropValue != null) { string propValue; if (prop.PropertyType.FullName == null) { continue; } if (prop.PropertyType.FullName.Equals(boolType) || prop.PropertyType.FullName.Equals(boolNullableType)) { propValue = Convert.ToBoolean(objPropValue, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(intType) || prop.PropertyType.FullName.Equals(intNullableType)) { propValue = Convert.ToInt32(objPropValue, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(stringType)) { propValue = Convert.ToString(objPropValue, CultureInfo.InvariantCulture); } else if (prop.PropertyType.FullName.Equals(viewModeType)) { // Only save ViewMode if it has a non-default value. ViewMode viewMode = (ViewMode)Enum.Parse(typeof(ViewMode), prop.GetValue(galleryControlSettings, null).ToString(), true); if (viewMode == ViewMode.NotSet) { // Property not assigned. Delete the record. if (gcsDto != null) { ctx.GalleryControlSettings.Remove(gcsDto); } continue; // We're done with this property, so let's move on to the next one. } propValue = viewMode.ToString(); } else { propValue = prop.GetValue(galleryControlSettings, null).ToString(); } // Insert or update the item. if (gcsDto == null) { gcsDto = new GalleryControlSettingDto { ControlId = galleryControlSettings.ControlId, SettingName = propName, SettingValue = propValue }; ctx.GalleryControlSettings.Add(gcsDto); } else { gcsDto.SettingValue = propValue; } } else { // Property not assigned. Delete the record. if (gcsDto != null) { ctx.GalleryControlSettings.Remove(gcsDto); } // Include this only for debug purposes. //System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true); //string msg = String.Format(CultureInfo.CurrentCulture, "Deleted Gallery Control Setting \"{0}\". Stack trace: {1}", prop.Name, st); //errMessages.Add(msg); } } ctx.SaveChanges(); } }
/// <summary> /// Persist the synchronization information to the data store. /// </summary> /// <param name="synchStatus">An <see cref="ISynchronizationStatus"/> object containing the synchronization information /// to persist to the data store.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.SynchronizationInProgressException">Thrown when the data /// store indicates another synchronization is already in progress for this gallery.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="synchStatus" /> is null.</exception> public override void Synchronize_SaveStatus(ISynchronizationStatus synchStatus) { if (synchStatus == null) throw new ArgumentNullException("synchStatus"); using (GspContext ctx = new GspContext()) { SynchronizeDto sDto = ctx.Synchronizes.Find(synchStatus.GalleryId); if (sDto != null) { if ((sDto.SynchId != synchStatus.SynchId) && ((sDto.SynchState == (int)SynchronizationState.SynchronizingFiles) || (sDto.SynchState == (int)SynchronizationState.PersistingToDataStore))) { throw new ErrorHandler.CustomExceptions.SynchronizationInProgressException(); } else { sDto.SynchId = synchStatus.SynchId; sDto.SynchState = (int)synchStatus.Status; sDto.TotalFiles = synchStatus.TotalFileCount; sDto.CurrentFileIndex = synchStatus.CurrentFileIndex; } } else { sDto = new SynchronizeDto { SynchId = synchStatus.SynchId, FKGalleryId = synchStatus.GalleryId, SynchState = (int)synchStatus.Status, TotalFiles = synchStatus.TotalFileCount, CurrentFileIndex = synchStatus.CurrentFileIndex }; ctx.Synchronizes.Add(sDto); } ctx.SaveChanges(); } }
/// <summary> /// Return a collection representing all the gallery settings in the data store. /// If no records are found in the data store, an empty collection is returned. /// </summary> /// <returns> /// Returns a collection containing all the gallery settings in the data store. /// </returns> public override IEnumerable<GallerySettingDto> GallerySetting_GetGallerySettings() { using (GspContext ctx = new GspContext()) { return ctx.GallerySettings.OrderBy(g => g.FKGalleryId).ToList(); } }
/// <summary> /// Return a collection representing the application errors. If no objects are found /// in the data store, an empty collection is returned. /// </summary> /// <returns> /// Returns a collection object with all application error fields. /// </returns> public override IEnumerable<AppErrorDto> AppError_GetAppErrors() { using (GspContext ctx = new GspContext()) { return ctx.AppErrors.ToList(); } }
private static void PersistRoleToDataStore(IGalleryServerRole role) { // Update the existing role or insert if it doesn't exist. using (GspContext ctx = new GspContext()) { RoleDto roleDto = ctx.Roles.Find(role.RoleName); if (roleDto == null) { roleDto = new RoleDto { RoleName = role.RoleName, AllowViewAlbumsAndObjects = role.AllowViewAlbumOrMediaObject, AllowViewOriginalImage = role.AllowViewOriginalImage, AllowAddChildAlbum = role.AllowAddChildAlbum, AllowAddMediaObject = role.AllowAddMediaObject, AllowEditAlbum = role.AllowEditAlbum, AllowEditMediaObject = role.AllowEditMediaObject, AllowDeleteChildAlbum = role.AllowDeleteChildAlbum, AllowDeleteMediaObject = role.AllowDeleteMediaObject, AllowSynchronize = role.AllowSynchronize, HideWatermark = role.HideWatermark, AllowAdministerGallery = role.AllowAdministerGallery, AllowAdministerSite = role.AllowAdministerSite }; ctx.Roles.Add(roleDto); } else { roleDto.AllowViewAlbumsAndObjects = role.AllowViewAlbumOrMediaObject; roleDto.AllowViewOriginalImage = role.AllowViewOriginalImage; roleDto.AllowAddChildAlbum = role.AllowAddChildAlbum; roleDto.AllowAddMediaObject = role.AllowAddMediaObject; roleDto.AllowEditAlbum = role.AllowEditAlbum; roleDto.AllowEditMediaObject = role.AllowEditMediaObject; roleDto.AllowDeleteChildAlbum = role.AllowDeleteChildAlbum; roleDto.AllowDeleteMediaObject = role.AllowDeleteMediaObject; roleDto.AllowSynchronize = role.AllowSynchronize; roleDto.HideWatermark = role.HideWatermark; roleDto.AllowAdministerGallery = role.AllowAdministerGallery; roleDto.AllowAdministerSite = role.AllowAdministerSite; } ctx.SaveChanges(); } }