Admin.cs

// Copyright � 2007 Jeffrey Bazinet, http://www.vwd-cms.com/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Xml;
using System.Security.Principal;
using VwdCms.Configuration;
using System.Collections.Generic;

namespace VwdCms.Admin
{
    public class Admin : System.Web.UI.Page
    {
        private bool UITesting = false; // will turn on/off certain debugging features

        public enum Views
        {
            None,
            PageEditor,
            CodeEditor,
            XmlEditor,
            Preview,
            ImageZoom,
            DocHelper,
            ServerSettings,
            ConfigEditor
        }
        public enum UserViews
        {
            None,
            Editor,
            Code,
            Preview
        }

        private Hashtable htExtensions = null;
        private Hashtable htMasterPages = null;
        private string DefaultLanguageID = VwdCms.Configuration.Utilities.DefaultLanguage;

        protected System.Web.UI.WebControls.Panel pnlMessage;
        protected System.Web.UI.WebControls.Panel pnlError;
        protected System.Web.UI.WebControls.Panel pnlInfoBar;
        protected System.Web.UI.WebControls.Label lblVersion;
        protected System.Web.UI.WebControls.Label lblCurrentFile;
        protected System.Web.UI.WebControls.Label lblChanges;

        protected VwdCms.ToolbarContainer tbcTop;
        protected VwdCms.ToolbarContainer tbcEditor;
        protected VwdCms.ToolbarContainer tbcBottom;
        protected VwdCms.Admin.ToolbarTop tbrTop;
        protected VwdCms.Admin.ToolbarBottom tbrBottom;

        protected VwdCms.Admin.Filelist ctlFilelist;
        protected VwdCms.SplitterBar sbFilelist;

        protected System.Web.UI.HtmlControls.HtmlGenericControl ifrmPreview;
        protected VwdCms.TextEdit txtCode;
        protected VwdCms.Admin.XmlEditor xmlEdit;
        protected VwdCms.Admin.PageEditor ctlPageEditor;
        protected VwdCms.Admin.DocumentHelper ctlDocHelper;
        protected VwdCms.ImageZoom izImageZoom;
        protected VwdCms.Admin.ServerSettingsViewer ctlServerSettings;
        protected VwdCms.Admin.ConfigEditor ctlConfigEditor;

        protected HtmlGenericControl divCurtain;
        protected HtmlInputHidden hdnClientWidth;

        private string _imageUrl = VwdCms.Configuration.Utilities.AdminImageUrl;

        private bool _forcePreview = false;

        // blue theme
        // toolbar colors: tan:  #ece9d8; blue: #88aee4; green: # silver: #
        // lightsteelblue: #B0C4DE, skyblue:#87CEEB, aliceblue:#F0F8FF
        //private string _adminToolbarBackgroundColor = "#cee3fc"; //"#c0d9fb"; //"#cce4fb"; //"#B0C4DE"; //"#ece9d8"; //"#88aee4";
        //private string _editorToolbarBackgroundColor = "#ece9d8";

        // black theme 
        private string _adminToolbarBackgroundColor = "#202020";
        private string _editorToolbarBackgroundColor = "#ece9d8";

        private void SetElementImages()
        {
            bool useIconMatrix = false;

            this.tbrTop.UseIconMatrix = useIconMatrix;
            this.txtCode.UseIconMatrix = useIconMatrix; 
            this.xmlEdit.UseIconMatrix = useIconMatrix;
            this.izImageZoom.UseIconMatrix = useIconMatrix;
            this.tbrBottom.UseIconMatrix = useIconMatrix;

            if (useIconMatrix)
            {
                RegisterIconMatrixScript();
            }

            if (this.izImageZoom != null)
            {
                this.izImageZoom.ImageUrl = _imageUrl;
            }

            if (this.txtCode != null)
            {
                this.txtCode.ImageUrl = _imageUrl;
            }

            this.tbcTop.SeparatorImage = _imageUrl + "separator-blue.gif";
            this.tbrTop.SeparatorImage = _imageUrl + "separator-blue.gif";
            this.tbcEditor.SeparatorImage = _imageUrl + "separator-blue.gif";
            this.tbcBottom.SeparatorImage = _imageUrl + "separator-tan.gif";
            this.tbrBottom.SeparatorImage = _imageUrl + "separator-tan.gif";
        }

        private void RegisterIconMatrixScript()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<script type=\"text/javascript\">\r\n <!-- \r\n");

            sb.Append("function VwdCmsAdmin_setImages()\r\n");
            sb.Append("{\r\n");
            sb.Append("\tvar i = 0;\r\n");
            sb.Append("\tfor (i=0; i<document.images.length; i++)\r\n");
            sb.Append("\t{\r\n");
            sb.Append("\t\tif(document.images[i].className == 'VwdCmsAdmin_MatrixIcon' || document.images[i].className == 'miL')\r\n");
            sb.Append("\t\t{\r\n");
            sb.Append("\t\t\tdocument.images[i].src = _imgIcons.src;\r\n");
            sb.Append("\t\t}\r\n");
            sb.Append("\t}\r\n");
            sb.Append("}\r\n");

            sb.Append("var _imgIcons = new Image();\r\n");
            sb.Append("_imgIcons.src = '");
            sb.Append(VwdCms.Configuration.Utilities.AdminImageUrl);
            sb.Append("icons.gif';\r\n");
            
