Esempio n. 1
0
        private static void MoveFile(string filepath, string sourceFilePath)
        {
            // Move file to album. If IOException happens, wait 1 second and try again, up to 10 times.
            while (true)
            {
                int       counter  = 0;
                const int maxTries = 10;
                try
                {
                    File.Move(sourceFilePath, filepath);
                    break;
                }
                catch (IOException ex)
                {
                    counter++;
                    ex.Data.Add("CannotMoveFile", string.Format("This error occurred while trying to move file '{0}' to '{1}'. This error has occurred {2} times. The system will try again up to a maximum of {3} attempts.", sourceFilePath, filepath, counter, maxTries));
                    AppErrorController.LogError(ex);

                    if (counter >= maxTries)
                    {
                        break;
                    }

                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
        /// <summary>
        /// Initialize the components of the Gallery Server Pro application that do not require access to an HttpContext.
        /// This method is designed to be run at application startup. The business layer
        /// is initialized with the current trust level and a few configuration settings. The business layer also initializes
        /// the data store, including verifying a minimal level of data integrity, such as at least one record for the root album.
        /// </summary>
        /// <remarks>This is the only method, apart from those invoked through web services, that is not handled by the global error
        /// handling routine in Gallery.cs. This method wraps its calls in a try..catch that passes any exceptions to
        /// <see cref="AppErrorController.HandleGalleryException(Exception)"/>. If that method does not transfer the user to a friendly error page, the exception
        /// is re-thrown.</remarks>
        private static void InitializeApplication()
        {
            lock (_sharedLock)
            {
                if (AppSetting.Instance.IsInitialized)
                {
                    return;
                }

                string msg = CheckForDbCompactionRequest();

                Business.Gallery.GalleryCreated += new EventHandler <GalleryCreatedEventArgs>(GalleryCreated);

                GallerySettings.GallerySettingsSaved += new EventHandler <GallerySettingsEventArgs>(GallerySettingsSaved);

                GalleryObject.MetadataLoaded += new EventHandler(GalleryObjectMetadataLoaded);

                // Set web-related variables in the business layer and initialize the data store.
                InitializeBusinessLayer();

                UserController.ProcessInstallerFile();

                // Make sure installation has its own unique encryption key.
                ValidateEncryptionKey();

                MediaConversionQueue.Instance.Process();

                // If there is a message from the DB compaction, record it now. We couldn't do it before because the DB
                // wasn't fully initialized.
                if (!String.IsNullOrEmpty(msg))
                {
                    AppErrorController.LogEvent(msg, int.MinValue);
                }
            }
        }
Esempio n. 3
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 config file
        /// for the parent album does not represent an existing album. That is, returns null if the userAlbumParentAlbumId
        /// in galleryserverpro.config does not match an existing album.
        /// </summary>
        /// <param name="userName">The user name representing the user who is the owner of the album.</param>
        /// <returns>Returns the newly created user album. It has already been persisted to the database.
        /// Returns null if the ID specified in the config file for the parent album does not represent an existing album.
        /// That is, returns null if the userAlbumParentAlbumId in galleryserverpro.config does not match an existing album.</returns>
        public static IAlbum CreateUserAlbum(string userName)
        {
            Core   core = Config.GetCore();
            string albumNameTemplate = core.UserAlbumNameTemplate;

            IAlbum parentAlbum;

            try
            {
                parentAlbum = Factory.LoadAlbumInstance(core.UserAlbumParentAlbumId, false);
            }
            catch (ErrorHandler.CustomExceptions.InvalidAlbumException ex)
            {
                // The parent album does not exist. Record the error and return null.
                string msg = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Error_User_Album_Parent_Invalid_Ex_Msg, core.UserAlbumParentAlbumId);
                AppErrorController.LogError(new ErrorHandler.CustomExceptions.WebException(msg, ex));
                return(null);
            }

            IAlbum album = Factory.CreateAlbumInstance();

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

            SaveAlbumIdToProfile(album.Id, userName);

            HelperFunctions.PurgeCache();

            return(album);
        }
Esempio n. 4
0
        /// <summary>
        /// Verifies the user album for the specified <paramref name="userName">user</paramref> exists if it is supposed to exist
        /// (creating it if necessary), or does not exist if not (that is, deleting it if necessary). Returns a reference to the user
        /// album if a user album exists or has just been created; otherwise returns null. Also returns null if user albums are
        /// disabled at the application level or userAlbumParentAlbumId in galleryserverpro.config does not match an existing album.
        /// A user album is created if user albums are enabled but none for the user exists. If user albums are enabled at the
        /// application level but the user has disabled them in his profile, the album is deleted if it exists.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Returns a reference to the user album for the specified <paramref name="userName">user</paramref>, or null
        /// if user albums are disabled or the userAlbumParentAlbumId in galleryserverpro.config does not match an existing album.</returns>
        /// <exception cref="ArgumentException">Thrown when <paramref name="userName" /> is null or empty.</exception>
        public static IAlbum ValidateUserAlbum(string userName)
        {
            if (!Config.GetCore().EnableUserAlbum)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("userName");
            }

            bool userAlbumExists      = false;
            bool userAlbumShouldExist = ProfileController.GetProfile(userName).EnableUserAlbum;

            IAlbum album = null;

            int albumId = GetUserAlbumId(userName);

            if (albumId > int.MinValue)
            {
                try
                {
                    // Try loading the album.
                    album = Factory.LoadAlbumInstance(albumId, false);

                    userAlbumExists = true;
                }
                catch (InvalidAlbumException) { }
            }

            // Delete or create if necessary. Deleting should only be needed if
            if (userAlbumExists && !userAlbumShouldExist)
            {
                try
                {
                    AlbumController.DeleteAlbum(album);
                }
                catch (Exception ex)
                {
                    // Log any errors that happen but don't let them bubble up.
                    AppErrorController.LogError(ex);
                }
                finally
                {
                    album = null;
                }
            }
            else if (!userAlbumExists && userAlbumShouldExist)
            {
                album = AlbumController.CreateUserAlbum(userName);
            }

            return(album);
        }
Esempio n. 5
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);
        }
