Пример #1
0
        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);
        }
Пример #2
0
        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;
        }
Пример #3
0
        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();
        }
        /// <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>
        /// Persist the specified media queue item to the data store. The ID of the new item is assigned to
        /// <see cref="MediaQueueDto.MediaQueueId"/>.
        /// </summary>
        /// <param name="mediaQueue">The media queue item to persist to the data store.</param>
        public override void MediaQueue_Save(MediaQueueDto mediaQueue)
        {
            if (mediaQueue == null)
                throw new ArgumentNullException("mediaQueue");

            using (GspContext ctx = new GspContext())
            {
                if (mediaQueue.MediaQueueId == int.MinValue)
                {
                    ctx.MediaQueues.Add(mediaQueue);
                }
                else
                {
                    MediaQueueDto dbItem = ctx.MediaQueues.Find(mediaQueue.MediaQueueId);
                    if (dbItem != null)
                    {
                        ctx.Entry(dbItem).CurrentValues.SetValues(mediaQueue);
                    }
                }

                ctx.SaveChanges();
            }
            //  ctx.MediaQueues.Attach(mediaQueue);
            //  ctx.Entry(mediaQueue).State = EntityState.Modified;
        }
        /// <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>
        /// 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 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>
        /// 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>
        /// Persist the gallery-specific properties of the <paramref name="mimeType"/> to the data store. Currently, only the
        /// <see cref="IMimeType.AllowAddToGallery"/> property is unique to the gallery identified in <see cref="IMimeType.GalleryId"/>;
        /// the other properties are application-wide and at present there is no API to modify them. In other words, this method saves whether a
        /// particular MIME type is enabled or disabled for a particular gallery.
        /// </summary>
        /// <param name="mimeType">The MIME type instance to save.</param>
        /// <exception cref="ArgumentException">Thrown when the <see cref="IMimeType.MimeTypeGalleryId"/> property of the <paramref name="mimeType" />
        /// parameter is not set to a valid value.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="mimeType" /> is null.</exception>
        public override void MimeType_Save(IMimeType mimeType)
        {
            if (mimeType == null)
                throw new ArgumentNullException("mimeType");

            if (mimeType.MimeTypeGalleryId == int.MinValue)
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "The MimeTypeGalleryId property must be set to a valid value. Instead, it was {0}.", mimeType.MimeTypeGalleryId), "mimeType");
            }

            using (GspContext ctx = new GspContext())
            {
                MimeTypeGalleryDto mtDto = ctx.MimeTypeGalleries.Find(mimeType.MimeTypeGalleryId);

                if (mtDto != null)
                {
                    mtDto.IsEnabled = mimeType.AllowAddToGallery;
                    ctx.SaveChanges();
                }
            }
        }
        /// <summary>
        /// Persist the specified media object to the data store. Return the ID of the media object.
        /// </summary>
        /// <param name="mediaObject">An instance of <see cref="IGalleryObject"/> to persist to the data store.</param>
        /// <returns>
        /// Return the ID of the media object. If this is a new media 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="mediaObject" /> is null.</exception>
        public override int MediaObject_Save(IGalleryObject mediaObject)
        {
            if (mediaObject == null)
                throw new ArgumentNullException("mediaObject");

            using (GspContext ctx = new GspContext())
            {
                if (mediaObject.IsNew)
                {
                    MediaObjectDto moDto = new MediaObjectDto
                                                                    {
                                                                        HashKey = mediaObject.Hashkey,
                                                                        FKAlbumId = mediaObject.Parent.Id,
                                                                        ThumbnailFilename = mediaObject.Thumbnail.FileName,
                                                                        ThumbnailWidth = mediaObject.Thumbnail.Width,
                                                                        ThumbnailHeight = mediaObject.Thumbnail.Height,
                                                                        ThumbnailSizeKB = mediaObject.Thumbnail.FileSizeKB,
                                                                        OptimizedFilename = mediaObject.Optimized.FileName,
                                                                        OptimizedWidth = mediaObject.Optimized.Width,
                                                                        OptimizedHeight = mediaObject.Optimized.Height,
                                                                        OptimizedSizeKB = mediaObject.Optimized.FileSizeKB,
                                                                        OriginalFilename = mediaObject.Original.FileName,
                                                                        OriginalWidth = mediaObject.Original.Width,
                                                                        OriginalHeight = mediaObject.Original.Height,
                                                                        OriginalSizeKB = mediaObject.Original.FileSizeKB,
                                                                        ExternalHtmlSource = mediaObject.Original.ExternalHtmlSource,
                                                                        ExternalType = (mediaObject.Original.ExternalType == MimeTypeCategory.NotSet ? String.Empty : mediaObject.Original.ExternalType.ToString()),
                                                                        Title = mediaObject.Title,
                                                                        Seq = mediaObject.Sequence,
                                                                        CreatedBy = mediaObject.CreatedByUserName,
                                                                        DateAdded = mediaObject.DateAdded,
                                                                        LastModifiedBy = mediaObject.LastModifiedByUserName,
                                                                        DateLastModified = mediaObject.DateLastModified,
                                                                        IsPrivate = mediaObject.IsPrivate
                                                                    };

                    ctx.MediaObjects.Add(moDto);
                    ctx.SaveChanges(); // Save now so we can get at the ID

                    if (mediaObject.Id != moDto.MediaObjectId)
                        mediaObject.Id = moDto.MediaObjectId;

                    // Insert metadata items, if any, into MediaObjectMetadata table.
                    InsertMetadataItems(mediaObject, ctx);
                }
                else
                {
                    MediaObjectDto moDto = ctx.MediaObjects.Find(mediaObject.Id);

                    if (moDto != null)
                    {
                        moDto.HashKey = mediaObject.Hashkey;
                        moDto.FKAlbumId = mediaObject.Parent.Id;
                        moDto.ThumbnailFilename = mediaObject.Thumbnail.FileName;
                        moDto.ThumbnailWidth = mediaObject.Thumbnail.Width;
                        moDto.ThumbnailHeight = mediaObject.Thumbnail.Height;
                        moDto.ThumbnailSizeKB = mediaObject.Thumbnail.FileSizeKB;
                        moDto.OptimizedFilename = mediaObject.Optimized.FileName;
                        moDto.OptimizedWidth = mediaObject.Optimized.Width;
                        moDto.OptimizedHeight = mediaObject.Optimized.Height;
                        moDto.OptimizedSizeKB = mediaObject.Optimized.FileSizeKB;
                        moDto.OriginalFilename = mediaObject.Original.FileName;
                        moDto.OriginalWidth = mediaObject.Original.Width;
                        moDto.OriginalHeight = mediaObject.Original.Height;
                        moDto.OriginalSizeKB = mediaObject.Original.FileSizeKB;
                        moDto.ExternalHtmlSource = mediaObject.Original.ExternalHtmlSource;
                        moDto.ExternalType = (mediaObject.Original.ExternalType == MimeTypeCategory.NotSet ? String.Empty : mediaObject.Original.ExternalType.ToString());
                        moDto.Title = mediaObject.Title;
                        moDto.Seq = mediaObject.Sequence;
                        moDto.CreatedBy = mediaObject.CreatedByUserName;
                        moDto.DateAdded = mediaObject.DateAdded;
                        moDto.LastModifiedBy = mediaObject.LastModifiedByUserName;
                        moDto.DateLastModified = mediaObject.DateLastModified;
                        moDto.IsPrivate = mediaObject.IsPrivate;

                        // Update metadata items, if necessary, in MediaObjectMetadata table.
                        UpdateMetadataItems(mediaObject, ctx);
                    }
                }

                ctx.SaveChanges();
            }

            return mediaObject.Id;
        }
        /// <summary>
        /// Permanently delete the specified media object from the data store. This action cannot
        /// be undone.
        /// </summary>
        /// <param name="mediaObject">The <see cref="IGalleryObject"/> to delete from the data store.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="mediaObject" /> is null.</exception>
        public override void MediaObject_Delete(IGalleryObject mediaObject)
        {
            if (mediaObject == null)
                throw new ArgumentNullException("mediaObject");

            using (GspContext ctx = new GspContext())
            {
                MediaObjectDto mDto = ctx.MediaObjects.Find(mediaObject.Id);

                if (mDto != null)
                {
                    ctx.MediaObjects.Remove(mDto);
                    ctx.SaveChanges(); // Cascade relationship will auto-delete metadata items
                }
            }
        }