            sb.Append("// -->\r\n");
            sb.Append("</script>\r\n");

            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "AdminStartupScript", sb.ToString());
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {
            // get the Cms Config settins
            CmsConfig cfgmgr = CmsConfig.Current;
            CmsHost host = cfgmgr.CurrentHost;

            SetElementImages();

            // determine if pnlMessage should be displayed
            if ((UITesting || host.DemoMode)  host.ShowAdminBanner)
            {
                VwdCms.ContentControl ccDemo = new ContentControl();
                ccDemo.ShowEditLink = ShowEditLinks.NotInDemoMode;
                ccDemo.ContentFolder = "Content";
                ccDemo.ContentFile = "DemoBanner.content";
                this.pnlMessage.Controls.Add(ccDemo);

                int pbm = this.PostBackCount % 2;
                VwdCms.ContentControl ccDemoAd = new ContentControl();
                ccDemoAd.ShowEditLink = ShowEditLinks.NotInDemoMode;
                ccDemoAd.ContentFolder = "Ads";
                ccDemoAd.ContentFile = "DemoAd" + pbm.ToString() + ".content";
                this.pnlMessage.Controls.Add(ccDemoAd);

                this.pnlMessage.Visible = true;
            }
            else
            {
                this.pnlMessage.Controls.Clear();
                this.pnlMessage.Visible = false;
            }

            // set the information labels on the bottom toolbar
            this.tbrBottom.HostName = this.Page.Request.Url.Host;
            if (host.DemoMode)
            {
                this.tbrBottom.UserName = "webdemouser";
                this.tbrBottom.ImpersonationLevel = "Identify";
            }
            else
            {
                System.Security.Principal.WindowsIdentity identity = null;
                identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                this.tbrBottom.UserName = identity.Name;
                this.tbrBottom.ImpersonationLevel = identity.ImpersonationLevel.ToString();
            }

            // create the top and bottom toolbars
            this.tbrTop.ItemClick += new EventHandler(this.tbrTop_ItemClick);
            this.tbrTop.LoadItems();
            this.tbrBottom.ItemClick += new EventHandler(this.tbrBottom_ItemClick);
            this.tbrBottom.LoadItems();

            // set the Filelist width
            string filelistWidth = this.sbFilelist.LeftColumnWidth;
            if (string.IsNullOrEmpty(filelistWidth))
            {
                filelistWidth = "235px";
            }
            this.ctlFilelist.Width = new Unit(filelistWidth);

            this.pnlError.Controls.Clear();
            this.pnlError.Visible = false;

            this.lblChanges.Text = string.Empty;

            if (UITesting)
            {
                // testing the error panel
                Exception ex = new FileNotFoundException();
                this.ErrorMessage = new ExceptionReport("Cannot find the file", ex);
                ex = new ArgumentOutOfRangeException();
                this.ErrorMessage = new ExceptionReport("Invalid Argument", ex);
                ex = new ArgumentNullException();
                this.ErrorMessage = new ExceptionReport("Argument cannot be null", ex);

            }

            if (this.ctlConfigEditor != null  this.ctlConfigEditor.Visible)
            {
                this.ctlConfigEditor.CmsSettingsChanged += new CommandEventHandler(ctlConfigEditor_CmsSettingsChanged);
            }

            this.ctlFilelist.EditFileClick += new CommandEventHandler(ctlFilelist_EditFileClick);
            this.ctlFilelist.CurrentFolderChanged += new CommandEventHandler(ctlFilelist_CurrentFolderChanged);
            this.ctlFilelist.CurrentFileChanged += new CommandEventHandler(ctlFilelist_CurrentFileChanged);
            this.ctlFilelist.Errors += new CommandEventHandler(ctlFilelist_Errors);
            this.ctlFilelist.RecentFilesCleared += new CommandEventHandler(ctlFilelist_RecentFilesCleared);

            htExtensions = VwdCms.Configuration.Utilities.LoadExtensions();
            htMasterPages = VwdCms.Configuration.Utilities.LoadMasterPages();

            if (this.ctlPageEditor.Visible)
            {
                this.ctlPageEditor.CurrentFolder = this.ctlFilelist.CurrentFolder;
                this.ctlPageEditor.Errors += new CommandEventHandler(ctlPageEditor_Errors);
            }
            if (this.xmlEdit.Visible)
            {
                this.xmlEdit.Errors += new CommandEventHandler(xmlEdit_Errors);
            }

            if (this.ctlDocHelper != null)
            {
                this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
                this.ctlDocHelper.Languages = this.tbrTop.SortedLanguageList;
                this.ctlDocHelper.CurrentLanguage = this.CurrentLanguage;
                this.ctlDocHelper.CurrentVersion = this.CurrentVersion;
                this.ctlDocHelper.Extensions = htExtensions;
                this.ctlDocHelper.FolderChanged += new CommandEventHandler(this.lnkFolder_Command);
                this.ctlDocHelper.Errors += new CommandEventHandler(ctlDocHelper_Errors);
                this.ctlDocHelper.CreateFolder += new CommandEventHandler(ctlDocHelper_Refresh);
                this.ctlDocHelper.CreateDocument += new CommandEventHandler(ctlDocHelper_Refresh);
                this.ctlDocHelper.DeleteDocument += new CommandEventHandler(ctlDocHelper_Refresh);
                this.ctlDocHelper.RenameDocument += new CommandEventHandler(ctlDocHelper_Refresh);
                this.ctlDocHelper.Cancel += new CommandEventHandler(ctlDocHelper_Refresh);
                this.ctlDocHelper.CopyDocument += new CommandEventHandler(ctlDocHelper_Refresh);
                this.ctlDocHelper.PublishDocument += new CommandEventHandler(ctlDocHelper_PublishDocument);
                this.ctlDocHelper.VersionChanged += new CommandEventHandler(ctlDocHelper_VersionChanged);
            }

            // check the querystring for a file to edit if this is not a postback
            if (this.Page.IsPostBack)
            {
                this.PostBackCount++;
            }
            else
            {
                // initial page load, perform config
                this.UserView = UserViews.None;
                this.CurrentView = Views.None;

                // check query string to see if a file was passed in to edit
                SetCurrentFileFromQueryString(host.DemoMode);
            }
            
            // always load the filelist items so postbacks can be handled
            this.LoadItems();

            // manually code the handling for the post-back for the save 
            // button because it is using javascript to submit the form
            string evttrg = this.Page.Request.Form["__EVENTTARGET"];
            if (evttrg == "tbrTop$tbbSave")
            {
                this.Save();
            }
        }

        private void SetCurrentFileFromQueryString(bool demoMode)
        {
            string vpFile = this.Page.Request.QueryString["file"];

            if (!string.IsNullOrEmpty(vpFile))
            {
                try
                {
                    bool editAllowed = false;

                    vpFile = vpFile.ToLower();
                    vpFile = vpFile.Trim();
                    vpFile = vpFile.Replace("\\", "/");
                    vpFile = vpFile.Replace(" ", string.Empty);
                    
                    string lpFile = this.Server.MapPath(vpFile);
                    editAllowed = File.Exists(lpFile);

                    if (editAllowed && demoMode)
                    {
                        FileInfo finf = new FileInfo(lpFile);
                        editAllowed = VwdCms.Configuration.Utilities.IsFileAllowedInDemo(finf);
                    }

                    if (editAllowed)
                    {
                        this.ctlFilelist.CurrentFile = vpFile;
                        this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.GetFolder(vpFile);
                        this.ctlFilelist.AddRecentItem(vpFile);
                    }
                    else
                    {
                        this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.SitePath;
                        this.ctlFilelist.CurrentFile = string.Empty;
                    }
                }
                catch
                {
                    this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.SitePath;
                    this.ctlFilelist.CurrentFile = string.Empty;
                }
            }
            else
            {
                this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.SitePath;
                this.ctlFilelist.CurrentFile = string.Empty;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            CmsConfig cfg = CmsConfig.Current;

            if (cfg.Exceptions.Count > 0)
            {
                string msg = "There were " + cfg.Exceptions.Count.ToString()
                    + " errors / exceptions while attempting to load the VWD-CMS Configuration Settings "
                    + " from '" + CmsConfig.ConfigFile + "'.br/br/Open the 'Server Settings' view to "
                    + " see the error information. The 'Server Settings' view can be opened by clicking on the "
                    + " Server Settings icon on the toolbar at the bottom left of this page.";
                this.ErrorMessage = new ExceptionReport(msg);
            }

            this.RenderCurrentView();
            this.LoadItems();


            string unsavedScript = "\r\nscript type=\"text/javascript\">\r\n"
                + "\tvar showUnsavedChangesMessage = " + cfg.CmsSettings.ShowUnsavedChangesMessage.ToString().ToLower() + ";\r\n"
                + "</script>\r\n";
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AdminUnsavedChangesScript", unsavedScript);

            base.OnPreRender(e);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            // this script needs to be the last onsubmit script to be registered
            // child controls also register onsubmit scripts and since this script
            // has a 'return' in it, any code after this one will not get executed
            this.Page.ClientScript.RegisterOnSubmitStatement(this.GetType(),
                "VwdCmsAdminBeforeSubmitScript", "return VwdCmsAdmin_beforeSubmit();\r\n");
            base.OnPreRenderComplete(e);
        }

        private int PostBackCount
        {
            get { return Convert.ToInt32(this.ViewState["PostBackCount"]); }
            set { this.ViewState["PostBackCount"] = value; }
        }
        private string SavedVersion
        {
            get { return Convert.ToString(this.ViewState["SavedVersion"]); }
            set { this.ViewState["SavedVersion"] = value; }
        }
        private string SavedLanguage
        {
            get { return Convert.ToString(this.ViewState["SavedLanguage"]); }
            set { this.ViewState["SavedLanguage"] = value; }
        }

        void tbrTop_ItemClick(object sender, System.EventArgs e)
        {
            Control toolbarControl = (Control)sender;
            switch (toolbarControl.ID)
            {
                case "rblView":
                    this.UserView = (UserViews)Convert.ToInt32(this.tbrTop.ViewList.SelectedValue);
                    break;
                case "rblVersion":
                    if (this.tbrTop.VersionList.SelectedValue != this.SavedVersion)
                    {
                        this.SetVersion();
                    }
                    break;
                case "ddlLanguage":
                    // nothing to do
                    break;
                case "tbbSiteFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.SitePath);
                    break;
                case "tbbContentFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.ContentFolder);
                    break;
                case "tbbNavigationFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.NavigationFolder);
                    break;
                case "tbbAdsFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.AdsFolder);
                    break;
                case "tbbImageFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.ImageFolder);
                    break;
                case "tbbProductImageFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.ProductImageFolder);
                    break;
                case "tbbMasterFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.MasterFolder);
                    break;
                case "tbbScriptsFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.ScriptsFolder);
                    break;
                case "tbbCssFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.CssFolder);
                    break;
                case "tbbEmailFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.EmailFolder);
                    break;
                case "tbbTemplateFolder":
                    this.ChangeFolder(sender, VwdCms.Configuration.Utilities.TemplateFolder);
                    break;
                case "tbbSave":
                    this.Save();
                    break;
                case "tbbPublish":
                    this.Publish();
                    break;
                case "tbbNewPage":
                    this.NewPage();
                    break;
                case "tbbCopy":
                    this.Copy();
                    break;
                case "tbbNewFolder":
                    this.NewFolder();
                    break;
                case "tbbNewDoc":
                    this.NewDoc();
                    break;
                case "tbbNewContent":
                    this.NewContent();
                    break;
                case "tbbRefresh":
                    this.Refresh();
                    break;
            }
        }

        void tbrBottom_ItemClick(object sender, System.EventArgs e)
        {
            Control toolbarControl = (Control)sender;
            switch (toolbarControl.ID)
            {
                case "tbbConfigEditor":
                    this.CurrentView = Views.ConfigEditor;
                    break;
                case "tbbServerSettings":
                    this.CurrentView = Views.ServerSettings;
                    break;
            }
        }

        private void ChangeFolder(object sender, string vpFolder)
        {
            this.ctlFilelist.CurrentFile = string.Empty;
            this.ctlFilelist.CurrentFolder = vpFolder;
            if (this.CurrentView == Views.DocHelper  !sender.Equals(this.ctlDocHelper))
            {
                if (this.ctlDocHelper.Mode == "document" || this.ctlDocHelper.Mode == "folder")
                {
                    this.ctlDocHelper.CurrentFolder = vpFolder;
                }
                else
                {
                    this.CurrentView = Views.None;
                }
            }            
        }

        private void Save()
        {
            string lpFile = this.ctlFilelist.CurrentLocalFile;
            if (this.CheckPermissions())
            {
                Views view = this.CurrentView;
                FileExtension fe = this.CurrentFileExtensionObject;
                string language = this.CurrentLanguage;
                string version = VwdCms.Constants.LiveVersion;
                string vpFile = this.ctlFilelist.CurrentFile;
                string vpVersionFile = vpFile;
                string lpVersionFile = lpFile;

                if (fe.Versions)
                {
                    version = this.CurrentVersion;
                    vpVersionFile = GetVersionSpecificFile(vpFile);
                    lpVersionFile = GetVersionSpecificFile(lpFile);
                }
                bool success = false;

                if (view == Views.XmlEditor)
                {
                    try
                    {
                        this.xmlEdit.CurrentFile = vpFile;
                        this.xmlEdit.Save();
                    }
                    catch (Exception ex)
                    {
                        string msg = "Failed while trying to save the file '" + vpFile + "'.\r\n\r\n";
                        ErrorMessage = new ExceptionReport(msg, ex);
                    }
                }
                else if (view == Views.CodeEditor)
                {
                    if (fe.FileFormat == FileFormats.XML  fe.Extension != ".config")
                    {
                        success = SaveToXmlFile(lpVersionFile, "content", this.CurrentCode);
                    }
                    else
                    {
                        success = WriteFile(lpVersionFile, this.CurrentCode);
                    }
                }
                else if (view == Views.PageEditor)
                {
                    // update the codefile's write timestamp
                    try
                    {
                        File.SetLastWriteTime(lpVersionFile, DateTime.Now);
                    }
                    catch
                    {
                        // do nothing 
                    }

                    try
                    {
                        // now save the content changes
                        this.ctlPageEditor.Version = version;
                        this.ctlPageEditor.Language = language;
                        this.ctlPageEditor.CurrentFile = vpFile;
                        this.ctlPageEditor.SetPageContent();
                    }
                    catch (Exception ex)
                    {
                        string msg = "Failed while trying to save the content file'.\r\n\r\n";
                        ErrorMessage = new ExceptionReport(msg, ex);
                    }
                    this.ctlPageEditor.GetPageContent();
                }
            }
        }

        private void Copy()
        {
            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "copy";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.CurrentFile = this.ctlFilelist.CurrentFile;
            this.CurrentView = Views.DocHelper;
        }

        private void NewPage()
        {
            bool demo = CmsConfig.Current.CurrentHost.DemoMode;
            if (demo)
            {
                this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.DemoFolder;
                this.ctlDocHelper.WarningMessage = "The folder has been changed to '" + VwdCms.Configuration.Utilities.DemoFolder + "'.<br/><br/>";
            }
            
            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "document";
            string currFolder = this.ctlFilelist.CurrentFolder;
            ManagedFolder mf = CmsConfig.Current.GetManagedFolder(this.ctlFilelist.CurrentFolder);

            if (mf != null  !mf.ExtensionAllowed(VwdCms.Constants.LivePageExtension))
            {
                this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.SitePath;
                this.ctlDocHelper.WarningMessage = "WARNING:<br/>"
                    + "The folder has been changed to '" + this.ctlFilelist.CurrentFolder + "'<br/>"
                    + "because the folder '" + currFolder + "'<br/>"
                    + "cannot contain Web Pages / Web Forms.<br/><br/>";
            }
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.Extension = VwdCms.Constants.LivePageExtension;
            this.CurrentView = Views.DocHelper;
        }

        private void NewContent()
        {
            // configure and display the NewDocument control
            string currentFolder = this.ctlFilelist.CurrentFolder;
            string contentFolder = VwdCms.Configuration.Utilities.ContentFolder;
            if (currentFolder != contentFolder)
            {
                this.ctlFilelist.CurrentFolder = contentFolder;
                this.ctlDocHelper.WarningMessage = "WARNING:<br/>"
                    + "The folder has been changed to '" + contentFolder + "'.<br/><br/>";
            }

            this.ctlDocHelper.Mode = "document";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.Extension = ".content";
            this.CurrentView = Views.DocHelper;
        }

        private void NewDoc()
        {
            bool demo = CmsConfig.Current.CurrentHost.DemoMode;
            if (demo)
            {
                this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.DemoFolder;
                this.ctlDocHelper.WarningMessage = "The folder has been changed to '" + VwdCms.Configuration.Utilities.DemoFolder + "'.<br/><br/>";
            }
            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "document";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.Extension = string.Empty;
            this.CurrentView = Views.DocHelper;
        }

        private void NewFolder()
        {
            bool demo = CmsConfig.Current.CurrentHost.DemoMode;
            if (demo)
            {
                this.ctlFilelist.CurrentFolder = VwdCms.Configuration.Utilities.DemoFolder;
                this.ctlDocHelper.WarningMessage = "The folder has been changed to '" + VwdCms.Configuration.Utilities.DemoFolder + "'.<br/><br/>";
            }
            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "folder";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.CurrentView = Views.DocHelper;
        }
        private void Refresh()
        {
            string file = this.ctlFilelist.CurrentFile;
            lnkEdit_Command(null, new CommandEventArgs("refresh", file));
        }

        void Publish()
        {
            // first save the draft version, then prompt for 
            // confirmation to publish
            this.Save();

            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "publish";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.CurrentFile = this.ctlFilelist.CurrentFile;
            this.CurrentView = Views.DocHelper;
        }

        void ctlConfigEditor_CmsSettingsChanged(object sender, CommandEventArgs e)
        {
            CmsSettings settings = (CmsSettings)e.CommandArgument;

            ApplyCmsSettings(settings);

            // the view is set to 'None' so that GetView can determine what view to show 
            this.CurrentView = Views.None;
        
        }

        private void LoadItems()
        {
            string version = VwdCms.Constants.LiveVersion; // always load the items using "live", not this.CurrentVersion;

            this.ctlFilelist.LoadItems(this.lnkFolder_Command, this.lnkEdit_Command,
                this.lnkDelete_Command, this.lnkRename_Command, this.CurrentLanguage,
                htExtensions, htMasterPages, this.tbrTop.SortedLanguageList, version);
            this.ctlFilelist.LoadRecentItems(this.lnkFolder_Command, this.lnkEdit_Command,
                this.lnkDelete_Command, this.lnkRename_Command, this.CurrentLanguage,
                htExtensions, htMasterPages, this.tbrTop.SortedLanguageList, version);
        }

        void ctlFilelist_Errors(object sender, CommandEventArgs e)
        {
            string msg = Convert.ToString(e.CommandArgument);
            ErrorMessage = new ExceptionReport(msg);
        }

        void ctlFilelist_CurrentFolderChanged(object sender, CommandEventArgs e)
        {
            if (this.ctlPageEditor.Visible)
            {
                if (this.ctlPageEditor.CurrentFolder != this.ctlFilelist.CurrentFolder)
                {
                    this.ctlPageEditor.CurrentFolder = this.ctlFilelist.CurrentFolder;
                }
            }
            SetTitle();
        }

        private void SetTitle()
        {
            string title = "VWD-CMS Admin";
            if (CmsConfig.Current.CurrentHost.DemoMode)
            {
                title = "VWD-CMS for ASP.NET Websites";
            }
            else
            {
                title = this.ctlFilelist.CurrentFile;

                if (string.IsNullOrEmpty(title))
                {
                    title = this.ctlFilelist.CurrentFolder;
                }

                if (string.IsNullOrEmpty(title))
                {
                    title = "VWD-CMS Admin";
                }
            }
            this.Page.Title = title;
        }
        void ctlFilelist_EditFileClick(object sender, CommandEventArgs e)
        {
            // the edit link on the filelist was clicked
            // this is different from CurrentFileChanged because the user may 
            // have clicked on the same file that they are currently editing
            // it is important to ensure that the view gets set properly even 
            // if the file has not changed

            // the view is set to 'None' so that GetView can determine what view to show 
            this.CurrentView = Views.None;
        }
        void ctlFilelist_CurrentFileChanged(object sender, CommandEventArgs e)
        {
            SetTitle();

            if (this.txtCode != null  this.txtCode.Visible)
            {
                this.txtCode.ClearSelection();
            }

            this.CurrentView = Views.None;

        }
        void ctlFilelist_RecentFilesCleared(object sender, CommandEventArgs e)
        {
            // nothing to do
        }

        private void ApplyCmsSettings(CmsSettings settings)
        {
            if (settings == null)
            {
                settings = CmsConfig.Current.CmsSettings;
            }

            // txtCode 
            if (this.txtCode.Visible)
            {
                if (this.CurrentView == Views.CodeEditor)
                {
                    this.txtCode.BuildControls();
                }
                this.txtCode.ShowImages = !settings.SlowConnection;
                this.txtCode.TextArea.Style.Add("font-family", settings.EditorFontFamily);
                this.txtCode.TextArea.Style.Add("font-size", settings.EditorFontSize);
                this.txtCode.LineWrap = settings.EditorLineWrap ? VwdCms.Configuration.LineWraps.Soft : VwdCms.Configuration.LineWraps.None;
            }

            // xmlEdit
            if (this.xmlEdit.Visible)
            {
                this.xmlEdit.ApplyCmsSettings();
            }

            this.tbrTop.ApplyCmsSettings();
            this.tbrBottom.ApplyCmsSettings();

            this.ctlFilelist.ApplyCmsSettings();

            if (this.ctlPageEditor.Visible)
            {
                this.ctlPageEditor.ApplyCmsSettings(settings);
            }

            if (settings.SlowConnection)
            {
                // set the background image of the toolbar containers
                this.tbcTop.Style.Remove("background-image");
                this.tbcBottom.Style.Remove("background-image");
                this.tbcEditor.Style.Remove("background-image");

                // set the backgroung-color of the toolbar containers
                this.tbcTop.Style.Add("background-color", _adminToolbarBackgroundColor);
                this.tbcBottom.Style.Add("background-color", _adminToolbarBackgroundColor);
                this.tbcEditor.Style.Add("background-color", _editorToolbarBackgroundColor);

                // set the curtain style
                this.divCurtain.Style.Remove("background-image");
                this.divCurtain.InnerHtml = "VWD-CMS";

                // splitterbars
                this.sbFilelist.Style.Remove("background-image");
            }
            else
            {
                // set the background image of the toolbar containers
                // banner-tan.gif, banner-blue.gif, banner-green.gif, banner-silver.gif
                // colors: tan:  #eeede5; blue: #98c0f8; green: # silver: #
                this.tbcTop.Style.Add("background-image", "url(" + _imageUrl + "banner-blue.gif)");
                this.tbcBottom.Style.Add("background-image", "url(" + _imageUrl + "banner-blue.gif)");
                this.tbcEditor.Style.Add("background-image", "url(" + _imageUrl + "banner-tan.gif)");

                // set the curtain style
                this.divCurtain.InnerHtml = "&nbsp;";
                this.divCurtain.Style.Add("background-image", "url(" + _imageUrl +"curtain.jpg)");
                
                // splitterbars
                this.sbFilelist.Style.Add("background-image", "url(" + _imageUrl + "vsplitter.gif)");
            }
        }

        void ctlDocHelper_PublishDocument(object sender, CommandEventArgs e)
        {
            if (this.CheckPermissions())
            {
                string vpPage = string.Empty;

                try
                {
                    CmsConfig cfg = CmsConfig.Current;

                    // user has confirmed publishing of the draft version
                    // draft version has already been saved in 'lnkPublish_Command' before confirmation

                    // gather information
                    vpPage = this.ctlFilelist.CurrentFile;
                    string masterPageFile = VwdCms.Admin.PageEditor.GetPageMasterPageFile(vpPage, VwdCms.Constants.DraftVersion);
                    string pageName = VwdCms.Configuration.Utilities.GetFilename(vpPage, false);
                    pageName = VwdCms.Configuration.Utilities.RemoveExtension(pageName);

                    string classNameLive = VwdCms.Admin.DocumentHelper.GetPageClassName(pageName, VwdCms.Constants.LiveVersion);
                    string classNameDraft = classNameLive + VwdCms.Constants.DraftClassNameSuffix;

                    string lpPageFileLive = VwdCms.Configuration.Utilities.GetPageFile(vpPage, VwdCms.Constants.LiveVersion, true);
                    string lpCodeFileLive = VwdCms.Configuration.Utilities.GetPageCodeBehindFile(vpPage, VwdCms.Constants.LiveVersion, true);
                    string lpPageFileDraft = VwdCms.Configuration.Utilities.GetPageFile(vpPage, VwdCms.Constants.DraftVersion, true);
                    string lpCodeFileDraft = VwdCms.Configuration.Utilities.GetPageCodeBehindFile(vpPage, VwdCms.Constants.DraftVersion, true);

                    // load the "draft" files to be published and remove
                    // any "draft" specific code, content before writing 
                    // them out as as the "live" versions

                    // example:
                    // MyPage.draft.aspx                        (page file)
                    // MyPage.draft.aspx.cs                    (code file)
                    // MyPage.draft.aspx.english.pagecontent    (pagecontent, english)
                    // MyPage.draft.aspx.german.pagecontent    (pagecontent, german)

                    // 1. page file: if it has CodeFile and Inherits attributes in 
                    //    the page declaration, then modify it 
                    // 2. if there is a code file, the class name will need 
                    //    to be changed (remove the "_Draft" suffix from it)
                    // 3. pagecontent files, copy for all configured languages
                    string source = null;
                    string sourceLower = null;
                    string search = null;
                    string replace = null;
                    int index = 0;
                    bool hasCodeFile = false;

                    // load the files and make the substitutions/removals

                    // Page File (MyPage.draft.aspx)
                    source = ReadFile(lpPageFileDraft);
                    if (!string.IsNullOrEmpty(source))
                    {
                        // page file: look for the CodeFile attribute. If the code 
                        // file is not in the format of CodeFile="MyPage.draft.aspx.cs" (see example above)
                        // then it may have been customized and we don't want to 
                        // make any changes to it.
                        sourceLower = source.ToLower();
                        search = "CodeFile=\"" + pageName + VwdCms.Constants.DraftCodeExtension + "\"";
                        search = search.ToLower();
                        index = sourceLower.IndexOf(search, 0);
                        if (index != -1)
                        {
                            replace = "CodeFile=\"" + pageName + VwdCms.Constants.LiveCodeExtension + "\"";
                            source = source.Remove(index, search.Length);
                            source = source.Insert(index, replace);
                            hasCodeFile = true;
                        }

                        // page file: look for the Inherits attribute. If the Inherits value
                        // is not in the format of Inherits="MyPage_Draft" (see example above)
                        // then it may have been customized and we don't want to 
                        // make any changes to it.
                        sourceLower = source.ToLower();
                        search = "Inherits=\"" + classNameDraft + "\"";
                        search = search.ToLower();
                        index = sourceLower.IndexOf(search, 0);
                        if (index != -1)
                        {
                            replace = "Inherits=\"" + classNameLive + "\"";
                            source = source.Remove(index, search.Length);
                            source = source.Insert(index, replace);
                        }

                        // save the modified source to the "live" version
                        WriteFile(lpPageFileLive, source);

                        // if a CodeFile attribute was found, load the "draft" version
                        // of the code file and change the class name
                        if (hasCodeFile)
                        {
                            source = ReadFile(lpCodeFileDraft);
                            if (!string.IsNullOrEmpty(source))
                            {
                                sourceLower = source.ToLower();
                                search = "class " + classNameDraft;
                                search = search.ToLower();
                                index = sourceLower.IndexOf(search, 0);
                                if (index != -1)
                                {
                                    replace = "class " + classNameLive;
                                    source = source.Remove(index, search.Length);
                                    source = source.Insert(index, replace);
                                }
                                // save the modified source to the "live" version
                                WriteFile(lpCodeFileLive, source);
                            }
                        }
                    }

                    // now copy the "pagecontent" files
                    string lpContentFileDraft = null;
                    string lpContentFileLive = null;
                    string languageID = null;
                    VwdCms.Configuration.Language language = null;
                    foreach (KeyValuePairstring, VwdCms.Configuration.Language kvp in cfg.Languages)
                    {
                        language = (VwdCms.Configuration.Language)kvp.Value;
                        languageID = language.ID;

                        lpContentFileDraft = VwdCms.Configuration.Utilities.GetPageContentFileLocal(vpPage, languageID, VwdCms.Constants.DraftVersion);
                        lpContentFileLive = VwdCms.Configuration.Utilities.GetPageContentFileLocal(vpPage, languageID, VwdCms.Constants.LiveVersion);

                        if (File.Exists(lpContentFileDraft))
                        {
                            try
                            {
                                VwdCms.Admin.IO.CopyFile(lpContentFileDraft, lpContentFileLive, true);
                            }
                            catch (Exception ex)
                            {
                                string msg = "Failed while trying to copy the file '{0}' to '{1}'.\r\n\r\n";
                                msg = string.Format(msg, lpContentFileDraft, lpContentFileLive);
                                ErrorMessage = new ExceptionReport(msg, ex);
                            }
                        }
                    }

                    // switch the version to "live"
                    if (this.tbrTop.VersionList != null)
                    {
                        ListItem itm = this.tbrTop.VersionList.Items.FindByValue(VwdCms.Constants.LiveVersion);
                        this.tbrTop.VersionList.SelectedIndex = this.tbrTop.VersionList.Items.IndexOf(itm);
                    }
                }
                catch (Exception ex)
                {
                    string msg = "Failed while trying to publish the draft to the live site'.\r\n\r\n";
                    ErrorMessage = new ExceptionReport(msg, ex);
                }
                finally
                {
                    try
                    {
                        CmsHost host = CmsConfig.Current.CurrentHost;
                        if (!string.IsNullOrEmpty(vpPage)  host != null  host.DemoMode)
                        {
                            string page = vpPage;
                            page = page.Substring(VwdCms.Configuration.Utilities.SitePath.Length);
                            StringBuilder sbActivity = new StringBuilder();
                            sbActivity.Append("Publish Document<br/><br/>");
                            sbActivity.Append("<a href=\"" + VwdCms.Configuration.Utilities.SiteUrl + page + "\">" + page + "</a><br/>");
                            this.SendDemoActivityReport(sbActivity.ToString());
                        }
                    }
                    catch { }
                }
            }
            this.CurrentView = Views.None;
        }

        void ctlDocHelper_Refresh(object sender, CommandEventArgs e)
        {
            Type enumType = typeof(DocumentHelper.Commands);
            DocumentHelper.Commands cmd;
            cmd = (DocumentHelper.Commands)System.Enum.Parse(enumType, e.CommandName);

            string arg = e.CommandArgument.ToString();

            switch (cmd)
            {
                case DocumentHelper.Commands.RenameDocument:
                    // remove the old document name from the Recent files list
                    // set the current file in the file list
                    string[] files = arg.Split('|');
                    if (files != null  files.Length == 2)
                    {
                        this.ctlFilelist.CurrentFile = files[0]; // new file
                        RemoveFilesFromRecentList(files[1]); // list of files that were renamed
                    }
                    else
                    {
                        // this should never happen
                        // clear the current file in the file list
                        this.ctlFilelist.CurrentFile = string.Empty;
                    }
                    break;

                case DocumentHelper.Commands.CreateDocument:
                case DocumentHelper.Commands.CopyDocument:
                    // set the current file in the file list
                    this.ctlFilelist.CurrentFile = Convert.ToString(e.CommandArgument);

                    if (CmsConfig.Current.CurrentHost.DemoMode)
                    {
                        this.ForcePreview = true;
                        this.CurrentPreview = this.ctlFilelist.CurrentFile;
                        this.CurrentView = Views.Preview;
                    }
                        
                    break;

                case DocumentHelper.Commands.DeleteDocument:
                    // clear the current file in the file list
                    // remove the old document name from the Recent files list
                    this.ctlFilelist.CurrentFile = string.Empty;
                    RemoveFilesFromRecentList(arg);
                    break;

                default:
                    // clear the current file in the file list
                    this.ctlFilelist.CurrentFile = string.Empty;
                    break;
            }

            try
            {
                CmsHost host = CmsConfig.Current.CurrentHost;
                if (host != null  host.DemoMode)
                {
                    StringBuilder sbActivity = new StringBuilder();
                    sbActivity.Append(cmd.ToString() + "<br/><br/>");
                    if (cmd == DocumentHelper.Commands.DeleteDocument)
                    {
                        sbActivity.Append("Deleted Files: " + arg.Replace(";", "<br/>"));
                    }
                    else
                    {
                        string currentFile = this.ctlFilelist.CurrentFile;
                        currentFile = currentFile.Substring(VwdCms.Configuration.Utilities.SitePath.Length);
                        sbActivity.Append(currentFile + "<br/><br/>");
                        sbActivity.Append("<a href=\"" + VwdCms.Configuration.Utilities.SiteUrl + currentFile + "\">" + currentFile + "</a>");
                    }
                    this.SendDemoActivityReport(sbActivity.ToString());
                }
            }
            catch { }

            this.CurrentView = Views.None;
        }

        void xmlEdit_Errors(object sender, CommandEventArgs e)
        {
            this.ErrorMessage = new ExceptionReport(Convert.ToString(e.CommandArgument));

        }

        void ctlDocHelper_Errors(object sender, CommandEventArgs e)
        {
            ExceptionReport er = null;
            if (e.CommandArgument.GetType() == typeof(ExceptionReport))
            {
                er = e.CommandArgument as ExceptionReport;
            }
            
            if (er == null)
            {
                er = new ExceptionReport(Convert.ToString(e.CommandArgument));
            }

            this.ErrorMessage = er;
        }

        void ctlPageEditor_Errors(object sender, CommandEventArgs e)
        {
            this.ErrorMessage = new ExceptionReport(Convert.ToString(e.CommandArgument));
        }

        private void RemoveFilesFromRecentList(string filesToRemove)
        {
            // remove the old document name from the Recent files list
            string[] files = filesToRemove.Split(';');
            if (files != null  files.Length  0)
            {
                foreach (string file in files)
                {
                    if (!string.IsNullOrEmpty(file))
                    {
                        this.ctlFilelist.RemoveRecentItem(file);
                    }
                }
            }
        }

        private string CurrentLanguage
        {
            get
            {
                // determine the language
                string language = null;
                if (this.tbrTop.LanguageList != null)
                {
                    language = this.tbrTop.LanguageList.SelectedValue;
                }
                if (language == null || language == string.Empty)
                {
                    language = this.DefaultLanguageID;
                }
                return language;
            }
        }
        private string CurrentVersion
        {
            get
            {
                string version = VwdCms.Constants.LiveVersion;
                if (this.tbrTop.VersionList != null  this.tbrTop.VersionList.Enabled)
                {
                    version = this.tbrTop.VersionList.SelectedValue;
                }
                return version;
            }
        }

        private ExceptionReport ErrorMessage
        {
            set
            {
                ExceptionReport er = value;
                string vpApp = this.Page.Request.ApplicationPath;
                string lpApp = this.Page.Server.MapPath(vpApp);
                string userName = string.Empty;
                string impersonationLevel = string.Empty;
                CmsConfig cfg = CmsConfig.Current;
                CmsHost host = null;

                if (cfg != null)
                {
                    host = cfg.CurrentHost;
                }

                if (host.DemoMode)
                {
                    userName = "webdemouser";
                    impersonationLevel = "Identify";
                }
                else
                {
                    System.Security.Principal.WindowsIdentity identity = null;
                    identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                    userName = identity.Name;
                    impersonationLevel = identity.ImpersonationLevel.ToString();
                }

                HtmlGenericControl div = null;
                StringBuilder sb = null;
                bool slowConn = cfg.CmsSettings.SlowConnection;

                if (this.pnlError.Controls.Count == 0)
                {
                    // header
                    div = new HtmlGenericControl("div");
                    div.Attributes.Add("class", "VwdCmsAdmin_ErrorHeader");
                    div.InnerHtml = "VWD-CMS ERROR REPORT:";
                    this.pnlError.Controls.Add(div);

                    // information
                    div = new HtmlGenericControl("div");
                    div.Attributes.Add("class", "VwdCmsAdmin_Information");
                    if (slowConn)
                    {
                        div.Style.Remove("background-image");
                    }
                    else
                    {
                        div.Style.Add("background-image", "url(" + _imageUrl + "information.gif)");
                    }
                    sb = new StringBuilder();
                    sb.Append("<b>General Information:</b><br/>Errors are often caused by inadequate file system permissions. Verify that the ");
                    sb.Append("Executing Identity (User Account) has read and write permissions to the folder ");
                    sb.Append("and verify that the Imperonation Level is 'Impersonation'. You can modify the ");
                    sb.Append("imperonation settings for VWD-CMS in the /VwdCms/web.config file. (");
                    sb.Append("Executing Identity:");
                    sb.Append(userName);
                    sb.Append(", Impersonation Level: ");
                    sb.Append(impersonationLevel);
                    sb.Append(")");

                    // do not show local file paths
                    sb.Replace(lpApp, string.Empty);

                    div.InnerHtml = sb.ToString();
                    this.pnlError.Controls.Add(div);
                    // separator
                    this.pnlError.Controls.Add(new LiteralControl("<hr/>"));
                }

                // error details
                div = new HtmlGenericControl("div");
                div.Attributes.Add("class", "VwdCmsAdmin_Error");
                if (slowConn)
                {
                    div.Style.Remove("background-image");
                }
                else
                {
                    div.Style.Add("background-image", "url(" + _imageUrl + "error.gif)");
                }
                sb = new StringBuilder();
                sb.Append("<b>Error Details:</b><br/>");
                sb.Append(er.Message);
                sb.Replace("\r\n", "&nbsp;<br/>");
                sb.Replace("\r", "&nbsp;<br/>");
                sb.Replace("\n", "&nbsp;<br/>");

                // do not show local file paths
                sb.Replace(lpApp, string.Empty);
                
                div.InnerHtml = sb.ToString();
                this.pnlError.Controls.Add(div);

                // separator
                this.pnlError.Controls.Add(new LiteralControl("<hr/>"));

                this.pnlError.Visible = true;

                // check to see if an ExceptionNotification email should be sent
                try
                {
                    if (er.Message != VwdCms.Admin.Security.PermissionDeniedMsg)
                    {
                        if (host != null  host.DemoMode  !string.IsNullOrEmpty(host.DemoActivityNotify))
                        {
                            // send an email to the webmaster notifying of an exception

                            // build the body of the ExceptionNotificationEmail

                            // *********************************************
                            //  General Information
                            // *********************************************
                            sb = new StringBuilder();

                            sb.Append("<b>AbsoluteUri:</b> ");
                            sb.Append(this.Page.Request.Url.AbsoluteUri);
                            sb.Append("<br/>");

                            sb.Append("<b>Host:</b> ");
                            sb.Append(this.Page.Request.Url.Host);
                            sb.Append("<br/>");

                            sb.Append("<b>CmsHost.Domain:</b> " + host.Domain + "<br/>");
                            sb.Append("<b>CmsHost.CmsMode:</b> " + host.CmsMode + "<br/>");
                            sb.Append("<b>CmsHost.UseSSL:</b> " + Convert.ToString(host.UseSSL) + "<br/>");
                            sb.Append("<br/>");

                            string memberName = "anonymous";
                            bool membershipInstalled = !string.IsNullOrEmpty(host.ApplicationId);
                            if (membershipInstalled)
                            {
                                MembershipUser user = Membership.GetUser();
                                if (user != null)
                                {
                                    memberName = user.UserName;
                                }
                            }
                            sb.Append("<b>Member Name:</b> ");
                            sb.Append(memberName);
                            sb.Append("<br/>");

                            sb.Append("<b>User IP:</b> ");
                            sb.Append(this.Page.Request.UserHostAddress);
                            sb.Append("<br/>");


                            // *********************************************
                            //  VwdCms.Admin.Admin Page information
                            // *********************************************

                            sb.Append("<b>Admin.CurrentView:</b> " + this.CurrentView.ToString() + "<br/>");
                            sb.Append("<b>Admin.CurrentLanguage:</b> " + this.CurrentLanguage + "<br/>");
                            sb.Append("<b>Admin.CurrentVersion:</b> " + this.CurrentVersion + "<br/>");
                            sb.Append("<b>Admin.Filelist.CurrentFile:</b> " + this.ctlFilelist.CurrentFile + "<br/>");
                            sb.Append("<b>Admin.Filelist.CurrentFolder:</b> " + this.ctlFilelist.CurrentFolder + "<br/>");
                            sb.Append("<br/>");
                            if (this.ctlDocHelper != null)
                            {
                                sb.Append("<b>Admin.DocHelper.Mode:</b> " + this.ctlDocHelper.Mode + "<br/>");
                                sb.Append("<b>Admin.DocHelper.Visible:</b> " + Convert.ToString(this.ctlDocHelper.Visible) + "<br/>");
                                sb.Append("<b>Admin.DocHelper.CurrentFile:</b> " + this.ctlDocHelper.CurrentFile + "<br/>");
                                sb.Append("<b>Admin.DocHelper.CurrentFolder:</b> " + this.ctlDocHelper.CurrentFolder + "<br/>");
                                sb.Append("<b>Admin.DocHelper.CurrentLanguage:</b> " + this.ctlDocHelper.CurrentLanguage + "<br/>");
                                sb.Append("<b>Admin.DocHelper.CurrentVersion:</b> " + this.ctlDocHelper.CurrentVersion + "<br/>");
                            }
                            sb.Append("<br/>");
                            if (this.ctlPageEditor != null)
                            {
                                sb.Append("<b>Admin.PageEditor.Visible:</b> " + Convert.ToString(this.ctlPageEditor.Visible) + "<br/>");
                                sb.Append("<b>Admin.PageEditor.CurrentFile:</b> " + this.ctlPageEditor.CurrentFile + "<br/>");
                                sb.Append("<b>Admin.PageEditor.CurrentFolder:</b> " + this.ctlPageEditor.CurrentFolder + "<br/>");
                                sb.Append("<b>Admin.PageEditor.Language:</b> " + this.ctlPageEditor.Language + "<br/>");
                                sb.Append("<b>Admin.PageEditor.Version:</b> " + this.ctlPageEditor.Version + "<br/>");
                            }
                            sb.Append("<br/>");

                            FileExtension fext = this.CurrentFileExtensionObject;
                            string fileExtInfo = "<i>Object not set</i>";
                            if (fext != null)
                            {
                                fileExtInfo = fext.Name + " (" + fext.Extension + ")";
                            }
                            sb.Append("<b>Admin.CurrentFileExtensionObject:</b> " + fileExtInfo + "<br/><br/>");

                            sb.Append("<b>Admin.Page.IsPostBack:</b> " + Convert.ToString(this.Page.IsPostBack) + "<br/>");
                            sb.Append("<b>Admin.PostBackCount:</b> " + Convert.ToString(this.PostBackCount) + "<br/>");
                            sb.Append("<b>Admin.Page.IsCrossPagePostBack:</b> " + Convert.ToString(this.Page.IsCrossPagePostBack) + "<br/>");


                            // *********************************************
                            //  Request information
                            // *********************************************
                            sb.Append("<b>Admin.Page.Request.HttpMethod:</b> " + Convert.ToString(this.Page.Request.HttpMethod) + "<br/>");
                            
                            string formKey = null;
                            formKey = System.Web.UI.Page.postEventArgumentID; //"__EVENTARGUMENT"
                            sb.Append("<b>Admin.Page.Request.Form[" + formKey + "]:</b> " + Convert.ToString(this.Page.Request.Form[formKey]) + "<br/>");

                            formKey = System.Web.UI.Page.postEventSourceID; //"__EVENTTARGET"
                            sb.Append("<b>Admin.Page.Request.Form[" + formKey + "]:</b> " + Convert.ToString(this.Page.Request.Form[formKey]) + "<br/>");
                            

                            // *********************************************
                            //  Exception Report properties
                            // *********************************************
                            sb.Append("<b>ExceptionReport.Message:</b> ");
                            if (er.Message != null)
                            {
                                sb.Append("<span style=\"font-weight:bold;color:firebrick;\">" + er.Message + "</span>");
                            }
                            else
                            {
                                sb.Append("<i>No Message Provided</i>");
                            }
                            sb.Append("<br/>");

                            sb.Append("<b>ExceptionReport.Class:</b> ");
                            if (er.Class != null)
                            {
                                sb.Append(er.Class);
                            }
                            else
                            {
                                sb.Append("<i>No Class Information</i>");
                            }
                            sb.Append("<br/>");

                            sb.Append("<b>ExceptionReport.Method:</b> ");
                            if (er.Method != null)
                            {
                                sb.Append(er.Method);
                            }
                            else
                            {
                                sb.Append("<i>No Method Information</i>");
                            }
                            sb.Append("<br/>");

                            sb.Append("<b>ExceptionReport.Action:</b> ");
                            if (er.Action != null)
                            {
                                sb.Append(er.Action);
                            }
                            else
                            {
                                sb.Append("<i>No Action Information</i>");
                            }
                            sb.Append("<br/><br/>");

                            sb.Append("<b>ExceptionReport.Exception:</b><br/>");
                            if (er.Exception != null)
                            {
                                sb.Append(er.Exception.ToString());
                            }
                            else
                            {
                                sb.Append("<i>No Exception Information</i>");
                            }
                            sb.Append("<br/><br/>");

                            sb.Append("<b>ExceptionReport.StackTrace:</b><br/>");
                            if (er.StackTrace != null)
                            {
                                sb.Append(er.StackTrace.ToString());
                            }
                            else
                            {
                                sb.Append("<i>No StackTrace Information</i>");
                            }
                            sb.Append("<br/><br/>");

                            // ***********************************
                            //   User Submitted Content
                            // ***********************************
                            sb.Append("<b>*** User Submitted Content Information ***</b><br/>");
                            
                            sb.Append("<b>Admin.CurrentCode:</b><br/>");
                            if (this.CurrentCode != null)
                            {
                                sb.Append(HttpUtility.HtmlEncode(this.CurrentCode));
                            }
                            sb.Append("<br/><br/>");

                            sb.Append("<b>Admin.PageEditor.ContentText:</b><br/>");
                            if (this.CurrentCode != null)
                            {
                                sb.Append(HttpUtility.HtmlEncode(this.ctlPageEditor.ContentText));
                            }
                            sb.Append("<br/><br/>");


                            sb.Replace("\r\n", "<br/>");
                            sb.Replace("\r", "<br/>");
                            sb.Replace("\n", "<br/>");
                            sb.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");


                            VwdCms.Email.Email.SendExceptionNotificationEmail(sb.ToString(), "ExceptionNotification.email", host.ExceptionNotify);
                        }
                    }
                }
                catch (Exception ex1)
                {
                    System.Diagnostics.Debug.Write(ex1.ToString());
                }
            }
        }

        private string CurrentCode
        {
            get
            {
                string code = this.txtCode.Text;

                CmsConfig cfg = CmsConfig.Current;
                CmsHost host = null;
                bool demo = false;
                if ( cfg != null )
                {
                    host = cfg.CurrentHost;
                    if (host != null)
                    {
                        demo = host.DemoMode;
                    }
                }

                string extension = this.ctlFilelist.CurrentFileExtension;
                if (demo  (extension == VwdCms.Constants.LivePageExtension || extension == VwdCms.Constants.DraftPageExtension))
                {
                    // need to make sure that the Page Directive has not been altered
                    string pageDirective = null;

                    if (cfg.SiteSettings.ContainsKey("DemoPageDirective"))
                    {
                        pageDirective = cfg.SiteSettings["DemoPageDirective"].Value;
                    }

                    if (string.IsNullOrEmpty(pageDirective))
                    {
                        pageDirective = "<%@Page MasterPageFile=\"~/VwdCms/Master/SiteMaster3.master\" CompilationMode=\"Never\" %>";
                    }

                    System.Web.RegularExpressions.DirectiveRegex dre = null;
                    dre = new System.Web.RegularExpressions.DirectiveRegex();

                    System.Text.RegularExpressions.Match match = dre.Match(code);

                    if (match.Success)
                    {
                        code = dre.Replace(code, pageDirective);
                    }
                    else
                    {
                        code = pageDirective + "\r\n" + code;
                    }
                }
                    
                return code;
            }
        }

        private void SetCodeText(string text)
        {
            if (this.txtCode.Visible)
            {
                this.txtCode.Text = text;
            }
        }

        private bool ForcePreview
        {
            get { return _forcePreview; }
            set { _forcePreview = value; }
        }

        private string CurrentPreview
        {
            get
            {
                return this.ifrmPreview.Attributes["src"];
            }
            set
            {
                if (value == null || value == string.Empty)
                {
                    this.ifrmPreview.Attributes.Add("src", string.Empty);
                }
                else
                {
                    string language = this.CurrentLanguage;
                    string version = VwdCms.Constants.LiveVersion;
                    if (this.tbrTop.VersionList != null)
                    {
                        version = this.tbrTop.VersionList.SelectedValue;
                    }
                    if (version == null || version == string.Empty)
                    {
                        version = VwdCms.Constants.LiveVersion;
                    }
                    string url = value;
                    bool demo = CmsConfig.Current.CurrentHost.DemoMode;

                    if (this.tbrTop.SortedLanguageList != null  this.tbrTop.SortedLanguageList.Count  1)
                    {
                        url += "?" + VwdCms.Configuration.Language.LanguageQueryArg + "=" + language;
                    }

                    this.ifrmPreview.Attributes.Add("src", url);
                }
            }
        }

        private void lnkFolder_Command(object sender, CommandEventArgs e)
        {
            string vpFolder = Convert.ToString(e.CommandArgument);
            this.ChangeFolder(sender, vpFolder);
        }

        private void lnkEdit_Command(object sender, CommandEventArgs e)
        {
            string vpFile = Convert.ToString(e.CommandArgument);

            if (vpFile != null  vpFile != string.Empty)
            {
                string extension = VwdCms.Configuration.Utilities.GetExtension(vpFile);
                string vpFolder = VwdCms.Configuration.Utilities.GetFolder(vpFile);
                string lpFolder = VwdCms.Configuration.Utilities.GetLocalPath(vpFolder);
                string filename = vpFile.Replace(vpFolder, string.Empty);

                this.ctlFilelist.CurrentFolder = vpFolder;
                this.ctlFilelist.CurrentFile = vpFile;
            }

            this.CurrentView = Views.None;
        }

        private void lnkRename_Command(object sender, CommandEventArgs e)
        {
            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "rename";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.CurrentFile = Convert.ToString(e.CommandArgument);
            this.CurrentView = Views.DocHelper;
        }

        private void lnkPreview_Command(object sender, CommandEventArgs e)
        {
            string url = Convert.ToString(e.CommandArgument);
        }

        private FileExtension GetFileExtensionObject(string extension)
        {
            return (FileExtension)htExtensions[extension.ToLower()];
        }

        void ctlDocHelper_VersionChanged(object sender, CommandEventArgs e)
        {
            string version = Convert.ToString(e.CommandArgument);

            if (this.tbrTop.VersionList != null)
            {
                ListItem itm = this.tbrTop.VersionList.Items.FindByValue(version);
                if (itm != null)
                {
                    this.tbrTop.VersionList.SelectedIndex = this.tbrTop.VersionList.Items.IndexOf(itm);
                }
            }

        }

        private string SetVersion()
        {
            FileExtension fe = this.CurrentFileExtensionObject;
            string version = VwdCms.Constants.LiveVersion;
            if (fe != null  fe.Versions)
            {
                if (this.tbrTop.VersionList != null)
                {
                    version = this.tbrTop.VersionList.SelectedValue;
                    if (version == null || version == string.Empty)
                    {
                        version = VwdCms.Constants.LiveVersion;
                    }
                    
                    ListItem itm = this.tbrTop.VersionList.Items.FindByValue(version);
                    this.tbrTop.VersionList.SelectedIndex = this.tbrTop.VersionList.Items.IndexOf(itm);
                }
            }

            if (version == VwdCms.Constants.DraftVersion)
            {
                CreateDraftFiles();
            }

            return version;
        }

        private void CreateDraftFiles()
        {
            try
            {
                // create the draft files for the current file if they are missing

                // don't know if we are editing the aspx or the aspx.cs file,
                // but it should not matter, just create all of the files

                string vpCurrFile = this.ctlFilelist.CurrentFile;
                string currExt = VwdCms.Configuration.Utilities.GetExtensionComplete(vpCurrFile);
                string vpPageName = vpCurrFile.Substring(0, vpCurrFile.Length - currExt.Length);
                string lpPageName = this.Page.Server.MapPath(vpPageName);

                // this page will have an aspx file and maybe an aspx.cs file
                // and it will have a .language.pagecontent file

                StringBuilder sbCode = null;
                StringBuilder sbPage = null;

                // first check to see if the draft.aspx file exists
                System.Web.RegularExpressions.DirectiveRegex dre = null;
                dre = new System.Web.RegularExpressions.DirectiveRegex();
                string attribute = null;
                string lpLivePage = lpPageName + VwdCms.Constants.LivePageExtension;
                string lpDraftPage = lpPageName + VwdCms.Constants.DraftPageExtension;
                int i = 0;
                int adjust = 0;
                string codeFileAttLive = null;
                string inheritsAttLive = null;
                string codeFileAttDraft = null;
                string inheritsAttDraft = null;
                Match match = null;
                CaptureCollection ccNames = null;
                CaptureCollection ccValues = null;

                if (File.Exists(lpLivePage)  !File.Exists(lpDraftPage))
                {
                    // need to create it
                    sbPage = new StringBuilder(ReadFile(lpLivePage));

                    // edit the CodeFile and Inherits for the Draft version
                    match = dre.Match(sbPage.ToString());
                    if (match.Success)
                    {
                        ccNames = match.Groups["attrname"].Captures;
                        ccValues = match.Groups["attrval"].Captures;

                        for (i = 0; i  ccNames.Count; i++)
                        {
                            attribute = ccNames[i].Value;
                            if (attribute.ToLower() == "codefile")
                            {
                                codeFileAttLive = ccValues[i].Value;
                                codeFileAttDraft = codeFileAttLive.Substring(0, codeFileAttLive.Length - VwdCms.Constants.LiveCodeExtension.Length);
                                codeFileAttDraft = codeFileAttDraft + VwdCms.Constants.DraftCodeExtension;
                                sbPage.Remove(ccValues[i].Index + adjust, ccValues[i].Length);
                                sbPage.Insert(ccValues[i].Index + adjust, codeFileAttDraft);
                                adjust += codeFileAttDraft.Length - codeFileAttLive.Length;
                            }
                            else if (attribute.ToLower() == "inherits")
                            {
                                inheritsAttLive = ccValues[i].Value;
                                inheritsAttDraft = inheritsAttLive + VwdCms.Constants.DraftClassNameSuffix;
                                sbPage.Remove(ccValues[i].Index + adjust, ccValues[i].Length);
                                sbPage.Insert(ccValues[i].Index + adjust, inheritsAttDraft);
                                adjust += inheritsAttDraft.Length - inheritsAttLive.Length;
                            }
                        }
                    }

                }

                // do the aspx.cs file (need to rename the class to have _Draft suffix)
                // uses 'inheritsAttLive' from the page section
                string lpLiveCode = lpPageName + VwdCms.Constants.LiveCodeExtension;
                string lpDraftCode = lpPageName + VwdCms.Constants.DraftCodeExtension;
                if (inheritsAttLive != null)
                {
                    if (File.Exists(lpLiveCode)  !File.Exists(lpDraftCode))
                    {
                        sbCode = new StringBuilder(ReadFile(lpLiveCode));

                        string classQuery = "public\\s*partial\\s*class\\s*" + inheritsAttLive + "\\s*:";
                        string newClassDef = "public partial class " + inheritsAttLive + VwdCms.Constants.DraftClassNameSuffix + " :";
                        Regex re = new Regex(classQuery);
                        sbCode = new StringBuilder(re.Replace(sbCode.ToString(), newClassDef));

                    }
                }

                // write the code file first because the page file references it
                if (sbCode != null)
                {
                    WriteFile(lpDraftCode, sbCode.ToString());
                }
                if (sbPage != null)
                {
                    WriteFile(lpDraftPage, sbPage.ToString());
                }

                // copy the .pagecontent file for this language
                string lpContentLive = VwdCms.Configuration.Utilities.GetPageContentFile(vpCurrFile, this.CurrentLanguage, VwdCms.Constants.LiveVersion, true);
                string lpContentDraft = VwdCms.Configuration.Utilities.GetPageContentFile(vpCurrFile, this.CurrentLanguage, VwdCms.Constants.DraftVersion, true);
                if (File.Exists(lpContentLive)  !File.Exists(lpContentDraft))
                {
                    File.Copy(lpContentLive, lpContentDraft);
                }
            }
            catch (Exception ex)
            {
                string msg = "Failed while creating the draft files.\r\n\r\n";
                this.ErrorMessage = new ExceptionReport(msg, ex);
            }

        }

        private UserViews UserView
        {
            get
            {
                object uv = this.ViewState["UserView"];
                return (uv == null) ? UserViews.None : (UserViews)uv;
            }
            set { this.ViewState["UserView"] = value; }
        }

        private FileExtension CurrentFileExtensionObject
        {
            get
            {
                string vpCurrentFile = this.ctlFilelist.CurrentFile;
                // get the FileExtension object: try using CompleteExtension first, then Extension
                string extension = VwdCms.Configuration.Utilities.GetExtensionComplete(vpCurrentFile);
                FileExtension fe = GetFileExtensionObject(extension);
                if (fe == null)
                {
                    extension = this.ctlFilelist.CurrentFileExtension;
                    fe = GetFileExtensionObject(extension);
                }
                return fe;
            }
        }

        private Views CurrentView
        {
            get 
            { 
                Views currentView = Views.None;
                object vs = this.ViewState["CurrentView"]; 
                if (vs != null )
                {
                    currentView = (Views)vs;
                }
                return currentView;
            }
            set 
            { 
                this.ViewState["CurrentView"] = value; 
            
            }
        }

        private Views GetView(FileExtension fe, UserViews userView)
        {
            Views view = Views.None;

            if (fe != null)
            {
                if (userView != UserViews.None)
                {
                    // translate the requested 'UserView' into a 'View'
                    // for the current FileExtension
                    if (fe.Editor  userView == UserViews.Editor)
                    {
                        if (fe.FileFormat == FileFormats.XML)
                        {
                            view = Views.XmlEditor;
                        }
                        else if (fe.FileFormat == FileFormats.Image)
                        {
                            view = Views.ImageZoom;
                        }
                        else
                        {
                            view = Views.PageEditor;
                        }
                    }
                    else if (fe.Code  userView == UserViews.Code)
                    {
                        view = Views.CodeEditor;
                    }
                    else if (fe.Preview  userView == UserViews.Preview)
                    {
                        view = Views.Preview;
                    }
                }

                // if the requested view was not supported, try getting the default view
                if (view == Views.None  !string.IsNullOrEmpty(fe.DefaultView))
                {
                    Type enumType = typeof(Views);
                    view = (Views)System.Enum.Parse(enumType, fe.DefaultView);
                }

                // make sure that only managed aspx pages use the PageEditor
                bool isManaged = VwdCms.Configuration.Utilities.IsManagedPage(this.ctlFilelist.CurrentFile);
                if (view == Views.PageEditor  !isManaged)
                {
                    view = Views.CodeEditor;
                }
            }

            // update the current view property
            this.CurrentView = view;

            // update the view list to reflect the view
            if (this.tbrTop.ViewList != null)
            {
                this.tbrTop.ViewList.ClearSelection();
                UserViews uv = UserViews.None;
                switch (view)
                {
                    case Views.None:
                    case Views.ConfigEditor:
                    case Views.ServerSettings:
                        uv = UserViews.None;
                        //this.ctlFilelist.CurrentFile = string.Empty;
                        break;
                    case Views.DocHelper:
                        uv = UserViews.None;
                        break;
                    case Views.CodeEditor:
                        uv = UserViews.Code;
                        break;
                    case Views.XmlEditor:
                    case Views.ImageZoom:
                    case Views.PageEditor:
                        uv = UserViews.Editor;
                        break;
                    case Views.Preview:
                        uv = UserViews.Preview;
                        break;
                }
                if (uv != UserViews.None)
                {
                    ListItem itm = this.tbrTop.ViewList.Items.FindByValue(Convert.ToInt32(uv).ToString());
                    if (itm != null)
                    {
                        this.tbrTop.ViewList.SelectedIndex = this.tbrTop.ViewList.Items.IndexOf(itm);
                    }
                }
            }

            return view;
        }


        private void RenderCurrentView()
        {
            try
            {
                // // clear out any content in the controls
                if (this.ctlPageEditor.Visible)
                {
                    this.ctlPageEditor.ClearPageContent();
                }
                this.SetCodeText(string.Empty);
                if (this.xmlEdit.Visible)
                {
                    this.xmlEdit.Clear();
                }

                // hide all edit controls
                this.tbcEditor.Visible = false;
                this.txtCode.Visible = false;
                this.ifrmPreview.Visible = false;
                this.ctlPageEditor.Visible = false;
                this.xmlEdit.Visible = false;
                this.lblVersion.Visible = true;
                this.izImageZoom.Visible = false;
                this.ctlDocHelper.Visible = false;
                this.ctlServerSettings.Visible = false;
                this.ctlConfigEditor.Visible = false;

                // disable specialized toolbar buttons
                this.tbrTop.SetItemEnabled("save", false);
                this.tbrTop.SetItemEnabled("publish", false);
                this.tbrTop.SetItemEnabled("copy", false);

                // disable the view, language, and version selection controls
                if (this.tbrTop.ViewList != null) { this.tbrTop.ViewList.Enabled = false; }
                if (this.tbrTop.VersionList != null) { this.tbrTop.VersionList.Enabled = false; }
                if (this.tbrTop.LanguageList != null) { this.tbrTop.LanguageList.Enabled = false; }

                CmsConfig cmscfg = CmsConfig.Current;
                CmsSettings settings = cmscfg.CmsSettings;
                CmsHost host = cmscfg.CurrentHost;
                string vpCurrentPreview = null;
                string vpCurrentFile = this.ctlFilelist.CurrentFile;
                string vpCurrentFolder = this.ctlFilelist.CurrentFolder;
                string vpVersionFile = vpCurrentFile;
                FileExtension fe = this.CurrentFileExtensionObject;
                string language = this.CurrentLanguage;
                string version = this.CurrentVersion;
                bool isManaged = false;

                Views view = this.CurrentView;

                if (this.ForcePreview)
                {
                    this.ForcePreview = false;
                    view = Views.Preview;
                }
                else
                {
                    // clear out the preview
                    this.CurrentPreview = string.Empty;

                    // show and load the appropriate controls for the view
                    if (view == Views.ConfigEditor)
                    {
                        this.ctlConfigEditor.Visible = true;
                        this.pnlInfoBar.Visible = false;
                    }
                    else if (view == Views.DocHelper)
                    {
                        this.ctlDocHelper.Visible = true;
                    }
                    else if (view == Views.ServerSettings)
                    {
                        this.ctlServerSettings.Visible = true;
                        this.ctlServerSettings.LoadSettings();
                        this.pnlInfoBar.Visible = false;
                    }
                    else
                    {
                        // get the current language selection
                        this.SavedLanguage = language;

                        // is the current file a managed aspx page?
                        isManaged = VwdCms.Configuration.Utilities.IsManagedPage(this.ctlFilelist.CurrentFile);

                        // get the current version selection
                        this.SavedVersion = version;

                        // determine the current view based on the user's selection 
                        // and the current FileExtension object
                        view = this.GetView(fe, this.UserView);

                        // enable or disable the view and version selection controls
                        if (view != Views.None  !string.IsNullOrEmpty(vpCurrentFile))
                        {
                            if (this.tbrTop.ViewList != null) { this.tbrTop.ViewList.Enabled = true; }
                            if (this.tbrTop.VersionList != null) { this.tbrTop.VersionList.Enabled = true; }
                            if (view == Views.PageEditor)
                            {
                                if (this.tbrTop.LanguageList != null) { this.tbrTop.LanguageList.Enabled = false; }
                            }
                        }

                        // VERSION: enable or disable the items in the Version List and the Language List
                        if (this.tbrTop.VersionList != null  this.tbrTop.VersionList.Enabled)
                        {
                            if (fe != null  fe.Versions  isManaged)
                            {
                                this.tbrTop.VersionList.Items[0].Enabled = true;
                                this.tbrTop.VersionList.Items[1].Enabled = true;
                                if (this.tbrTop.LanguageList != null) { this.tbrTop.LanguageList.Enabled = true; }
                            }
                            else
                            {
                                this.tbrTop.VersionList.Items[0].Enabled = false;
                                this.tbrTop.VersionList.Items[1].Enabled = false;
                                if (this.tbrTop.LanguageList != null) { this.tbrTop.LanguageList.Enabled = false; }
                            }
                        }


                        // VIEW: enable / disable the radio buttons
                        if (this.tbrTop.ViewList != null  this.tbrTop.ViewList.Enabled)
                        {
                            this.tbrTop.ViewList.Items[0].Enabled = (fe.Editor  isManaged);
                            this.tbrTop.ViewList.Items[1].Enabled = fe.Code;
                            this.tbrTop.ViewList.Items[2].Enabled = fe.Preview;
                        }

                        // now configure the page and controls
                        this.pnlInfoBar.Visible = !string.IsNullOrEmpty(vpCurrentFile);
                        this.lblCurrentFile.Text = vpCurrentFile;

                        // display the version to the user
                        if (version == VwdCms.Constants.DraftVersion)
                        {
                            this.lblVersion.Text = VwdCms.Constants.DraftVersion.ToUpper();
                            this.lblVersion.Style.Add("color", "#006699");
                        }
                        else
                        {
                            this.lblVersion.Text = VwdCms.Constants.LiveVersion.ToUpper();
                            this.lblVersion.Style.Add("color", "firebrick");
                        }

                        // determine the correct file if this fileextension supports versions
                        if (fe != null  fe.Versions)
                        {
                            vpVersionFile = GetVersionSpecificFile(vpCurrentFile, view, version);
                        }

                        // check to see if in Demo mode or if help should be displayed
                        if (view == Views.None)
                        {
                            if (host.DemoMode || settings.ShowHelpAtStartup)
                            {
                                view = Views.Preview;
                                vpCurrentPreview = VwdCms.Configuration.Utilities.HelpFolder + "UserGuide.aspx";
                            }
                        }
                    }
                }
                // render the controls for the current view
                if (view == Views.None)
                {
                    // don't render any controls
                }
                else if (view == Views.ImageZoom)
                {
                    this.tbcEditor.Visible = true;
                    this.izImageZoom.Visible = true;
                    this.izImageZoom.ImageUrl = vpCurrentFile;
                }
                else if (view == Views.Preview)
                {
                    vpCurrentPreview = string.IsNullOrEmpty(vpCurrentPreview) ? vpVersionFile : vpCurrentPreview;
                    if (!string.IsNullOrEmpty(vpCurrentPreview))
                    {
                        this.ifrmPreview.Visible = true;
                        if (string.IsNullOrEmpty(vpCurrentPreview))
                        {
                            if (host.DemoMode || settings.ShowHelpAtStartup)
                            {
                                vpCurrentPreview = VwdCms.Configuration.Utilities.HelpFolder + "UserGuide.aspx";
                            }
                        }
                        this.CurrentPreview = vpCurrentPreview;
                    }
                }
                else if (view == Views.CodeEditor)
                {
                    this.tbcEditor.Visible = true;
                    this.txtCode.Visible = true;
                    this.lblVersion.Visible = isManaged;

                    if (!string.IsNullOrEmpty(vpVersionFile))
                    {
                        this.tbrTop.SetItemEnabled("save", true);
                        this.tbrTop.SetItemEnabled("copy", true);

                        string lpCodeFile = VwdCms.Configuration.Utilities.GetLocalPath(vpVersionFile);

                        if (fe.FileFormat == FileFormats.XML)
                        {
                            this.SetCodeText(GetXmlNodeText(lpCodeFile, "content"));
                        }
                        else
                        {
                            this.SetCodeText(ReadFile(lpCodeFile));
                        }
                        txtCode.SetTextType(((fe == null) ? null : fe.Extension));
                    }
                }
                else if (view == Views.PageEditor)
                {
                    // don't use vpVersionFile here because the PageEditor handles 
                    // getting the correct file based on the version

                    this.tbcEditor.Visible = true;
                    this.ctlPageEditor.Visible = true;
                    this.lblVersion.Visible = true;

                    this.ctlPageEditor.Language = this.CurrentLanguage;
                    this.ctlPageEditor.Version = this.CurrentVersion;
                    this.ctlPageEditor.CurrentFile = vpCurrentFile;
                    this.ctlPageEditor.GetPageContent();

                    this.tbrTop.SetItemEnabled("save", true);
                    this.tbrTop.SetItemEnabled("publish", (version == VwdCms.Constants.DraftVersion));
                    this.tbrTop.SetItemEnabled("copy", true);

                }
                else if (view == Views.XmlEditor)
                {
                    this.tbcEditor.Visible = true;
                    this.xmlEdit.Visible = true;

                    this.xmlEdit.CurrentFile = vpCurrentFile;

                    this.tbrTop.SetItemEnabled("save", true);
                    this.tbrTop.SetItemEnabled("copy", true);
                }
            }
            catch (Exception ex)
            {
                string msg = "Exception in SetViewMode:\r\n\r\n" + ex.ToString();
                this.ErrorMessage = new ExceptionReport(msg, ex);
            }
            ApplyCmsSettings(null);
        }

        private string GetVersionSpecificFile(string pathfile)
        {
            return GetVersionSpecificFile(pathfile, this.CurrentView, this.CurrentVersion);
        }

        private string GetVersionSpecificFile(string pathfile, Views view, string version)
        {
            // switch the filename if in draft version mode
            if (version == VwdCms.Constants.DraftVersion)
            {
                string extension = VwdCms.Configuration.Utilities.GetExtensionComplete(pathfile);
                pathfile = VwdCms.Configuration.Utilities.RemoveExtensionComplete(pathfile);
                if (view == Views.CodeEditor)
                {
                    if (extension == VwdCms.Constants.LiveCodeExtension)
                    {
                        pathfile += VwdCms.Constants.DraftCodeExtension;
                    }
                    else
                    {
                        pathfile += VwdCms.Constants.DraftPageExtension;
                    }
                }
                else
                {
                    pathfile += VwdCms.Constants.DraftPageExtension;
                }
            }
            return pathfile;
        }

        private void lnkDelete_Command(object sender, CommandEventArgs e)
        {
            // configure and display the NewDocument control
            this.ctlDocHelper.Mode = "delete";
            this.ctlDocHelper.CurrentFolder = this.ctlFilelist.CurrentFolder;
            this.ctlDocHelper.CurrentFile = Convert.ToString(e.CommandArgument);
            this.CurrentView = Views.DocHelper;
        }

        private string ReadFile(string localpathfile)
        {
            string text = null;
            try
            {
                text = VwdCms.IO.ReadFile(localpathfile);
            }
            catch (Exception ex)
            {
                this.ErrorMessage = new ExceptionReport(ex.Message, ex);
            }
            return text;
        }

        private bool WriteFile(string localpathfile, string text)
        {
            bool success = false;
            try
            {
                success = VwdCms.Admin.IO.WriteFile(localpathfile, text);
            }
            catch (Exception ex)
            {
                string msg = "Failed while trying to write to the file '{0}'.\r\n\r\n";
                msg = string.Format(msg, localpathfile);
                this.ErrorMessage = new ExceptionReport(msg, ex);
            }
            return success;
        }

        private bool SaveToXmlFile(string localpathfile, string nodeName, string text)
        {
            bool success = false;
            try
            {
                success = VwdCms.Admin.IO.SaveToXmlFile(localpathfile, nodeName, text);
            }
            catch (Exception ex)
            {
                this.ErrorMessage = new ExceptionReport(ex.Message, ex);
            }
            return success;
        }

        private string GetXmlNodeText(string localpathfile, string nodeName)
        {
            string text = null;
            try
            {
                text = VwdCms.IO.GetXmlNodeText(localpathfile, nodeName);
            }
            catch (Exception ex)
            {
                this.ErrorMessage = new ExceptionReport(ex.Message, ex);
            }
            return text;
        }

        private void SendDemoActivityReport(string activity)
        {
            try
            {
                if (!string.IsNullOrEmpty(activity))
                {
                    string to = CmsConfig.Current.CurrentHost.DemoActivityNotify;
                    VwdCms.Email.Email.SendDemoActivityNotificationEmail(activity, "DemoActivityNotification.email", to);
                }
            }
            catch { }
        }

        private bool CheckPermissions()
        {
            bool granted = false;
            try
            {
                if (VwdCms.Admin.Security.WritePermission(this.ctlFilelist.CurrentLocalFile))
                {
                    granted = true;
                }
                else
                {
                    this.ErrorMessage = new ExceptionReport(VwdCms.Admin.Security.PermissionDeniedMsg);
                }
            }
            catch (Exception ex)
            {
                this.ErrorMessage = new ExceptionReport(ex);
            }
            return granted;
        }
    }
}