Esempio n. 1
0
    /// <summary>
    /// Provides operations necessary to create and store new library file.
    /// </summary>
    private void HandleLibrariesUpload()
    {
        // Get related library info
        if (LibraryInfo != null)
        {
            MediaFileInfo mediaFile = null;

            // Get the site name
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
            string   siteName = (si != null) ? si.SiteName : SiteContext.CurrentSiteName;

            string message = string.Empty;
            try
            {
                // Check the allowed extensions
                CheckAllowedExtensions();

                if (MediaFileID > 0)
                {
                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileModify"))
                    {
                        throw new Exception(GetString("media.security.nofilemodify"));
                    }

                    #endregion


                    mediaFile = MediaFileInfoProvider.GetMediaFileInfo(MediaFileID);
                    if (mediaFile != null)
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mediaFile);

                        if (IsMediaThumbnail)
                        {
                            string newFileExt = Path.GetExtension(ucFileUpload.FileName).TrimStart('.');
                            if ((ImageHelper.IsImage(newFileExt)) && (newFileExt.ToLowerCSafe() != "ico") &&
                                (newFileExt.ToLowerCSafe() != "wmf"))
                            {
                                // Update or creation of Media File update
                                string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                if (!String.IsNullOrEmpty(previewSuffix))
                                {
                                    string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                    string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, siteName, previewSuffix));
                                    string previewFolder    = DirectoryHelper.CombinePath(Path.EnsureSlashes(LibraryFolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                    byte[] previewFileBinary = new byte[ucFileUpload.PostedFile.ContentLength];
                                    ucFileUpload.PostedFile.InputStream.Read(previewFileBinary, 0, ucFileUpload.PostedFile.ContentLength);

                                    // Delete current preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath);

                                    // Save preview file
                                    MediaFileInfoProvider.SaveFileToDisk(siteName, LibraryInfo.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false, false);

                                    // Log synchronization task
                                    SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                }

                                // Drop the cache dependencies
                                CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                            }
                            else
                            {
                                message = GetString("media.file.onlyimgthumb");
                            }
                        }
                        else
                        {
                            // Get folder path
                            string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(LibraryInfo.LibraryID), mediaFile.FilePath));

                            // If file system permissions are sufficient for file update
                            if (DirectoryHelper.CheckPermissions(path, false, true, true, true))
                            {
                                // Delete existing media file
                                MediaFileInfoProvider.DeleteMediaFile(LibraryInfo.LibrarySiteID, LibraryInfo.LibraryID, mediaFile.FilePath, true);

                                // Update media file preview
                                if (MediaLibraryHelper.HasPreview(siteName, LibraryInfo.LibraryID, mediaFile.FilePath))
                                {
                                    // Get new unique file name
                                    string newName = URLHelper.GetSafeFileName(ucFileUpload.PostedFile.FileName, siteName);

                                    // Get new file path
                                    string newPath = DirectoryHelper.CombinePath(path, newName);
                                    newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);
                                    newName = Path.GetFileName(newPath);

                                    // Rename preview
                                    MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                    // Delete preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                                }

                                // Receive media info on newly posted file
                                mediaFile = GetUpdatedFile(mediaFile);

                                // Save media file information
                                MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                            }
                            else
                            {
                                // Set error message
                                message = String.Format(GetString("media.accessdeniedtopath"), path);
                            }
                        }
                    }
                }
                else
                {
                    #region "Check permissions"

                    // Creation of new media file
                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileCreate"))
                    {
                        throw new Exception(GetString("media.security.nofilecreate"));
                    }

                    #endregion


                    // No file for upload specified
                    if (!ucFileUpload.HasFile)
                    {
                        throw new Exception(GetString("media.newfile.errorempty"));
                    }

                    // Create new media file record
                    mediaFile = new MediaFileInfo(ucFileUpload.PostedFile, LibraryID, LibraryFolderPath, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, LibraryInfo.LibrarySiteID);

                    mediaFile.FileDescription = "";

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                }
            }
            catch (Exception ex)
            {
                // Creation of new media file failed
                message = ex.Message;
            }
            finally
            {
                // Create media file info string
                string mediaInfo = "";
                if ((mediaFile != null) && (mediaFile.FileID > 0) && (IncludeNewItemInfo))
                {
                    mediaInfo = mediaFile.FileID + "|" + LibraryFolderPath.Replace('\\', '>').Replace("'", "\\'");
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                if (RaiseOnClick)
                {
                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "UploaderOnClick", ScriptHelper.GetScript("if (parent.UploaderOnClick) { parent.UploaderOnClick('" + MediaFileName.Replace(" ", "").Replace(".", "").Replace("-", "") + "'); }"));
                }

                string script = String.Format(@"
if (typeof(parent.DFU) !== 'undefined') {{ 
    parent.DFU.OnUploadCompleted('{0}'); 
}} 
if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{
    window.parent.InitRefresh_{1}({2}, false, '{3}'{4});
}}", QueryHelper.GetString("containerid", ""), ParentElemID, ScriptHelper.GetString(message.Trim()), mediaInfo, (InsertMode ? ", 'insert'" : ", 'update'"));

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "RefreshParrent", ScriptHelper.GetScript(script));
            }
        }
    }
