コード例 #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DisplayObject"/> class.
        /// </summary>
        /// <param name="width">The width of this object, in pixels.</param>
        /// <param name="height">The height of this object, in pixels.</param>
        /// <param name="filename">The name of the file representing this object. Example: sonorandesert.jpg</param>
        /// <param name="parent">The media object to which this display object applies.</param>
        /// <param name="displayType">The type of the display object.</param>
        /// <param name="displayObjectCreator">The object responsible for generating the file this display object points to.</param>
        private DisplayObject(int width, int height, string filename, IGalleryObject parent, DisplayObjectType displayType, IDisplayObjectCreator displayObjectCreator)
        {
            this._width = width;
            this._height = height;
            this._filename = filename;

            if (!String.IsNullOrEmpty(filename))
            {
                this._mimeType = Factory.LoadMimeType(parent.GalleryId, this._filename);
            }

            if (this._mimeType == null)
            {
                this._mimeType = new NullObjects.NullMimeType();
            }

            this._parent = parent;
            this._displayType = displayType;
            this._displayObjectCreator = displayObjectCreator;
            this._displayObjectCreator.Parent = this;

            if (this._parent is IAlbum)
            {
                this._mediaObjectId = int.MinValue;
            }
            else
            {
                this._mediaObjectId = parent.Id;
            }
        }
