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. int counter = 0; const int maxTries = 10; while (true) { 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)); AppEventController.LogError(ex); if (counter >= maxTries) { throw; } Thread.Sleep(1000); } } }
/// <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> private static void SendEmail(MailMessage mail, bool suppressException) { try { if (mail == null) { throw new ArgumentNullException("mail"); } using (SmtpClient smtpClient = new SmtpClient()) { var appSettings = AppSetting.Instance; smtpClient.EnableSsl = appSettings.SendEmailUsingSsl; string smtpServer = appSettings.SmtpServer; int smtpServerPort; if (!Int32.TryParse(appSettings.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 - General page (preferred), or (2) web.config (Ex: configuration/system.net/mailSettings/smtp/network host='your SMTP server')."); } smtpClient.Send(mail); } } catch (Exception ex) { AppEventController.LogError(ex); if (!suppressException) { throw; } } }
/// <summary> /// Creates the media object from the file specified in <paramref name="options" />. /// </summary> /// <param name="options">The options.</param> /// <returns>List{ActionResult}.</returns> /// <exception cref="Events.CustomExceptions.GallerySecurityException">Thrown when user is not authorized to add a media object to the album.</exception> /// <remarks>This function can be invoked from a thread that does not have access to the current HTTP context (for example, when /// uploading ZIP files). Therefore, be sure nothing in this body (or the functions it calls) uses HttpContext.Current, or at /// least check it for null first.</remarks> 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, true); if (HttpContext.Current != null) { SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddMediaObject, RoleController.GetGalleryServerRolesForUser(), album.Id, album.GalleryId, Utils.IsAuthenticated, album.IsPrivate, album.IsVirtualAlbum); } else { // We are extracting files from a zip archive (we know this because this is the only scenario that happens on a background // thread where HttpContext.Current is null). Tweak the security check slightly to ensure the HTTP context isn't used. // The changes are still secure because options.CurrentUserName is assigned in the server's API method. SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddMediaObject, RoleController.GetGalleryServerRolesForUser(options.CurrentUserName), album.Id, album.GalleryId, !String.IsNullOrWhiteSpace(options.CurrentUserName), album.IsPrivate, album.IsVirtualAlbum); } var extension = Path.GetExtension(options.FileName); if (extension != null && ((extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) && (options.ExtractZipFile))) { List <ActionResult> result; // Extract the files from the zipped file. using (var zip = new ZipUtility(options.CurrentUserName, RoleController.GetGalleryServerRolesForUser(options.CurrentUserName))) { using (var fs = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read)) { result = zip.ExtractZipFile(fs, album, options.DiscardOriginalFile); } } album.SortAsync(true, options.CurrentUserName, true); return(result); } 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); album.Sort(true, options.CurrentUserName); return(new List <ActionResult> { result }); } } catch (Exception ex) { AppEventController.LogError(ex); return(new List <ActionResult> { new ActionResult { Title = options.FileName, Status = ActionResultStatus.Error.ToString(), 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 } }