Esempio n. 2
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(LibraryID);

        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "manage"))
        {
            // Check 'File create' permission
            if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filecreate"))
            {
                RaiseOnNotAllowed("filecreate");
                return;
            }
        }

        if (String.IsNullOrWhiteSpace(fileUploader.FileName) && !fileUploader.HasFile)
        {
            lblError.Text    = GetString("media.selectfile");
            lblError.Visible = true;
            return;
        }

        // Check if preview file is image
        if ((previewUploader.HasFile) &&
            (!ImageHelper.IsImage(Path.GetExtension(previewUploader.FileName))) &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".ico") &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".tif") &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".tiff") &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".wmf"))
        {
            lblError.Text    = GetString("Media.File.PreviewIsNotImage");
            lblError.Visible = true;
            return;
        }

        // Check if the preview file with given extension is allowed for library module
        // Check if file with given extension is allowed for library module
        string fileExt        = Path.GetExtension(fileUploader.FileName).TrimStart('.');
        string previewFileExt = Path.GetExtension(previewUploader.FileName).TrimStart('.');

        // Check file extension
        if (!MediaLibraryHelper.IsExtensionAllowed(fileExt))
        {
            lblError.Text    = String.Format(GetString("media.newfile.extensionnotallowed"), fileExt);
            lblError.Visible = true;
            return;
        }

        // Check preview extension
        if ((previewFileExt.Trim() != "") && !MediaLibraryHelper.IsExtensionAllowed(previewFileExt))
        {
            lblError.Text    = String.Format(GetString("media.newfile.extensionnotallowed"), previewFileExt);
            lblError.Visible = true;
            return;
        }

        if (mli != null)
        {
            try
            {
                // Create new Media file
                MediaFileInfo mfi = new MediaFileInfo(fileUploader.PostedFile, LibraryID, DestinationPath);

                // Save record to the database
                MediaFileInfoProvider.SetMediaFileInfo(mfi);

                // Save preview if presented
                if (previewUploader.HasFile)
                {
                    // Get preview suffix if not set
                    if (String.IsNullOrEmpty(PreviewSuffix))
                    {
                        PreviewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(SiteContext.CurrentSiteName);
                    }

                    if (!String.IsNullOrEmpty(PreviewSuffix))
                    {
                        // Get physical path within the media library
                        String path;
                        if ((DestinationPath != null) && DestinationPath.TrimEnd('/') != "")
                        {
                            path = DirectoryHelper.CombinePath(Path.EnsureBackslashes(DestinationPath, true), MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName));
                        }
                        else
                        {
                            path = MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName);
                        }

                        string previewExtension = Path.GetExtension(previewUploader.PostedFile.FileName);
                        string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mfi.FileName, mfi.FileExtension, previewExtension, SiteContext.CurrentSiteName, PreviewSuffix));

                        // Save preview file
                        MediaFileInfoProvider.SaveFileToDisk(SiteContext.CurrentSiteName, mli.LibraryFolder, path, previewName, previewExtension, mfi.FileGUID, previewUploader.PostedFile.InputStream, false);
                    }
                }

                // Clear cache
                if (PortalContext.CurrentPageManager != null)
                {
                    PortalContext.CurrentPageManager.ClearCache();
                }

                // Display info to the user
                lblInfo.Text    = GetString("media.fileuploaded");
                lblInfo.Visible = true;

                if (OnAfterFileUpload != null)
                {
                    OnAfterFileUpload();
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                lblError.ToolTip = ex.StackTrace;
            }
        }
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(LibraryID);

        // Check 'File create' permission
        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filecreate"))
        {
            RaiseOnNotAllowed("filecreate");
            return;
        }

        // No file for upload specified
        if (!FileUpload.HasFile)
        {
            lblError.Text = GetString("media.newfile.errorempty");
            return;
        }

        // Check if preview file is image
        if ((PreviewUpload.HasFile) &&
            (!ImageHelper.IsImage(Path.GetExtension(PreviewUpload.FileName))) &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".ico") &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".tif") &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".tiff") &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".wmf"))
        {
            lblError.Text = GetString("Media.File.PreviewIsNotImage");
            return;
        }

        if (mli != null)
        {
            // Get file extension
            string fileExtension = Path.GetExtension(FileUpload.FileName).TrimStart('.');

            // Check file extension
            if (MediaLibraryHelper.IsExtensionAllowed(fileExtension))
            {
                try
                {
                    // Create new media file record
                    MediaFileInfo mediaFile = new MediaFileInfo(FileUpload.PostedFile, LibraryID, FolderPath);
                    mediaFile.FileDescription = txtFileDescription.Text;

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);

                    // Save preview if presented
                    if (PreviewUpload.HasFile)
                    {
                        string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(CMSContext.CurrentSiteName);

                        if (!String.IsNullOrEmpty(previewSuffix))
                        {
                            string previewExtension = Path.GetExtension(PreviewUpload.PostedFile.FileName);
                            string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, CMSContext.CurrentSiteName, previewSuffix));
                            string previewFolder    = MediaLibraryHelper.EnsurePath(FolderPath.TrimEnd('/')) + "/" + MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName);

                            byte[] previewFileBinary = new byte[PreviewUpload.PostedFile.ContentLength];
                            PreviewUpload.PostedFile.InputStream.Read(previewFileBinary, 0, PreviewUpload.PostedFile.ContentLength);

                            // Save preview file
                            MediaFileInfoProvider.SaveFileToDisk(CMSContext.CurrentSiteName, mli.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false);

                            // Log synchronization task
                            SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                        }
                    }

                    string normalizedFolderPath = MediaLibraryHelper.EnsurePath(FolderPath).Trim('/');

                    // If the event was fired by control itself- no save another media file should be proceeded
                    if (e != null)
                    {
                        ltlScript.Text += ScriptHelper.GetScript("RefreshAndClose('" + normalizedFolderPath.Replace("\'", "\\'") + "');");
                    }
                    else
                    {
                        ltlScript.Text += ScriptHelper.GetScript("RefreshParent('" + normalizedFolderPath.Replace("\'", "\\'") + "');");
                    }
                }
                catch (Exception ex)
                {
                    // Creation of new media file failed
                    lblError.Text = GetString("media.newfile.failed") + ": " + ex.Message;
                }
            }
            else
            {
                // The file with extension selected isn't allowed
                lblError.Text = String.Format(GetString("media.newfile.extensionnotallowed"), fileExtension);
            }
        }
    }