コード例 #2
0
ファイル: MediaObject.cs プロジェクト: haimon74/KanNaim
		/// <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>
		public static int Save(IGalleryObject mediaObject)
		{
			int mediaObjectId = mediaObject.Id;

			if (mediaObject.IsNew)
			{
				// Insert new record into MediaObject table.
				SqlCommand cmd = GetCommandMediaObjectInsert(mediaObject);
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();

				mediaObjectId = Convert.ToInt32(cmd.Parameters["@Identity"].Value, System.Globalization.NumberFormatInfo.InvariantInfo);

				if (mediaObject.Id != mediaObjectId)
				{
					mediaObject.Id = mediaObjectId;
				}

				// Insert metadata items, if any, into MediaObjectMetadata table.
				InsertMetadataItems(mediaObject);
			}
			else
			{
				SqlCommand cmd = GetCommandMediaObjectUpdate(mediaObject);
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();

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

			return mediaObjectId;
		}
コード例 #3
0
ファイル: rotateimage.aspx.cs プロジェクト: haimon74/KanNaim
		protected static int GetImageHeight(IGalleryObject galleryObject)
		{
			if (galleryObject.Optimized.Height > int.MinValue)
				return galleryObject.Optimized.Height;
			else
				return galleryObject.Thumbnail.Height;
		}
コード例 #4
0
        /// <summary>
        /// Adds the specified gallery object.
        /// </summary>
        /// <param name="item">The gallery object.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="item" /> is null.</exception>
        public void Add(IGalleryObject item)
        {
            if (item == null)
                throw new ArgumentNullException("item", "Cannot add null to an existing GalleryObjectCollection. Items.Count = " + Items.Count);

            Items.TryAdd(GetKey(item), item);
        }
コード例 #5
0
ファイル: rotateimage.aspx.cs プロジェクト: haimon74/KanNaim
		protected static int GetImageWidth(IGalleryObject galleryObject)
		{
			if (galleryObject.Optimized.Width > int.MinValue)
				return galleryObject.Optimized.Width;
			else
				return galleryObject.Thumbnail.Width;
		}
コード例 #6
0
ファイル: DisplayObject.cs プロジェクト: haimon74/KanNaim
		private bool _hasBeenDisposed; // Used by Dispose() methods
		
		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="DisplayObject"/> class.
		/// </summary>
		/// <param name="width">The width of this object, in pixels.</param>
		/// <param name="height">The height of this object, in pixels.</param>
		/// <param name="filename">The name of the file representing this object. Example: sonorandesert.jpg</param>
		/// <param name="parent">The media object to which this display object applies.</param>
		/// <param name="displayType">The type of the display object.</param>
		/// <param name="displayObjectCreator">The object responsible for generating the file this display object points to.</param>
		private DisplayObject(int width, int height, string filename, IGalleryObject parent, DisplayObjectType displayType, IDisplayObjectCreator displayObjectCreator)
		{
#if DEBUG
			tt.Tools.StartingMethod(width, height, filename, parent, displayType, displayObjectCreator);
#endif

			this._width = width;
			this._height = height;
			this._filename = filename;

			if (!String.IsNullOrEmpty(filename))
			{
				this._mimeType = GalleryServerPro.Business.MimeType.LoadInstanceByFilePath(this._filename);
			}

			if (this._mimeType == null)
			{
				this._mimeType = new NullObjects.NullMimeType();
			}

			this._parent = parent;
			this._displayType = displayType;
			this._displayObjectCreator = displayObjectCreator;

			if (this._parent is IAlbum)
			{
				this._mediaObjectId = int.MinValue;
			}
			else
			{
				this._mediaObjectId = parent.Id;
			}
		}
コード例 #7
0
ファイル: rotateimage.aspx.cs プロジェクト: haimon74/KanNaim
		protected string GetImageUrl(IGalleryObject galleryObject)
		{
			if ((galleryObject.Optimized.Width > int.MinValue) || (galleryObject.Optimized.Height > int.MinValue))
				return GetOptimizedUrl(galleryObject);
			else
				return GetThumbnailUrl(galleryObject);
		}
コード例 #8
0
        /// <summary>
        /// Copy the specified object and place it in the specified destination album. This method creates a completely separate copy
        /// of the original, including copying the physical files associated with this object. The copy is persisted to the data
        /// store and then returned to the caller. When copying albums, all the album's children, grandchildren, etc are also copied.
        /// The audit fields of the copied objects are automatically updated before saving.
        /// </summary>
        /// <param name="galleryObjectToCopy">The gallery object to copy.</param>
        /// <param name="destinationAlbum">The album to which the current object should be copied.</param>
        /// <returns>
        /// Returns a new gallery object that is an exact copy of the original, except that it resides in the specified
        /// destination album, and of course has a new ID. Child objects are recursively copied.
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObjectToCopy" /> is null.</exception>
        public static IGalleryObject CopyGalleryObject(IGalleryObject galleryObjectToCopy, IAlbum destinationAlbum)
        {
            if (galleryObjectToCopy == null)
                throw new ArgumentNullException("galleryObjectToCopy");

            string currentUser = Utils.UserName;

            return galleryObjectToCopy.CopyTo(destinationAlbum, currentUser);
        }
コード例 #9
0
 /// <summary>
 /// Gets a value that uniquely identifies the specified <paramref name="galleryObject" /> (ex: "a25", "m223").
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 /// <returns>Returns an ID.</returns>
 protected static string GetId(IGalleryObject galleryObject)
 {
     // Prepend an 'a' (for album) or 'm' (for media object) to the ID to indicate whether it is
     // an album ID or media object ID.
     if (galleryObject is Album)
         return "a" + galleryObject.Id.ToString(CultureInfo.InvariantCulture);
     else
         return "m" + galleryObject.Id.ToString(CultureInfo.InvariantCulture);
 }
コード例 #10
0
        /// <summary>
        /// Gets the URL to the specified <paramref name="galleryObject" />.
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <returns>Returns a string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObject" /> is null.</exception>
        protected string GetImageUrl(IGalleryObject galleryObject)
        {
            if (galleryObject == null)
                throw new ArgumentNullException("galleryObject");

            if ((galleryObject.Optimized.Width > int.MinValue) || (galleryObject.Optimized.Height > int.MinValue))
                return GetOptimizedUrl(galleryObject);
            else
                return GetThumbnailUrl(galleryObject);
        }
コード例 #11
0
        /// <summary>
        /// Gets the width of the specified <paramref name="galleryObject" />.
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <returns>The width.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObject" /> is null.</exception>
        protected static int GetImageWidth(IGalleryObject galleryObject)
        {
            if (galleryObject == null)
                throw new ArgumentNullException("galleryObject");

            if (galleryObject.Optimized.Width > int.MinValue)
                return galleryObject.Optimized.Width;
            else
                return galleryObject.Thumbnail.Width;
        }
コード例 #12
0
 /// <summary>
 /// Gets the CSS class to apply to the thumbnail object.
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 /// <returns>Returns a CSS class.</returns>
 protected static string GetThumbnailCssClass(IGalleryObject galleryObject)
 {
     // If it's an album then specify the appropriate CSS class so that the "Album"
     // header appears over the thumbnail. This is to indicate to the user that the
     // thumbnail represents an album.
     if (galleryObject is Album)
         return "thmb album";
     else
         return "thmb";
 }
コード例 #13
0
        /// <summary>
        /// Calculate the potential hard drive savings, in KB, if all original files were deleted from <paramref name="galleryObject"/>.
        /// If <paramref name="galleryObject"/> is an Album, then the value includes the sum of the size of all original files
        /// within the album.
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <returns>Returns the potential hard drive savings, in KB, if all original files were deleted from <paramref name="galleryObject"/>.</returns>
        protected static string GetSavings(IGalleryObject galleryObject)
        {
            if (galleryObject == null)
                throw new ArgumentNullException("galleryObject");

            if (galleryObject.GetType() == typeof(Album))
                return String.Format(CultureInfo.CurrentCulture, "({0} KB)", GetFileSizeKbAllOriginalFilesInAlbum((IAlbum)galleryObject));
            else
                return String.Format(CultureInfo.CurrentCulture, "({0} KB)", galleryObject.Original.FileSizeKB);
        }
コード例 #14
0
ファイル: GalleryObject.cs プロジェクト: haimon74/KanNaim
		private bool _hasBeenDisposed; // Used by Dispose() methods

		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="GalleryObject"/> class.
		/// </summary>
		protected GalleryObject()
		{
			this._parent = new NullObjects.NullGalleryObject();
			this._thumbnail = new NullObjects.NullDisplayObject();
			this._optimized = new NullObjects.NullDisplayObject();
			this._original = new NullObjects.NullDisplayObject();

			// Default IsSynchronized to true. It is set to false during a synchronization.
			this.IsSynchronized = true;
		}
コード例 #15
0
        protected string GetMediaObjectUrl(IGalleryObject mediaObject)
        {
            switch (mediaObject.GalleryObjectType)
            {
                case GalleryObjectType.Image: return GetOptimizedUrl(mediaObject);
                case GalleryObjectType.Video: return GetThumbnailUrl(mediaObject);
            }

            return null;
        }
コード例 #16
0
		/// <summary>
		/// Move the specified object to the specified destination album. This method moves the physical files associated with this
		/// object to the destination album's physical directory. The object's Save() method is invoked to persist the changes to the
		/// data store. When moving albums, all the album's children, grandchildren, etc are also moved. 
		/// The audit fields are automatically updated before saving.
		/// </summary>
		/// <param name="galleryObjectToMove">The gallery object to move.</param>
		/// <param name="destinationAlbum">The album to which the current object should be moved.</param>
		public static void MoveGalleryObject(IGalleryObject galleryObjectToMove, IAlbum destinationAlbum)
		{
			string currentUser = Util.UserName;
			DateTime currentTimestamp = DateTime.Now;

			galleryObjectToMove.LastModifiedByUserName = currentUser;
			galleryObjectToMove.DateLastModified = currentTimestamp;

			galleryObjectToMove.MoveTo(destinationAlbum);
		}
コード例 #17
0
        /// <summary>
        /// Gets a value that uniquely identifies the specified <paramref name="galleryObject" /> (ex: "a25", "m223").
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <returns>Returns an ID.</returns>
        protected static string GetId(IGalleryObject galleryObject)
        {
            if (galleryObject == null)
                throw new ArgumentNullException("galleryObject");

            // Prepend an 'a' (for album) or 'm' (for media object) to the ID to indicate whether it is
            // an album ID or media object ID.
            if (galleryObject is Album)
                return "a" + galleryObject.Id.ToString(CultureInfo.InvariantCulture);
            else
                return "m" + galleryObject.Id.ToString(CultureInfo.InvariantCulture);
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GalleryObject"/> class.
        /// </summary>
        protected GalleryObject()
        {
            this._parent = new NullObjects.NullGalleryObject();
            this._thumbnail = new NullObjects.NullDisplayObject();
            this._optimized = new NullObjects.NullDisplayObject();
            this._original = new NullObjects.NullDisplayObject();

            // Default IsSynchronized to false. It is set to true during a synchronization.
            this.IsSynchronized = false;
            this.IsWritable = true;

            this.BeforeAddMetaItem += OnBeforeAddMetaItem;
        }
コード例 #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GalleryObjectMetadataItem" /> class.
 /// </summary>
 /// <param name="mediaObjectMetadataId">The value that uniquely indentifies this metadata item.</param>
 /// <param name="galleryObject">The gallery object this metadata item applies to.</param>
 /// <param name="rawValue">The raw value of the metadata item. Typically this is the value extracted from 
 /// the metadata of the media file.</param>
 /// <param name="value">The value of the metadata item (e.g. "F5.7", "1/500 sec.").</param>
 /// <param name="hasChanges">if set to <c>true</c> this object has changes that have not been persisted to the database.</param>
 /// <param name="metaDef">The meta definition.</param>
 public GalleryObjectMetadataItem(int mediaObjectMetadataId, IGalleryObject galleryObject, string rawValue, string value, bool hasChanges, IMetadataDefinition metaDef)
 {
     _mediaObjectMetadataId = mediaObjectMetadataId;
     GalleryObject = galleryObject;
     _metadataItemName = metaDef.MetadataItem;
     _description = metaDef.DisplayName;
     _rawValue = rawValue;
     _value = value;
     _hasChanges = hasChanges;
     MetaDefinition = metaDef;
     _isVisible = false;
     IsDeleted = false;
 }
コード例 #20
0
        protected static string GetWidthAndHeightStyle(IGalleryObject mediaObject)
        {
            var width = mediaObject.Optimized.Width;
            var height = mediaObject.Optimized.Height;

            if (mediaObject.GalleryObjectType == GalleryObjectType.Video)
            {
                width = mediaObject.Thumbnail.Width;
                height = mediaObject.Thumbnail.Height;
            }

            return String.Format(CultureInfo.InvariantCulture, "width:{0}px;height:{1}px;", width, height);
        }
コード例 #21
0
        /// <summary>
        /// Move the specified object to the specified destination album. This method moves the physical files associated with this
        /// object to the destination album's physical directory. The object's Save() method is invoked to persist the changes to the
        /// data store. When moving albums, all the album's children, grandchildren, etc are also moved. 
        /// The audit fields are automatically updated before saving.
        /// </summary>
        /// <param name="galleryObjectToMove">The gallery object to move.</param>
        /// <param name="destinationAlbum">The album to which the current object should be moved.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObjectToMove" /> is null.</exception>
        public static void MoveGalleryObject(IGalleryObject galleryObjectToMove, IAlbum destinationAlbum)
        {
            if (galleryObjectToMove == null)
                throw new ArgumentNullException("galleryObjectToMove");

            string currentUser = Utils.UserName;
            DateTime currentTimestamp = DateTime.Now;

            galleryObjectToMove.LastModifiedByUserName = currentUser;
            galleryObjectToMove.DateLastModified = currentTimestamp;

            galleryObjectToMove.MoveTo(destinationAlbum);
        }
コード例 #22
0
 /// <summary>
 /// Permanently delete the specified media object from the data store. This action cannot
 /// be undone. This action also deletes the related metadata items.
 /// </summary>
 /// <param name="mediaObject">The <see cref="IGalleryObject" /> to delete from the data store.</param>
 public static void Delete(IGalleryObject mediaObject)
 {
     // Related metadata items in the MediaObjectMetadataItem table are deleted
     // via a cascade delete rule configured between this table and the MediaObject table.
     using (SqlConnection cn = SqlDataProvider.GetDbConnection())
     {
         using (SqlCommand cmd = GetCommandMediaObjectDelete(mediaObject.Id, cn))
         {
             cn.Open();
             cmd.ExecuteNonQuery();
         }
     }
 }
コード例 #23
0
        /// <summary>
        /// Return the requested display object from the specified media object. If Unknown is passed in the 
        /// displayType parameter, and the object is an image, return the optimized object. If an optimized 
        /// version does not exist, return the original object. If Unknown is passed in the displayType parameter, 
        /// and the object is NOT an image, return the original object. If a thumbnail is requested, always 
        /// return a thumbnail object.
        /// </summary>
        /// <param name="mediaObject">The media object containing the display object to return.</param>
        /// <param name="displayType">One of the DisplayObjectType enumeration values indicating which object to return.</param>
        /// <returns>Returns the requested display object from the specified media object.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="mediaObject" /> is null.</exception>
        public static IDisplayObject GetDisplayObject(IGalleryObject mediaObject, DisplayObjectType displayType)
        {
            if (mediaObject == null)
                throw new ArgumentNullException("mediaObject");

            IDisplayObject displayObject;
            switch (displayType)
            {
                case DisplayObjectType.Thumbnail:
                    {
                        displayObject = mediaObject.Thumbnail;
                        break;
                    }
                case DisplayObjectType.Unknown:
                case DisplayObjectType.Optimized:
                    {
                        // Switch to original if it's not in the queue, there isn't an optimized file, or the opt file
                        // is the same as the original file.
                        bool isOptMissing = String.IsNullOrEmpty(mediaObject.Optimized.FileName);
                        bool notInQueue = !MediaConversionQueue.Instance.IsWaitingInQueueOrProcessing(mediaObject.Id);
                        bool isOptSameAsOriginal = (mediaObject.Optimized.FileName == mediaObject.Original.FileName);
                        if (notInQueue && (isOptMissing || isOptSameAsOriginal))
                            displayObject = mediaObject.Original;
                        else
                            displayObject = mediaObject.Optimized;

                        //displayObject = (mediaObject.Optimized.FileName == mediaObject.Original.FileName) ? mediaObject.Original : mediaObject.Optimized;
                        break;
                    }
                case DisplayObjectType.Original:
                    {
                        displayObject = mediaObject.Original;
                        break;
                    }
                default:
                    {
                        displayObject = (mediaObject.Optimized.FileName == mediaObject.Original.FileName) ? mediaObject.Original : mediaObject.Optimized;
                        break;
                    }
            }

            return displayObject;
        }
コード例 #24
0
		private static void DeleteFromFileSystem(IGalleryObject galleryObject)
		{
			// Delete thumbnail file.
			if (System.IO.File.Exists(galleryObject.Thumbnail.FileNamePhysicalPath))
			{
				System.IO.File.Delete(galleryObject.Thumbnail.FileNamePhysicalPath);
			}

			// Delete optimized file.
			if (System.IO.File.Exists(galleryObject.Optimized.FileNamePhysicalPath))
			{
				System.IO.File.Delete(galleryObject.Optimized.FileNamePhysicalPath);
			}

			// Delete original file.
			if (System.IO.File.Exists(galleryObject.Original.FileNamePhysicalPath))
			{
				System.IO.File.Delete(galleryObject.Original.FileNamePhysicalPath);
			}
		}
コード例 #25
0
        /// <summary>
        /// Return the requested display object from the specified media object. If Unknown is passed in the 
        /// displayType parameter, and the object is an image, return the optimized object. If an optimized 
        /// version does not exist, return the original object. If Unknown is passed in the displayType parameter, 
        /// and the object is NOT an image, return the original object. If a thumbnail is requested, always 
        /// return a thumbnail object.
        /// </summary>
        /// <param name="mediaObject">The media object containing the display object to return.</param>
        /// <param name="displayType">One of the DisplayObjectType enumeration values indicating which object to return.</param>
        /// <returns>Returns the requested display object from the specified media object.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="mediaObject" /> is null.</exception>
        public static IDisplayObject GetDisplayObject(IGalleryObject mediaObject, DisplayObjectType displayType)
        {
            if (mediaObject == null)
                throw new ArgumentNullException("mediaObject");

            IDisplayObject displayObject = null;

            if (displayType == DisplayObjectType.Thumbnail)
            {
                displayObject = mediaObject.Thumbnail;
            }
            else if (mediaObject is GalleryServerPro.Business.Image)
            {
                displayObject = GetDisplayObjectForImage(mediaObject, displayType);
            }
            else
            {
                displayObject = mediaObject.Original;
            }

            return displayObject;
        }
コード例 #26
0
		/// <summary>
		/// Persist the gallery object to the data store. This method updates the audit fields before saving. All gallery objects should be
		/// saved through this method rather than directly invoking the gallery object's Save method, unless you want to
		/// manually update the audit fields yourself.
		/// </summary>
		/// <param name="galleryObject">The gallery object to persist to the data store.</param>
		/// <param name="userName">The user name to be associated with the modifications. This name is stored in the internal
		/// audit fields associated with this gallery object.</param>
		public static void SaveGalleryObject(IGalleryObject galleryObject, string userName)
		{
			DateTime currentTimestamp = DateTime.Now;

			if (galleryObject.IsNew)
			{
				galleryObject.CreatedByUserName = userName;
				galleryObject.DateAdded = currentTimestamp;
			}

			if (galleryObject.HasChanges)
			{
				galleryObject.LastModifiedByUserName = userName;
				galleryObject.DateLastModified = currentTimestamp;
			}

			// Verify that any role needed for album ownership exists and is properly configured.
			RoleController.ValidateRoleExistsForAlbumOwner(galleryObject as IAlbum);

			// Persist to data store.
			galleryObject.Save();
		}
コード例 #27
0
        private void ConfigureControls()
        {
            this.TaskHeaderText  = Resources.GalleryServerPro.Task_Rotate_Image_Header_Text;
            this.TaskBodyText    = Resources.GalleryServerPro.Task_Rotate_Image_Body_Text;
            this.OkButtonText    = Resources.GalleryServerPro.Task_Rotate_Image_Ok_Button_Text;
            this.OkButtonToolTip = Resources.GalleryServerPro.Task_Rotate_Image_Ok_Button_Tooltip;

            this.PageTitle = Resources.GalleryServerPro.Task_Rotate_Image_Page_Title;

            IGalleryObjectCollection images = new GalleryObjectCollection();
            IGalleryObject           image  = this.GetMediaObject();

            if (image is GalleryServerPro.Business.Image)
            {
                images.Add(image);
                rptr.DataSource = images;
                rptr.DataBind();
            }
            else
            {
                Util.Redirect(Web.PageId.mediaobject, "moid={0}&msg={1}", image.Id, ((int)Message.CannotRotateObjectNotRotatable).ToString(CultureInfo.InvariantCulture));
            }
        }
コード例 #28
0
        private static void DeleteFromFileSystem(IGalleryObject galleryObject, bool deleteAllFromFileSystem)
        {
            // Delete thumbnail file.
            if (System.IO.File.Exists(galleryObject.Thumbnail.FileNamePhysicalPath))
            {
                System.IO.File.Delete(galleryObject.Thumbnail.FileNamePhysicalPath);
            }

            // Delete optimized file.
            if (!galleryObject.Optimized.FileName.Equals(galleryObject.Original.FileName))
            {
                if (System.IO.File.Exists(galleryObject.Optimized.FileNamePhysicalPath))
                {
                    System.IO.File.Delete(galleryObject.Optimized.FileNamePhysicalPath);
                }
            }

            // Delete original file.
            if (deleteAllFromFileSystem && System.IO.File.Exists(galleryObject.Original.FileNamePhysicalPath))
            {
                System.IO.File.Delete(galleryObject.Original.FileNamePhysicalPath);
            }
        }
コード例 #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DisplayObject"/> class.
        /// </summary>
        /// <param name="parent">The parent.</param>
        /// <param name="displayType">The display type.</param>
        /// <param name="mimeType">Specifies the category to which this mime type belongs. This usually corresponds to the first portion of 
        /// the full mime type description. (e.g. "image" if the full mime type is "image/jpeg").</param>
        private DisplayObject(IGalleryObject parent, DisplayObjectType displayType, MimeTypeCategory mimeType)
        {
            if (displayType != DisplayObjectType.External)
                throw new BusinessException(String.Format(CultureInfo.CurrentCulture, "This overload of the DisplayObject constructor can only be called when the displayType parameter is DisplayObjectType.External. Instead, it was {0}.", displayType.ToString()));

            this._width = int.MinValue;
            this._height = int.MinValue;
            this._filename = String.Empty;
            this._mimeType = GalleryServerPro.Business.MimeType.CreateInstance(mimeType);
            this._externalType = this._mimeType.TypeCategory;
            this._parent = parent;
            this._displayType = displayType;
            this._displayObjectCreator = new NullObjects.NullDisplayObjectCreator { Parent = this };

            if (this._parent is IAlbum)
            {
                this._mediaObjectId = int.MinValue;
            }
            else
            {
                this._mediaObjectId = parent.Id;
            }
        }
コード例 #30
0
        private void BindData()
        {
            //Get the data associated with the album and display
            if (this.GalleryObjectsDataSource == null)
            {
                // Sueetie Modified - Retrieve Recent Photos
                if (DataHelper.GetIntFromQueryString("aid", 1) == -1)
                {
                    List <SueetieMediaObject> sueetieMediaObjects = SueetieMedia.GetSueetieMediaObjectList(this.GalleryPage.CurrentSueetieGalleryID, true);

                    sueetieMediaObjects.Sort(delegate(SueetieMediaObject x, SueetieMediaObject y) { return(DateTime.Compare(y.DateAdded, x.DateAdded)); });

                    int _photoCount = SueetieConfiguration.Get().Media.RecentPhotoCount;
                    if (_photoCount > sueetieMediaObjects.Count)
                    {
                        _photoCount = sueetieMediaObjects.Count;
                    }
                    IGalleryObjectCollection _galleryObjects = new GalleryObjectCollection();
                    for (int i = 0; i < _photoCount; i++)
                    {
                        IGalleryObject _galleryObject = Factory.LoadMediaObjectInstance(sueetieMediaObjects[i].MediaObjectID);
                        _galleryObjects.Add(_galleryObject);
                    }

                    _galleryObjects.Sort();
                    DisplayThumbnails(_galleryObjects, true);
                }
                else
                {
                    DisplayThumbnails(this.GalleryPage.GetAlbum().GetChildGalleryObjects(true, this.GalleryPage.IsAnonymousUser), true);
                }
            }
            else
            {
                DisplayThumbnails(this.GalleryObjectsDataSource, false);
            }
        }
コード例 #31
0
ファイル: ZipUtility.cs プロジェクト: vbraziel/GalleryServer
        /// <summary>
        /// Gets the full path to the media object file, returning the thumbnail, compressed, or
        /// original file as specified in <paramref name="mediaSize"/>.
        /// If a media object does not have a physical file (for example, external media objects), then return <see cref="string.Empty" />.
        /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg
        /// </summary>
        /// <param name="mediaObject">The media object for which to return a path to the media file.</param>
        /// <param name="mediaSize">Size of the media file to return.</param>
        /// <returns>Returns the full path to the media object file or an empty string.</returns>
        private static string GetMediaFilePath(IGalleryObject mediaObject, DisplayObjectType mediaSize)
        {
            switch (mediaSize)
            {
            case DisplayObjectType.Thumbnail:
                return(mediaObject.Thumbnail.FileNamePhysicalPath);

            case DisplayObjectType.Optimized:
                if (string.IsNullOrWhiteSpace(mediaObject.Optimized.FileNamePhysicalPath))
                {
                    return(mediaObject.Original.FileNamePhysicalPath);
                }
                else
                {
                    return(mediaObject.Optimized.FileNamePhysicalPath);
                }

            case DisplayObjectType.Original:
                return(mediaObject.Original.FileNamePhysicalPath);

            default:
                return(string.Empty);
            }
        }
コード例 #32
0
        private IGalleryObject GetDefaultGalleryAlbum(IGalleryControlSettings gcs)
        {
            if (!gcs.AlbumId.HasValue)
            {
                return(null);                // We should never get here because the calling method should have already verified there is a value, but we'll be extra safe.
            }

            IGalleryObject defaultGalleryAlbum = null;

            try
            {
                defaultGalleryAlbum = Factory.LoadAlbumInstance(gcs.AlbumId.Value);
            }
            catch (InvalidAlbumException ex)
            {
                // Album doesn't exist. This won't prevent us from deleting the album but we should note the issue, since
                // it can cause problems to specify an album that doesn't exist for the default gallery object.
                string galleryDescription = Factory.LoadGallery(_albumToDelete.GalleryId).Description;
                string msg = String.Format(CultureInfo.CurrentCulture, Resources.Error_Default_Gallery_Object_Album_Invalid_Ex_Msg, galleryDescription, _albumToDelete.Id);
                EventController.RecordError(new BusinessException(msg, ex), AppSetting.Instance, _albumToDelete.GalleryId, Factory.LoadGallerySettings());
            }

            return(defaultGalleryAlbum);
        }
コード例 #33
0
        private void CreateNewMediaObject(IAlbum album, FileInfo file)
        {
            try
            {
                IGalleryObject mediaObject = Factory.CreateMediaObjectInstance(file, album);
                HelperFunctions.UpdateAuditFields(mediaObject, this._userName);
                mediaObject.Save();

                Core core = ConfigManager.GetGalleryServerProConfigSection().Core;
                if (!core.MediaObjectPathIsReadOnly && (core.DiscardOriginalImageDuringImport) && (mediaObject is Business.Image))
                {
                    ((Business.Image)mediaObject).DeleteHiResImage();
                    mediaObject.Save();
                }

                mediaObject.IsSynchronized = true;

                System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(mediaObject.Hashkey));
            }
            catch (GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException)
            {
                this._synchStatus.SkippedMediaObjects.Add(new KeyValuePair <string, string>(file.FullName.Remove(0, _mediaObjectPhysicalPathLength + 1), Resources.SynchronizationStatus_Disabled_File_Type_Msg));
            }
        }
コード例 #34
0
        private IGalleryObject GetDefaultGalleryAlbum(IGalleryControlSettings gcs)
        {
            if (!gcs.AlbumId.HasValue)
            {
                return(null);                // We should never get here because the calling method should have already verified there is a value, but we'll be extra safe.
            }

            IGalleryObject defaultGalleryAlbum = null;

            try
            {
                defaultGalleryAlbum = Factory.LoadAlbumInstance(gcs.AlbumId.Value);
            }
            catch (InvalidAlbumException ex)
            {
                // Album doesn't exist. This won't prevent us from deleting the album but we should note the issue, since
                // it can cause problems to specify an album that doesn't exist for the default gallery object.
                string galleryDescription = Factory.LoadGallery(_albumToDelete.GalleryId).Description;
                string msg = $"Default Gallery Asset Album Invalid: The gallery '{galleryDescription}' has an album ID specified ({_albumToDelete.Id}) as the default gallery asset and it does not match an existing album. Review this setting in the administration area.";
                EventController.RecordError(new BusinessException(msg, ex), AppSetting.Instance, _albumToDelete.GalleryId, Factory.LoadGallerySettings());
            }

            return(defaultGalleryAlbum);
        }
コード例 #35
0
        private int rotateImages()
        {
            // Rotate any images on the hard drive according to the user's wish.
            int returnValue = int.MinValue;

            Dictionary <int, RotateFlipType> imagesToRotate = retrieveUserSelections();

            try
            {
                HelperFunctions.BeginTransaction();
                foreach (KeyValuePair <int, RotateFlipType> kvp in imagesToRotate)
                {
                    IGalleryObject image = Factory.LoadImageInstance(kvp.Key);
                    image.Rotation = kvp.Value;

                    try
                    {
                        GalleryObjectController.SaveGalleryObject(image);
                    }
                    catch (UnsupportedImageTypeException)
                    {
                        returnValue = (int)Message.CannotRotateInvalidImage;
                    }
                }
                HelperFunctions.CommitTransaction();
            }
            catch
            {
                HelperFunctions.RollbackTransaction();
                throw;
            }

            HelperFunctions.PurgeCache();

            return(returnValue);
        }
コード例 #36
0
        private static ActionResult CreateMediaObject(string filePath, IAlbum album, AddMediaObjectSettings options)
        {
            var result = new ActionResult()
            {
                Title = Path.GetFileName(filePath)
            };

            try
            {
                using (IGalleryObject go = Factory.CreateMediaObjectInstance(filePath, album))
                {
                    SaveGalleryObject(go);

                    if (options.DiscardOriginalFile)
                    {
                        go.DeleteOriginalFile();
                        GalleryObjectController.SaveGalleryObject(go);
                    }

                    result.Status = ActionResultStatus.Success;
                }
            }
            catch (UnsupportedMediaObjectTypeException ex)
            {
                try
                {
                    File.Delete(filePath);
                }
                catch (UnauthorizedAccessException) { }                 // Ignore an error; the file will continue to exist in the destination album directory

                result.Status  = ActionResultStatus.Error;
                result.Message = ex.Message;
            }

            return(result);
        }
コード例 #37
0
ファイル: ZipUtility.cs プロジェクト: ericjbeltran/2009
        /// <summary>
        /// Adds the <paramref name="zipContentFile"/> as a media object to the <paramref name="album"/>.
        /// </summary>
        /// <param name="zipContentFile">A reference to a file in a ZIP archive.</param>
        /// <param name="album">The album to which the file should be added as a media object.</param>
        private void AddMediaObjectToGallery(ZipEntry zipContentFile, IAlbum album)
        {
            string zipFileName = Path.GetFileName(zipContentFile.Name).Trim();

            if (zipFileName.Length == 0)
            {
                return;
            }

            string uniqueFilename = HelperFunctions.ValidateFileName(album.FullPhysicalPathOnDisk, zipFileName);
            string uniqueFilepath = Path.Combine(album.FullPhysicalPathOnDisk, uniqueFilename);

            // Extract the file from the zip stream and save as the specified filename.
            ExtractFileFromZipStream(uniqueFilepath);

            // Get the file we just saved to disk.
            FileInfo mediaObjectFile = new FileInfo(uniqueFilepath);

            try
            {
                IGalleryObject mediaObject = Factory.CreateMediaObjectInstance(mediaObjectFile, album);
                HelperFunctions.UpdateAuditFields(mediaObject, this._userName);
                mediaObject.Save();

                if ((_discardOriginalImage) && (mediaObject is Business.Image))
                {
                    ((Business.Image)mediaObject).DeleteHiResImage();
                    mediaObject.Save();
                }
            }
            catch (ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException ex)
            {
                this._skippedFiles.Add(new KeyValuePair <string, string>(mediaObjectFile.Name, ex.Message));
                File.Delete(mediaObjectFile.FullName);
            }
        }
コード例 #38
0
        private bool DoesOriginalExceedOptimizedTriggers(IGalleryObject mediaObject)
        {
            // Note: This function also exists in the ImageOptimizedCreator class.

            // Test 1: Is the file size of the original greater than OptimizedImageTriggerSizeKB?
            bool isOriginalFileSizeGreaterThanTriggerSize = false;

            if (mediaObject.Original.FileSizeKB > _optimizedTriggerSizeKb)
            {
                isOriginalFileSizeGreaterThanTriggerSize = true;
            }

            // Test 2: Is the width or length of the original greater than the MaxOptimizedLength?
            bool isOriginalLengthGreaterThanMaxAllowedLength = false;

            double originalWidth  = 0;
            double originalHeight = 0;

            try
            {
                var size = mediaObject.Original.GetSize();
                originalWidth  = size.Width;
                originalHeight = size.Height;
            }
            catch (UnsupportedImageTypeException ex)
            {
                EventController.RecordError(ex, AppSetting.Instance, _galleryId, Factory.LoadGallerySettings());
            }

            if ((originalWidth > _optimizedMaxLength) || (originalHeight > _optimizedMaxLength))
            {
                isOriginalLengthGreaterThanMaxAllowedLength = true;
            }

            return(isOriginalFileSizeGreaterThanTriggerSize | isOriginalLengthGreaterThanMaxAllowedLength);
        }
コード例 #39
0
        /// <summary>
        /// Converts the <paramref name="mediaObject"/> to an instance of <see cref="Entity.MediaItem" />.
        /// The returned object DOES have the <see cref="Entity.MediaItem.MetaItems" /> property assigned.
        /// The instance can be JSON-serialized and sent to the browser. Do not pass an
        /// <see cref="IAlbum" /> to this function.
        /// </summary>
        /// <param name="mediaObject">The media object to convert to an instance of
        /// <see cref="Entity.MediaItem"/>.</param>
        /// <param name="indexInAlbum">The one-based index of this media object within its album. This value is assigned to
        /// <see cref="Entity.MediaItem.Index" />.</param>
        /// <param name="browsers">An <see cref="System.Array"/> of browser ids for the current browser. This
        /// is a list of strings that represent the various categories of browsers the current browser belongs
        /// to. This is typically populated by calling ToArray() on the Request.Browser.Browsers property.
        /// If set to null, the property is automatically populated.</param>
        /// <returns>
        /// Returns an <see cref="Entity.MediaItem"/> object containing information
        /// about the requested media object.
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="mediaObject" /> or
        /// <paramref name="browsers" /> is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown when <paramref name="browsers" /> does
        /// not contain any elements.</exception>
        public static MediaItem ToMediaItem(IGalleryObject mediaObject, int indexInAlbum, Array browsers)
        {
            if (mediaObject == null)
            {
                throw new ArgumentNullException("mediaObject");
            }

            if (browsers == null)
            {
                throw new ArgumentNullException("browsers");
            }

            if (browsers.Length == 0)
            {
                throw new ArgumentOutOfRangeException("browsers", "The browsers array parameter must have at least one element.");
            }

            var isBeingProcessed = MediaConversionQueue.Instance.IsWaitingInQueueOrProcessing(mediaObject.Id, MediaQueueItemConversionType.CreateOptimized);

            var moEntity = new MediaItem
            {
                Id               = mediaObject.Id,
                AlbumId          = mediaObject.Parent.Id,
                AlbumTitle       = mediaObject.Parent.Title,
                Index            = indexInAlbum,
                Title            = mediaObject.Title,
                Views            = GetViews(mediaObject, browsers).ToArray(),
                HighResAvailable = isBeingProcessed || (!String.IsNullOrEmpty(mediaObject.Optimized.FileName)) && (mediaObject.Original.FileName != mediaObject.Optimized.FileName),
                IsDownloadable   = !(mediaObject is ExternalMediaObject),
                MimeType         = (int)mediaObject.MimeType.TypeCategory,
                ItemType         = (int)mediaObject.GalleryObjectType,
                MetaItems        = ToMetaItems(mediaObject.MetadataItems.GetVisibleItems(), mediaObject)
            };

            return(moEntity);
        }
コード例 #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageOptimizedCreator"/> class.
 /// </summary>
 /// <param name="galleryObject">The media object.</param>
 public ImageOptimizedCreator(IGalleryObject galleryObject)
 {
     GalleryObject = galleryObject;
 }
コード例 #41
0
        /// <summary>
        /// Adds the uploaded files to the gallery. This method is called when the application is operating under full trust. In this case,
        /// the ComponentArt Upload control is used. The logic is nearly identical to that in AddUploadedFilesLessThanFullTrust - the only
        /// differences are syntax differences arising from the different file upload control.
        /// </summary>
        /// <param name="files">The files to add to the gallery.</param>
        private void AddUploadedFilesForFullTrust(UploadedFileInfoCollection files)
        {
            // Clear the list of hash keys so we're starting with a fresh load from the data store.
            try
            {
                MediaObjectHashKeys.Clear();

                string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk;

                HelperFunctions.BeginTransaction();

                UploadedFileInfo[] fileInfos = new UploadedFileInfo[files.Count];
                files.CopyTo(fileInfos, 0);
                Array.Reverse(fileInfos);

                foreach (UploadedFileInfo file in fileInfos)
                {
                    if (String.IsNullOrEmpty(file.FileName))
                    {
                        continue;
                    }

                    if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked))
                    {
                        #region Extract the files from the zipped file.

                        lock (file)
                        {
                            if (File.Exists(file.TempFileName))
                            {
                                using (ZipUtility zip = new ZipUtility(Util.UserName, RoleController.GetGalleryServerRolesForUser()))
                                {
                                    this._skippedFiles.AddRange(zip.ExtractZipFile(file.GetStream(), this.GetAlbum(), chkDiscardOriginalImage.Checked));
                                }
                            }
                            else
                            {
                                // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the
                                // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not
                                // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on
                                // to the next one.
                                this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg));
                                continue;                                 // Skip to the next file.
                            }
                        }

                        #endregion
                    }
                    else
                    {
                        #region Add the file

                        string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName);
                        string filepath = Path.Combine(albumPhysicalPath, filename);