Пример #13
0
        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();
        }
        /// <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);
                        ctx.SaveChanges();
                        metaDataItem.MediaObjectMetadataId = mDto.MediaObjectMetadataId;
                    }
                    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>
        /// 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)
            {
                int tmpId = 0;
                var mDtos = new Dictionary<int, MediaObjectMetadataDto>();
                var metas = new Dictionary<int, IGalleryObjectMetadataItem>();

                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);

                    metas.Add(++tmpId, metaDataItem);
                    mDtos.Add(tmpId, mDto);
                }

                ctx.SaveChanges();

                // Loop through each metadata item again, find the matching DTO object, and update
                // the newly assigned ID.
                foreach (KeyValuePair<int, IGalleryObjectMetadataItem> kvp in metas)
                {
                    MediaObjectMetadataDto mDto;
                    if (mDtos.TryGetValue(kvp.Key, out mDto))
                    {
                        kvp.Value.MediaObjectMetadataId = mDto.MediaObjectMetadataId;
                    }
                }
            }
        }
        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();
            }
        }
        /// <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>
        /// Permanently delete the profile records for the specified <paramref name="userName"/>.
        /// </summary>
        /// <param name="userName">The user name that uniquely identifies the user.</param>
        public override void Profile_DeleteProfileForUser(string userName)
        {
            using (GspContext ctx = new GspContext())
            {
                foreach (UserGalleryProfileDto pDto in (from p in ctx.UserGalleryProfiles where p.UserName == userName select p))
                {
                    ctx.UserGalleryProfiles.Remove(pDto);
                }

                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>
        /// Permanently delete the profile records associated with the specified <paramref name="galleryId"/>.
        /// </summary>
        /// <param name="galleryId">The gallery ID.</param>
        public override void Profile_DeleteProfilesForGallery(int galleryId)
        {
            using (GspContext ctx = new GspContext())
            {
                foreach (UserGalleryProfileDto pDto in (from p in ctx.UserGalleryProfiles where p.FKGalleryId == galleryId select p))
                {
                    ctx.UserGalleryProfiles.Remove(pDto);
                }

                ctx.SaveChanges();
            }
        }
        /// <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>
        /// Persist the specified <paramref name="profile"/> to the data store.
        /// </summary>
        /// <param name="profile">The profile to persist to the data store.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="profile" /> is null.</exception>
        public override void Profile_Save(IUserProfile profile)
        {
            if (profile == null)
                throw new ArgumentNullException("profile");

            using (GspContext ctx = new GspContext())
            {
                foreach (IUserGalleryProfile userGalleryProfile in profile.GalleryProfiles)
                {
                    IUserGalleryProfile ugp = userGalleryProfile;

                    // ShowMediaObjectMetadata
                    UserGalleryProfileDto pDto = (from p in ctx.UserGalleryProfiles where p.UserName == ugp.UserName && p.FKGalleryId == ugp.GalleryId && p.SettingName == "ShowMediaObjectMetadata" select p).FirstOrDefault();

                    if (pDto == null)
                    {
                        pDto = new UserGalleryProfileDto
                                        {
                                            UserName = ugp.UserName,
                                            FKGalleryId = ugp.GalleryId,
                                            SettingName = "ShowMediaObjectMetadata",
                                            SettingValue = ugp.ShowMediaObjectMetadata.ToString(CultureInfo.InvariantCulture)
                                        };

                        ctx.UserGalleryProfiles.Add(pDto);
                    }
                    else
                    {
                        pDto.SettingValue = ugp.ShowMediaObjectMetadata.ToString(CultureInfo.InvariantCulture);
                    }

                    // EnableUserAlbum
                    pDto = (from p in ctx.UserGalleryProfiles where p.UserName == ugp.UserName && p.FKGalleryId == ugp.GalleryId && p.SettingName == "EnableUserAlbum" select p).FirstOrDefault();

                    if (pDto == null)
                    {
                        pDto = new UserGalleryProfileDto
                                        {
                                            UserName = ugp.UserName,
                                            FKGalleryId = ugp.GalleryId,
                                            SettingName = "EnableUserAlbum",
                                            SettingValue = ugp.EnableUserAlbum.ToString(CultureInfo.InvariantCulture)
                                        };

                        ctx.UserGalleryProfiles.Add(pDto);
                    }
                    else
                    {
                        pDto.SettingValue = ugp.EnableUserAlbum.ToString(CultureInfo.InvariantCulture);
                    }

                    // UserAlbumId
                    pDto = (from p in ctx.UserGalleryProfiles where p.UserName == ugp.UserName && p.FKGalleryId == ugp.GalleryId && p.SettingName == "UserAlbumId" select p).FirstOrDefault();

                    if (pDto == null)
                    {
                        pDto = new UserGalleryProfileDto
                                        {
                                            UserName = ugp.UserName,
                                            FKGalleryId = ugp.GalleryId,
                                            SettingName = "UserAlbumId",
                                            SettingValue = ugp.UserAlbumId.ToString(CultureInfo.InvariantCulture)
                                        };

                        ctx.UserGalleryProfiles.Add(pDto);
                    }
                    else
                    {
                        pDto.SettingValue = ugp.UserAlbumId.ToString(CultureInfo.InvariantCulture);
                    }
                }

                ctx.SaveChanges();
            }
        }
        /// <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>
        /// Permanently delete the specified album from the data store, including any
        /// child albums and media objects (cascading delete). This action cannot be undone.
        /// </summary>
        /// <param name="album">The <see cref="IAlbum"/> to delete from the data store.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception>
        public override void Album_Delete(IAlbum album)
        {
            if (album == null)
                throw new ArgumentNullException("album");

            using (GspContext ctx = new GspContext())
            {
                // Get a list of this album and all its child albums. Then delete.
                List<int> albumIds = new List<int>();
                albumIds.Add(album.Id);
                albumIds.AddRange(GetChildAlbumIds(album));

                foreach (AlbumDto aDto in (from a in ctx.Albums where albumIds.Contains(a.AlbumId) select a))
                {
                    ctx.Albums.Remove(aDto);
                }

                ctx.SaveChanges();

                //        // First, create a table to hold this album ID and all child album IDs, then
                //        // insert the album into our temporary table.
                //        string tmpTableName = "tmp" + Guid.NewGuid().ToString().Replace("-", String.Empty);

                //        string sql = String.Format(@"CREATE TABLE {0} (aid int, apid int, processed int);", tmpTableName);

                //        ctx.Database.ExecuteSqlCommand(sql);

                //        try
                //        {
                //          sql = String.Concat("INSERT INTO ", tmpTableName, " SELECT AlbumId, AlbumParentId, 0 FROM [gs_Album] WHERE AlbumId = {0};");
                //          ctx.Database.ExecuteSqlCommand(sql, album.Id);

                //          /* Set up a loop where we insert the children of the first album, and their children, and so on, until no
                //    children are left. The end result is that the table is filled with info about the album and all his descendents.
                //    The processed field in tmpAlbum represents the # of levels from the bottom. Thus the records
                //    with the MAX processed value is the ID of the album passed to this function, and the records with the MIN level (should always be 1)
                //    represent the most distant descendents. */

                //          bool foundRecords;
                //          do
                //          {
                //            sql = String.Format(@"INSERT INTO {0}
                //SELECT AlbumId, AlbumParentId, -1
                //FROM [gs_Album] WHERE AlbumParentId IN (SELECT aid FROM {0} WHERE processed = 0);", tmpTableName);
                //            ctx.Database.ExecuteSqlCommand(sql);

                //            sql = String.Format(@"UPDATE {0} SET processed = processed + 1;", tmpTableName);
                //            ctx.Database.ExecuteSqlCommand(sql);

                //            sql = String.Format(@"SELECT COUNT(*) FROM {0} WHERE processed = 0;", tmpTableName);
                //            foundRecords = (ctx.Database.ExecuteSqlCommand(sql) > 0);
                //          } while (foundRecords);

                //          /* At this point tmpAlbum contains info about the album and all its descendents. Delete all media objects
                //             * and roles associated with these albums, and then delete the albums.
                //             * Only delete albums that are not the root album (apid <> 0). */

                //          sql = String.Format(@"DELETE FROM [gs_MediaObject] WHERE FKAlbumId IN (SELECT aid FROM {0});", tmpTableName);
                //          ctx.Database.ExecuteSqlCommand(sql);

                //          sql = String.Format(@"DELETE FROM [gs_Role_Album] WHERE FKAlbumId IN (SELECT aid FROM {0} WHERE apid <> 0);", tmpTableName);
                //          ctx.Database.ExecuteSqlCommand(sql);

                //          sql = String.Format(@"DELETE FROM [gs_Album] WHERE AlbumId IN (SELECT aid FROM {0} WHERE apid <> 0);", tmpTableName);
                //          ctx.Database.ExecuteSqlCommand(sql);
                //        }
                //        finally
                //        {
                //          ctx.Database.ExecuteSqlCommand(String.Format(CultureInfo.CurrentCulture, "DROP TABLE {0};", tmpTableName));
                //        }
            }
        }
        /// <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>
        /// Permanently delete this gallery server role from the data store, including the list of role/album relationships
        /// associated with this role. This action cannot be undone.
        /// </summary>
        /// <param name="role">An instance of <see cref="IGalleryServerRole"/> to delete from the data store.</param>
        public override void Role_Delete(IGalleryServerRole role)
        {
            // Delete a gallery server role. This procedure only deletes it from the custom gallery server tables,
            // not the ASP.NET role membership table(s). The web application code that invokes this procedure also
            // uses the standard ASP.NET technique to delete the role from the membership table(s).
            // First delete the records from the role/album association table, then delete the role.
            using (GspContext ctx = new GspContext())
            {
                foreach (RoleAlbumDto raDto in (from ra in ctx.RoleAlbums where ra.FKRoleName == role.RoleName select ra))
                {
                    ctx.RoleAlbums.Remove(raDto);
                }

                ctx.Roles.Remove(ctx.Roles.Find(role.RoleName));

                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>
        /// Delete the media queue item from the data store.
        /// </summary>
        /// <param name="mediaQueue">The media queue item to delete from the data store.</param>
        public override void MediaQueue_Delete(MediaQueueDto mediaQueue)
        {
            if (mediaQueue == null)
                throw new ArgumentNullException("mediaQueue");

            using (GspContext ctx = new GspContext())
            {
                ctx.MediaQueues.Attach(mediaQueue);

                ctx.MediaQueues.Remove(mediaQueue);
                ctx.SaveChanges();
            }
        }