Esempio n. 6
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>
        /// 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);
        }
Esempio n. 8
0
        /// <summary>
        /// Verifies that the album meets the prerequisites to be safely deleted but does not actually delete the album. Throws a
        /// CannotDeleteAlbumException when it cannot be deleted. Specifically, the function checks to see if user albums are enabled, and
        /// if they are, it checks if the album to delete contains the user album parent album. If it does, the validation fails and an
        /// exception is thrown.
        /// </summary>
        /// <param name="albumToDelete">The album to delete.</param>
        /// <remarks>This function is automatically called when using the <see cref="DeleteAlbum"/> method, so it is not necessary to
        /// invoke when using that method. Typically you will call this method when there are several items to delete and you want to
        /// check all of them before deleting any of them, such as we have on the Delete Objects page.</remarks>
        /// <exception cref="ErrorHandler.CustomExceptions.CannotDeleteAlbumException">Thrown when the album does not meet the
        /// requirements for safe deletion. At this time this exception is thrown only when the album is or contains the user album
        /// parent album and user albums are enabled.</exception>
        public static void ValidateBeforeAlbumDelete(IAlbum albumToDelete)
        {
            if (!Config.GetCore().EnableUserAlbum)
            {
                return;
            }

            IGalleryObject userAlbumParent;

            try
            {
                userAlbumParent = Factory.LoadAlbumInstance(Config.GetCore().UserAlbumParentAlbumId, false);
            }
            catch (ErrorHandler.CustomExceptions.InvalidAlbumException ex)
            {
                // User album doesn't exist. Record the error and then return because there is no problem
                // with deleting the current album.
                string msg = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Error_User_Album_Parent_Invalid_Ex_Msg, albumToDelete.Id);
                AppErrorController.LogError(new ErrorHandler.CustomExceptions.WebException(msg, ex));
                return;
            }

            // Test #1: Are we trying to delete the album that is specified as the user album parent album?
            bool albumToDeleteIsUserAlbumContainer = (userAlbumParent.Id == albumToDelete.Id);

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

            while (!(albumParent is GalleryServerPro.Business.NullObjects.NullGalleryObject))
            {
                if (albumParent.Id == albumToDelete.Id)
                {
                    userAlbumExistsInAlbumToDelete = true;
                    break;
                }
                albumParent = albumParent.Parent;
            }

            bool okToDelete = (!(albumToDeleteIsUserAlbumContainer || userAlbumExistsInAlbumToDelete));

            if (!okToDelete)
            {
                // Album is or contains the user album parent album and user albums are enabled. Throw exception.
                string albumTitle = String.Concat("'", albumToDelete.Title, "' (ID# ", albumToDelete.Id, ")");
                string msg        = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Task_Delete_Album_Cannot_Delete_Contains_User_Album_Parent_Ex_Msg, albumTitle);
                throw new ErrorHandler.CustomExceptions.CannotDeleteAlbumException(msg);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Gets Gallery Server roles representing the roles for the currently logged-on user. Returns an
        /// empty collection if no user is logged in or the user is logged in but not assigned to any roles (Count = 0).
        /// </summary>
        /// <returns>Returns a collection of Gallery Server roles representing the roles for the currently logged-on user.
        /// Returns an empty collection if no user is logged in or the user is logged in but not assigned to any roles (Count = 0).</returns>
        public static IGalleryServerRoleCollection GetGalleryServerRolesForUser()
        {
            if (!Util.IsAuthenticated)
            {
                return(new GalleryServerRoleCollection());
            }

            // Get cached dictionary entry matching logged on user. If not found, retrieve from business layer and add to cache.
            Dictionary <string, IGalleryServerRoleCollection> rolesCache = (Dictionary <string, IGalleryServerRoleCollection>)HelperFunctions.GetCache(CacheItem.GalleryServerRoles);

            IGalleryServerRoleCollection roles;

            if (HttpContext.Current.Session != null)
            {
                if ((rolesCache != null) && (rolesCache.TryGetValue(CacheKeyNameForRoles, out roles)))
                {
                    return(roles);
                }
            }

            // No roles in the cache, so get from business layer and add to cache.
            roles = Factory.LoadGalleryServerRoles(GetRolesForUser(Util.UserName));

            if (rolesCache == null)
            {
                // The factory method should have created a cache item, so try again.
                rolesCache = (Dictionary <string, IGalleryServerRoleCollection>)HelperFunctions.GetCache(CacheItem.GalleryServerRoles);
                if (rolesCache == null)
                {
                    AppErrorController.LogError(new WebException("The method Factory.LoadGalleryServerRoles() should have created a cache entry, but none was found. This is not an issue if it occurs occasionally, but should be addressed if it is frequent."));
                    return(roles);
                }
            }

            // Add to the cache, but only if we have access to the session ID.
            if (HttpContext.Current.Session != null)
            {
                lock (rolesCache)
                {
                    if (!rolesCache.ContainsKey(CacheKeyNameForRoles))
                    {
                        rolesCache.Add(CacheKeyNameForRoles, roles);
                    }
                }
                HelperFunctions.SetCache(CacheItem.GalleryServerRoles, rolesCache);
            }

            return(roles);
        }
        /// <summary>
        /// Initialize the Gallery Server Pro application. This method is designed to be run at application startup. The business layer
        /// is initialized with the current trust level and a few configuration settings. The business layer also initializes
        /// the data store, including verifying a minimal level of data integrity, such as at least one record for the root album.
        /// Initialization that requires an HttpContext is also performed. When this method completes, <see cref="IAppSetting.IsInitialized" />
        /// will be <c>true</c>, but <see cref="GalleryController.IsInitialized" /> will be <c>true</c> only when an HttpContext instance
        /// exists. If this function is initially called from a place where an HttpContext doesn't exist, it will automatically be called
        /// again later, eventually being called from a place where an HttpContext does exist, thus completing app initialization.
        /// </summary>
        public static void InitializeGspApplication()
        {
            try
            {
                InitializeApplication();

                lock (_sharedLock)
                {
                    if (IsInitialized)
                    {
                        return;
                    }

                    if (HttpContext.Current != null)
                    {
                        // Set application key so ComponentArt knows it is properly licensed.
                        HttpContext.Current.Application["ComponentArtWebUI_AppKey"] = "This edition of ComponentArt Web.UI is licensed for Gallery Server Pro application only.";

                        // Add a dummy value to session so that the session ID remains constant. (This is required by RoleController.GetRolesForUser())
                        // Check for null session first. It will be null when this is triggered by a web method that does not have
                        // session enabled (that is, the [WebMethod(EnableSession = true)] attribute). That's OK because the roles functionality
                        // will still work (we might have to an extra data call, though), and we don't want the overhead of session for some web methods.
                        if (HttpContext.Current.Session != null)
                        {
                            HttpContext.Current.Session.Add("1", "1");
                        }

                        // Update the user accounts in a few gallery settings. The DotNetNuke version requires this call to happen when there
                        // is an HttpContext, so to reduce differences between the two branches we put it here.
                        AddMembershipDataToGallerySettings();

                        _isInitialized = true;
                    }

                    //InsertSampleUsersAndRoles();
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                // Let the error handler deal with it. It will decide whether to transfer the user to a friendly error page.
                // If the function returns, that means it didn't redirect, so we should re-throw the exception.
                AppErrorController.HandleGalleryException(ex);
                throw;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Send an e-mail to the users that are subscribed to new account notifications. These are specified in the
        /// usersToNotifyWhenAccountIsCreated configuration setting. If RequireEmailValidationForSelfRegisteredUser
        /// is enabled, do not send an e-mail at this time. Instead, it is sent when the user clicks the confirmation
        /// link in the e-mail.
        /// </summary>
        /// <param name="user">An instance of <see cref="UserEntity"/> that represents the newly created account.</param>
        /// <param name="isSelfRegistration">Indicates when the user is creating his or her own account. Set to false when an
        /// administrator creates an account.</param>
        /// <param name="isEmailVerified">If set to <c>true</c> the e-mail has been verified to be a valid, active e-mail address.</param>
        private static void NotifyAdminsOfNewlyCreatedAccount(UserEntity user, bool isSelfRegistration, bool isEmailVerified)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (isSelfRegistration && !isEmailVerified && Config.GetCore().RequireEmailValidationForSelfRegisteredUser)
            {
                return;
            }

            EmailTemplate emailTemplate;

            if (isSelfRegistration && Config.GetCore().RequireApprovalForSelfRegisteredUser)
            {
                emailTemplate = EmailController.GetEmailTemplate(EmailTemplateForm.AdminNotificationAccountCreatedRequiresApproval, user);
            }
            else
            {
                emailTemplate = EmailController.GetEmailTemplate(EmailTemplateForm.AdminNotificationAccountCreated, user);
            }

            foreach (string accountName in Config.GetCore().UsersToNotifyWhenAccountIsCreated.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                UserEntity account = GetUser(accountName, true);

                if (!String.IsNullOrEmpty(account.Email))
                {
                    MailAddress admin = new MailAddress(account.Email, account.UserName);
                    try
                    {
                        EmailController.SendEmail(admin, emailTemplate.Subject, emailTemplate.Body);
                    }
                    catch (WebException ex)
                    {
                        AppErrorController.LogError(ex);
                    }
                    catch (SmtpException ex)
                    {
                        AppErrorController.LogError(ex);
                    }
                }
            }
        }
        /// <summary>
        /// Compacts and, if necessary, repairs the database. Applies only to SQL CE. A detailed message describing
        /// the result of the operation is assigned to <paramref name="message" />.
        /// </summary>
        /// <param name="message">A detailed message describing the result of the operation.</param>
        /// <returns>Returns <c>true</c> if the operation is successful; otherwise returns <c>false</c>.</returns>
        public static bool CompactAndRepairDatabase(out string message)
        {
            IDataProvider dataProvider = Factory.GetDataProvider();

            if (dataProvider.DataStore != ProviderDataStore.SqlCe)
            {
                message = String.Concat(dataProvider.DataStore, " does not support the compact and repair function.");
                return(false);
            }

            bool      compactSuccessful = false;
            bool      repairNeeded      = false;
            bool      repairSuccessful  = false;
            Exception ex = null;

            try
            {
                dataProvider.Compact();
                compactSuccessful = true;

                if (!dataProvider.Verify())
                {
                    repairNeeded = true;
                    dataProvider.Repair();

                    repairSuccessful = dataProvider.Verify();
                }
            }
            catch (Exception exception)
            {
                ex = exception;
                AppErrorController.LogError(ex);
            }

            message = GetCompactAndRepairMessage(ex, compactSuccessful, repairNeeded, repairSuccessful);
            return(ex == null);
        }
Esempio n. 13
0
        private static List <ActionResult> CreateMediaObjectFromFile(AddMediaObjectSettings options)
        {
            string sourceFilePath = Path.Combine(AppSetting.Instance.PhysicalApplicationPath, GlobalConstants.TempUploadDirectory, options.FileNameOnServer);

            try
            {
                IAlbum album = AlbumController.LoadAlbumInstance(options.AlbumId, true);

                if ((Path.GetExtension(options.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (options.ExtractZipFile))
                {
                    // Extract the files from the zipped file.
                    using (ZipUtility zip = new ZipUtility(Utils.UserName, RoleController.GetGalleryServerRolesForUser()))
                    {
                        using (FileStream fs = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
                        {
                            return(zip.ExtractZipFile(fs, album, options.DiscardOriginalFile));
                        }
                    }
                }
                else
                {
                    string albumPhysicalPath = album.FullPhysicalPathOnDisk;
                    string filename          = HelperFunctions.ValidateFileName(albumPhysicalPath, options.FileName);
                    string filepath          = Path.Combine(albumPhysicalPath, filename);

                    MoveFile(filepath, sourceFilePath);

                    ActionResult result = CreateMediaObject(filepath, album, options);
                    return(new List <ActionResult>()
                    {
                        result
                    });
                }
            }
            catch (Exception ex)
            {
                AppErrorController.LogError(ex);
                return(new List <ActionResult>()
                {
                    new ActionResult()
                    {
                        Title = options.FileName,
                        Status = ActionResultStatus.Error,
                        Message = "The event log may have additional details."
                    }
                });
            }
            finally
            {
                try
                {
                    // If the file still exists in the temp directory, delete it. Typically this happens when we've
                    // extracted the contents of a zip file (since other files will have already been moved to the dest album.)
                    if (File.Exists(sourceFilePath))
                    {
                        File.Delete(sourceFilePath);
                    }
                }
                catch (IOException) { }                 // Ignore an error; not a big deal if it continues to exist in the temp directory
                catch (UnauthorizedAccessException) { } // Ignore an error; not a big deal if it continues to exist in the temp directory
            }
        }