#if DEBUG
                        TechInfoSystems.TracingTools.Tools.MarkSpot(string.Format(CultureInfo.CurrentCulture, "Attempting to move file {0} to {1}...", file.FileName, filepath));
#endif
                        lock (file)
                        {
                            if (File.Exists(file.TempFileName))
                            {
                                file.SaveAs(filepath);
                            }
                            else
                            {
                                // When one of the files causes an OutOfMemoryException, this can cause the other files to disappear from the
                                // temp upload directory. This seems to be an issue with the ComponentArt Upload control, since this does not
                                // seem to happen with the ASP.NET FileUpload control. If the file doesn't exist, make a note of it and move on
                                // to the next one.
                                this._skippedFiles.Add(new KeyValuePair <string, string>(file.FileName, Resources.GalleryServerPro.Task_Add_Objects_Uploaded_File_Does_Not_Exist_Msg));
                                continue;                                 // Skip to the next file.
                            }
                        }

                        try
                        {
                            IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum());
                            GalleryObjectController.SaveGalleryObject(go);

                            if ((chkDiscardOriginalImage.Checked) && (go is Business.Image))
                            {
                                ((Business.Image)go).DeleteHiResImage();
                                GalleryObjectController.SaveGalleryObject(go);
                            }
                        }
                        catch (UnsupportedMediaObjectTypeException ex)
                        {
                            try
                            {
                                File.Delete(filepath);
                            }
                            catch (UnauthorizedAccessException) { }                             // Ignore an error; the file will end up getting deleted during cleanup maintenance

                            this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message));
                        }

                        #endregion
                    }
                }

                HelperFunctions.CommitTransaction();
            }
            catch
            {
                HelperFunctions.RollbackTransaction();
                throw;
            }
            finally
            {
                // Delete the uploaded temporary files, as by this time they have been saved to the destination directory.
                foreach (UploadedFileInfo file in files)
                {
                    try
                    {
                        System.IO.File.Delete(file.TempFileName);
                    }
                    catch (UnauthorizedAccessException) { }                     // Ignore an error; the file will end up getting deleted during cleanup maintenance
                }

                // Clear the list of hash keys to free up memory.
                MediaObjectHashKeys.Clear();

                HelperFunctions.PurgeCache();
            }
        }