Esempio n. 4
0
    /// <summary>
    /// Provides operations necessary to create and store new library file.
    /// </summary>
    private void HandleLibrariesUpload()
    {
        // Get related library info
        if (LibraryInfo != null)
        {
            MediaFileInfo mediaFile = null;

            // Get the site name
            string   siteName = CMSContext.CurrentSiteName;
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
            if (si != null)
            {
                siteName = si.SiteName;
            }

            string message = string.Empty;
            try
            {
                // Check the allowed extensions
                CheckAllowedExtensions();

                if (MediaFileID > 0)
                {
                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileModify"))
                    {
                        throw new Exception(GetString("media.security.nofilemodify"));
                    }

                    #endregion

                    mediaFile = MediaFileInfoProvider.GetMediaFileInfo(MediaFileID);
                    if (mediaFile != null)
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mediaFile);

                        if (IsMediaThumbnail)
                        {
                            string newFileExt = Path.GetExtension(ucFileUpload.FileName).TrimStart('.');
                            if ((ImageHelper.IsImage(newFileExt)) && (newFileExt.ToLower() != "ico") &&
                                (newFileExt.ToLower() != "wmf"))
                            {
                                // Update or creation of Media File update
                                string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                if (!String.IsNullOrEmpty(previewSuffix))
                                {
                                    string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                    string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, siteName, previewSuffix));
                                    string previewFolder    = DirectoryHelper.CombinePath(MediaLibraryHelper.EnsurePath(LibraryFolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                    byte[] previewFileBinary = new byte[ucFileUpload.PostedFile.ContentLength];
                                    ucFileUpload.PostedFile.InputStream.Read(previewFileBinary, 0, ucFileUpload.PostedFile.ContentLength);

                                    // Delete current preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath, false);

                                    // Save preview file
                                    MediaFileInfoProvider.SaveFileToDisk(siteName, LibraryInfo.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false, false);

                                    // Log synchronization task
                                    SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                }

                                // Drop the cache dependencies
                                CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                            }
                            else
                            {
                                message = GetString("media.file.onlyimgthumb");
                            }
                        }
                        else
                        {
                            // Delete existing media file
                            MediaFileInfoProvider.DeleteMediaFile(LibraryInfo.LibrarySiteID, LibraryInfo.LibraryID, mediaFile.FilePath, true, false);

                            // Update media file preview
                            if (MediaLibraryHelper.HasPreview(siteName, LibraryInfo.LibraryID, mediaFile.FilePath))
                            {
                                // Get new file path
                                string newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(mediaFile.FilePath).TrimEnd('/'), ucFileUpload.PostedFile.FileName);
                                newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);

                                // Get new unique file name
                                string newName = Path.GetFileName(newPath);

                                // Rename preview
                                MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                // Delete preview thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                            }

                            // Receive media info on newly posted file
                            mediaFile = GetUpdatedFile(mediaFile.Generalized.DataClass);

                            MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                        }
                    }
                }
                else
                {
                    // Creation of new media file

                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileCreate"))
                    {
                        throw new Exception(GetString("media.security.nofilecreate"));
                    }

                    #endregion

                    // No file for upload specified
                    if (!ucFileUpload.HasFile)
                    {
                        throw new Exception(GetString("media.newfile.errorempty"));
                    }

                    // Create new media file record
                    mediaFile = new MediaFileInfo(ucFileUpload.PostedFile, LibraryID, LibraryFolderPath, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, LibraryInfo.LibrarySiteID);

                    mediaFile.FileDescription = "";

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                }
            }
            catch (Exception ex)
            {
                // Creation of new media file failed
                message = ex.Message;
            }
            finally
            {
                // Create media file info string
                string mediaInfo = "";
                if ((mediaFile != null) && (mediaFile.FileID > 0) && (IncludeNewItemInfo))
                {
                    mediaInfo = mediaFile.FileID + "|" + LibraryFolderPath.Replace('\\', '>').Replace("'", "\\'");
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false" + ((mediaInfo != "") ? ", '" + mediaInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}window.close();"));
            }
        }
    }
