Ejemplo n.º 1
0
        /// <summary>
        /// Gets the watermark to use when the application is in reduced functionality mode.
        /// </summary>
        /// <param name="galleryId">The gallery ID.</param>
        /// <returns>Returns a <see cref="Watermark" /> instance.</returns>
        public static Watermark GetReducedFunctionalityModeWatermark(int galleryId)
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);

            Watermark tempWatermark = null;

            try
            {
                tempWatermark = new Watermark();
                tempWatermark.WatermarkText       = GalleryServerPro.Business.Properties.Resources.Reduced_Functionality_Mode_Watermark_Text;
                tempWatermark.TextFontName        = gallerySetting.WatermarkTextFontName;
                tempWatermark.TextColor           = HelperFunctions.GetColor(gallerySetting.WatermarkTextColor);
                tempWatermark.TextHeightPixels    = 0;
                tempWatermark.TextWidthPercent    = 100;
                tempWatermark.TextOpacityPercent  = 100;
                tempWatermark.TextLocation        = ContentAlignment.MiddleCenter;
                tempWatermark._watermarkImage     = GalleryServerPro.Business.Properties.Resources.GSP_Logo;
                tempWatermark.ImageWidthPercent   = 85;
                tempWatermark.ImageOpacityPercent = 50;
                tempWatermark.ImageLocation       = ContentAlignment.BottomCenter;
            }
            catch
            {
                if (tempWatermark != null)
                {
                    tempWatermark.Dispose();
                }

                throw;
            }

            return(tempWatermark);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the name of the requested media file, without the prefix (e.g. "zThumb_", "zOpt_").
        /// 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.</returns>
        private static string GetMediaFileNameForZip(IGalleryObject mediaObject, DisplayObjectType mediaSize)
        {
            string           fileName       = String.Empty;
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(mediaObject.GalleryId);

            switch (mediaSize)
            {
            case DisplayObjectType.Thumbnail:
                fileName = mediaObject.Thumbnail.FileName.Replace(gallerySetting.ThumbnailFileNamePrefix, String.Empty);
                break;

            case DisplayObjectType.Optimized:
                fileName = mediaObject.Optimized.FileName.Replace(gallerySetting.OptimizedFileNamePrefix, String.Empty);
                break;

            case DisplayObjectType.Original:
                fileName = mediaObject.Original.FileNamePhysicalPath;
                break;
            }

            if (String.IsNullOrEmpty(fileName))
            {
                fileName = mediaObject.Original.FileName;
            }

            return(fileName);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Performs any necessary actions that must occur before an album is deleted. Specifically, it deletes the owner role
        /// if one exists for the album, but only when this album is the only one assigned to the role. It also clears out
        /// <see cref="IGallerySettings.UserAlbumParentAlbumId" /> if the album's ID matches it. This function recursively calls
        /// itself to make sure all child albums are processed.
        /// </summary>
        /// <param name="album">The album to be deleted, or one of its child albums.</param>
        private static void OnBeforeAlbumDelete(IAlbum album)
        {
            // If there is an owner role associated with this album, and the role is not assigned to any other albums, delete it.
            if (!String.IsNullOrEmpty(album.OwnerRoleName))
            {
                IGalleryServerRole role = RoleController.GetGalleryServerRoles().GetRole(album.OwnerRoleName);

                if ((role != null) && (role.AllAlbumIds.Count == 1) && role.AllAlbumIds.Contains(album.Id))
                {
                    RoleController.DeleteGalleryServerProRole(role.RoleName);
                }
            }

            // If the album is specified as the user album container, clear out the setting. The ValidateBeforeAlbumDelete()
            // function will throw an exception if user albums are enabled, so this should only happen when user albums
            // are disabled, so it is safe to clear it out.
            int userAlbumParentAlbumId = Factory.LoadGallerySetting(album.GalleryId).UserAlbumParentAlbumId;

            if (album.Id == userAlbumParentAlbumId)
            {
                IGallerySettings gallerySettingsWriteable = Factory.LoadGallerySetting(album.GalleryId, true);
                gallerySettingsWriteable.UserAlbumParentAlbumId = 0;
                gallerySettingsWriteable.Save();
            }

            // Recursively validate child albums.
            foreach (IGalleryObject childAlbum in album.GetChildGalleryObjects(GalleryObjectType.Album))
            {
                OnBeforeAlbumDelete((IAlbum)childAlbum);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the watermark that is configured for the specified <paramref name="galleryId" />.
        /// </summary>
        /// <param name="galleryId">The gallery ID.</param>
        /// <returns>Returns a <see cref="Watermark" /> instance.</returns>
        public static Watermark GetUserSpecifiedWatermark(int galleryId)
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);

            Watermark tempWatermark = null;

            try
            {
                tempWatermark = new Watermark();
                tempWatermark.WatermarkText       = gallerySetting.WatermarkText;
                tempWatermark.TextFontName        = gallerySetting.WatermarkTextFontName;
                tempWatermark.TextColor           = HelperFunctions.GetColor(gallerySetting.WatermarkTextColor);
                tempWatermark.TextHeightPixels    = gallerySetting.WatermarkTextFontSize;
                tempWatermark.TextWidthPercent    = gallerySetting.WatermarkTextWidthPercent;
                tempWatermark.TextOpacityPercent  = gallerySetting.WatermarkTextOpacityPercent;
                tempWatermark.TextLocation        = gallerySetting.WatermarkTextLocation;
                tempWatermark.ImagePath           = gallerySetting.WatermarkImagePath;
                tempWatermark.ImageWidthPercent   = gallerySetting.WatermarkImageWidthPercent;
                tempWatermark.ImageOpacityPercent = gallerySetting.WatermarkImageOpacityPercent;
                tempWatermark.ImageLocation       = gallerySetting.WatermarkImageLocation;
            }
            catch
            {
                if (tempWatermark != null)
                {
                    tempWatermark.Dispose();
                }

                throw;
            }

            return(tempWatermark);
        }
Ejemplo n.º 5
0
        private bool DoesOriginalExceedOptimizedDimensionTriggers()
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(this._galleryObject.GalleryId);

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

            if (this._galleryObject.Original.FileSizeKB > gallerySetting.OptimizedImageTriggerSizeKb)
            {
                isOriginalFileSizeGreaterThanTriggerSize = true;
            }

            // Test 2: Is the width or length of the original greater than the MaxOptimizedLength?
            bool isOriginalLengthGreaterThanMaxAllowedLength = false;
            int  optimizedMaxLength = gallerySetting.MaxOptimizedLength;
            int  originalWidth      = 0;
            int  originalHeight     = 0;

            try
            {
                originalWidth  = this._galleryObject.Original.Bitmap.Width;
                originalHeight = this._galleryObject.Original.Bitmap.Height;
            }
            catch (UnsupportedImageTypeException) { }

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

            return(isOriginalFileSizeGreaterThanTriggerSize | isOriginalLengthGreaterThanMaxAllowedLength);
        }
        /// <summary>
        /// Gets the target height for the optimized version of the <paramref name="mediaObject"/>. This value is applied to
        /// the {Height} replacement parameter in the encoder settings, if present. The first matching rule is returned:
        /// 1. The <paramref name="mediaObject" /> has a height meta value.
        /// 2. The height of the original file (videos only).
        /// 3. The default value for the media type (e.g. <see cref="IGallerySettings.DefaultVideoPlayerHeight" /> for video and
        /// cref="IGallerySettings.DefaultAudioPlayerHeight" /> for audio).
        /// </summary>
        /// <param name="mediaObject">The media object.</param>
        /// <param name="gallerySettings">The gallery settings.</param>
        /// <param name="encoderSetting">An instance of <see cref="IMediaEncoderSettings" />.</param>
        /// <returns>System.Int32.</returns>
        /// <exception cref="System.ComponentModel.InvalidEnumArgumentException">Thrown when the <paramref name="mediaObject" /> is not a
        /// video, audio, or generic item.</exception>
        private static int GetTargetHeight(IGalleryObject mediaObject, IGallerySettings gallerySettings, IMediaEncoderSettings encoderSetting)
        {
            IGalleryObjectMetadataItem miHeight;

            if (mediaObject.MetadataItems.TryGetMetadataItem(MetadataItemName.Height, out miHeight))
            {
                return(HelperFunctions.ParseInteger(miHeight.Value));
            }

            switch (mediaObject.GalleryObjectType)
            {
            case GalleryObjectType.Video:
                var height = FFmpeg.ParseSourceVideoHeight(FFmpeg.GetOutput(mediaObject.Original.FileNamePhysicalPath, mediaObject.GalleryId));

                return(height > int.MinValue ? height : mediaObject.Original.Height);

            case GalleryObjectType.Audio:
                return(gallerySettings.DefaultAudioPlayerHeight);

            case GalleryObjectType.Generic:                     // Should never hit this because we don't encode generic objects, but for completeness let's put it in
                return(gallerySettings.DefaultGenericObjectHeight);

            default:
                throw new System.ComponentModel.InvalidEnumArgumentException(String.Format("MediaConversionQueue.GetTargetHeight was not designed to handle the enum value {0}. The function must be updated.", mediaObject.GalleryObjectType));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Sends the email. Any exception that occurs is recorded but not allowed to propagate up the stack. Use this overload
        /// to send an e-mail on a background thread. The <paramref name="mailInfoObject"/> object is disposed at the end of the function.
        /// </summary>
        /// <param name="mailInfoObject">An instance of <see cref="Dictionary&lt;MailMessage, IGallerySettings&gt;" /> containing the e-mail
        /// and the associated gallery settings to use to send it.</param>
        private static void SendEmail(object mailInfoObject)
        {
            if (mailInfoObject == null)
            {
                throw new ArgumentException("mailInfoObject");
            }

            Dictionary <MailMessage, IGallerySettings> mailInfo = mailInfoObject as Dictionary <MailMessage, IGallerySettings>;

            if (mailInfo == null)
            {
                throw new ArgumentException(string.Format("The parameter must be an instance of System.Collections.Generic.Dictionary<MailMessage, IGallerySettings>. Instead, it was {0}.", mailInfoObject.GetType()));
            }

            foreach (KeyValuePair <MailMessage, IGallerySettings> mediaObjectKeyValue in mailInfo)
            {
                MailMessage      mailMessage     = mediaObjectKeyValue.Key;
                IGallerySettings gallerySettings = mediaObjectKeyValue.Value;

                SendEmail(mailMessage, true, gallerySettings);

                if (mailMessage != null)
                {
                    mailMessage.Dispose();
                }
            }
        }
Ejemplo n.º 8
0
        private static void DeleteAlbumDirectory(string albumPath, int galleryId)
        {
            // Delete the directory (recursive).
            if (System.IO.Directory.Exists(albumPath))
            {
                System.IO.Directory.Delete(albumPath, true);
            }

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);

            // Delete files and folders from thumbnail cache, if needed.
            string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(albumPath, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);

            if (thumbnailPath != albumPath)
            {
                if (System.IO.Directory.Exists(thumbnailPath))
                {
                    System.IO.Directory.Delete(thumbnailPath, true);
                }
            }

            // Delete files and folders from optimized image cache, if needed.
            string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(albumPath, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);

            if (optimizedPath != albumPath)
            {
                if (System.IO.Directory.Exists(optimizedPath))
                {
                    System.IO.Directory.Delete(optimizedPath, true);
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Generate the file for this display object and save it to the file system. The routine may decide that
        /// a file does not need to be generated, usually because it already exists. However, it will always be
        /// created if the relevant flag is set on the parent IGalleryObject. (Example: If
        /// <see cref="IGalleryObject.RegenerateThumbnailOnSave" /> = true, the thumbnail file will
        /// always be created.) No data is persisted to the data store.
        /// </summary>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedImageTypeException">Thrown when the original
        /// image associated with this gallery object cannot be loaded into a <see cref="Bitmap"/> class because it is an
        /// incompatible or corrupted image type.</exception>
        public void GenerateAndSaveFile()
        {
            // If necessary, generate and save the thumbnail version of the original image.
            if (!(IsThumbnailImageRequired()))
            {
                return;                 // No thumbnail image required.
            }

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(_imageObject.GalleryId);

            // Determine file name and path of the thumbnail image.
            string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(this._imageObject.Original.FileInfo.DirectoryName, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);
            string newFilename   = GenerateNewFilename(thumbnailPath, ImageFormat.Jpeg, gallerySetting.ThumbnailFileNamePrefix);
            string newFilePath   = Path.Combine(thumbnailPath, newFilename);

            bool thumbnailCreated = false;

            if (Array.IndexOf <string>(gallerySetting.ImageMagickFileTypes, Path.GetExtension(_imageObject.Original.FileName).ToLowerInvariant()) >= 0)
            {
                thumbnailCreated = GenerateThumbnailImageUsingImageMagick(newFilePath, gallerySetting);
            }

            if (!thumbnailCreated)
            {
                GenerateThumbnailImageUsingDotNet(newFilePath, gallerySetting);
            }

            this._imageObject.Thumbnail.FileName             = newFilename;
            this._imageObject.Thumbnail.FileNamePhysicalPath = newFilePath;

            int fileSize = (int)(this._imageObject.Thumbnail.FileInfo.Length / 1024);

            this._imageObject.Thumbnail.FileSizeKB = (fileSize < 1 ? 1 : fileSize);             // Very small files should be 1, not 0.
        }
        /// <summary>
        /// Adds the specified gallery.
        /// </summary>
        /// <param name="item">The gallery to add.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="item" /> is null.</exception>
        public void Add(IGallerySettings item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item", "Cannot add null to an existing GallerySettingsCollection. Items.Count = " + _items.Count);
            }

            _items.TryAdd(item.GalleryId, item);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generates the HTML to display a nicely formatted thumbnail image of the specified <paramref name="galleryObject" />, including a
        /// border, shadows and (possibly) rounded corners.
        /// </summary>
        /// <param name="galleryObject">The gallery object to be used as the source for the thumbnail image.</param>
        /// <param name="gallerySettings">The gallery settings that govern display of the <paramref name="galleryObject" />.</param>
        /// <param name="includeHyperlinkToObject">if set to <c>true</c> wrap the image tag with a hyperlink so the user can click through
        /// to the media object view of the item.</param>
        /// <param name="allowAlbumTextWrapping">if set to <c>true</c> the album title is allowed to wrap to a second line if needed.
        /// Set to <c>false</c> when vertical space is limited.</param>
        /// <returns>Returns HTML that displays a nicely formatted thumbnail image of the specified <paramref name="galleryObject" /></returns>
        public static string GenerateThumbnailHtml(IGalleryObject galleryObject, IGallerySettings gallerySettings, HttpBrowserCapabilities browserCaps, bool includeHyperlinkToObject, bool allowAlbumTextWrapping)
        {
            if (IsInternetExplorer1To8(browserCaps))
            {
                return(GenerateThumbnailHtmlForIE1To8(galleryObject, gallerySettings, includeHyperlinkToObject, allowAlbumTextWrapping));
            }

            return(GenerateThumbnailHtmlForStandardBrowser(galleryObject, gallerySettings, includeHyperlinkToObject, allowAlbumTextWrapping));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sets the media object path for the new gallery to the path of the current gallery. The change is persisted to the data store.
        /// </summary>
        /// <param name="gallery">The gallery.</param>
        private void SetMediaObjectPathForNewGallery(IGallery gallery)
        {
            IGallerySettings gallerySettings = Factory.LoadGallerySetting(gallery.GalleryId, true);

            gallerySettings.MediaObjectPath = GallerySettings.MediaObjectPath;
            gallerySettings.ThumbnailPath   = GallerySettings.ThumbnailPath;
            gallerySettings.OptimizedPath   = GallerySettings.OptimizedPath;

            gallerySettings.Save();
        }
Ejemplo n.º 13
0
        private void GenerateGenericThumbnailImage(string newFilePath, IGallerySettings gallerySetting)
        {
            // Build a generic thumbnail.
            var sourceFilePath = GetGenericThumbnailFilePath(GalleryObject.MimeType);

            var size = ImageHelper.SaveImageFileAsJpeg(sourceFilePath, newFilePath, gallerySetting.MaxThumbnailLength, true, gallerySetting.ThumbnailImageJpegQuality);

            GalleryObject.Thumbnail.Width  = size.Width;
            GalleryObject.Thumbnail.Height = size.Height;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Executes the actual media conversion, returning an object that contains settings and the
        /// results of the conversion.
        /// </summary>
        /// <param name="mediaObject">The media object.</param>
        /// <param name="encoderSetting">The encoder setting that defines the conversion parameters.</param>
        /// <returns>
        /// Returns an instance of <see cref="MediaConversionSettings"/> containing settings and
        /// results used in the conversion.
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="mediaObject" /> or
        /// <paramref name="encoderSetting" /> is null.</exception>
        private MediaConversionSettings ExecuteMediaConversion(IGalleryObject mediaObject, IMediaEncoderSettings encoderSetting)
        {
            if (mediaObject == null)
            {
                throw new ArgumentNullException("mediaObject");
            }

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

            AttemptedEncoderSettings.Add(encoderSetting);

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(mediaObject.GalleryId);

            // Determine file name and path of the new file.
            string optimizedPath            = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(mediaObject.Original.FileInfo.DirectoryName, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(mediaObject.Original.FileInfo.Name);
            string newFilename = GenerateNewFilename(optimizedPath, fileNameWithoutExtension, encoderSetting.DestinationFileExtension, gallerySetting.OptimizedFileNamePrefix);
            string newFilePath = Path.Combine(optimizedPath, newFilename);

            MediaConversionSettings mediaSettings = new MediaConversionSettings
            {
                FilePathSource      = mediaObject.Original.FileNamePhysicalPath,
                FilePathDestination = newFilePath,
                EncoderSetting      = encoderSetting,
                GalleryId           = mediaObject.GalleryId,
                MediaQueueId        = _currentMediaQueueItemId,
                TimeoutMs           = gallerySetting.MediaEncoderTimeoutMs,
                MediaObjectId       = mediaObject.Id,
                FFmpegArgs          = String.Empty,
                FFmpegOutput        = String.Empty,
                CancellationToken   = CancelTokenSource.Token
            };

            mediaSettings.FFmpegOutput = FFmpeg.CreateMedia(mediaSettings);
            mediaSettings.FileCreated  = ValidateFile(mediaSettings.FilePathDestination);

            if (!mediaSettings.FileCreated)
            {
                // Could not create the requested version of the file. Record the event, then try again,
                // using the next encoder setting (if one exists).
                string msg = String.Format(CultureInfo.CurrentCulture, "FAILURE: FFmpeg was not able to create video '{0}'.", Path.GetFileName(mediaSettings.FilePathDestination));
                RecordEvent(msg, mediaSettings);

                IMediaEncoderSettings nextEncoderSetting = GetEncoderSetting(mediaObject);
                if (nextEncoderSetting != null)
                {
                    return(ExecuteMediaConversion(mediaObject, nextEncoderSetting));
                }
            }

            return(mediaSettings);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Sends an e-mail containing details about the <paramref name="ev" /> to all users who are configured to receive e-mail
        /// notifications in the specified <paramref name="gallerySettings" /> and who have valid e-mail addresses. (That is, e-mails are
        /// sent to users identified in the property <see cref="IGallerySettings.UsersToNotifyWhenErrorOccurs" />.) A list of usernames
        /// of those were were notified is returned. No e-mails are sent to any usernames in <paramref name="usersWhoWereAlreadyNotified" />.
        /// </summary>
        /// <param name="ev">The application event to be sent to users.</param>
        /// <param name="appSettings">The application settings containing the e-mail configuration data.</param>
        /// <param name="gallerySettings">The gallery settings containing configuration data such as the list of users to be notified.
        /// The users are identified in the <see cref="IGallerySettings.UsersToNotifyWhenErrorOccurs" /> property.</param>
        /// <param name="usersWhoWereAlreadyNotified">The users who were previously notified about the <paramref name="ev" />.</param>
        /// <returns>Returns a list of usernames of those were were notified during execution of this function.</returns>
        /// <exception cref="System.ArgumentNullException">ev</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="ev" /> or <paramref name="gallerySettings" />
        /// is null.</exception>
        private static List <string> SendMail(IEvent ev, IAppSetting appSettings, IGallerySettings gallerySettings, List <string> usersWhoWereAlreadyNotified)
        {
            #region Validation

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

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

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

            #endregion

            if (usersWhoWereAlreadyNotified == null)
            {
                usersWhoWereAlreadyNotified = new List <string>();
            }

            var notifiedUsers = new List <string>();

            //If email reporting has been turned on, send detailed event report.
            if (!gallerySettings.SendEmailOnError)
            {
                return(notifiedUsers);
            }

            MailAddress emailSender = null;

            if (!String.IsNullOrWhiteSpace(appSettings.EmailFromAddress))
            {
                emailSender = new MailAddress(appSettings.EmailFromAddress, appSettings.EmailFromName);
            }

            foreach (var user in gallerySettings.UsersToNotifyWhenErrorOccurs)
            {
                if (!usersWhoWereAlreadyNotified.Contains(user.UserName))
                {
                    if (SendMail(ev, user, appSettings, emailSender))
                    {
                        notifiedUsers.Add(user.UserName);
                    }
                }
            }

            return(notifiedUsers);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Send an e-mail with the specified properties. The e-mail will appear to come from the name and email specified in the
        /// <see cref="IGallerySettings.EmailFromName" /> and <see cref="IGallerySettings.EmailFromAddress" /> configuration settings.
        /// If <paramref name="sendOnBackgroundThread"/> is <c>true</c>, the e-mail is sent on a background thread and the function
        /// returns immediately. An exception is thrown if an error occurs while sending the e-mail, unless <paramref name="sendOnBackgroundThread"/>
        /// is true, in which case the error is logged but the exception does not propagate back to the calling thread.
        /// </summary>
        /// <param name="emailRecipients">The e-mail recipients.</param>
        /// <param name="subject">The text to appear in the subject of the email.</param>
        /// <param name="body">The body of the e-mail. If the body is HTML, specify true for <paramref name="isBodyHtml" />.</param>
        /// <param name="isBodyHtml">Indicates whether the body of the e-mail is in HTML format. When false, the body is
        /// assumed to be plain text.</param>
        /// <param name="galleryId">The gallery ID containing the e-mail configuration settings to use.</param>
        /// <param name="sendOnBackgroundThread">If set to <c>true</c>, send e-mail on a background thread. This causes any errors
        /// to be silently handled by the error logging system, so if it is important for any errors to propogate to the caller,
        /// such as when testing the e-mail function in the Site Administration area, set to <c>false</c>.</param>
        /// <exception cref="WebException">Thrown when a SMTP Server is not specified. (Not thrown when
        /// <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        /// <exception cref="SmtpException">Thrown when the connection to the SMTP server failed, authentication failed,
        /// or the operation timed out. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        /// <exception cref="SmtpFailedRecipientsException">The message could not be delivered to one or more of the
        /// <paramref name="emailRecipients"/>. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="emailRecipients" /> is null.</exception>
        public static void SendEmail(MailAddressCollection emailRecipients, string subject, string body, bool isBodyHtml, int galleryId, bool sendOnBackgroundThread)
        {
            if (emailRecipients == null)
            {
                throw new ArgumentNullException("emailRecipients");
            }

            IGallerySettings gallerySettings = Factory.LoadGallerySetting(galleryId);

            MailAddress emailSender = new MailAddress(gallerySettings.EmailFromAddress, gallerySettings.EmailFromName);
            MailMessage mail        = null;

            try
            {
                mail = new MailMessage();
                foreach (MailAddress mailAddress in emailRecipients)
                {
                    mail.To.Add(mailAddress);
                }
                mail.From       = emailSender;
                mail.Subject    = subject;
                mail.Body       = body;
                mail.IsBodyHtml = isBodyHtml;

                // Because sending the e-mail takes a long time, spin off a thread to send it, unless caller specifically doesn't want to.
                if (sendOnBackgroundThread)
                {
                    // We need to pass two items to the thread (MailMessage and IGallerySettings), but the Start method only takes one. We'll
                    // get around this by wrapping both objects in a dictionary instance and pass that.
                    Dictionary <MailMessage, IGallerySettings> mails = new Dictionary <MailMessage, IGallerySettings>(1);

                    mails.Add(mail, gallerySettings);

                    Thread notifyAdminThread = new Thread(SendEmail);
                    notifyAdminThread.Start(mails);
                }
                else
                {
                    SendEmail(mail, false, gallerySettings);
                    mail.Dispose();
                }
            }
            catch
            {
                if (mail != null)
                {
                    mail.Dispose();
                }

                throw;
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Perform a synchronize according to the specified <paramref name="syncSettingsObject" />.
        /// When complete, update the <see cref="IGallerySettings.LastAutoSync" /> property to the current date/time and persist
        /// to the data store. The <paramref name="syncSettingsObject" /> is specified as <see cref="Object" /> so that this method can
        /// be invoked on a separate thread using <see cref="System.Threading.Thread" />. Any exceptions that occur during the
        /// sync are caught and logged to the event log. NOTE: This method does not perform any security checks; the calling
        /// code must ensure the requesting user is authorized to run the sync.
        /// </summary>
        /// <param name="syncSettingsObject">The synchronize settings object. It must be of type <see cref="SynchronizeSettingsEntity" />.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="syncSettingsObject" /> is null.</exception>
        /// <exception cref="ArgumentException">Thrown when <paramref name="syncSettingsObject" /> is not of type
        /// <see cref="SynchronizeSettingsEntity" />.</exception>
        public static void Synchronize(object syncSettingsObject)
        {
            if (syncSettingsObject == null)
            {
                throw new ArgumentNullException("syncSettingsObject");
            }

            SynchronizeSettingsEntity syncSettings = syncSettingsObject as SynchronizeSettingsEntity;

            if (syncSettings == null)
            {
                throw new ArgumentException(String.Format("The parameter must be an instance of SynchronizeSettingsEntity. Instead, it was {0}.", syncSettingsObject.GetType()));
            }

            IAlbum album = syncSettings.AlbumToSynchronize;

            AppErrorController.LogEvent(String.Format("INFO (not an error): {0} synchronization of album '{1}' (ID {2}) and all child albums has started.", syncSettings.SyncInitiator, album.Title, album.Id), album.GalleryId);

            try
            {
                SynchronizationManager synchMgr = new SynchronizationManager(album.GalleryId);

                synchMgr.IsRecursive        = syncSettings.IsRecursive;
                synchMgr.OverwriteThumbnail = syncSettings.OverwriteThumbnails;
                synchMgr.OverwriteOptimized = syncSettings.OverwriteOptimized;
                synchMgr.RegenerateMetadata = syncSettings.RegenerateMetadata;

                synchMgr.Synchronize(Guid.NewGuid().ToString(), album, "Admin");

                if (syncSettings.SyncInitiator == SyncInitiator.AutoSync)
                {
                    // Update the date/time of this auto-sync and save to data store.
                    IGallerySettings gallerySettings = Factory.LoadGallerySetting(album.GalleryId, true);
                    gallerySettings.LastAutoSync = DateTime.Now;
                    gallerySettings.Save(false);

                    // The above Save() only updated the database; now we need to update the in-memory copy of the settings.
                    // We have to do this instead of simply calling gallerySettings.Save(true) because that overload causes the
                    // gallery settings to be cleared and reloaded, and the reloading portion done by the AddMembershipDataToGallerySettings
                    // function fails in DotNetNuke because there isn't a HttpContext.Current instance at this moment (because this code is
                    // run on a separate thread).
                    IGallerySettings gallerySettingsReadOnly = Factory.LoadGallerySetting(album.GalleryId, false);
                    gallerySettingsReadOnly.LastAutoSync = gallerySettings.LastAutoSync;
                }
            }
            catch (Exception ex)
            {
                AppErrorController.LogError(ex, album.GalleryId);
            }

            AppErrorController.LogEvent(String.Format("INFO (not an error): {0} synchronization of album '{1}' (ID {2}) and all child albums is complete.", syncSettings.SyncInitiator, album.Title, album.Id), album.GalleryId);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Sends the e-mail. If <paramref name="suppressException"/> is <c>true</c>, record any exception that occurs but do not
        /// let it propagate out of this function. When <c>false</c>, record the exception and re-throw it. The caller is
        /// responsible for disposing the <paramref name="mail"/> object.
        /// </summary>
        /// <param name="mail">The mail message to send.</param>
        /// <param name="suppressException">If <c>true</c>, record any exception that occurs but do not
        /// let it propagate out of this function. When <c>false</c>, record the exception and re-throw it.</param>
        /// <param name="gallerySettings">The settings containing e-mail configuration data.</param>
        private static void SendEmail(MailMessage mail, bool suppressException, IGallerySettings gallerySettings)
        {
            try
            {
                if (mail == null)
                {
                    throw new ArgumentNullException("mail");
                }

                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.EnableSsl = gallerySettings.SendEmailUsingSsl;

                    string smtpServer = gallerySettings.SmtpServer;
                    int    smtpServerPort;
                    if (!Int32.TryParse(gallerySettings.SmtpServerPort, out smtpServerPort))
                    {
                        smtpServerPort = Int32.MinValue;
                    }

                    // Specify SMTP server if it is specified in the gallery settings. The server might have been assigned via web.config,
                    // so only update this if we have a setting.
                    if (!String.IsNullOrEmpty(smtpServer))
                    {
                        smtpClient.Host = smtpServer;
                    }

                    // Specify port number if it is specified in the gallery settings and it's not the default value of 25. The port
                    // might have been assigned via web.config, so only update this if we have a setting.
                    if ((smtpServerPort > 0) && (smtpServerPort != 25))
                    {
                        smtpClient.Port = smtpServerPort;
                    }

                    if (String.IsNullOrEmpty(smtpClient.Host))
                    {
                        throw new WebException(@"Cannot send e-mail because a SMTP Server is not specified. This can be configured in any of the following places: (1) Site Admin - Gallery Settings page (preferred), or (2) web.config (Ex: configuration/system.net/mailSettings/smtp/network host='your SMTP server').");
                    }

                    smtpClient.Send(mail);
                }
            }
            catch (Exception ex)
            {
                AppErrorController.LogError(ex);

                if (!suppressException)
                {
                    throw;
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates an album, assigns the user name as the owner, saves it, and returns the newly created album.
        /// A profile entry is created containing the album ID. Returns null if the ID specified in the gallery settings
        /// for the parent album does not represent an existing album. That is, returns null if <see cref="IGallerySettings.UserAlbumParentAlbumId" />
        /// does not match an existing album.
        /// </summary>
        /// <param name="userName">The user name representing the user who is the owner of the album.</param>
        /// <param name="galleryId">The gallery ID for the gallery in which the album is to be created.</param>
        /// <returns>
        /// Returns the newly created user album. It has already been persisted to the database.
        /// Returns null if the ID specified in the gallery settings for the parent album does not represent an existing album.
        /// That is, returns null if <see cref="IGallerySettings.UserAlbumParentAlbumId" />
        /// does not match an existing album.
        /// </returns>
        public static IAlbum CreateUserAlbum(string userName, int galleryId)
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);

            string albumNameTemplate = gallerySetting.UserAlbumNameTemplate;

            IAlbum parentAlbum;

            try
            {
                parentAlbum = AlbumController.LoadAlbumInstance(gallerySetting.UserAlbumParentAlbumId, false);
            }
            catch (InvalidAlbumException ex)
            {
                // The parent album does not exist. Record the error and return null.
                string galleryDescription = Utils.HtmlEncode(Factory.LoadGallery(gallerySetting.GalleryId).Description);
                string msg = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Error_User_Album_Parent_Invalid_Ex_Msg, galleryDescription, gallerySetting.UserAlbumParentAlbumId);
                AppErrorController.LogError(new WebException(msg, ex), galleryId);
                return(null);
            }

            IAlbum album = null;

            try
            {
                album = Factory.CreateEmptyAlbumInstance(parentAlbum.GalleryId);

                album.Title         = albumNameTemplate.Replace("{UserName}", userName);
                album.Summary       = gallerySetting.UserAlbumSummaryTemplate;
                album.OwnerUserName = userName;
                //newAlbum.ThumbnailMediaObjectId = 0; // not needed
                album.Parent    = parentAlbum;
                album.IsPrivate = parentAlbum.IsPrivate;
                GalleryObjectController.SaveGalleryObject(album, userName);

                SaveAlbumIdToProfile(album.Id, userName, album.GalleryId);

                HelperFunctions.PurgeCache();
            }
            catch
            {
                if (album != null)
                {
                    album.Dispose();
                }

                throw;
            }

            return(album);
        }
        private void GenerateThumbnailImageUsingImageMagick(string newFilePath, IGallerySettings gallerySetting)
        {
            // Generate a temporary filename to store the thumbnail created by ImageMagick.
            string tmpImageThumbnailPath = Path.Combine(AppSetting.Instance.TempUploadDirectory, String.Concat(Guid.NewGuid().ToString(), ".jpg"));

            // Request that ImageMagick create the thumbnail. If successful, the file will be created. If not, it fails silently.
            ImageMagick.GenerateThumbnail(this._galleryObject.Original.FileNamePhysicalPath, tmpImageThumbnailPath, this._galleryObject.GalleryId);

            if (File.Exists(tmpImageThumbnailPath))
            {
                int newWidth, newHeight;
                // ImageMagick successfully created a thumbnail image. Now resize it to the width and height we need.
                using (Bitmap originalBitmap = new Bitmap(tmpImageThumbnailPath))
                {
                    ImageHelper.CalculateThumbnailWidthAndHeight(originalBitmap.Width, originalBitmap.Height, out newWidth, out newHeight, false, gallerySetting.MaxThumbnailLength);

                    // Get JPEG quality value (0 - 100). This is ignored if imgFormat = GIF.
                    int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                    // Generate the new image and save to disk.
                    ImageHelper.SaveImageFile(originalBitmap, newFilePath, ImageFormat.Jpeg, newWidth, newHeight, jpegQuality);
                }

                try
                {
                    // Now delete the thumbnail image created by FFmpeg, but no worries if an error happens. The file is in the temp directory
                    // which is cleaned out each time the app starts anyway.
                    File.Delete(tmpImageThumbnailPath);
                }
                catch (IOException ex)
                {
                    ErrorHandler.Error.Record(ex, this._galleryObject.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
                }
                catch (UnauthorizedAccessException ex)
                {
                    ErrorHandler.Error.Record(ex, this._galleryObject.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
                }
                catch (NotSupportedException ex)
                {
                    ErrorHandler.Error.Record(ex, this._galleryObject.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
                }

                this._galleryObject.Thumbnail.Width  = newWidth;
                this._galleryObject.Thumbnail.Height = newHeight;
            }
            else
            {
                // ImageMagick didn't create an image, so default to a generic one.
                GenerateGenericThumbnailImage(newFilePath, gallerySetting);
            }
        }
Ejemplo n.º 21
0
        private static bool IsAnonymousUserAuthorized(SecurityActions securityRequests, bool isPrivateAlbum, int galleryId, SecurityActionsOption secActionsOption)
        {
            // Anonymous user. Return true for viewing-related permission requests on PUBLIC albums; return false for all others.
            IGallerySettings gallerySettings = Factory.LoadGallerySetting(galleryId);

            if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests))
            {
                return(IsAnonymousUserAuthorizedForSingleSecurityAction(securityRequests, isPrivateAlbum, gallerySettings));
            }
            else
            {
                return(IsAnonymousUserAuthorizedForMultipleSecurityActions(securityRequests, isPrivateAlbum, gallerySettings, secActionsOption));
            }
        }
Ejemplo n.º 22
0
        private void DataBindMediaPathInGalleriesGridRow(GridViewRowEventArgs e)
        {
            Label lblMediaPath = (Label)e.Row.FindControl("lblMediaPath");

            if (lblMediaPath == null)
            {
                throw new WebException("Cannot find a Label with ID='lblMediaPath' in the current row of the GridView 'gvGalleries'.");
            }

            IGallery         gallery         = (IGallery)e.Row.DataItem;
            IGallerySettings gallerySettings = Factory.LoadGallerySetting(gallery.GalleryId);

            lblMediaPath.Text = gallerySettings.MediaObjectPath;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Removes potentially dangerous HTML and Javascript in <paramref name="html"/>. If the configuration
        /// setting <see cref="IGallerySettings.AllowUserEnteredHtml" /> is true, then the input is cleaned so that all
        /// HTML tags that are not in a predefined list are HTML-encoded and invalid HTML attributes are deleted. If
        /// <see cref="IGallerySettings.AllowUserEnteredHtml" /> is false, then all HTML tags are deleted. If the setting
        /// <see cref="IGallerySettings.AllowUserEnteredJavascript" /> is true, then script tags and the text "javascript:"
        /// is allowed. Note that if script is not in the list of valid HTML tags defined in <see cref="IGallerySettings.AllowedHtmlTags" />,
        /// it will be deleted even when <see cref="IGallerySettings.AllowUserEnteredJavascript" /> is true. When the setting
        /// is false, all script tags and instances of the text "javascript:" are deleted.
        /// </summary>
        /// <param name="html">The string containing the HTML tags.</param>
        /// <param name="galleryId">The gallery ID. This is used to look up the appropriate configuration values for the gallery.</param>
        /// <returns>
        /// Returns a string with potentially dangerous HTML tags deleted.
        /// </returns>
        public static string Clean(string html, int galleryId)
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);

            if (gallerySetting.AllowUserEnteredHtml)
            {
                HtmlValidator scrubber = new HtmlValidator(html, gallerySetting.AllowedHtmlTags, gallerySetting.AllowedHtmlAttributes, gallerySetting.AllowUserEnteredJavascript);
                return(scrubber.Clean());
            }
            else
            {
                // HTML not allowed. Pass in empty variables for the valid tags and attributes.
                HtmlValidator scrubber = new HtmlValidator(html, null, null, gallerySetting.AllowUserEnteredJavascript);
                return(scrubber.Clean());
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Generate the file for this display object and save it to the file system. The routine may decide that
        /// a file does not need to be generated, usually because it already exists. However, it will always be
        /// created if the relevant flag is set on the parent <see cref="IGalleryObject" />. (Example: If
        /// <see cref="IGalleryObject.RegenerateThumbnailOnSave" /> = true, the thumbnail file will always be created.) No data is
        /// persisted to the data store.
        /// </summary>
        /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.UnsupportedImageTypeException">Thrown when the original
        /// image associated with this gallery object cannot be loaded into a <see cref="Bitmap"/> class because it is an
        /// incompatible or corrupted image type.</exception>
        public void GenerateAndSaveFile()
        {
            // If necessary, generate and save the optimized version of the original image.
            if (!(IsOptimizedImageRequired()))
            {
                bool rotateIsRequested = (this._galleryObject.Rotation != RotateFlipType.RotateNoneFlipNone);

                if (rotateIsRequested || ((this._galleryObject.IsNew) && (String.IsNullOrEmpty(this._galleryObject.Optimized.FileName))))
                {
                    // One of the following is true:
                    // 1. The original is being rotated and there isn't a separate optimized image.
                    // 2. This is a new object that doesn't need a separate optimized image.
                    // In either case, set the optimized properties equal to the original properties.
                    this._galleryObject.Optimized.FileName   = this._galleryObject.Original.FileName;
                    this._galleryObject.Optimized.Width      = this._galleryObject.Original.Width;
                    this._galleryObject.Optimized.Height     = this._galleryObject.Original.Height;
                    this._galleryObject.Optimized.FileSizeKB = this._galleryObject.Original.FileSizeKB;
                }
                return;                 // No optimized image required.
            }

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(_galleryObject.GalleryId);

            // Determine file name and path of the optimized image.
            string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(this._galleryObject.Original.FileInfo.DirectoryName, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);
            string newFilename   = GenerateNewFilename(optimizedPath, ImageFormat.Jpeg, gallerySetting.OptimizedFileNamePrefix);
            string newFilePath   = Path.Combine(optimizedPath, newFilename);

            bool thumbnailCreated = false;

            if (Array.IndexOf <string>(gallerySetting.ImageMagickFileTypes, Path.GetExtension(_galleryObject.Original.FileName).ToLowerInvariant()) >= 0)
            {
                thumbnailCreated = GenerateOptimizedImageUsingImageMagick(newFilePath, gallerySetting);
            }

            if (!thumbnailCreated)
            {
                GenerateOptimizedImageUsingDotNet(newFilePath, gallerySetting);
            }

            this._galleryObject.Optimized.FileName             = newFilename;
            this._galleryObject.Optimized.FileNamePhysicalPath = newFilePath;

            int fileSize = (int)(this._galleryObject.Optimized.FileInfo.Length / 1024);

            this._galleryObject.Optimized.FileSizeKB = (fileSize < 1 ? 1 : fileSize);             // Very small files should be 1, not 0.
        }
        /// <summary>
        /// Generate the thumbnail image for this display object and save it to the file system. The routine may decide that
        /// a file does not need to be generated, usually because it already exists. However, it will always be
        /// created if the relevant flag is set on the parent <see cref="IGalleryObject" />. (Example: If
        /// <see cref="IGalleryObject.RegenerateThumbnailOnSave" /> = true, the thumbnail file will always be created.) No data is
        /// persisted to the data store.
        /// </summary>
        public void GenerateAndSaveFile()
        {
            // If necessary, generate and save the thumbnail version of the original image.
            if (!(IsThumbnailImageRequired()))
            {
                return;                 // No thumbnail image required.
            }

            // All thumbnails should be JPEG format. (Making GIFs from GIF originals resulted in poor quality thumbnail
            // GIFs, so all thumbnails are JPEG, even those from GIFs.)
            ImageFormat imgFormat = ImageFormat.Jpeg;

            // Determine path where thumbnail should be saved. If no thumbnail path is specified in the config file,
            // use the same directory as the original.
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(_galleryObject.GalleryId);
            string           thumbnailPath  = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(this._galleryObject.Parent.FullPhysicalPath, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);

            // Determine name of new file and make sure it is unique in the directory. (Example: If original = puppy.jpg, thumbnail = zThumb_puppy.jpg)
            string newFilename = HelperFunctions.ValidateFileName(thumbnailPath, GenerateNewFilename(imgFormat, gallerySetting.ThumbnailFileNamePrefix));

            // Combine the directory and filename to create the full path to the file.
            string newFilePath = Path.Combine(thumbnailPath, newFilename);

            // Get reference to the bitmap from which the thumbnail image will be generated.
            int newWidth, newHeight;

            using (Bitmap originalBitmap = GetGenericThumbnailBitmap(this._galleryObject.MimeType))
            {
                ImageHelper.CalculateThumbnailWidthAndHeight(originalBitmap.Width, originalBitmap.Height, out newWidth, out newHeight, true, gallerySetting.MaxThumbnailLength);

                // Get JPEG quality value (0 - 100). This is ignored if imgFormat = GIF.
                int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                // Generate the new image and save to disk.
                ImageHelper.SaveImageFile(originalBitmap, newFilePath, imgFormat, newWidth, newHeight, jpegQuality);
            }

            this._galleryObject.Thumbnail.Width                = newWidth;
            this._galleryObject.Thumbnail.Height               = newHeight;
            this._galleryObject.Thumbnail.FileName             = newFilename;
            this._galleryObject.Thumbnail.FileNamePhysicalPath = newFilePath;

            int fileSize = (int)(this._galleryObject.Thumbnail.FileInfo.Length / 1024);

            this._galleryObject.Thumbnail.FileSizeKB = (fileSize < 1 ? 1 : fileSize);             // Very small files should be 1, not 0.
        }
Ejemplo n.º 26
0
        private void GenerateGenericThumbnailImage(string newFilePath, IGallerySettings gallerySetting)
        {
            // Build a generic thumbnail.
            using (Bitmap originalBitmap = GetGenericThumbnailBitmap(GalleryObject.MimeType))
            {
                var newSize = CalculateWidthAndHeight(new System.Windows.Size(originalBitmap.Width, originalBitmap.Height), gallerySetting.MaxThumbnailLength, true);

                // Get JPEG quality value (0 - 100).
                int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                // Generate the new image and save to disk.
                var size = ImageHelper.SaveImageFile(originalBitmap, newFilePath, ImageFormat.Jpeg, newSize.Width, newSize.Height, jpegQuality);

                GalleryObject.Thumbnail.Width  = (int)size.Width;
                GalleryObject.Thumbnail.Height = (int)size.Height;
            }
        }
        /// <summary>
        /// Checks the album to be deleted to see if it is specified as the user album container or if one of its children is the user
        /// album container. If user albums are disabled, no action is taken. If a problem is found, the member variables are updated
        /// with details.
        /// </summary>
        private void CheckForUserAlbumConflict()
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(_albumToDelete.GalleryId);

            if (!gallerySetting.EnableUserAlbum)
            {
                return;
            }

            IGalleryObject userAlbumParent;

            try
            {
                userAlbumParent = Factory.LoadAlbumInstance(gallerySetting.UserAlbumParentAlbumId);
            }
            catch (InvalidAlbumException ex)
            {
                // User album doesn't exist. Record the error and then return because there is no problem with deleting the current album.
                string galleryDescription = Factory.LoadGallery(gallerySetting.GalleryId).Description;
                string msg = $"User Album Parent Invalid: The gallery '{galleryDescription}' has an album ID specified ({_albumToDelete.Id}) as the user album container and it does not match an existing album. Review this setting in the administration area.";
                EventController.RecordError(new WebException(msg, ex), AppSetting.Instance, _albumToDelete.GalleryId, Factory.LoadGallerySettings());
                return;
            }

            // Test #1: Are we trying to delete the album that is specified as the user album parent album?
            if (userAlbumParent.Id == _albumToDelete.Id)
            {
                _validationFailure       = true;
                _validationFailureReason = GalleryObjectDeleteValidationFailureReason.AlbumSpecifiedAsUserAlbumContainer;
                return;
            }

            // Test #2: Does the user album parent album exist somewhere below the album we want to delete?
            IGalleryObject albumParent = userAlbumParent.Parent;

            while (!(albumParent is NullGalleryObject))
            {
                if (albumParent.Id == _albumToDelete.Id)
                {
                    _validationFailure       = true;
                    _validationFailureReason = GalleryObjectDeleteValidationFailureReason.AlbumContainsUserAlbumContainer;
                    return;
                }
                albumParent = albumParent.Parent;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Checks the album to be deleted to see if it is specified as the user album container or if one of its children is the user
        /// album container. If user albums are disabled, no action is taken. If a problem is found, the member variables are updated
        /// with details.
        /// </summary>
        private void CheckForUserAlbumConflict()
        {
            IGallerySettings gallerySetting = Factory.LoadGallerySetting(_albumToDelete.GalleryId);

            if (!gallerySetting.EnableUserAlbum)
            {
                return;
            }

            IGalleryObject userAlbumParent;

            try
            {
                userAlbumParent = Factory.LoadAlbumInstance(gallerySetting.UserAlbumParentAlbumId);
            }
            catch (InvalidAlbumException ex)
            {
                // User album doesn't exist. Record the error and then return because there is no problem with deleting the current album.
                string galleryDescription = Factory.LoadGallery(gallerySetting.GalleryId).Description;
                string msg = String.Format(CultureInfo.CurrentCulture, Resources.Error_User_Album_Parent_Invalid_Ex_Msg, galleryDescription, _albumToDelete.Id);
                EventController.RecordError(new WebException(msg, ex), AppSetting.Instance, _albumToDelete.GalleryId, Factory.LoadGallerySettings());
                return;
            }

            // Test #1: Are we trying to delete the album that is specified as the user album parent album?
            if (userAlbumParent.Id == _albumToDelete.Id)
            {
                _validationFailure       = true;
                _validationFailureReason = GalleryObjectDeleteValidationFailureReason.AlbumSpecifiedAsUserAlbumContainer;
                return;
            }

            // Test #2: Does the user album parent album exist somewhere below the album we want to delete?
            IGalleryObject albumParent = userAlbumParent.Parent;

            while (!(albumParent is NullGalleryObject))
            {
                if (albumParent.Id == _albumToDelete.Id)
                {
                    _validationFailure       = true;
                    _validationFailureReason = GalleryObjectDeleteValidationFailureReason.AlbumContainsUserAlbumContainer;
                    return;
                }
                albumParent = albumParent.Parent;
            }
        }
Ejemplo n.º 29
0
        private static bool ValidateRemoteSync(IAlbum album, string password)
        {
            IGallerySettings gallerySettings = Factory.LoadGallerySetting(album.GalleryId);

            if (!gallerySettings.EnableRemoteSync)
            {
                AppErrorController.LogEvent(String.Format(CultureInfo.CurrentCulture, "Cannot start synchronization: A web service request to start synchronizing album '{0}' (ID {1}) was received, but the gallery is currently configured to disallow remote synchronizations. This feature can be enabled on the Albums page in the Site admin area.", album.Title, album.Id), album.GalleryId);
                return(false);
            }

            if (!gallerySettings.RemoteAccessPassword.Equals(password))
            {
                AppErrorController.LogEvent(String.Format(CultureInfo.CurrentCulture, "Cannot start synchronization: A web service request to start synchronizing album '{0}' (ID {1}) was received, but the specified password is incorrect.", album.Title, album.Id), album.GalleryId);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Sends an e-mail containing details about the <paramref name="appError" /> to all users who are configured to receive e-mail
        /// notifications in the specified <paramref name="gallerySettings" /> and who have valid e-mail addresses. (That is, e-mails are
        /// sent to users identified in the property <see cref="IGallerySettings.UsersToNotifyWhenErrorOccurs" />.) A list of usernames
        /// of those were were notified is returned. No e-mails are sent to any usernames in <paramref name="usersWhoWereAlreadyNotified" />.
        /// </summary>
        /// <param name="appError">The application error to be sent to users.</param>
        /// <param name="gallerySettings">The gallery settings containing the e-mail configuration data and list of users to be notified.
        /// The users are identified in the <see cref="IGallerySettings.UsersToNotifyWhenErrorOccurs" /> property.</param>
        /// <param name="usersWhoWereAlreadyNotified">The users who were previously notified about the <paramref name="appError" />.</param>
        /// <returns>Returns a list of usernames of those were were notified during execution of this function.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="appError" /> or <paramref name="gallerySettings" />
        /// is null.</exception>
        private static List <String> SendMail(IAppError appError, IGallerySettings gallerySettings, List <String> usersWhoWereAlreadyNotified)
        {
            #region Validation

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

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

            #endregion

            if (usersWhoWereAlreadyNotified == null)
            {
                usersWhoWereAlreadyNotified = new List <string>();
            }

            List <String> notifiedUsers = new List <string>();

            //If email reporting has been turned on, send detailed error report.
            if (!gallerySettings.SendEmailOnError)
            {
                return(notifiedUsers);
            }

            MailAddress emailSender = new MailAddress(gallerySettings.EmailFromAddress, gallerySettings.EmailFromName);

            foreach (IUserAccount user in gallerySettings.UsersToNotifyWhenErrorOccurs)
            {
                if (!usersWhoWereAlreadyNotified.Contains(user.UserName))
                {
                    if (SendMail(appError, user, gallerySettings, emailSender))
                    {
                        notifiedUsers.Add(user.UserName);
                    }
                }
            }

            return(notifiedUsers);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Assigns the <paramref name="value" /> to the specified <paramref name="property" /> of the <paramref name="gallerySetting" />
        /// instance. The <paramref name="value" /> is converted to the appropriate enumeration before assignment.
        /// </summary>
        /// <param name="gallerySetting">The gallery setting instance containing the <paramref name="property" /> to assign.</param>
        /// <param name="property">The property to assign the <paramref name="value" /> to.</param>
        /// <param name="value">The value to assign to the <paramref name="property" />.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="value" /> cannot be parsed into a
        /// <see cref="MetadataItemName" /> value.</exception>
        private static void AssignMetadataItemNameProperty(IGallerySettings gallerySetting, PropertyInfo property, string value)
        {
            MetadataItemName metaName;

            try
            {
                metaName = (MetadataItemName)Enum.Parse(typeof(MetadataItemName), value, true);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot convert the string {0} to a MetadataItemName enumeration value.", value), ex);
            }

            property.SetValue(gallerySetting, metaName, null);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Assigns the <paramref name="value" /> to the specified <paramref name="property" /> of the <paramref name="gallerySetting" />
        /// instance. The <paramref name="value" /> is converted to the appropriate enumeration before assignment.
        /// </summary>
        /// <param name="gallerySetting">The gallery setting instance containing the <paramref name="property" /> to assign.</param>
        /// <param name="property">The property to assign the <paramref name="value" /> to.</param>
        /// <param name="value">The value to assign to the <paramref name="property" />.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="value" /> cannot be parsed into a
        /// <see cref="ContentAlignment" /> value.</exception>
        private static void AssignContentAlignmentProperty(IGallerySettings gallerySetting, PropertyInfo property, string value)
        {
            ContentAlignment contentAlignment;

            try
            {
                contentAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), value, true);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot convert the string {0} to a ContentAlignment enumeration value. The following values are valid: TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight", value), ex);
            }

            property.SetValue(gallerySetting, contentAlignment, null);
        }
Ejemplo n.º 33
0
        /// <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>
        internal static void SaveGallerySetting(IGallerySettings gallerySettings)
        {
            using (SqlConnection cn = SqlDataProvider.GetDbConnection())
            {
                using (SqlCommand cmd = GetCommandGallerySettingUpdate(cn))
                {
                    cmd.Parameters["@GalleryId"].Value = gallerySettings.GalleryId;

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

                    cn.Open();

                    foreach (PropertyInfo prop in gsType.GetProperties())
                    {
                        if (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();
                        }

                        // Update the item.
                        cmd.Parameters["@SettingName"].Value = prop.Name;
                        cmd.Parameters["@SettingValue"].Value = propValue;

                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
Ejemplo n.º 34
0
 private static bool IsAnonymousUserAuthorizedForSingleSecurityAction(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings)
 {
     return (securityRequests == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing ||
         (securityRequests == SecurityActions.ViewOriginalMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing && gallerySettings.EnableAnonymousOriginalMediaObjectDownload;
 }
Ejemplo n.º 35
0
        private static void AssignMediaEncoderSettingsProperty(IGallerySettings gallerySetting, PropertyInfo property, string[] mediaEncodings)
        {
            IMediaEncoderSettingsCollection mediaEncoderSettings = (IMediaEncoderSettingsCollection)property.GetValue(gallerySetting, null);
            int seq = 0;

            foreach (string mediaEncStr in mediaEncodings)
            {
                // Each string item is double-pipe-delimited. Ex: ".avi||.mp4||-i {SourceFilePath} {DestinationFilePath}"
                string[] mediaEncoderItems = mediaEncStr.Split(new [] { "||" }, 3, StringSplitOptions.None);

                if (mediaEncoderItems.Length != 3)
                {
                    throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot parse the media encoder definitions for property {0}. Encountered invalid string: '{1}'", property.Name, mediaEncStr));
                }

                mediaEncoderSettings.Add(new MediaEncoderSettings(mediaEncoderItems[0], mediaEncoderItems[1], mediaEncoderItems[2], seq));
                seq++;
            }

            mediaEncoderSettings.Validate();
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Assign reference to gallery settings for the current gallery.
        /// </summary>
        /// <exception cref="InvalidAlbumException">Thrown when an album is requested but does not exist.</exception>
        /// <exception cref="GallerySecurityException">Thrown when the user is requesting an album or media object they don't have 
        /// permission to view.</exception>
        /// <remarks>This must be called from <see cref="GalleryPage_Init" />! It can't go in the <see cref="GalleryPage" /> constructor 
        /// because that is too early to access the GalleryId property, and it can't go in the GallerySettings property getter because 
        /// that is too late if a gallery has to be dynamically created.)</remarks>
        private void LoadGallerySettings()
        {
            try
            {
                this._gallerySetting = Factory.LoadGallerySetting(GalleryId);
            }
            catch (GallerySecurityException)
            {
                // The user is requesting an album or media object they don't have permission to view. Manually load the gallery settings
                // from the query string parameter and assign the gallery ID property so that they are available in the RequiresLogin()
                // function later in GalleryPage_Init(). That code will take care of redirecting the user to the login page.
                int albumId = Utils.GetQueryStringParameterInt32("aid");
                int mediaObjectId = Utils.GetQueryStringParameterInt32("moid");

                if ((albumId == int.MinValue))
                {
                    albumId = this.GalleryControl.AlbumId;
                }

                if (mediaObjectId == int.MinValue)
                {
                    mediaObjectId = this.GalleryControl.MediaObjectId;
                }

                if (albumId > int.MinValue)
                {
                    try
                    {
                        _galleryId = AlbumController.LoadAlbumInstance(albumId, false).GalleryId;
                        this._gallerySetting = Factory.LoadGallerySetting(_galleryId);
                    }
                    catch (InvalidAlbumException) { }
                }
                else if (mediaObjectId > int.MinValue)
                {
                    try
                    {
                        _galleryId = Factory.LoadMediaObjectInstance(mediaObjectId).Parent.GalleryId;
                        this._gallerySetting = Factory.LoadGallerySetting(_galleryId);
                    }
                    catch (InvalidMediaObjectException) { }
                    catch (InvalidAlbumException) { }
                }

                throw; // Re-throw GallerySecurityException
            }
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Assigns the <paramref name="value" /> to the specified <paramref name="property" /> of the <paramref name="gallerySetting" />
        /// instance. The <paramref name="value" /> is converted to the appropriate enumeration before assignment.
        /// </summary>
        /// <param name="gallerySetting">The gallery setting instance containing the <paramref name="property" /> to assign.</param>
        /// <param name="property">The property to assign the <paramref name="value" /> to.</param>
        /// <param name="value">The value to assign to the <paramref name="property" />.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="value" /> cannot be parsed into a
        /// <see cref="MediaObjectTransitionType" /> value.</exception>
        private static void AssignMediaObjectTransitionTypeProperty(IGallerySettings gallerySetting, PropertyInfo property, string value)
        {
            MediaObjectTransitionType transitionType;

            try
            {
                transitionType = (MediaObjectTransitionType)Enum.Parse(typeof(MediaObjectTransitionType), value, true);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot convert the string {0} to a MediaObjectTransitionType enumeration value. The following values are valid: None, Fade", value), ex);
            }

            property.SetValue(gallerySetting, transitionType, null);
        }
        /// <summary>
        /// Generates the HTML to display a nicely formatted thumbnail image of the specified <paramref name="galleryObject" />, including a 
        /// border, shadows and rounded corners. This function generates a drop shadow using native CSS keywords.
        /// This works for all modern browsers except IE up until version 9, which finally added support.
        /// </summary>
        /// <param name="galleryObject">The gallery object to be used as the source for the thumbnail image.</param>
        /// <param name="gallerySettings">The gallery settings that govern display of the <paramref name="galleryObject" />.</param>
        /// <param name="includeHyperlinkToObject">if set to <c>true</c> wrap the image tag with a hyperlink so the user can click through
        /// to the media object view of the item.</param>
        /// <param name="allowAlbumTextWrapping">if set to <c>true</c> the album title is allowed to wrap to a second line if needed.
        /// Set to <c>false</c> when vertical space is limited.</param>
        /// <returns>Returns HTML that displays a nicely formatted thumbnail image of the specified <paramref name="galleryObject" /></returns>
        private static string GenerateThumbnailHtmlForStandardBrowser(IGalleryObject galleryObject, IGallerySettings gallerySettings, bool includeHyperlinkToObject, bool allowAlbumTextWrapping)
        {
            string html = String.Format(CultureInfo.InvariantCulture, @"
            {0}<div class='gsp_i_c' style='width:{1}px;'>
            {2}
                <img src='{3}' title='{4}' alt='{4}' style='width:{1}px;height:{5}px;' />
            {6}
            </div>
            ",
                                        GetAlbumText(galleryObject.Title, galleryObject.GetType(), gallerySettings, allowAlbumTextWrapping), // 0
                                        galleryObject.Thumbnail.Width, // 1
                                        GenerateHyperlinkBegin(galleryObject, gallerySettings.ThumbnailClickShowsOriginal, includeHyperlinkToObject), // 2
                                        GetThumbnailUrl(galleryObject), // 3
                                        GetHovertip(galleryObject), // 4
                                        galleryObject.Thumbnail.Height, // 5
                                        GenerateHyperlinkEnd(includeHyperlinkToObject) // 6
                );

            return html;
        }
        /// <summary>
        /// Generates the HTML to display a nicely formatted thumbnail image of the specified <paramref name="galleryObject"/>, including a
        /// border, shadows and (possibly) rounded corners.
        /// </summary>
        /// <param name="galleryObject">The gallery object to be used as the source for the thumbnail image.</param>
        /// <param name="gallerySettings">The gallery settings that govern display of the <paramref name="galleryObject"/>.</param>
        /// <param name="browserCaps">The browser capabilities. This may be found at Request.Browser.</param>
        /// <param name="includeHyperlinkToObject">if set to <c>true</c> wrap the image tag with a hyperlink so the user can click through
        /// to the media object view of the item.</param>
        /// <param name="allowAlbumTextWrapping">if set to <c>true</c> the album title is allowed to wrap to a second line if needed.
        /// Set to <c>false</c> when vertical space is limited.</param>
        /// <returns>
        /// Returns HTML that displays a nicely formatted thumbnail image of the specified <paramref name="galleryObject"/>
        /// </returns>
        public static string GenerateThumbnailHtml(IGalleryObject galleryObject, IGallerySettings gallerySettings, HttpBrowserCapabilities browserCaps, bool includeHyperlinkToObject, bool allowAlbumTextWrapping)
        {
            if (IsInternetExplorer1To8(browserCaps))
            {
                return GenerateThumbnailHtmlForIE1To8(galleryObject, gallerySettings, includeHyperlinkToObject, allowAlbumTextWrapping);
            }

            return GenerateThumbnailHtmlForStandardBrowser(galleryObject, gallerySettings, includeHyperlinkToObject, allowAlbumTextWrapping);
        }
Ejemplo n.º 40
0
        private static void AssignMetadataDisplaySettingsProperty(IGallerySettings gallerySetting, PropertyInfo property, string[] metadata)
        {
            IMetadataDefinitionCollection metadataItems = (IMetadataDefinitionCollection)property.GetValue(gallerySetting, null);
            int seq = 0;

            foreach (string nameValuePair in metadata)
            {
                // Each string item is colon-delimited, with the first item being the numerical value of the FormattedMetadataItemName
                // enumeration, and the second value being a character 'T' or 'F' indicating whether the metadata item is visible.
                string[] nameOrValue = nameValuePair.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);

                if (nameOrValue.Length != 2)
                {
                    throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot parse the metadata definitions for property {0}. Encountered invalid string: '{1}'", property.Name, nameValuePair));
                }

                bool isVisible = (nameOrValue[1].Trim() == "T" ? true : false);

                int metadataDefInt;
                if (Int32.TryParse(nameOrValue[0], out metadataDefInt))
                {
                    if (FormattedMetadataItemNameEnumHelper.IsValidFormattedMetadataItemName((FormattedMetadataItemName)metadataDefInt))
                    {
                        metadataItems.Add(new MetadataDefinition((FormattedMetadataItemName)metadataDefInt, isVisible, seq, gallerySetting.GalleryId));

                        seq += 1;
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "The integer {0} does not map to a known value of {1}. Details: The function FormattedMetadataItemNameEnumHelper.IsValidFormattedMetadataItemName() returned false when evaluating this value. If the enumeration definition has recently changed, this function must be updated to include the change. The MetadataDisplaySettings property in the gallery settings table may need to be manually updated to remove references to this invalid enumeration value.", metadataDefInt, typeof(FormattedMetadataItemName)));
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot parse the metadata definitions for property {0}. Encountered invalid string: '{1}'", property.Name, nameValuePair));
                }
            }

            metadataItems.Validate(gallerySetting.GalleryId);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Sends the e-mail. If <paramref name="suppressException"/> is <c>true</c>, record any exception that occurs but do not
        /// let it propagate out of this function. When <c>false</c>, record the exception and re-throw it. The caller is
        /// responsible for disposing the <paramref name="mail"/> object.
        /// </summary>
        /// <param name="mail">The mail message to send.</param>
        /// <param name="suppressException">If <c>true</c>, record any exception that occurs but do not
        /// let it propagate out of this function. When <c>false</c>, record the exception and re-throw it.</param>
        /// <param name="gallerySettings">The settings containing e-mail configuration data.</param>
        private static void SendEmail(MailMessage mail, bool suppressException, IGallerySettings gallerySettings)
        {
            try
            {
                if (mail == null)
                    throw new ArgumentNullException("mail");

                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.EnableSsl = gallerySettings.SendEmailUsingSsl;

                    string smtpServer = gallerySettings.SmtpServer;
                    int smtpServerPort;
                    if (!Int32.TryParse(gallerySettings.SmtpServerPort, out smtpServerPort))
                        smtpServerPort = Int32.MinValue;

                    // Specify SMTP server if it is specified in the gallery settings. The server might have been assigned via web.config,
                    // so only update this if we have a setting.
                    if (!String.IsNullOrEmpty(smtpServer))
                    {
                        smtpClient.Host = smtpServer;
                    }

                    // Specify port number if it is specified in the gallery settings and it's not the default value of 25. The port
                    // might have been assigned via web.config, so only update this if we have a setting.
                    if ((smtpServerPort > 0) && (smtpServerPort != 25))
                    {
                        smtpClient.Port = smtpServerPort;
                    }

                    if (String.IsNullOrEmpty(smtpClient.Host))
                        throw new WebException(@"Cannot send e-mail because a SMTP Server is not specified. This can be configured in any of the following places: (1) Site Admin - Gallery Settings page (preferred), or (2) web.config (Ex: configuration/system.net/mailSettings/smtp/network host='your SMTP server').");

                    smtpClient.Send(mail);
                }
            }
            catch (Exception ex)
            {
                AppErrorController.LogError(ex);

                if (!suppressException)
                    throw;
            }
        }
        /// <summary>
        /// Generates the HTML to display a nicely formatted thumbnail image of the specified <paramref name="galleryObject" />, including a 
        /// border and shadows. This function generates a drop shadow using the technique described at http://www.positioniseverything.net/articles/dropshadows.html
        /// Since all other modern browsers, including IE9, support box shadows using native CSS commands, this function is only used for
        /// IE 1 to 8.
        /// </summary>
        /// <param name="galleryObject">The gallery object to be used as the source for the thumbnail image.</param>
        /// <param name="gallerySettings">The gallery settings that govern display of the <paramref name="galleryObject" />.</param>
        /// <param name="includeHyperlinkToObject">if set to <c>true</c> wrap the image tag with a hyperlink so the user can click through
        /// to the media object view of the item.</param>
        /// <param name="allowAlbumTextWrapping">if set to <c>true</c> the album title is allowed to wrap to a second line if needed.
        /// Set to <c>false</c> when vertical space is limited.</param>
        /// <returns>Returns HTML that displays a nicely formatted thumbnail image of the specified <paramref name="galleryObject" /></returns>
        private static string GenerateThumbnailHtmlForIE1To8(IGalleryObject galleryObject, IGallerySettings gallerySettings, bool includeHyperlinkToObject, bool allowAlbumTextWrapping)
        {
            string html = String.Format(CultureInfo.InvariantCulture, @"
                {0}<div class='op0' style='width:{1}px;height:{2}px;'>
                    <div class='op1'>
                        <div class='op2'>
                            <div class='sb'>
                                <div class='ib'>
                                    {3}
                                        <img src='{4}' title='{5}' alt='{5}' style='width:{6}px;height:{7}px;' />
                                    {8}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            ",
                                        GetAlbumText(galleryObject.Title, galleryObject.GetType(), gallerySettings, allowAlbumTextWrapping), // 0
                                        galleryObject.Thumbnail.Width + 15, // 1
                                        galleryObject.Thumbnail.Height + 10, // 2
                                        GenerateHyperlinkBegin(galleryObject, gallerySettings.ThumbnailClickShowsOriginal, includeHyperlinkToObject), // 3
                                        GetThumbnailUrl(galleryObject), // 4
                                        GetHovertip(galleryObject), // 5
                                        galleryObject.Thumbnail.Width, // 6
                                        galleryObject.Thumbnail.Height, // 7
                                        GenerateHyperlinkEnd(includeHyperlinkToObject) // 8
                );

            return html;
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Sends an e-mail containing details about the <paramref name="appError" /> to all users who are configured to receive e-mail
        /// notifications in the specified <paramref name="gallerySettings" /> and who have valid e-mail addresses. (That is, e-mails are
        /// sent to users identified in the property <see cref="IGallerySettings.UsersToNotifyWhenErrorOccurs" />.) A list of usernames
        /// of those were were notified is returned. No e-mails are sent to any usernames in <paramref name="usersWhoWereAlreadyNotified" />.
        /// </summary>
        /// <param name="appError">The application error to be sent to users.</param>
        /// <param name="gallerySettings">The gallery settings containing the e-mail configuration data and list of users to be notified.
        /// The users are identified in the <see cref="IGallerySettings.UsersToNotifyWhenErrorOccurs" /> property.</param>
        /// <param name="usersWhoWereAlreadyNotified">The users who were previously notified about the <paramref name="appError" />.</param>
        /// <returns>Returns a list of usernames of those were were notified during execution of this function.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="appError" /> or <paramref name="gallerySettings" />
        /// is null.</exception>
        private static List<String> SendMail(IAppError appError, IGallerySettings gallerySettings, List<String> usersWhoWereAlreadyNotified)
        {
            #region Validation

            if (appError == null)
                throw new ArgumentNullException("appError");

            if (gallerySettings == null)
                throw new ArgumentNullException("gallerySettings");

            #endregion

            if (usersWhoWereAlreadyNotified == null)
            {
                usersWhoWereAlreadyNotified = new List<string>();
            }

            List<String> notifiedUsers = new List<string>();

            //If email reporting has been turned on, send detailed error report.
            if (!gallerySettings.SendEmailOnError)
            {
                return notifiedUsers;
            }

            MailAddress emailSender = new MailAddress(gallerySettings.EmailFromAddress, gallerySettings.EmailFromName);

            foreach (IUserAccount user in gallerySettings.UsersToNotifyWhenErrorOccurs)
            {
                if (!usersWhoWereAlreadyNotified.Contains(user.UserName))
                {
                    if (SendMail(appError, user, gallerySettings, emailSender))
                    {
                        notifiedUsers.Add(user.UserName);
                    }
                }
            }

            return notifiedUsers;
        }
        /// <summary>
        /// Return a string representing the title of the album. It is truncated and purged of
        /// HTML tags if necessary.  Returns an empty string if the gallery object is not an album
        /// (<paramref name="galleryObjectType"/> != typeof(<see cref="Album"/>))
        /// </summary>
        /// <param name="title">The title of the album as stored in the data store.</param>
        /// <param name="galleryObjectType">The type of the object to which the title belongs.</param>
        /// <param name="gallerySettings">The gallery settings.</param>
        /// <param name="allowAlbumTextWrapping">Indicates whether to allow the album title to wrap to a new line when required. When false,
        /// the CSS class "gsp_nowrap" is specified to prevent wrapping.</param>
        /// <returns>
        /// Returns a string representing the title of the album. It is truncated (if necessary)
        /// and purged of HTML tags.
        /// </returns>
        private static string GetAlbumText(string title, Type galleryObjectType, IGallerySettings gallerySettings, bool allowAlbumTextWrapping)
        {
            if (galleryObjectType != typeof(Album))
                return String.Empty;

            int maxLength = gallerySettings.MaxAlbumThumbnailTitleDisplayLength;
            string truncatedText = Utils.TruncateTextForWeb(title, maxLength);
            string nowrap = (allowAlbumTextWrapping ? String.Empty : " gsp_nowrap");

            if (truncatedText.Length != title.Length)
                return String.Format(CultureInfo.CurrentCulture, "<p class=\"albumtitle {0}\"><b>{1}</b> {2}...</p>", nowrap, Resources.GalleryServerPro.UC_ThumbnailView_Album_Title_Prefix_Text, truncatedText);
            else
                return String.Format(CultureInfo.CurrentCulture, "<p class=\"albumtitle {0}\"><b>{1}</b> {2}</p>", nowrap, Resources.GalleryServerPro.UC_ThumbnailView_Album_Title_Prefix_Text, truncatedText);
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Sends an e-mail containing details about the <paramref name="appError" /> to the specified <paramref name="user" />. Returns
        /// <c>true</c> if the e-mail is successfully sent.
        /// </summary>
        /// <param name="appError">The application error to be sent to users.</param>
        /// <param name="user">The user to send the e-mail to.</param>
        /// <param name="gallerySettings">The gallery settings containing the e-mail configuration data.</param>
        /// <param name="emailSender">The account that that will appear in the "From" portion of the e-mail.</param>
        /// <returns>Returns <c>true</c> if the e-mail is successfully sent; otherwise <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="appError" />, <paramref name="user" />, 
        /// <paramref name="gallerySettings" />, or <paramref name="emailSender" /> is null.</exception>
        private static bool SendMail(IAppError appError, IUserAccount user, IGallerySettings gallerySettings, MailAddress emailSender)
        {
            #region Validation

            if (appError == null)
                throw new ArgumentNullException("appError");

            if (user == null)
                throw new ArgumentNullException("user");

            if (gallerySettings == null)
                throw new ArgumentNullException("gallerySettings");

            if (emailSender == null)
                throw new ArgumentNullException("emailSender");

            #endregion

            bool emailWasSent = false;

            if (!IsValidEmail(user.Email))
            {
                return false;
            }

            MailAddress emailRecipient = new MailAddress(user.Email, user.UserName);
            try
            {
                using (MailMessage mail = new MailMessage(emailSender, emailRecipient))
                {
                    if (String.IsNullOrEmpty(appError.ExceptionType))
                        mail.Subject = Resources.Email_Subject_When_No_Ex_Type_Present;
                    else
                        mail.Subject = String.Concat(Resources.Email_Subject_Prefix_When_Ex_Type_Present, " ", appError.ExceptionType);

                    mail.Body = appError.ToHtmlPage();
                    mail.IsBodyHtml = true;

                    using (SmtpClient smtpClient = new SmtpClient())
                    {
                        smtpClient.EnableSsl = gallerySettings.SendEmailUsingSsl;

                        // Specify SMTP server if it is specified. The server might have been assigned via web.config,
                        // so only update this if we have a config setting.
                        if (!String.IsNullOrEmpty(gallerySettings.SmtpServer))
                        {
                            smtpClient.Host = gallerySettings.SmtpServer;
                        }

                        // Specify port number if it is specified and it's not the default value of 25. The port
                        // might have been assigned via web.config, so only update this if we have a config setting.
                        int smtpServerPort;
                        if (!Int32.TryParse(gallerySettings.SmtpServerPort, out smtpServerPort))
                            smtpServerPort = int.MinValue;

                        if ((smtpServerPort > 0) && (smtpServerPort != 25))
                        {
                            smtpClient.Port = smtpServerPort;
                        }

                        smtpClient.Send(mail);
                    }

                    emailWasSent = true;
                }
            }
            catch (Exception ex2)
            {
                string errorMsg = String.Concat(ex2.GetType(), ": ", ex2.Message);

                if (ex2.InnerException != null)
                    errorMsg += String.Concat(" ", ex2.InnerException.GetType(), ": ", ex2.InnerException.Message);

                appError.ExceptionData.Add(new KeyValuePair<string, string>(Resources.Cannot_Send_Email_Lbl, errorMsg));
            }

            return emailWasSent;
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Gets the target width for the optimized version of the <paramref name="mediaObject"/>. This value is applied to 
        /// the {Width} replacement parameter in the encoder settings, if present. The first matching rule is returned:
        /// 1. The <paramref name="mediaObject" /> has a width meta value.
        /// 2. The width of the original file (videos only).
        /// 3. The default value for the media type (e.g. <see cref="IGallerySettings.DefaultVideoPlayerWidth" /> for video and
        /// cref="IGallerySettings.DefaultAudioPlayerWidth" /> for audio).
        /// </summary>
        /// <param name="mediaObject">The media object.</param>
        /// <param name="gallerySettings">The gallery settings.</param>
        /// <param name="encoderSetting">An instance of <see cref="IMediaEncoderSettings" />.</param>
        /// <returns>System.Int32.</returns>
        /// <exception cref="System.ComponentModel.InvalidEnumArgumentException">Thrown when the <paramref name="mediaObject" /> is not a
        /// video, audio, or generic item.</exception>
        private static int GetTargetWidth(IGalleryObject mediaObject, IGallerySettings gallerySettings, IMediaEncoderSettings encoderSetting)
        {
            IGalleryObjectMetadataItem miWidth;
            if (mediaObject.MetadataItems.TryGetMetadataItem(MetadataItemName.Width, out miWidth))
            {
                return HelperFunctions.ParseInteger(miWidth.Value);
            }

            switch (mediaObject.GalleryObjectType)
            {
                case GalleryObjectType.Video:
                    var width = FFmpeg.ParseSourceVideoWidth(FFmpeg.GetOutput(mediaObject.Original.FileNamePhysicalPath, mediaObject.GalleryId));

                    return width > int.MinValue ? width : gallerySettings.DefaultVideoPlayerWidth;

                case GalleryObjectType.Audio:
                    return gallerySettings.DefaultAudioPlayerWidth;

                case GalleryObjectType.Generic: // Should never hit this because we don't encode generic objects, but for completeness let's put it in
                    return gallerySettings.DefaultGenericObjectWidth;

                default:
                    throw new System.ComponentModel.InvalidEnumArgumentException(String.Format("MediaConversionQueue.GetTargetWidth was not designed to handle the enum value {0}. The function must be updated.", mediaObject.GalleryObjectType));
            }
        }
        private void GenerateThumbnailImageUsingImageMagick(string newFilePath, IGallerySettings gallerySetting)
        {
            // Generate a temporary filename to store the thumbnail created by ImageMagick.
            string tmpImageThumbnailPath = Path.Combine(AppSetting.Instance.TempUploadDirectory, String.Concat(Guid.NewGuid().ToString(), ".jpg"));

            // Request that ImageMagick create the thumbnail. If successful, the file will be created. If not, it fails silently.
            ImageMagick.GenerateImage(GalleryObject.Original.FileNamePhysicalPath, tmpImageThumbnailPath, GalleryObject.GalleryId);

            if (File.Exists(tmpImageThumbnailPath))
            {
                try
                {
                    // ImageMagick successfully created a thumbnail image. Now resize it to the width and height we need.
                    using (var originalBitmap = new Bitmap(tmpImageThumbnailPath))
                    {
                        var newSize = CalculateWidthAndHeight(new System.Windows.Size(originalBitmap.Width, originalBitmap.Height), gallerySetting.MaxThumbnailLength, false);

                        // Get JPEG quality value (0 - 100). This is ignored if imgFormat = GIF.
                        int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                        // Generate the new image and save to disk.
                        var size = ImageHelper.SaveImageFile(originalBitmap, newFilePath, ImageFormat.Jpeg, newSize.Width, newSize.Height, jpegQuality);

                        GalleryObject.Thumbnail.Width = (int)size.Width;
                        GalleryObject.Thumbnail.Height = (int)size.Height;
                    }
                }
                catch (Exception ex)
                {
                    ex.Data.Add("GSP Info", String.Format("This error occurred while trying to process the ImageMagick-generated file {0}. The original file is {1}. A generic thumbnail image will be created instead.", tmpImageThumbnailPath, GalleryObject.Original.FileNamePhysicalPath));
                    Events.EventController.RecordError(ex, AppSetting.Instance, GalleryObject.GalleryId, Factory.LoadGallerySettings());

                    // Default to a generic thumbnail image.
                    GenerateGenericThumbnailImage(newFilePath, gallerySetting);
                }

                try
                {
                    // Now delete the thumbnail image created by FFmpeg, but no worries if an error happens. The file is in the temp directory
                    // which is cleaned out each time the app starts anyway.
                    File.Delete(tmpImageThumbnailPath);
                }
                catch (IOException ex)
                {
                    ex.Data.Add("GSP Info", "This error was handled and did not interfere with the user experience.");
                    Events.EventController.RecordError(ex, AppSetting.Instance, GalleryObject.GalleryId, Factory.LoadGallerySettings());
                }
                catch (UnauthorizedAccessException ex)
                {
                    ex.Data.Add("GSP Info", "This error was handled and did not interfere with the user experience.");
                    Events.EventController.RecordError(ex, AppSetting.Instance, GalleryObject.GalleryId, Factory.LoadGallerySettings());
                }
                catch (NotSupportedException ex)
                {
                    ex.Data.Add("GSP Info", "This error was handled and did not interfere with the user experience.");
                    Events.EventController.RecordError(ex, AppSetting.Instance, GalleryObject.GalleryId, Factory.LoadGallerySettings());
                }
            }
            else
            {
                // ImageMagick didn't create an image, so default to a generic one.
                GenerateGenericThumbnailImage(newFilePath, gallerySetting);
            }
        }
Ejemplo n.º 48
0
 /// <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>
 public override void GallerySetting_Save(IGallerySettings gallerySettings)
 {
     GalleryData.SaveGallerySetting(gallerySettings);
 }
        private void GenerateGenericThumbnailImage(string newFilePath, IGallerySettings gallerySetting)
        {
            // Build a generic thumbnail.
            using (Bitmap originalBitmap = GetGenericThumbnailBitmap(GalleryObject.MimeType))
            {
                var newSize = CalculateWidthAndHeight(new System.Windows.Size(originalBitmap.Width, originalBitmap.Height), gallerySetting.MaxThumbnailLength, true);

                // Get JPEG quality value (0 - 100).
                int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                // Generate the new image and save to disk.
                var size = ImageHelper.SaveImageFile(originalBitmap, newFilePath, ImageFormat.Jpeg, newSize.Width, newSize.Height, jpegQuality);

                GalleryObject.Thumbnail.Width = (int)size.Width;
                GalleryObject.Thumbnail.Height = (int)size.Height;
            }
        }
Ejemplo n.º 50
0
        private static bool IsAnonymousUserAuthorizedForSingleSecurityAction(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings)
        {
            bool isAuthorized = false;

            if ((securityRequests == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing)
                isAuthorized = true;

            if ((securityRequests == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing && gallerySettings.AllowAnonymousHiResViewing)
                isAuthorized = true;

            return isAuthorized;
        }
        /// <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();
            }
        }
Ejemplo n.º 52
0
        private static bool IsAnonymousUserAuthorizedForMultipleSecurityActions(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings, SecurityActionsOption secActionsOption)
        {
            // There are multiple security actions in securityAction enum.  Iterate through each one and determine if the user
            // has permission for it.
            List<bool> authResults = new List<bool>();
            foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests))
            {
                authResults.Add(IsAnonymousUserAuthorizedForSingleSecurityAction(securityAction, isPrivateAlbum, gallerySettings));
            }

            if (secActionsOption == SecurityActionsOption.RequireAll)
            {
                return (authResults.Count > 0 ? authResults.TrueForAll(delegate(bool value) { return value; }) : false);
            }
            else if (secActionsOption == SecurityActionsOption.RequireOne)
            {
                return authResults.Contains(true);
            }
            else
            {
                throw new InvalidEnumArgumentException("secActionsOption", (int)secActionsOption, typeof(SecurityActionsOption));
            }
        }
        private void GenerateThumbnailImageUsingDotNet(string newFilePath, IGallerySettings gallerySetting)
        {
            // All thumbnails should be JPEG format. (My tests show that making GIFs from GIF originals resulted in poor quality thumbnail
            // GIFs, so all thumbnails are JPEG, even those from GIFs.)
            ImageFormat imgFormat = ImageFormat.Jpeg;

            // Don't call Dispose() on originalBitmap unless an exception occurs. That is because it is a reference to a
            // bitmap of the original image, and there is code in the Image class's Saved event that calls Dispose().
            Bitmap originalBitmap = null;
            int newWidth, newHeight;
            try
            {
                // Get reference to the bitmap from which the optimized image will be generated.
                originalBitmap = this._imageObject.Original.Bitmap;
                ImageHelper.CalculateThumbnailWidthAndHeight(originalBitmap.Width, originalBitmap.Height, out newWidth, out newHeight, false, gallerySetting.MaxThumbnailLength);

                // Get JPEG quality value (0 - 100). This is ignored if imgFormat = GIF.
                int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                // Generate the new image and save to disk.
                ImageHelper.SaveImageFile(originalBitmap, newFilePath, imgFormat, newWidth, newHeight, jpegQuality);
            }
            catch (ErrorHandler.CustomExceptions.UnsupportedImageTypeException)
            {
                if (originalBitmap != null)
                    originalBitmap.Dispose();

                throw;
            }

            this._imageObject.Thumbnail.Width = newWidth;
            this._imageObject.Thumbnail.Height = newHeight;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Assigns the <paramref name="value" /> to the specified <paramref name="property" /> of the <paramref name="gallerySetting" />
        /// instance. The <paramref name="value" /> is converted to the appropriate enumeration before assignment.
        /// </summary>
        /// <param name="gallerySetting">The gallery control setting instance containing the <paramref name="property" /> to assign.</param>
        /// <param name="property">The property to assign the <paramref name="value" /> to.</param>
        /// <param name="value">The value to assign to the <paramref name="property" />.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="value" /> cannot be parsed into a
        /// <see cref="SlideShowType" /> value.</exception>
        private static void AssignSlideShowTypeProperty(IGallerySettings gallerySetting, PropertyInfo property, string value)
        {
            SlideShowType ssType;

            try
            {
                ssType = (SlideShowType)Enum.Parse(typeof(SlideShowType), value, true);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySettings.AssignSlideShowTypeProperty cannot convert the string {0} to a SlideShowType enumeration value. The following values are valid: NotSet, Inline, FullScreen", value), ex);
            }

            property.SetValue(gallerySetting, ssType, null);
        }
        private bool GenerateThumbnailImageUsingImageMagick(string newFilePath, IGallerySettings gallerySetting)
        {
            // Generate a temporary filename to store the thumbnail created by ImageMagick.
            string tmpImageThumbnailPath = Path.Combine(AppSetting.Instance.TempUploadDirectory, String.Concat(Guid.NewGuid().ToString(), ".jpg"));

            // Request that ImageMagick create the thumbnail. If successful, the file will be created. If not, it fails silently.
            ImageMagick.GenerateThumbnail(this._imageObject.Original.FileNamePhysicalPath, tmpImageThumbnailPath, this._imageObject.GalleryId);

            if (File.Exists(tmpImageThumbnailPath))
            {
                // Save the path so it can be used later by the optimized image creator.
                _imageObject.Original.TempFilePath = tmpImageThumbnailPath;

                int newWidth;
                int newHeight;
                // ImageMagick successfully created a thumbnail image. Now resize it to the width and height we need.
                using (Bitmap originalBitmap = new Bitmap(tmpImageThumbnailPath))
                {
                    ImageHelper.CalculateThumbnailWidthAndHeight(originalBitmap.Width, originalBitmap.Height, out newWidth, out newHeight, false, gallerySetting.MaxThumbnailLength);

                    // Get JPEG quality value (0 - 100).
                    int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                    // Generate the new image and save to disk.
                    ImageHelper.SaveImageFile(originalBitmap, newFilePath, ImageFormat.Jpeg, newWidth, newHeight, jpegQuality);
                }

                try
                {
                    // Now delete the thumbnail image created by FFmpeg, but no worries if an error happens. The file is in the temp directory
                    // which is cleaned out each time the app starts anyway.
                    //File.Delete(tmpImageThumbnailPath);
                }
                catch (Exception ex)
                {
                    ErrorHandler.Error.Record(ex, this._imageObject.GalleryId, Factory.LoadGallerySettings(), AppSetting.Instance);
                }

                this._imageObject.Thumbnail.Width = newWidth;
                this._imageObject.Thumbnail.Height = newHeight;

                return true;
            }
            else
            {
                return false;
            }
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Assigns the <paramref name="value" /> to the specified <paramref name="property" /> of the <paramref name="gallerySetting" />
        /// instance. The <paramref name="value" /> is converted to the appropriate enumeration before assignment.
        /// </summary>
        /// <param name="gallerySetting">The gallery setting instance containing the <paramref name="property" /> to assign.</param>
        /// <param name="property">The property to assign the <paramref name="value" /> to.</param>
        /// <param name="value">The value to assign to the <paramref name="property" />.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="value" /> cannot be parsed into a
        /// <see cref="PagerPosition" /> value.</exception>
        private static void AssignPagerPositionProperty(IGallerySettings gallerySetting, PropertyInfo property, string value)
        {
            PagerPosition pagerPosition;

            try
            {
                pagerPosition = (PagerPosition)Enum.Parse(typeof(PagerPosition), value, true);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentOutOfRangeException(String.Format(CultureInfo.CurrentCulture, "GallerySetting.RetrieveGallerySettingsFromDataStore cannot convert the string {0} to a PagerPosition enumeration value. The following values are valid: Top, Bottom, TopAndBottom", value), ex);
            }

            property.SetValue(gallerySetting, pagerPosition, null);
        }
Ejemplo n.º 57
0
 public abstract void GallerySetting_Save(IGallerySettings gallerySettings);
Ejemplo n.º 58
0
        private static void AssignUserAccountsProperty(IGallerySettings gallerySetting, PropertyInfo property, string[] userNames)
        {
            IUserAccountCollection userAccounts = (IUserAccountCollection)property.GetValue(gallerySetting, null);

            foreach (string userName in userNames)
            {
                if (!String.IsNullOrEmpty(userName.Trim()))
                {
                    userAccounts.Add(new UserAccount(userName.Trim()));
                }
            }
        }
        private void GenerateGenericThumbnailImage(string newFilePath, IGallerySettings gallerySetting)
        {
            int newWidth, newHeight;

            // Build a generic thumbnail.
            using (Bitmap originalBitmap = GetGenericThumbnailBitmap(this._galleryObject.MimeType))
            {
                ImageHelper.CalculateThumbnailWidthAndHeight(originalBitmap.Width, originalBitmap.Height, out newWidth, out newHeight, true, gallerySetting.MaxThumbnailLength);

                // Get JPEG quality value (0 - 100).
                int jpegQuality = gallerySetting.ThumbnailImageJpegQuality;

                // Generate the new image and save to disk.
                ImageHelper.SaveImageFile(originalBitmap, newFilePath, ImageFormat.Jpeg, newWidth, newHeight, jpegQuality);
            }

            this._galleryObject.Thumbnail.Width = newWidth;
            this._galleryObject.Thumbnail.Height = newHeight;
        }