コード例 #42
0
        /// <summary>
        /// Gets an HTML string representing the content of the <paramref name="galleryObject" />. For example,
        /// albums contain the title and caption while images contain a hyperlinked img tag pointing to 
        /// <paramref name="pageUrl" />. Other media objects contain the HTML generated by <paramref name="moBuilder" />.
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <param name="pageUrl">An URL pointing to a gallery page for the <paramref name="galleryObject" />
        /// Images use this value to create a hyperlink that is wrapped around the img tag.</param>
        /// <param name="moBuilder">An instance of <see cref="MediaObjectHtmlBuilder" />.</param>
        /// <returns><see cref="System.String" />.</returns>
        private static string GetGalleryObjectContent(IGalleryObject galleryObject, string pageUrl, MediaObjectHtmlBuilder moBuilder)
        {
            switch (galleryObject.GalleryObjectType)
            {
                case GalleryObjectType.Image:
                    return String.Format("<div><a href='{0}'>{1}</a></div><p>{2}</p><p>{3}</p>", pageUrl, moBuilder.GenerateHtml(), galleryObject.Title, galleryObject.Caption);

                case GalleryObjectType.Album:
                    return String.Format("<p>{0}</p><p>{1}</p>", galleryObject.Title, galleryObject.Caption);

                default:
                    // Don't include the hyperlink around the MO HTML because that interferes with audio/video controls.
                    return String.Format("<div>{0}</div><p>{1}</p><p>{2}</p>", moBuilder.GenerateHtml(), galleryObject.Title, galleryObject.Caption);
            }
        }