Esempio n. 5
0
        /// <summary>
        /// Provides operations necessary to create and store new files in media library.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleMediaLibraryUpload(UploaderHelper args, HttpContext context)
        {
            string uploadPath = Path.Combine(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(args.MediaLibraryArgs.LibraryID), args.MediaLibraryArgs.FolderPath);
            string filePath   = Path.Combine(uploadPath, args.FileName);

            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(args.MediaLibraryArgs.LibraryID);

            if (mli != null)
            {
                MediaFileInfo mediaFile = null;

                // Get the site name
                SiteInfo si       = SiteInfoProvider.GetSiteInfo(mli.LibrarySiteID);
                string   siteName = (si != null) ? si.SiteName : CMSContext.CurrentSiteName;

                try
                {
                    args.IsExtensionAllowed();

                    if (args.MediaLibraryArgs.MediaFileID > 0)
                    {
                        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "FileModify"))
                        {
                            throw new Exception(ResHelper.GetString("media.security.nofilemodify"));
                        }

                        mediaFile = MediaFileInfoProvider.GetMediaFileInfo(args.MediaLibraryArgs.MediaFileID);
                        if (mediaFile != null)
                        {
                            // Ensure object version
                            SynchronizationHelper.EnsureObjectVersion(mediaFile);

                            if (args.MediaLibraryArgs.IsMediaThumbnail)
                            {
                                if ((ImageHelper.IsImage(args.Extension)) && (args.Extension.ToLowerCSafe() != "ico") && (args.Extension.ToLowerCSafe() != "wmf"))
                                {
                                    // Update or creation of Media File update
                                    string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                    if (!String.IsNullOrEmpty(previewSuffix))
                                    {
                                        //string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                        string previewName   = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, args.Extension, siteName, previewSuffix));
                                        string previewFolder = String.Format("{0}\\{1}", MediaLibraryHelper.EnsurePath(args.MediaLibraryArgs.FolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                        // This method is limited to 2^32 byte files (4.2 GB)
                                        using (FileStream fs = File.OpenRead(args.FilePath))
                                        {
                                            byte[] previewFileBinary = new byte[fs.Length];
                                            fs.Read(previewFileBinary, 0, Convert.ToInt32(fs.Length));

                                            // Delete current preview thumbnails
                                            MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath, false);

                                            // Save preview file
                                            MediaFileInfoProvider.SaveFileToDisk(siteName, mli.LibraryFolder, previewFolder, previewName, args.Extension, mediaFile.FileGUID, previewFileBinary, false, false);

                                            // Log synchronization task
                                            SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                            fs.Close();
                                        }
                                    }
                                    // Drop the cache dependencies
                                    CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                                }
                                else
                                {
                                    args.Message = ResHelper.GetString("media.file.onlyimgthumb");
                                }
                            }
                            else
                            {
                                // Get folder path
                                string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mediaFile.FilePath));

                                // If file system permissions are sufficient for file update
                                if (DirectoryHelper.CheckPermissions(path, false, true, true, true))
                                {
                                    // Delete existing media file
                                    MediaFileInfoProvider.DeleteMediaFile(mli.LibrarySiteID, mli.LibraryID, mediaFile.FilePath, true, false);

                                    // Update media file preview
                                    if (MediaLibraryHelper.HasPreview(siteName, mli.LibraryID, mediaFile.FilePath))
                                    {
                                        // Get new unique file name
                                        string newName = URLHelper.GetSafeFileName(Path.GetFileName(args.Name), siteName);

                                        // Get new file path
                                        string newPath = DirectoryHelper.CombinePath(path, newName);
                                        newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);
                                        newName = Path.GetFileName(newPath);

                                        // Rename preview
                                        MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                        // Delete preview thumbnails
                                        MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                                    }

                                    // Receive media info on newly posted file
                                    mediaFile = GetUpdatedFile(mediaFile.Generalized.DataClass, args, mli);

                                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                                }
                            }
                        }
                    }
                    else
                    {
                        // Check 'File create' permission
                        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filecreate"))
                        {
                            throw new Exception(ResHelper.GetString("media.security.nofilecreate"));
                        }
                        mediaFile = new MediaFileInfo(args.FilePath, args.MediaLibraryArgs.LibraryID, args.MediaLibraryArgs.FolderPath, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);
                        MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                    }
                }
                catch (Exception ex)
                {
                    // Creation of new media file failed
                    args.Message = ex.Message;

                    // The CMS.IO library uses reflection to create an instance of file stream
                    if (ex is System.Reflection.TargetInvocationException)
                    {
                        if (ex.InnerException != null && !String.IsNullOrEmpty(ex.Message))
                        {
                            args.Message = ex.InnerException.Message;
                        }
                    }

                    // Log the error
                    EventLogProvider.LogException("MultiFileUploader", "UPLOADMEDIA", ex);
                }
                finally
                {
                    if (args.RaiseOnClick)
                    {
                        args.AfterScript += string.Format(@"
                        if(window.UploaderOnClick) 
                        {{
                            window.UploaderOnClick('{0}');
                        }}", args.MediaLibraryArgs.MediaFileName.Replace(" ", "").Replace(".", "").Replace("-", ""));
                    }

                    // Create media library info string
                    string mediaInfo = ((mediaFile != null) && (mediaFile.FileID > 0) && (args.IncludeNewItemInfo)) ? String.Format("'{0}|{1}', ", mediaFile.FileID, args.MediaLibraryArgs.FolderPath.Replace('\\', '>').Replace("'", "\\'")) : "";

                    // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end
                    args.AfterScript += string.Format(@"
                    if (window.InitRefresh_{0})
                    {{
                        window.InitRefresh_{0}('{1}', false, {2});
                    }}
                    else {{ 
                        if ('{1}' != '') {{
                            alert('{1}');
                        }}
                    }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), mediaInfo + (args.IsInsertMode ? "'insert'" : "'update'"));

                    args.AddEventTargetPostbackReference();
                    context.Response.Write(args.AfterScript);
                    context.Response.Flush();
                }
            }
        }