コード例 #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaObjectMetadataReadWriter" /> class.
 /// </summary>
 /// <param name="mediaObject">The media object.</param>
 protected MediaObjectMetadataReadWriter(IGalleryObject mediaObject)
     : base(mediaObject)
 {
 }
コード例 #44
0
 /// <summary>
 /// Gets a value to be initially used to set the width of the title below the thumbnail. This is later removed via jQuery
 /// after the equalSize() function standardizes all the thumbnail boxes. Without this setting the titles will push the
 /// width of the thumbnails to be as wide as the title.
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 /// <returns>An instance of <see cref="Unit" />.</returns>
 protected Unit GetTitleWidth(IGalleryObject galleryObject)
 {
     return(new Unit(galleryObject.Thumbnail.Width + 40, UnitType.Pixel));
 }
コード例 #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaObjectSaveBehavior"/> class.
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 public MediaObjectSaveBehavior(IGalleryObject galleryObject)
 {
     this._galleryObject = galleryObject;
 }
コード例 #46
0
 /// <summary>
 /// Create a new display object instance with the specified properties. No data is retrieved from the
 /// data store. A lazy load is used to inflate the object when necessary
 /// </summary>
 /// <param name="parent">The media object to which this display object applies.</param>
 /// <returns>Returns an instance representing a new display object with default properties.</returns>
 public static IDisplayObject CreateInstance(IGalleryObject parent)
 {
     return(CreateInstance(parent, string.Empty, int.MinValue, int.MinValue, DisplayObjectType.Unknown, new NullObjects.NullDisplayObjectCreator()));
 }
コード例 #47
0
 public void DoAddGalleryObject(IGalleryObject galleryObject)
 {
 }
コード例 #48
0
        /// <summary>
        /// Create a sample album and media object. This method is intended to be invoked once just after the application has been
        /// installed.
        /// </summary>
        /// <param name="galleryId">The ID for the gallery where the sample objects are to be created.</param>
        public static void CreateSampleObjects(int galleryId)
        {
            if (Factory.LoadGallerySetting(galleryId).MediaObjectPathIsReadOnly)
            {
                return;
            }

            DateTime currentTimestamp = DateTime.Now;
            IAlbum   sampleAlbum      = null;

            foreach (IAlbum album in Factory.LoadRootAlbumInstance(galleryId).GetChildGalleryObjects(GalleryObjectType.Album))
            {
                if (album.DirectoryName == "Samples")
                {
                    sampleAlbum = album;
                    break;
                }
            }
            if (sampleAlbum == null)
            {
                // Create sample album.
                sampleAlbum = Factory.CreateEmptyAlbumInstance(galleryId);

                sampleAlbum.Parent                 = Factory.LoadRootAlbumInstance(galleryId);
                sampleAlbum.Title                  = "Samples";
                sampleAlbum.DirectoryName          = "Samples";
                sampleAlbum.Summary                = "Welcome to Gallery Server Pro!";
                sampleAlbum.CreatedByUserName      = "******";
                sampleAlbum.DateAdded              = currentTimestamp;
                sampleAlbum.LastModifiedByUserName = "******";
                sampleAlbum.DateLastModified       = currentTimestamp;
                sampleAlbum.Save();
            }

            // Look for sample image in sample album.
            IGalleryObject sampleImage = null;

            foreach (IGalleryObject image in sampleAlbum.GetChildGalleryObjects(GalleryObjectType.Image))
            {
                if (image.Original.FileName == Constants.SAMPLE_IMAGE_FILENAME)
                {
                    sampleImage = image;
                    break;
                }
            }

            if (sampleImage == null)
            {
                // Sample image not found. Pull image from assembly and save to disk (if needed), then create a media object from it.
                string sampleDirPath       = Path.Combine(Factory.LoadGallerySetting(galleryId).FullMediaObjectPath, sampleAlbum.DirectoryName);
                string sampleImageFilepath = Path.Combine(sampleDirPath, Constants.SAMPLE_IMAGE_FILENAME);

                if (!File.Exists(sampleImageFilepath))
                {
                    Assembly asm = Assembly.GetExecutingAssembly();
                    using (Stream stream = asm.GetManifestResourceStream(String.Concat("GalleryServerPro.Web.gs.images.", Constants.SAMPLE_IMAGE_FILENAME)))
                    {
                        if (stream != null)
                        {
                            BinaryWriter bw     = new BinaryWriter(File.Create(sampleImageFilepath));
                            byte[]       buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            bw.Write(buffer);
                            bw.Flush();
                            bw.Close();
                        }
                    }
                }

                if (File.Exists(sampleImageFilepath))
                {
                    // Temporarily change a couple settings so that the thumbnail and compressed images are high quality.
                    IGallerySettings gallerySettings = Factory.LoadGallerySetting(galleryId);
                    int optTriggerSizeKb             = gallerySettings.OptimizedImageTriggerSizeKb;
                    int thumbImageJpegQuality        = gallerySettings.ThumbnailImageJpegQuality;
                    gallerySettings.ThumbnailImageJpegQuality   = 95;
                    gallerySettings.OptimizedImageTriggerSizeKb = 200;

                    // Create the media object from the file.
                    IGalleryObject image = Factory.CreateImageInstance(new FileInfo(sampleImageFilepath), sampleAlbum);
                    image.Title                  = "Margaret, Skyler and Roger Martin (July 2010)";
                    image.CreatedByUserName      = "******";
                    image.DateAdded              = currentTimestamp;
                    image.LastModifiedByUserName = "******";
                    image.DateLastModified       = currentTimestamp;
                    image.Save();

                    // Restore the default settings.
                    gallerySettings.OptimizedImageTriggerSizeKb = optTriggerSizeKb;
                    gallerySettings.ThumbnailImageJpegQuality   = thumbImageJpegQuality;
                }
            }
        }
コード例 #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VideoThumbnailCreator"/> class.
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 public VideoThumbnailCreator(IGalleryObject galleryObject)
 {
     GalleryObject = galleryObject;
 }
コード例 #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VideoMetadataReadWriter" /> class.
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 public VideoMetadataReadWriter(IGalleryObject galleryObject)
     : base(galleryObject)
 {
 }
コード例 #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GenericThumbnailCreator"/> class.
 /// </summary>
 /// <param name="galleryObject">The gallery object.</param>
 public GenericThumbnailCreator(IGalleryObject galleryObject)
 {
     GalleryObject = galleryObject;
 }
コード例 #52
0
 /// <summary>
 /// Creates an instance of <see cref="CacheItemMedia" /> from <paramref name="go" />. This instance is suitable for storing in cache.
 /// </summary>
 /// <param name="go">The media object.</param>
 /// <returns>An instance of <see cref="CacheItemMedia" />.</returns>
 public static CacheItemMedia CreateFrom(IGalleryObject go)
 {
     return(new CacheItemMedia(go.Id, go.GalleryId, go.Parent.Id, CacheItemDisplayObject.CreateFrom(go.Thumbnail, go.Optimized, go.Original), go.GalleryObjectType, go.Sequence, go.DateAdded, CacheItemMetaItem.FromMetaItems(go.MetadataItems, go.Id, go.GalleryObjectType), go.CreatedByUserName, go.LastModifiedByUserName, go.DateLastModified, go.IsPrivate));
 }
コード例 #53
0
        /// <summary>
        /// Adds the uploaded files to the gallery. This method is called when the application is operating at lesss than full trust. In this case,
        /// the ASP.NET FileUpload control is used. The logic is nearly identical to that in AddUploadedFilesForFullTrust - the only
        /// differences are syntax differences arising from the different file upload control.
        /// </summary>
        private void AddUploadedFilesLessThanFullTrust()
        {
            // Clear the list of hash keys so we're starting with a fresh load from the data store.
            try
            {
                MediaObjectHashKeys.Clear();

                string albumPhysicalPath = this.GetAlbum().FullPhysicalPathOnDisk;

                HelperFunctions.BeginTransaction();

                for (int i = 0; i < 5; i++)
                {
                    FileUpload file = (FileUpload)phUpload.FindControl("fuUpload" + i);

                    if (!file.HasFile)
                    {
                        continue;
                    }

                    if ((System.IO.Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (!chkDoNotExtractZipFile.Checked))
                    {
                        #region Extract the files from the zipped file.

                        // Extract the files from the zipped file.
                        using (ZipUtility zip = new ZipUtility(Util.UserName, RoleController.GetGalleryServerRolesForUser()))
                        {
                            this._skippedFiles.AddRange(zip.ExtractZipFile(file.FileContent, this.GetAlbum(), chkDiscardOriginalImage.Checked));
                        }

                        #endregion
                    }
                    else
                    {
                        #region Add the file

                        string filename = HelperFunctions.ValidateFileName(albumPhysicalPath, file.FileName);
                        string filepath = Path.Combine(albumPhysicalPath, filename);

#if DEBUG
                        TechInfoSystems.TracingTools.Tools.MarkSpot(string.Format(CultureInfo.CurrentCulture, "Attempting to move file {0} to {1}...", file.FileName, filepath));
#endif
                        file.SaveAs(filepath);

                        try
                        {
                            IGalleryObject go = Factory.CreateMediaObjectInstance(filepath, this.GetAlbum());
                            GalleryObjectController.SaveGalleryObject(go);

                            if ((chkDiscardOriginalImage.Checked) && (go is Business.Image))
                            {
                                ((Business.Image)go).DeleteHiResImage();
                                GalleryObjectController.SaveGalleryObject(go);
                            }
                        }
                        catch (UnsupportedMediaObjectTypeException ex)
                        {
                            try
                            {
                                File.Delete(filepath);
                            }
                            catch (UnauthorizedAccessException) { }                             // Ignore an error; the file will end up getting deleted during cleanup maintenance

                            this._skippedFiles.Add(new KeyValuePair <string, string>(filename, ex.Message));
                        }

                        #endregion
                    }
                }

                HelperFunctions.CommitTransaction();
            }
            catch
            {
                HelperFunctions.RollbackTransaction();
                throw;
            }
            finally
            {
                // Clear the list of hash keys to free up memory.
                MediaObjectHashKeys.Clear();

                HelperFunctions.PurgeCache();
            }
        }
コード例 #54
0
 /// <summary>
 /// Create a new display object instance with the specified properties. No data is retrieved from the
 /// data store. A lazy load is used to inflate the object when necessary
 /// </summary>
 /// <param name="parent">The media object to which this display object applies.</param>
 /// <param name="fileName">The name of the file representing this object. Example: sonorandesert.jpg</param>
 /// <param name="width">The width of this object, in pixels.</param>
 /// <param name="height">The height of this object, in pixels.</param>
 /// <param name="displayType">The type of the display object.</param>
 /// <param name="displayObjectCreator">The object responsible for generating the file this display object points to.</param>
 /// <returns>Create a new display object instance with the specified properties.</returns>
 public static IDisplayObject CreateInstance(IGalleryObject parent, string fileName, int width, int height, DisplayObjectType displayType, IDisplayObjectCreator displayObjectCreator)
 {
     return(new DisplayObject(width, height, fileName, parent, displayType, displayObjectCreator));
 }
コード例 #55
0
        private void SynchronizeMediaObjectFiles(DirectoryInfo directory, IAlbum album)
        {
            #region Parameter validation

            if (album == null)
            {
                throw new ArgumentNullException("album");
            }

            if (directory.FullName != album.FullPhysicalPath)
            {
                throw new ArgumentException("Error in SynchronizeMediaObjectFiles().");
            }

            #endregion

            //Update the media object table in the database with the file attributes of all
            //files in the directory passed to this function. Skip any hidden files.
            FileInfo[] files = directory.GetFiles();

            // First sort by the filename.
            Array.Sort <FileInfo>(files, delegate(FileInfo a, FileInfo b)
            {
                return(a.Name.CompareTo(b.Name));
            });

            foreach (FileInfo file in files)
            {
                if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    this._synchStatus.SkippedMediaObjects.Add(new KeyValuePair <string, string>(file.FullName.Remove(0, _mediaObjectPhysicalPathLength + 1), Resources.SynchronizationStatus_Hidden_File_Msg));
                    continue;
                }

                #region Process thumbnail or optimized image

                if (file.Name.StartsWith(_thumbnailPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    // We have a thumbnail image. If we are storing thumbnails in a different directory, delete the file. The user may have just
                    // specified a new thumbnail path, and we need to delete all the previous thumbnails from their original location.
                    if (_thumbnailRootPath != AppSetting.Instance.MediaObjectPhysicalPath)
                    {
                        File.Delete(file.FullName);
                    }
                    continue;
                }

                if (file.Name.StartsWith(_optimizedPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    // We have an optimized image. If we are storing optimized images in a different directory, delete the file. The user may have
                    // just specified a new optimized path, and we need to delete all the previous optimized images from their original location.
                    if (_optimizedRootPath != AppSetting.Instance.MediaObjectPhysicalPath)
                    {
                        File.Delete(file.FullName);
                    }
                    continue;
                }

                #endregion

                IGalleryObject mediaObject = null;
                // See if this file is an existing media object. First look in the album's children. If not there, search the hash
                // keys - maybe it was moved from another directory.
                foreach (IGalleryObject existingMO in album.GetChildGalleryObjects(GalleryObjectType.MediaObject))
                {
                    if (existingMO.Original.FileNamePhysicalPath == file.FullName)
                    {
                        mediaObject = existingMO;
                        break;
                    }
                }

                if ((mediaObject != null) || ((mediaObject == null) && this._mediaObjectsFromDataStore.TryGetValue(HelperFunctions.GetHashKey(file), out mediaObject)))
                {
                    // Found an existing media object matching the file on disk. Update properties, but only if its file extension
                    // is enabled. (If this is a media object that had been added to Gallery Server but its file type was
                    // subsequently disabled, we do not want to synchronize it - we want its info in the data store to be deleted.)
                    if (HelperFunctions.IsFileAuthorizedForAddingToGallery(file.Name))
                    {
                        UpdateExistingMediaObject(album, mediaObject);
                    }
                }
                else
                {
                    // No media object exists for this file. Create a new one.
                    CreateNewMediaObject(album, file);
                }

                int newFileIndex = this._synchStatus.CurrentFileIndex + 1;
                if (newFileIndex < this._synchStatus.TotalFileCount)
                {
                    UpdateStatus(newFileIndex, file.DirectoryName, file.Name);
                }

                if (this._synchStatus.ShouldTerminate)
                {
                    this._synchStatus.ShouldTerminate = false;
                    throw new GalleryServerPro.ErrorHandler.CustomExceptions.SynchronizationTerminationRequestedException();
                }
            }
        }
コード例 #56
0
        private void UpdateExistingMediaObject(IAlbum album, IGalleryObject mediaObject)
        {
            if (mediaObject.Parent.Id != album.Id)
            {
                mediaObject.Parent = album;
            }

            // If the generated hash key is the same as the one already assigned, then do nothing. Otherwise,
            // generate a guaranteed unique hash key with the GetHashKeyUnique function.
            if (mediaObject.Hashkey != HelperFunctions.GetHashKey(mediaObject.Original.FileInfo))
            {
                mediaObject.Hashkey = HelperFunctions.GetHashKeyUnique(mediaObject.Original.FileInfo);
            }

            // Check for existence of thumbnail.
            if (!File.Exists(mediaObject.Thumbnail.FileNamePhysicalPath))
            {
                mediaObject.RegenerateThumbnailOnSave = true;
            }

            Image image = mediaObject as Image;
            if (image != null)
            {
                EvaluateOriginalImage(image);

                EvaluateOptimizedImage(image);
            }
            else
            {
                UpdateNonImageWidthAndHeight(mediaObject);
            }

            HelperFunctions.UpdateAuditFields(mediaObject, this._userName);
            mediaObject.Save();
            mediaObject.IsSynchronized = true;
        }
コード例 #57
0
 public void RemoveGalleryObject(IGalleryObject galleryObject)
 {
 }
コード例 #58
0
        /// <summary>
        /// Builds the syndication item from the <paramref name="galleryObject" /> and having the properties specified
        /// in <paramref name="options" />.
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <param name="options">The options that direct the creation of HTML and URLs for a media object.</param>
        /// <returns>An instance of <see cref="SyndicationItem" />.</returns>
        private static SyndicationItem BuildSyndicationItem(IGalleryObject galleryObject, MediaObjectHtmlBuilderOptions options)
        {
            options.GalleryObject = galleryObject;
            options.DisplayType = (galleryObject.GalleryObjectType == GalleryObjectType.External ? DisplayObjectType.External : DisplayObjectType.Optimized);

            var moBuilder = new MediaObjectHtmlBuilder(options);

            var pageUrl = moBuilder.GetPageUrl();

            var content = GetGalleryObjectContent(galleryObject, pageUrl, moBuilder);

            var item = new SyndicationItem(
                RssEncode(HtmlValidator.RemoveHtml(galleryObject.Title, false)),
                SyndicationContent.CreateHtmlContent(content),
                new Uri(pageUrl),
                galleryObject.Id.ToString(CultureInfo.InvariantCulture),
                galleryObject.DateLastModified);

            item.PublishDate = galleryObject.DateAdded;
            item.Authors.Add(new SyndicationPerson() { Name = galleryObject.CreatedByUserName });
            item.Categories.Add(new SyndicationCategory(galleryObject.GalleryObjectType.ToString()));

            return item;
        }
コード例 #59
0
ファイル: ZipUtility.cs プロジェクト: Pathfinder-Fr/Website
        /// <summary>
        /// Adds the <paramref name="zipContentFile"/> as a media object to the <paramref name="album"/>.
        /// </summary>
        /// <param name="zipContentFile">A reference to a file in a ZIP archive.</param>
        /// <param name="album">The album to which the file should be added as a media object.</param>
        /// // Sueetie Modified - passing i for single logging of action
        private void AddMediaObjectToGallery(ZipEntry zipContentFile, IAlbum album, int i)
        {
            string zipFileName = Path.GetFileName(zipContentFile.Name).Trim();

            if (zipFileName.Length == 0)
            {
                return;
            }

            string uniqueFilename = HelperFunctions.ValidateFileName(album.FullPhysicalPathOnDisk, zipFileName);
            string uniqueFilepath = Path.Combine(album.FullPhysicalPathOnDisk, uniqueFilename);

            // Extract the file from the zip stream and save as the specified filename.
            ExtractFileFromZipStream(uniqueFilepath);

            // Get the file we just saved to disk.
            FileInfo mediaObjectFile = new FileInfo(uniqueFilepath);

            try
            {
                IGalleryObject mediaObject = Factory.CreateMediaObjectInstance(mediaObjectFile, album);
                HelperFunctions.UpdateAuditFields(mediaObject, this._userName);

                // Sueetie Modified - Fixes a weird bug where zipped Image file titles are empty when zipped from my machine
                if (mediaObject.Title.Trim().Length == 0)
                {
                    mediaObject.Title = mediaObjectFile.Name;
                }

                mediaObject.Save();

                if ((_discardOriginalImage) && (mediaObject is Business.Image))
                {
                    ((Business.Image)mediaObject).DeleteHiResImage();
                    mediaObject.Save();
                }

                // Sueetie Modified - Add mediaobject to Sueetie_Content - Single File

                SueetieContent sueetieContent = new SueetieContent
                {
                    SourceID      = mediaObject.Id,
                    ContentTypeID = SueetieMedia.ConvertContentType((int)mediaObject.MimeType.TypeCategory),
                    ApplicationID = (int)SueetieApplications.Current.ApplicationID,
                    UserID        = SueetieContext.Current.User.UserID,
                    IsRestricted  = ((Album)mediaObject.Parent).IsPrivate,
                    Permalink     = SueetieMedia.SueetieMediaObjectUrl(mediaObject.Id, mediaObject.GalleryId)
                };
                SueetieCommon.AddSueetieContent(sueetieContent);

                // Add Sueetie-specific data to Sueetie_gs_MediaObject

                SueetieMediaObject _sueetieMediaObject = new SueetieMediaObject();
                _sueetieMediaObject.MediaObjectID    = mediaObject.Id;
                _sueetieMediaObject.ContentTypeID    = SueetieMedia.ConvertContentType((int)mediaObject.MimeType.TypeCategory);
                _sueetieMediaObject.AlbumID          = mediaObject.Parent.Id;
                _sueetieMediaObject.InDownloadReport = false;
                SueetieMedia.CreateSueetieMediaObject(_sueetieMediaObject);

                SueetieMediaAlbum   sueetieAlbum   = SueetieMedia.GetSueetieMediaAlbum(mediaObject.Parent.Id);
                SueetieMediaGallery sueetieGallery = SueetieMedia.GetSueetieMediaGallery(((Album)mediaObject.Parent).GalleryId);
                if (i == 0 && sueetieGallery.IsLogged)
                {
                    SueetieLogs.LogUserEntry((UserLogCategoryType)sueetieAlbum.AlbumMediaCategoryID, sueetieAlbum.ContentID, SueetieContext.Current.User.UserID);
                }

                SueetieMedia.ClearMediaPhotoListCache(0);
                SueetieMedia.ClearSueetieMediaObjectListCache(mediaObject.GalleryId);
            }
            catch (ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException ex)
            {
                this._skippedFiles.Add(new KeyValuePair <string, string>(mediaObjectFile.Name, ex.Message));
                File.Delete(mediaObjectFile.FullName);
            }
        }
コード例 #60
0
        public void Save(IGalleryObject mediaObject)
        {
            if (mediaObject == null)
            {
                throw new ArgumentNullException("mediaObject");
            }

            if (mediaObject.IsNew)
            {
                var moDto = new MediaObjectDto
                {
                    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()),
                    Seq              = mediaObject.Sequence,
                    CreatedBy        = mediaObject.CreatedByUserName,
                    DateAdded        = mediaObject.DateAdded,
                    LastModifiedBy   = mediaObject.LastModifiedByUserName,
                    DateLastModified = mediaObject.DateLastModified,
                    IsPrivate        = mediaObject.IsPrivate
                };

                Add(moDto);
                Save();                 // Save now so we can get at the ID

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

                // Insert metadata items, if any, into metadata table.
                var repo = new MetadataRepository(Context);                 // Don't put in using construct because we don't want our Context disposed
                repo.Save(mediaObject.MetadataItems);
            }
            else
            {
                MediaObjectDto moDto = Find(mediaObject.Id);

                if (moDto != null)
                {
                    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.Seq              = mediaObject.Sequence;
                    moDto.CreatedBy        = mediaObject.CreatedByUserName;
                    moDto.DateAdded        = mediaObject.DateAdded;
                    moDto.LastModifiedBy   = mediaObject.LastModifiedByUserName;
                    moDto.DateLastModified = mediaObject.DateLastModified;
                    moDto.IsPrivate        = mediaObject.IsPrivate;

                    Save();

                    // Update metadata items, if necessary, in metadata table.
                    var repo = new MetadataRepository(Context);                     // Don't put in using construct because we don't want our Context disposed
                    repo.Save(mediaObject.MetadataItems);
                }
            }
        }