/// <summary>
    /// Gets and bulk updates eventss. Called when the "Get and bulk update events" button is pressed.
    /// Expects the LogEvent method to be run first.
    /// </summary>
    private bool GetAndBulkUpdateEvents()
    {
        // Create new instance of event log provider
        EventLogProvider eventLog = new EventLogProvider();

        // Get events matching the where condition
        string where = "EventCode = 'APIEXAMPLE'";
        DataSet events = eventLog.GetAllEvents(where, null);

        if (!DataHelper.DataSourceIsEmpty(events))
        {
            // Loop through the individual items
            foreach (DataRow eventDr in events.Tables[0].Rows)
            {
                // Create the object from DataRow
                EventLogInfo updateEvent = new EventLogInfo(eventDr);

                // Update the properties
                updateEvent.EventDescription = updateEvent.EventDescription.ToUpper();

                // Save the changes
                eventLog.SetEventLogInfo(updateEvent);
            }

            return true;
        }

        return false;
    }
Exemple #2
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="ti">Task info</param>
        public string Execute(TaskInfo ti)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyTask", "Execute", null, "This task was executed from '~/App_Code/Global/CMS/CMSCustom.cs'.");

            return null;
        }
    protected void btnClone_Click(object sender, EventArgs e)
    {
        try
        {
            CloneResult result = cloneObjectElem.CloneObject();
            if (result != null)
            {
                if (result.Errors.Count > 0)
                {
                    ShowError(ResHelper.LocalizeString(string.Join("\n", result.Errors.ToArray())));
                    SwitchToErrorMode();
                }
                else if (result.Warnings.Count > 0)
                {
                    ShowWarning(GetString("cloning.savedwithwarnings"), ResHelper.LocalizeString(string.Join("<br/>", result.Warnings.ToArray())), null);
                    SwitchToErrorMode();
                }
                else
                {
                    ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "CloneRefresh", cloneObjectElem.CloseScript, true);
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider provider = new EventLogProvider();
            provider.LogEvent(string.IsNullOrEmpty(objectType) ? "System" : objectType.ToLowerCSafe(), "CLONEOBJECT", ex);
            ShowError(ex.Message);

            if (!cloneObjectElem.UseTransaction)
            {
                SwitchToErrorMode();
            }
        }
    }
    /// <summary>
    /// Sets the specified site data.
    /// </summary>
    /// <param name="siteInfoObj">New site info data</param>
    protected override void SetSiteInfoInternal(SiteInfo siteInfoObj)
    {
        base.SetSiteInfoInternal(siteInfoObj);

        // Log the event that the site was updated
        EventLogProvider ev = new EventLogProvider();
        ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyCustomSiteInfoProvider", "SetSiteInfo", null, "The site was updated");
    }
    /// <summary>
    /// Removes the item from the cache.
    /// </summary>
    /// <param name="key">Cache key</param>
    protected override object RemoveInternal(string key)
    {
        // Log the event that the user was updated
        EventLogProvider ev = new EventLogProvider();
        ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyCustomCacheHelper", "Remove", null, "The cache item was removed");

        return base.RemoveInternal(key);
    }
    /// <summary>
    /// Clears event log for current site. Called when the "Clear event log" button is pressed.
    /// Expects the CreateAbuseReport method to be run first.
    /// </summary>
    private bool ClearLog()
    {
        // Create new instance of event log provider
        EventLogProvider eventLog = new EventLogProvider();

        // Clear event log for current site
        eventLog.ClearEventLog(CMSContext.CurrentUser.UserID, CMSContext.CurrentUser.UserName, HTTPHelper.UserHostAddress, CMSContext.CurrentSiteID);

        return true;
    }
    /// <summary>
    /// OkClick Handler.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        string culture = ValidationHelper.GetString(cultureSelector.Value, "");

        if ((culture != "") && ((currentCulture.ToLower() != culture.ToLower()) || chkDocuments.Checked))
        {
            // Set new culture
            SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId);
            if (si != null)
            {
                try
                {
                    // Set default culture and change current culture label
                    ObjectHelper.SetSettingsKeyValue(si.SiteName + ".CMSDefaultCultureCode", culture.Trim());

                    // Change culture of documents
                    if (chkDocuments.Checked)
                    {
                        // Change culture of the documents
                        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                        tree.ChangeCulture(si.SiteName, currentCulture, culture);
                    }

                    if (!LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Multilingual))
                    {
                        // If not multilingual, remove all cultures from the site and assign new culture
                        CultureInfoProvider.RemoveSiteCultures(si.SiteName);
                        CultureInfoProvider.AddCultureToSite(culture, si.SiteName);
                    }

                    ltlScript.Text = ScriptHelper.GetScript("wopener.ChangeCulture('" + chkDocuments.Checked.ToString() + "'); window.close();");
                }
                catch (Exception ex)
                {
                    EventLogProvider ev = new EventLogProvider();
                    ev.LogEvent("SiteManager", "ChangeDefaultCulture", ex);
                }
            }
        }
        else
        {
            ltlScript.Text = ScriptHelper.GetScript("window.close();");
        }
    }
    /// <summary>
    /// Logs error.
    /// </summary>
    /// <param name="message">Error message</param>
    /// <param name="eventCode">Event code</param>
    protected void LogEvent(string message, string eventCode)
    {
        try
        {
            // Add some additional information to the error message
            string info = "ORDER ID: " + orderId + "\r\n";
            info += "TRANSACTION ID: " + transactionId + "\r\n";
            info += "PAYMENT STATUS: " + paymentStatus + "\r\n";

            message = info + message;

            EventLogProvider evenLog = new EventLogProvider();
            evenLog.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "PayPal IPN", eventCode, 0, "", 0, "", "", message, 0, "");
        }
        catch
        {
            // Unable to log the event
        }
    }
    /// <summary>
    /// Generates sample data.
    /// </summary>
    private void GenerateData()
    {
        try
        {
            QueryDataParameters parameters = new QueryDataParameters();
            parameters.Add("siteId", CMSContext.CurrentSiteID);

            ConnectionHelper.ExecuteQuery("ecommerce.order.generateSampleData", parameters);

            // Log successful attempt
            EventLogProvider eventLog = new EventLogProvider();
            eventLog.LogEvent("I", DateTime.Now, "E-commerce data generator", "DATAGENERATED", CMSContext.CurrentSiteID);
            ShowConfirmation(GetString("com.reports.datagenerated"));
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Reports", "Generate", ex);
            ShowError(GetString("com.reports.operationFailed"));
        }
    }
    protected void btnHiddenImpersonate_Click(object sender, EventArgs e)
    {
        string originalUserName = ValidationHelper.GetString(SessionHelper.GetValue("OriginalUserName"), "");
        if (RequestHelper.IsFormsAuthentication())
        {
            UserInfo ui = UserInfoProvider.GetUserInfo(originalUserName);
            CMSContext.CurrentUser.UserImpersonate(ui);
        }
        else
        {
            SessionHelper.SetValue("ImpersonateUserName", null);
            SessionHelper.SetValue("OriginalUserName", null);

            CMSContext.CurrentUser.Invalidate(false);

            // Log event
            EventLogProvider log = new EventLogProvider();
            log.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Administration", "Impersonate", 0, null, 0, null, null, "User " + originalUserName + " has returned to his account.", CMSContext.CurrentSiteID, URLHelper.CurrentURL);

            URLHelper.Redirect(URLHelper.CurrentURL);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string domain = QueryHelper.GetText("domainname", String.Empty);

        if (domain != String.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain);
            if (lki != null)
            {
                LabelMessage.Text = GetString("CMSSiteManager.FeatureNotAvailable");

                // Log message to event log
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_WARNING, DateTime.Now, "Feature not available page", "FeatureNotAvailable", URLHelper.CurrentURL, "The requested feature is not available in the CMS edition you are using: " + LicenseHelper.GetEditionName(lki.Edition));
            }
            else
            {
                LabelMessage.Text = GetString("CMSSiteManager.LicenseNotFound").Replace("%%name%%", domain);
            }
        }
        titleElem.TitleText = GetString("CMSSiteManager.AccesDenied");
        titleElem.TitleImage = GetImageUrl("Others/Messages/denied.png");
    }
Exemple #12
0
    private string BuildStartupScript()
    {
        bool       enBBCode = IsSupport || (ChatHelper.EnableBBCodeSetting && EnableBBCode);
        WebControl input    = enBBCode ? ucBBEditor.TextArea : txtMessage;

        if (enBBCode)
        {
            txtMessage.Visible = false;
        }
        else
        {
            ucBBEditor.Visible = false;
        }

        JavaScriptSerializer sr = new JavaScriptSerializer();
        string json             = sr.Serialize(
            new
        {
            roomID               = RoomID,
            inputClientID        = GetString(input),
            buttonClientID       = GetString(btnSendMessage),
            groupID              = GroupID,
            chbWhisperClientID   = GetString(chbWhisper),
            drpRecipientClientID = GetString(drpRecipient),
            noneLabel            = ResHelper.GetString("chat.everyone"),
            enableBBCode         = enBBCode,
            bbCodeClientID       = GetString(ucBBEditor),
            btnCannedResponses   = GetString(btnCannedResponses),
            pnlContent           = GetString(pnlWebpartContent),
            envelopeID           = "#envelope_" + ClientID,
            informDialogID       = GetString(pnlChatMessageSendInfoDialog),
            btnInformDialogClose = GetString(btnChatMessageSendInformDialogClose)
        }
            );
        string startupScript = String.Format("InitChatSenderWebpart({0});", json);

        // If this webpart is for support person -> generate "Canned responses"
        if ((ChatOnlineUserHelper.GetLoggedInChatUser() != null) && (IsSupport == true))
        {
            // Get canned responses from database
            IEnumerable <ChatSupportCannedResponseInfo> cannedResponses = ChatSupportCannedResponseInfoProvider.GetCannedResponses(ChatOnlineUserHelper.GetLoggedInChatUser().ChatUserID, CMSContext.CurrentSiteID);

            if (cannedResponses.Count() > 0)
            {
                btnCannedResponses.Visible = true;

                // Register necessary files
                ScriptHelper.RegisterScriptFile(Page, "~/CMSWebParts/Chat/ChatMessageSend_files/CannedResponses.js");
                CSSHelper.RegisterCSSLink(Page, "~/App_Themes/Design/Chat/ChatIntelliSense.css");

                // Creates canned responses in format expected in javascript
                var cannedResponseToSerialize = from cr in cannedResponses
                                                let resolvedText = CMSContext.ResolveMacros(cr.ChatSupportCannedResponseText)
                                                                   select new
                {
                    label   = "#" + cr.ChatSupportCannedResponseTagName,
                    tooltip = TextHelper.LimitLength(resolvedText, mTooltipLength),
                    value   = resolvedText
                };

                // Serialize canned responses to JS Array expected by javascript
                string cannedResponsesJSArray = "";
                try
                {
                    cannedResponsesJSArray = sr.Serialize(cannedResponseToSerialize);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("Chat", "JSON serialization of canned responses", ex);
                }
                startupScript += string.Format("var CannedResponses = {0};", cannedResponsesJSArray);

                startupScript += string.Format("InitCannedResponses({0}, {1});", ScriptHelper.GetString("#" + input.ClientID), ScriptHelper.GetString("#" + btnCannedResponses.ClientID));
            }
        }

        return(startupScript);
    }
    /// <summary>
    /// Saves the item
    /// </summary>
    /// <param name="saveAndClose">Close dialog after save</param>
    private void Save(bool saveAndClose)
    {
        //Check valid input
        string errMsg = new Validator().
                        NotEmpty(txtName.Text, GetString("img.errors.filename")).
                        IsFolderName(txtName.Text, GetString("img.errors.filename")).
                        Result;

        if (!String.IsNullOrEmpty(errMsg))
        {
            ShowError(errMsg);
            return;
        }

        // Prepare the path
        string path = filePath;

        if (!newFile)
        {
            path = Path.GetDirectoryName(path);
        }
        path += "\\" + txtName.Text + extension;

        // Check the file name for existence
        if (!txtName.Text.EqualsCSafe(fileName, true))
        {
            if (File.Exists(path))
            {
                errMsg = GetString("general.fileexists");
            }
        }

        if (!String.IsNullOrEmpty(errMsg))
        {
            ShowError(errMsg);
            return;
        }

        bool success         = true;
        bool fileNameChanged = false;

        try
        {
            // Move the file to the new location
            if (!newFile && !path.EqualsCSafe(filePath, true))
            {
                File.WriteAllText(filePath, txtContent.Text);
                File.Move(filePath, path);
                fileNameChanged = true;
            }
            // Create the file or write into it
            else
            {
                File.WriteAllText(path, txtContent.Text);
            }
        }
        catch (Exception ex)
        {
            success = false;
            ShowError(GetString("general.saveerror"), ex.Message, null);
            EventLogProvider.LogException("FileSystemSelector", "SAVEFILE", ex);
        }

        if (success)
        {
            ShowChangesSaved();

            // Redirect for new items
            if (newFile && !saveAndClose)
            {
                string    fileIdentifier = Guid.NewGuid().ToString("N") + path.GetHashCode();
                Hashtable pp             = new Hashtable();
                pp.Add("filepath", URLHelper.UnMapPath(path));
                pp.Add("newfileextension", String.Empty);
                WindowHelper.Add(fileIdentifier, pp);

                string parameters     = String.Format("?identifier={0}&saved=1", fileIdentifier);
                string validationHash = QueryHelper.GetHash(parameters);
                string url            = UrlResolver.ResolveUrl("~/CMSModules/Content/Controls/Dialogs/Selectors/FileSystemSelector/EditTextFile.aspx") + parameters + "&hash=" + validationHash;
                URLHelper.Redirect(url);
            }

            // Update file name path stored in session in case of changing file name
            if (fileNameChanged)
            {
                prop["filepath"] = URLHelper.UnMapPath(path);
                WindowHelper.Add(identifier, prop);
            }

            String script = "wopener.SetRefreshAction();";
            if (saveAndClose)
            {
                script += "CloseDialog()";
            }
            ScriptHelper.RegisterStartupScript(Page, typeof(String), "closescript", ScriptHelper.GetScript(script));

            RegisterRefreshScript();
        }
    }
Exemple #14
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData()
    {
        try
        {
            treeElem.Nodes.Clear();

            // Get root files
            string rootDir = RootFolderPath;
            if (rootDir != null)
            {
                rootDir = rootDir.TrimEnd('\\');
            }
            if (!String.IsNullOrEmpty(MediaLibraryPath))
            {
                rootDir = DirectoryHelper.CombinePath(rootDir, MediaLibraryPath);
            }
            else if (!String.IsNullOrEmpty(MediaLibraryFolder))
            {
                rootDir = DirectoryHelper.CombinePath(rootDir, MediaLibraryFolder);
            }

            // Get the file and directories count
            int dirCount = 0;

            string[] directories = null;
            if (rootDir != null)
            {
                if (!Directory.Exists(rootDir))
                {
                    DirectoryHelper.EnsureDiskPath(Path.EnsureEndBackslash(rootDir), Server.MapPath("~"));
                }
                directories = Directory.GetDirectories(rootDir);
            }

            if (directories != null)
            {
                // Each directory contains directory for thumbnails
                dirCount = directories.Length - 1;
            }

            // Create root tree node
            TreeNode root;
            if (DisplayFilesCount)
            {
                int fileCount = 0;

                string[] files = Directory.GetFiles(rootDir);
                if (files != null)
                {
                    fileCount = files.Length;
                }

                root = CreateNode("<span class=\"Name\">" + MediaLibraryFolder + " (" + fileCount + ")</span>", MediaLibraryFolder, null, dirCount, 0);
            }
            else
            {
                root = CreateNode("<span class=\"Name\">" + MediaLibraryFolder + "</span>", MediaLibraryFolder, null, dirCount, 0);
            }

            // Keep root expanded
            root.Expand();

            // Add root node
            treeElem.Nodes.Add(root);

            if (!StopProcessing)
            {
                // Bind tree nodes
                if (String.IsNullOrEmpty(MediaLibraryPath))
                {
                    BindTreeView(RootFolderPath + MediaLibraryFolder, root, true);
                }
                else
                {
                    BindTreeView(DirectoryHelper.CombinePath(RootFolderPath, MediaLibraryPath), root, true);
                }
            }

            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "RemoveMultipleNodes_" + ClientID, ScriptHelper.GetScript("if (typeof(ResolveDuplicateNodes) != 'undefined') { ResolveDuplicateNodes('" + treeElem.ClientID + "') }"));
        }
        catch (Exception ex)
        {
            // Set error message
            lblError.Text    = GetString("FolderTree.FailedLoad") + ": " + ex.Message;
            lblError.ToolTip = EventLogProvider.GetExceptionLogMessage(ex);
        }
        finally
        {
            // Check for root node
            RootNodeLoaded = (treeElem.Nodes.Count > 0);
        }
    }
    /// <summary>
    /// Generates variants asynchronous.
    /// </summary>
    /// <param name="parameter">AsyncControl parameters</param>
    private void GenerateAndSave(object parameter)
    {
        try
        {
            // Regenerate already existing variants
            if (mRegenerateVariants)
            {
                ProductAttributeSet   productAttributeSet = new ProductAttributeSet(CategorySelector.SelectedCategories.Values.Where(x => x > VariantOptionInfo.NewOption));
                List <ProductVariant> existingVariants    = VariantHelper.AddNewCategoriesToVariantsOfProduct(ProductID, productAttributeSet);

                // Use special action contexts to turn off unnecessary actions
                using (ECommerceActionContext eCommerceContext = new ECommerceActionContext())
                {
                    eCommerceContext.TouchParent                  = false;
                    eCommerceContext.SetLowestPriceToParent       = false;
                    eCommerceContext.AssignDefaultTaxesToProducts = false;

                    existingVariants.ForEach(pVariant =>
                    {
                        AddLog(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(pVariant.Variant.SKUName)) + GetString("com.variants.isredefined"));
                        VariantHelper.SetProductVariant(pVariant);
                    });
                }

                // Save variant to update parent SKULastModified a SKUPrice properties
                var lastVariant = existingVariants.LastOrDefault();
                if (lastVariant != null)
                {
                    lastVariant.Variant.Generalized.SetObject();
                }
            }

            // Generate non-existing variants
            ProductVariant productVariant = null;

            // Use special action contexts to turn off unnecessary actions
            using (ECommerceActionContext eCommerceContext = new ECommerceActionContext())
            {
                eCommerceContext.TouchParent                  = false;
                eCommerceContext.SetLowestPriceToParent       = false;
                eCommerceContext.AssignDefaultTaxesToProducts = false;

                foreach (DataRow row in mVariantsToGenerate)
                {
                    IEnumerable <int> options = GetAllOptions(row, NewCategories.Union(ExistingCategories));
                    productVariant = new ProductVariant(ProductID, new ProductAttributeSet(options));
                    AddLog(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(productVariant.Variant.SKUName)) + GetString("com.variants.isdefined"));
                    productVariant.Set();
                }
            }

            // Save variant to update parent SKULastModified a SKUPrice properties
            if (productVariant != null)
            {
                productVariant.Variant.Generalized.SetObject();
            }
        }
        catch (Exception ex)
        {
            CurrentError = GetString("com.variant.definerror");
            EventLogProvider.LogException("Variant definition", "DEFINEVARIANT", ex);
        }
    }
    private static void Upgrade60Import()
    {
        EventLogProvider evp = new EventLogProvider();
        // Import
        try
        {
            RequestStockHelper.Remove("CurrentDomain", true);

            SiteImportSettings importSettings = new SiteImportSettings(CMSContext.CurrentUser)
                                                    {
                                                        DefaultProcessObjectType = ProcessObjectEnum.All,
                                                        SourceFilePath = mUpgradePackagePath,
                                                        WebsitePath = mWebsitePath
                                                    };

            ImportProvider.ImportObjectsData(importSettings);

            // Regenerate time zones
            TimeZoneInfoProvider.GenerateTimeZoneRules();

            #region "Separability"

            String webPartsPath = mWebsitePath + "CMSWebParts\\";
            List<String> files = new List<string>();
            // Create list of files to remove
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.BIZFORM))
            {
                files.AddRange(GetAllFiles(webPartsPath + "BizForms"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.BLOGS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Blogs"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.COMMUNITY))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Community"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.ECOMMERCE))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Ecommerce"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.EVENTMANAGER))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Events"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.FORUMS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Forums"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.MEDIALIBRARY))
            {
                files.AddRange(GetAllFiles(webPartsPath + "MediaLibrary"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.MESSAGEBOARD))
            {
                files.AddRange(GetAllFiles(webPartsPath + "MessageBoards"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.MESSAGING))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Messaging"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.NEWSLETTER))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Newsletters"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.NOTIFICATIONS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Notifications"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.ONLINEMARKETING))
            {
                files.AddRange(GetAllFiles(webPartsPath + "OnlineMarketing"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.POLLS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Polls"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.PROJECTMANAGEMENT))
            {
                files.AddRange(GetAllFiles(webPartsPath + "ProjectManagement"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.REPORTING))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Reporting"));
            }

            // Remove webparts for separated modules
            foreach (String file in files)
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception ex)
                {
                    evp.LogEvent("Upgrade to 6.0", "Upgrade", ex);
                }
            }

            #endregion

            evp.LogEvent("I", DateTime.Now, "Upgrade to 6.0", "Upgrade - Finish");
        }
        catch (Exception ex)
        {
            evp.LogEvent("Upgrade to 6.0", "Upgrade", ex);
        }
    }
    /// <summary>
    /// When exception occurs, log it to event log.
    /// </summary>
    /// <param name="ex">Exception to log</param>
    private void LogExceptionToEventLog(Exception ex)
    {
        EventLogProvider log = new EventLogProvider();

        log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "IMPORTFILE", CMSContext.CurrentUser.UserID, CMSContext.CurrentUser.UserName, 0, null, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSiteID, HTTPHelper.GetAbsoluteUri());

        AddError(GetString("tools.fileimport.failed") + " (" + ex.Message + ")");
    }
Exemple #18
0
    /// <summary>
    /// Yes button click event handler.
    /// </summary>
    protected void btnYes_Click(object sender, EventArgs e)
    {
        if (IsBannedIP())
        {
            return;
        }

        // Prepare the where condition
        string where = "NodeID = " + NodeID;

        // Get the documents
        DataSet ds = null;

        if (chkAllCultures.Checked)
        {
            ds = TreeProvider.SelectNodes(SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, -1, false);
        }
        else
        {
            ds = TreeProvider.SelectNodes(SiteName, "/%", CultureCode, false, null, where, null, -1, false);
        }

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            // Get node alias
            var nodeAlias = DataHelper.GetStringValue(ds.Tables[0].Rows[0], "NodeAlias", string.Empty);
            // Get parent alias path

            var parentAliasPath = TreePathUtils.GetParentPath(DataHelper.GetStringValue(ds.Tables[0].Rows[0], "NodeAliasPath", string.Empty));

            // Delete the documents
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                var aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty);
                var culture   = ValidationHelper.GetString(dr["DocumentCulture"], string.Empty);
                var className = ValidationHelper.GetString(dr["ClassName"], string.Empty);

                // Get the node
                var treeNode = TreeProvider.SelectSingleNode(SiteName, aliasPath, culture, false, className, false);

                if (treeNode != null)
                {
                    // Check delete permissions
                    var hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(treeNode, chkDestroy.Checked);

                    if (hasUserDeletePermission)
                    {
                        // Delete the document
                        try
                        {
                            LogDeleteActivity(treeNode);
                            DocumentHelper.DeleteDocument(treeNode, TreeProvider, chkAllCultures.Checked, chkDestroy.Checked);
                        }
                        catch (Exception ex)
                        {
                            EventLogProvider.LogEvent(EventType.ERROR, "Content", "DELETEDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, MembershipContext.AuthenticatedUser.UserID, MembershipContext.AuthenticatedUser.UserName, treeNode.NodeID, treeNode.GetDocumentName(), RequestContext.UserHostAddress, SiteContext.CurrentSiteID);
                            AddAlert(GetString("ContentRequest.DeleteFailed") + ": " + ex.Message);
                            return;
                        }
                    }
                    // Access denied - not authorized to delete the document
                    else
                    {
                        AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), treeNode.NodeAliasPath));
                        return;
                    }
                }
                else
                {
                    AddAlert(GetString("ContentRequest.ErrorMissingSource"));
                    return;
                }
            }

            RaiseOnAfterDelete();

            string rawUrl = RequestContext.RawURL.TrimEnd(new[] { '/' });
            if ((!string.IsNullOrEmpty(nodeAlias)) && (rawUrl.Substring(rawUrl.LastIndexOfCSafe('/')).Contains(nodeAlias)))
            {
                // Redirect to the parent url when current url belongs to deleted document
                URLHelper.Redirect(DocumentURLProvider.GetUrl(parentAliasPath));
            }
            else
            {
                // Redirect to current url
                URLHelper.Redirect(rawUrl);
            }
        }
        else
        {
            AddAlert(GetString("DeleteDocument.CultureNotExists"));
        }
    }
    /// <summary>
    /// Callback event handler.
    /// </summary>
    /// <param name="argument">Callback argument</param>
    public void RaiseCallbackEvent(string argument)
    {
        // Get arguments
        string[] args = argument.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        bool cancel = ValidationHelper.GetBoolean(args[0], false);
        int messageLength = 0;
        int errorLength = 0;
        int warningLength = 0;
        string machineName = null;

        if (args.Length == 5)
        {
            messageLength = ValidationHelper.GetInteger(args[1], 0);
            errorLength = ValidationHelper.GetInteger(args[2], 0);
            warningLength = ValidationHelper.GetInteger(args[3], 0);
            machineName = ValidationHelper.GetString(args[4], null);
        }

        // Check if on same machine
        if (machineName == SqlHelperClass.MachineName.ToLowerCSafe())
        {
            try
            {
                // Cancel Import
                if (cancel)
                {
                    ImportManager.Settings.Cancel();
                }

                hdnState.Value = ImportManager.Settings.GetLimitedProgressLog(messageLength, errorLength, warningLength);
            }
            catch (Exception ex)
            {
                EventLogProvider ev = new EventLogProvider();
                ev.LogEvent("NewSiteWizard", "IMPORT", ex);

                hdnState.Value = ImportManager.Settings.GetLimitedProgressLog(messageLength, errorLength, warningLength);
            }
            finally
            {
                if (ImportManager.Settings.GetProgressState() != LogStatusEnum.Info)
                {
                    // Delete presistent data
                    PersistentStorageHelper.RemoveValue(PersistentSettingsKey);
                }
            }
        }
    }
Exemple #20
0
 private void HandleError(Exception exception)
 {
     SalesForceError.Report(exception);
     EventLogProvider.LogException("Salesforce.com Connector", "MappingEditorPage", exception);
 }
Exemple #21
0
    /// <summary>
    /// Saves order information from ShoppingCartInfo object to database as new order.
    /// </summary>
    public override bool ProcessStep()
    {
        // Load first step if there is no address
        if (ShoppingCart.ShoppingCartBillingAddressID <= 0)
        {
            ShoppingCartControl.LoadStep(0);
            return(false);
        }

        // Check if customer is enabled
        if ((ShoppingCart.Customer != null) && (!ShoppingCart.Customer.CustomerEnabled))
        {
            lblError.Text = GetString("ecommerce.cartcontent.customerdisabled");
            return(false);
        }

        // Deal with order note
        ShoppingCartControl.SetTempValue(ORDER_NOTE, null);
        ShoppingCart.ShoppingCartNote = txtNote.Text.Trim();

        try
        {
            // Set order culture
            ShoppingCart.ShoppingCartCulture = LocalizationContext.PreferredCultureCode;

            // Update customer preferences
            CustomerInfoProvider.SetCustomerPreferredSettings(ShoppingCart);

            // Create order
            ShoppingCartInfoProvider.SetOrder(ShoppingCart);
        }
        catch (Exception ex)
        {
            // Show error
            lblError.Text = GetString("Ecommerce.OrderPreview.ErrorOrderSave");

            // Log exception
            EventLogProvider.LogException("Shopping cart", "SAVEORDER", ex, ShoppingCart.ShoppingCartSiteID, null);
            return(false);
        }

        // Track order items conversions
        ECommerceHelper.TrackOrderItemsConversions(ShoppingCart);

        // Track order conversion
        string name = ShoppingCartControl.OrderTrackConversionName;

        ECommerceHelper.TrackOrderConversion(ShoppingCart, name);

        // Track order activity
        string siteName = SiteContext.CurrentSiteName;

        if (LogActivityForCustomer)
        {
            ShoppingCartControl.TrackActivityPurchasedProducts(ShoppingCart, siteName, ContactID);
            ShoppingCartControl.TrackActivityPurchase(ShoppingCart.OrderId, ContactID,
                                                      SiteContext.CurrentSiteName, RequestContext.CurrentRelativePath,
                                                      ShoppingCart.TotalPriceInMainCurrency, CurrencyInfoProvider.GetFormattedPrice(ShoppingCart.TotalPriceInMainCurrency,
                                                                                                                                    CurrencyInfoProvider.GetMainCurrency(CMSContext.CurrentSiteID)));
        }

        // Raise finish order event
        ShoppingCartControl.RaiseOrderCompletedEvent();

        // When in CMSDesk
        if (ShoppingCartControl.IsInternalOrder)
        {
            if (chkSendEmail.Checked)
            {
                // Send order notification emails
                OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
            }
        }
        // When on the live site
        else if (ECommerceSettings.SendOrderNotification(SiteContext.CurrentSite.SiteName))
        {
            // Send order notification emails
            OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
            OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
        }

        return(true);
    }
Exemple #22
0
    private void wzdExport_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        switch (e.CurrentStepIndex)
        {
        case 0:
            // Apply settings
            if (!configExport.ApplySettings())
            {
                e.Cancel = true;
                return;
            }

            // Update settings
            ExportSettings = configExport.Settings;

            if (!configExport.ExportHistory)
            {
                ltlScriptAfter.Text = ScriptHelper.GetScript(
                    @"var actDiv = document.getElementById('actDiv');
if (actDiv != null) { actDiv.style.display='block'; }
var buttonsDiv = document.getElementById('buttonsDiv');
if (buttonsDiv != null) { buttonsDiv.disabled=true; }
BTN_Disable('" + NextButton.ClientID + @"');
StartSelectionTimer();");

                // Select objects asynchronously
                ctrlAsyncSelection.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());
                e.Cancel = true;
            }
            else
            {
                pnlExport.Settings = ExportSettings;
                pnlExport.ReloadData();

                wzdExport.ActiveStepIndex = e.NextStepIndex;
            }
            break;

        case 1:
            // Apply settings
            if (!pnlExport.ApplySettings())
            {
                e.Cancel = true;
                return;
            }
            ExportSettings = pnlExport.Settings;

            // Delete temporary files
            try
            {
                ExportProvider.DeleteTemporaryFiles(ExportSettings, true);
            }
            catch (Exception ex)
            {
                SetErrorLabel(ex.Message);
                e.Cancel = true;
                return;
            }

            try
            {
                // Save export history
                ExportHistoryInfo history = new ExportHistoryInfo
                {
                    ExportDateTime = DateTime.Now,
                    ExportFileName = ExportSettings.TargetFileName,
                    ExportSettings = ExportSettings.GetXML(),
                    ExportSiteID   = ExportSettings.SiteId,
                    ExportUserID   = MembershipContext.AuthenticatedUser.UserID
                };

                ExportHistoryInfo.Provider.Set(history);
            }
            catch (Exception ex)
            {
                SetErrorLabel(ex.Message);
                pnlError.ToolTip = EventLogProvider.GetExceptionLogMessage(ex);
                e.Cancel         = true;
                return;
            }

            if (ExportSettings.SiteId > 0)
            {
                ExportSettings.EventLogSource = String.Format(ExportSettings.GetAPIString("ExportSite.EventLogSiteSource", "Export '{0}' site"), ResHelper.LocalizeString(ExportSettings.SiteInfo.DisplayName));
            }

            // Start asynchronous export
            var manager = ExportManager;

            ExportSettings.LogContext = ctlAsyncExport.CurrentLog;
            manager.Settings          = ExportSettings;

            ctlAsyncExport.RunAsync(manager.Export, WindowsIdentity.GetCurrent());

            wzdExport.ActiveStepIndex = e.NextStepIndex;

            break;
        }
    }
 /// <summary>
 /// When exception occures, log it to event log.
 /// </summary>
 /// <param name="messageTitle">Title message</param>
 /// <param name="ex">Exception to log</param>
 private void LogExceptionToEventLog(string messageTitle, Exception ex)
 {
     AddError(messageTitle + ": " + ex.Message);
     LogContext.LogEventToCurrent(EventType.ERROR, "Content", "PUBLISHDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, 0, null, RequestContext.UserHostAddress, currentSiteId, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now);
 }
    /// <summary>
    /// Refreshes the security parameters in macros for all the objects of the specified object types.
    /// Signs all the macros with the current user if the old salt is not specified.
    /// </summary>
    /// <param name="objectTypes">Object types</param>
    /// <param name="oldSalt">Old salt </param>
    /// <param name="newSalt">New salt</param>
    private void RefreshSecurityParams(IEnumerable <string> objectTypes, string oldSalt, string newSalt)
    {
        var oldSaltSpecified = !string.IsNullOrEmpty(oldSalt) && !chkRefreshAll.Checked;
        var newSaltSpecified = !string.IsNullOrEmpty(newSalt) && !chkUseCurrentSalt.Checked;

        processedObjects.Clear();

        using (var context = new CMSActionContext())
        {
            context.LogEvents          = false;
            context.LogSynchronization = false;
            var processingString = GetString("macros.refreshsecurityparams.processing");

            foreach (var objectType in objectTypes)
            {
                var niceObjectType = GetNiceObjectTypeName(objectType);

                AddLog(string.Format(processingString, niceObjectType));

                try
                {
                    var infos = new InfoObjectCollection(objectType);

                    var csi          = infos.TypeInfo.ClassStructureInfo;
                    var orderByIndex = FindOrderByIndex(csi);
                    if (orderByIndex != null)
                    {
                        infos.OrderByColumns = orderByIndex.GetOrderBy();
                    }

                    infos.PageSize = 1000;

                    // Skip object types derived from general data class object type to avoid duplicities
                    if ((infos.TypeInfo.OriginalObjectType == DataClassInfo.OBJECT_TYPE) && (infos.TypeInfo.ObjectType != DataClassInfo.OBJECT_TYPE))
                    {
                        continue;
                    }

                    foreach (var info in infos)
                    {
                        try
                        {
                            bool refreshed;
                            if (oldSaltSpecified)
                            {
                                refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, oldSalt, newSaltSpecified ? newSalt : ValidationHelper.HashStringSalt, true);
                            }
                            else
                            {
                                if (chkRefreshAll.Checked && newSaltSpecified)
                                {
                                    // Do not check integrity, but use new salt
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true, newSalt);
                                }
                                else
                                {
                                    // Do not check integrity, sign everything with current user
                                    refreshed = MacroSecurityProcessor.RefreshSecurityParameters(info, MembershipContext.AuthenticatedUser.UserName, true);
                                }
                            }

                            if (refreshed)
                            {
                                var objectName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(info.Generalized.ObjectDisplayName));
                                processedObjects.Add(niceObjectType, objectName);
                            }
                        }
                        catch (Exception ex)
                        {
                            string message = "Signing " + TypeHelper.GetNiceObjectTypeName(info.TypeInfo.ObjectType) + " " + info.Generalized.ObjectDisplayName + " failed: " + ex.Message;
                            EventLogProvider.LogEvent(EventType.ERROR, "Import", "MACROSECURITY", message);
                        }
                    }
                }
                catch (Exception e)
                {
                    AddLog(e.Message);
                    EventLogProvider.LogException(EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "ERROR", e);
                }
            }
        }

        EventLogProvider.LogEvent(EventType.INFORMATION, EVENTLOG_SOURCE_REFRESHSECURITYPARAMS, "PROCESSEDOBJECTS", GetProcessedObjectsForEventLog());
    }
    /// <summary>
    /// Moves document.
    /// </summary>
    private void PerformAction(object parameter)
    {
        if (Action.ToLower() == "copy")
        {
            AddLog(GetString("media.copy.startcopy"));
        }
        else
        {
            AddLog(GetString("media.move.startmove"));
        }

        if (LibraryInfo != null)
        {
            // Library path (used in recursive copy process)
            string libPath = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder);

            // Ensure libPath is in original path type
            libPath = Path.GetFullPath(libPath);

            // Original path on disk from query
            string origPath = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, FolderPath));

            // New path on disk
            string newPath = null;

            // Original path in DB
            string origDBPath = MediaLibraryHelper.EnsurePath(FolderPath);

            // New path in DB
            string newDBPath = null;

            AddLog(NewPath);

            // Check if requested folder is in library root folder
            if (!origPath.StartsWith(libPath, StringComparison.CurrentCultureIgnoreCase))
            {
                CurrentError = GetString("media.folder.nolibrary");
                AddLog(CurrentError);
                return;
            }

            string origFolderName = Path.GetFileName(origPath);

            if ((String.IsNullOrEmpty(Files) && !mAllFiles) && string.IsNullOrEmpty(origFolderName))
            {
                NewPath = NewPath + "\\" + LibraryInfo.LibraryFolder;
                NewPath = NewPath.Trim('\\');
            }
            newPath = NewPath;

            // Process current folder copy/move action
            if (String.IsNullOrEmpty(Files) && !AllFiles)
            {
                newPath = newPath.TrimEnd('\\') + '\\' + origFolderName;
                newPath = newPath.Trim('\\');

                // Check if moving into same folder
                if ((Action.ToLower() == "move") && (newPath == FolderPath))
                {
                    CurrentError = GetString("media.move.foldermove");
                    AddLog(CurrentError);
                    return;
                }

                // Error if moving folder into itself
                string newRootPath = Path.GetDirectoryName(newPath).Trim();
                string newSubRootFolder = Path.GetFileName(newPath).ToLower().Trim();
                string originalSubRootFolder = Path.GetFileName(FolderPath).ToLower().Trim();
                if (String.IsNullOrEmpty(Files) && (Action.ToLower() == "move") && newPath.StartsWith(DirectoryHelper.EnsurePathBackSlash(FolderPath))
                    && (originalSubRootFolder == newSubRootFolder) && (newRootPath == FolderPath))
                {
                    CurrentError = GetString("media.move.movetoitself");
                    AddLog(CurrentError);
                    return;
                }

                // Get unique path for copy or move
                string path = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, newPath));
                path = MediaLibraryHelper.EnsureUniqueDirectory(path);
                newPath = path.Remove(0, (libPath.Length + 1));

                // Get new DB path
                newDBPath = MediaLibraryHelper.EnsurePath(newPath.Replace(DirectoryHelper.EnsurePathBackSlash(libPath), ""));
            }
            else
            {
                origDBPath = MediaLibraryHelper.EnsurePath(FolderPath);
                newDBPath = MediaLibraryHelper.EnsurePath(newPath.Replace(libPath, "")).Trim('/');
            }

            // Error if moving folder into its subfolder
            if ((String.IsNullOrEmpty(Files) && !AllFiles) && (Action.ToLower() == "move") && newPath.StartsWith(DirectoryHelper.EnsurePathBackSlash(FolderPath)))
            {
                CurrentError = GetString("media.move.parenttochild");
                AddLog(CurrentError);
                return;
            }

            // Error if moving files into same directory
            if ((!String.IsNullOrEmpty(Files) || AllFiles) && (Action.ToLower() == "move") && (newPath.TrimEnd('\\') == FolderPath.TrimEnd('\\')))
            {
                CurrentError = GetString("media.move.fileserror");
                AddLog(CurrentError);
                return;
            }

            NewPath = newPath;
            refreshScript = "if ((typeof(window.top.opener) != 'undefined') && (typeof(window.top.opener.RefreshLibrary) != 'undefined')) {window.top.opener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + ");} else if ((typeof(window.top.wopener) != 'undefined') && (typeof(window.top.wopener.RefreshLibrary) != 'undefined')) { window.top.wopener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + "); } window.top.close();";

            // If mFiles is empty handle directory copy/move
            if (String.IsNullOrEmpty(Files) && !mAllFiles)
            {
                try
                {
                    switch (Action.ToLower())
                    {
                        case "move":
                            MediaLibraryInfoProvider.MoveMediaLibraryFolder(CMSContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, false);
                            break;

                        case "copy":
                            MediaLibraryInfoProvider.CopyMediaLibraryFolder(CMSContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, false, CurrentUser.UserID);
                            break;
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + GetString("media.security.accessdenied");
                    EventLogProvider ev = new EventLogProvider();
                    ev.LogEvent("MediaFolder", this.Action, ex);
                    AddLog(CurrentError);
                    return;
                }
                catch (ThreadAbortException ex)
                {
                    string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                    if (state == CMSThread.ABORT_REASON_STOP)
                    {
                        // When canceled
                        CurrentInfo = GetString("general.actioncanceled");
                        AddLog(CurrentInfo);
                    }
                    else
                    {
                        // Log error
                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("MediaFolder", this.Action, ex);
                        AddLog(CurrentError);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                    EventLogProvider ev = new EventLogProvider();
                    ev.LogEvent("MediaFolder", this.Action, ex);
                    AddLog(CurrentError);
                    return;
                }
            }
            else
            {
                string origDBFilePath = null;
                string newDBFilePath = null;

                if (!mAllFiles)
                {
                    try
                    {
                        string[] files = Files.Split('|');
                        foreach (string filename in files)
                        {
                            origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? filename : origDBPath + "/" + filename;
                            newDBFilePath = (string.IsNullOrEmpty(newDBPath)) ? filename : newDBPath + "/" + filename;
                            AddLog(filename);
                            CopyMove(origDBFilePath, newDBFilePath);
                        }
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied");
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("MediaFile", this.Action, ex);
                        AddLog(CurrentError);
                        return;
                    }
                    catch (ThreadAbortException ex)
                    {
                        string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                        if (state == CMSThread.ABORT_REASON_STOP)
                        {
                            // When canceled
                            CurrentInfo = GetString("general.actioncanceled");
                            AddLog(CurrentInfo);
                        }
                        else
                        {
                            // Log error
                            CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                            EventLogProvider ev = new EventLogProvider();
                            ev.LogEvent("MediaFile", this.Action, ex);
                            AddLog(CurrentError);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("MediaFile", this.Action, ex);
                        AddLog(CurrentError);
                        return;
                    }
                }
                else
                {
                    HttpContext context = (parameter as HttpContext);
                    if (context != null)
                    {
                        HttpContext.Current = context;

                        DataSet files = GetFileSystemDataSource();
                        if (!DataHelper.IsEmpty(files))
                        {
                            foreach (DataRow file in files.Tables[0].Rows)
                            {
                                string fileName = ValidationHelper.GetString(file["FileName"], "");

                                AddLog(fileName);

                                origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? fileName : origDBPath + "/" + fileName;
                                newDBFilePath = (string.IsNullOrEmpty(newDBPath)) ? fileName : newDBPath + "/" + fileName;

                                // Clear current httpcontext for CopyMove action in threat
                                HttpContext.Current = null;

                                try
                                {
                                    CopyMove(origDBFilePath, newDBFilePath);
                                }
                                catch (UnauthorizedAccessException ex)
                                {
                                    CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied");
                                    EventLogProvider ev = new EventLogProvider();
                                    ev.LogEvent("MediaFile", this.Action, ex);
                                    AddLog(CurrentError);
                                    return;
                                }
                                catch (ThreadAbortException ex)
                                {
                                    string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                                    if (state == CMSThread.ABORT_REASON_STOP)
                                    {
                                        // When canceled
                                        CurrentInfo = GetString("general.actioncanceled");
                                        AddLog(CurrentInfo);
                                    }
                                    else
                                    {
                                        // Log error
                                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                        EventLogProvider ev = new EventLogProvider();
                                        ev.LogEvent("MediaFile", this.Action, ex);
                                        AddLog(CurrentError);
                                        return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                    EventLogProvider ev = new EventLogProvider();
                                    ev.LogEvent("MediaFile", this.Action, ex);
                                    AddLog(CurrentError);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /// <summary>
    /// When exception occurs, log it to event log.
    /// </summary>
    /// <param name="ex">Exception to log</param>
    private void LogExceptionToEventLog(Exception ex)
    {
        EventLogProvider.LogEvent(EventType.ERROR, "Content", "TRANSLATEDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, 0, null, RequestContext.UserHostAddress, currentSite.SiteID);

        AddError(ResHelper.GetString("ContentRequest.TranslationFailed", currentCulture) + ex.Message);
    }
Exemple #27
0
    /// <summary>
    /// Reloads the grid data.
    /// </summary>
    public override void ReloadData()
    {
        try
        {
            // Ensure grid definition before realod data
            LoadGridDefinition();

            RaiseOnBeforeDataReload();
            rowIndex = 1;

            // Get Current TOP N
            if (CurrentPageSize > 0)
            {
                int currentPageIndex = Pager.CurrentPage;
                int pageSize = (CurrentPageSize > 0) ? CurrentPageSize : UniGridView.PageSize;

                CurrentTopN = pageSize * (currentPageIndex + Pager.CurrentPagesGroupSize);
            }

            if (CurrentTopN < TopN)
            {
                CurrentTopN = TopN;
            }

            // If first/last button and direct page contol in pager is hidden use current topN for better performance
            if (!Pager.ShowDirectPageControl && !Pager.ShowFirstLastButtons)
            {
                TopN = CurrentTopN;
            }

            // Retrieve data
            UniGridView.DataSource = RetrieveData();

            // Sort external dataset only if no query and info object is set
            if (string.IsNullOrEmpty(Query) && (InfoObject == null) && (!DataHelper.DataSourceIsEmpty(UniGridView.DataSource) && !DataSourceIsSorted))
            {
                SortUniGridDataSource();
            }

            RaiseOnAfterDataReload();

            SetUnigridControls();

            // Check if datasource is loaded
            if (DataHelper.DataSourceIsEmpty(GridView.DataSource) && (pagerElem.CurrentPage > 1))
            {
                pagerElem.UniPager.CurrentPage = 1;
                ReloadData();
            }

            // Resolve the edit action URL
            if (!String.IsNullOrEmpty(EditActionUrl))
            {
                EditActionUrl = CMSContext.ResolveMacros(EditActionUrl);
            }

            SortColumns.Clear();
            UniGridView.DataBind();

            mRowsCount = DataHelper.GetItemsCount(UniGridView.DataSource);

            CheckFilterVisibility();
        }
        catch (Exception ex)
        {
            lblError.Text = GetString("unigrid.error.reload");
            lblError.Visible = true;

            // Display tooltip only development mode is enabled
            if (SettingsKeyProvider.DevelopmentMode)
            {
                lblError.ToolTip = ex.Message;
            }

            // Log exception
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("UniGrid", "RELOADDATA", ex.InnerException ?? ex);
        }
    }
    /// <summary>
    /// Process this step.
    /// </summary>
    public override bool ProcessStep()
    {
        // Do not process step if order is paid
        if (OrderIsPaid)
        {
            return(false);
        }

        // Shopping cart units are already saved in database (on "Update" or on "btnAddProduct_Click" actions)
        bool isOK = false;

        if (ShoppingCart != null)
        {
            // Reload data
            ReloadData();

            // Check available items before "Check out"
            ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

            if (checkResult.CheckFailed)
            {
                lblError.Text = checkResult.GetHTMLFormattedMessage();
            }
            else if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
            {
                // Indicates whether order saving process is successful
                isOK = true;

                try
                {
                    ShoppingCartInfoProvider.SetOrder(ShoppingCart);
                }
                catch (Exception ex)
                {
                    // Log exception
                    EventLogProvider.LogException("Shopping cart", "SAVEORDER", ex, ShoppingCart.ShoppingCartSiteID);
                    isOK = false;
                }

                if (isOK)
                {
                    lblInfo.Text = GetString("general.changessaved");

                    // Send order notification when editing existing order
                    if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems)
                    {
                        if (chkSendEmail.Checked)
                        {
                            OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                            OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
                        }
                    }
                    // Send order notification emails when on the live site
                    else if (ECommerceSettings.SendOrderNotification(SiteContext.CurrentSite.SiteName))
                    {
                        OrderInfoProvider.SendOrderNotificationToAdministrator(ShoppingCart);
                        OrderInfoProvider.SendOrderNotificationToCustomer(ShoppingCart);
                    }
                }
                else
                {
                    lblError.Text = GetString("ecommerce.orderpreview.errorordersave");
                }
            }
            // Go to the next step
            else
            {
                // Save other options
                if (!ShoppingCartControl.IsInternalOrder)
                {
                    ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
                }

                isOK = true;
            }
        }

        return(isOK);
    }
    protected void wzdImport_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        switch (e.CurrentStepIndex)
        {
                // Import type
            case 0:
                {
                    if (!siteType.SelectTemplate)
                    {
                        try
                        {
                            // Get blank web template
                            WebTemplateInfo wi = WebTemplateInfoProvider.GetWebTemplateInfo("BlankSite");
                            if (wi == null)
                            {
                                e.Cancel = true;
                                return;
                            }

                            WebTemplateID = wi.WebTemplateId;

                            string path = Server.MapPath(wi.WebTemplateFileName);
                            if (File.Exists(path + "\\template.zip"))
                            {
                                // Template from zip file
                                path += "\\" + ZipStorageProvider.GetZipFileName("template.zip");

                                ImportSettings.TemporaryFilesPath = path;
                                ImportSettings.SourceFilePath = path;
                                ImportSettings.TemporaryFilesCreated = true;
                                ImportSettings.RefreshMacroSecurity = true;
                            }
                            else
                            {
                                // Init the settings
                                ImportSettings.TemporaryFilesCreated = false;
                                ImportSettings.SourceFilePath = Server.MapPath(wi.WebTemplateFileName);
                                ImportSettings.RefreshMacroSecurity = true;
                            }

                            if (!File.Exists(ImportSettings.SourceFilePath))
                            {
                                try
                                {
                                    ImportProvider.CreateTemporaryFiles(ImportSettings);
                                }
                                catch (Exception ex)
                                {
                                    lblError.Visible = true;
                                    lblError.Text = ex.Message;
                                    e.Cancel = true;
                                    return;
                                }
                            }

                            if (SiteInfoProvider.GetSitesCount() == 0)
                            {
                                // No site exists, overwrite all
                                ImportSettings.ImportType = ImportTypeEnum.All;
                                ImportSettings.CopyFiles = false;
                            }
                            else
                            {
                                // Some site exists, only new objects
                                ImportSettings.ImportType = ImportTypeEnum.New;
                            }

                            ltlScriptAfter.Text = ScriptHelper.GetScript(
                                "var actDiv = document.getElementById('actDiv'); \n" +
                                "if (actDiv != null) { actDiv.style.display='block'; } \n" +
                                "var buttonsDiv = document.getElementById('buttonsDiv'); if (buttonsDiv != null) { buttonsDiv.disabled=true; } \n" +
                                "BTN_Disable('" + NextButton.ClientID + "'); \n" +
                                "StartSelectionTimer();"
                                );

                            // Preselect objects asynchronously
                            ctrlAsync.Parameter = "N";
                            ctrlAsync.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());

                            e.Cancel = true;
                        }
                        catch (Exception ex)
                        {
                            lblError.Text = ex.Message;
                            e.Cancel = true;
                            return;
                        }
                    }
                    else
                    {
                        siteDetails.SiteName = null;
                        siteDetails.SiteDisplayName = null;
                        selectTemplate.ReloadData();
                    }

                    wzdImport.ActiveStepIndex++;
                }
                break;

                // Template selection
            case 1:
                {
                    if (!selectTemplate.ApplySettings())
                    {
                        e.Cancel = true;
                        return;
                    }

                    // Init the settings
                    WebTemplateInfo wi = WebTemplateInfoProvider.GetWebTemplateInfo(selectTemplate.WebTemplateId);
                    if (wi == null)
                    {
                        throw new Exception("Web template not found.");
                    }

                    ImportSettings.IsWebTemplate = true;

                    string path = Server.MapPath(wi.WebTemplateFileName);
                    if (File.Exists(path + "\\template.zip"))
                    {
                        // Template from zip file
                        path += "\\" + ZipStorageProvider.GetZipFileName("template.zip");

                        ImportSettings.TemporaryFilesPath = path;
                        ImportSettings.SourceFilePath = path;
                        ImportSettings.TemporaryFilesCreated = true;
                        ImportSettings.RefreshMacroSecurity = true;
                    }
                    else
                    {
                        // Template from folder
                        ImportSettings.TemporaryFilesCreated = false;
                        ImportSettings.SourceFilePath = path;
                        ImportSettings.RefreshMacroSecurity = true;
                        try
                        {
                            ImportProvider.CreateTemporaryFiles(ImportSettings);
                        }
                        catch (Exception ex)
                        {
                            lblError.Visible = true;
                            lblError.Text = ex.Message;
                            e.Cancel = true;
                            return;
                        }
                    }

                    if (SiteInfoProvider.GetSitesCount() == 0)
                    {
                        // No site exists, overwrite all
                        ImportSettings.ImportType = ImportTypeEnum.All;
                    }
                    else
                    {
                        // Some site exists, only new objects
                        ImportSettings.ImportType = ImportTypeEnum.New;
                    }

                    ltlScriptAfter.Text = ScriptHelper.GetScript(
                        "var actDiv = document.getElementById('actDiv');\n" +
                        "if (actDiv != null) { actDiv.style.display='block'; }\n" +
                        "var buttonsDiv = document.getElementById('buttonsDiv');\n" +
                        "if (buttonsDiv != null) { buttonsDiv.disabled=true; }\n" +
                        "BTN_Disable('" + NextButton.ClientID + "');\n" +
                        "BTN_Disable('" + PreviousButton.ClientID + "');\n" +
                        "StartSelectionTimer();"
                        );

                    // Preselect objects asynchronously
                    ctrlAsync.Parameter = "T";
                    ctrlAsync.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());

                    e.Cancel = true;
                }
                break;

                // Site details
            case 2:
                if (!siteDetails.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Update settings
                ImportSettings = siteDetails.Settings;

                Culture = siteDetails.Culture;

                pnlImport.ReloadData(true);
                wzdImport.ActiveStepIndex++;
                break;

                // Objects selection
            case 3:
                if (!pnlImport.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Check licences
                string error = ImportExportControl.CheckLicenses(ImportSettings);
                if (!string.IsNullOrEmpty(error))
                {
                    lblError.Text = error;

                    e.Cancel = true;
                    return;
                }

                ImportSettings = pnlImport.Settings;

                PreviousButton.Enabled = false;
                NextButton.Enabled = false;

                SiteName = ImportSettings.SiteName;
                Domain = ImportSettings.SiteDomain;

                // Init the Mimetype helper (required for the Import)
                MimeTypeHelper.LoadMimeTypes();

                // Start asynchronnous Import
                ImportSettings.SetSettings(ImportExportHelper.SETTINGS_DELETE_TEMPORARY_FILES, false);
                ImportSettings.DefaultProcessObjectType = ProcessObjectEnum.Selected;
                ImportManager.Settings = ImportSettings;

                // Import site asynchronously
                ctrlImport.RunAsync(ImportManager.Import, WindowsIdentity.GetCurrent());
                ctrlImport.PostbackOnError = false;

                ltlScript.Text = ScriptHelper.GetScript("StartImportStateTimer();");
                wzdImport.ActiveStepIndex++;
                break;

                // Import progress
            case 4:
                PreviousButton.Visible = false;

                CultureHelper.SetPreferredCulture(Culture);
                if (siteType.SelectTemplate)
                {
                    // Done
                    finishSite.Domain = Domain;
                    finishSite.SiteIsRunning = SiteIsRunning;
                    wzdImport.ActiveStepIndex = 7;
                }
                else
                {
                    if (ImportManager.Settings.IsWarning())
                    {
                        try
                        {
                            // Convert default culture
                            TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                            tree.ChangeSiteDefaultCulture(SiteName, Culture, "en-US");

                            // Change root GUID
                            TreeNode root = DocumentHelper.GetDocument(SiteName, "/", Culture, false, "cms.root", null, null, 1, false, null, tree);
                            if (root != null)
                            {
                                root.NodeGUID = Guid.NewGuid();
                                DocumentHelper.UpdateDocument(root, tree);
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLogProvider ev = new EventLogProvider();
                            ev.LogEvent("NewSiteWizard", "FINISH", ex);
                            lblError.Text = ex.Message;
                            e.Cancel = true;
                            return;
                        }
                    }
                    selectMaster.SiteName = SiteName;
                    selectMaster.ReloadData();
                }
                break;

                // Master template
            case 5:
                if (!selectMaster.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                siteStructure.SiteName = SiteName;
                break;

                // Define site structure
            case 6:
                finishSite.Domain = Domain;
                finishSite.SiteIsRunning = SiteIsRunning;
                break;

                // Other steps
            default:
                wzdImport.ActiveStepIndex = e.NextStepIndex;
                break;
        }
    }
Exemple #30
0
    public void SynchronizeComplete(object parameter)
    {
        string result = null;

        eventCode      = "SYNCCOMPLETE";
        CanceledString = GetString("Tasks.SynchronizationCanceled");
        try
        {
            int sid = serverId;
            if (sid <= 0)
            {
                sid = SynchronizationInfoProvider.ENABLED_SERVERS;
            }

            AddLog(GetString("Synchronization.LoggingTasks"));

            // Synchronize root node
            IEnumerable <ISynchronizationTask> tasks = DocumentSynchronizationHelper.LogDocumentChange(SiteContext.CurrentSiteName, "/", TaskTypeEnum.UpdateDocument, null, sid, false, false);

            AddLog(GetString("Synchronization.RunningTasks"));

            // Run the synchronization
            StagingHelper.RunSynchronization(tasks, serverId, true, currentSiteId, AddLog);

            AddLog(GetString("Synchronization.LoggingTasks"));

            // Synchronize subnodes
            tasks = DocumentSynchronizationHelper.LogDocumentChange(SiteContext.CurrentSiteName, "/%", TaskTypeEnum.UpdateDocument, null, sid, false, false);

            AddLog(GetString("Synchronization.RunningTasks"));

            // Run the synchronization
            result = StagingHelper.RunSynchronization(tasks, serverId, true, currentSiteId, AddLog);

            // Log possible errors
            if (!string.IsNullOrEmpty(result))
            {
                CurrentError = GetString("Tasks.SynchronizationFailed");
                AddErrorLog(CurrentError, null);
            }
            else
            {
                CurrentInfo = GetString("Tasks.SynchronizationOK");
                AddLog(CurrentInfo);
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // Canceled by user
                CurrentInfo = CanceledString;
                AddLog(CurrentInfo);
            }
            else
            {
                CurrentError = GetString("Tasks.SynchronizationFailed");
                AddErrorLog(CurrentError, result);
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Staging", "SYNCHRONIZE", ex);

            CurrentError = GetString("Tasks.SynchronizationFailed") + ": " + ex.Message;
            AddErrorLog(CurrentError);
        }
        finally
        {
            // Finalize log context
            FinalizeContext();
        }
    }
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        // Process media file
        if (mfi == null)
        {
            mfi = MediaFileInfoProvider.GetMediaFileInfo(mediafileGuid, this.CurrentSiteName);
        }

        if (mfi != null)
        {
            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(mfi.FileLibraryID);
            if (mli != null)
            {
                string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath));
                bool permissionsOK = DirectoryHelper.CheckPermissions(path, false, true, true, true);

                if (permissionsOK)
                {
                    MediaFileInfo originalMfi = mfi.Clone(true);

                    try
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mfi);

                        if (isPreview && !String.IsNullOrEmpty(PreviewPath))
                        {
                            SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                            if (si != null)
                            {
                                string previewExt = (!String.IsNullOrEmpty(extension) && (extension != OldPreviewExt)) ? extension : OldPreviewExt;
                                string previewName = Path.GetFileNameWithoutExtension(PreviewPath);
                                string previewFolder = MediaLibraryHelper.EnsurePath(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(si.SiteName)));

                                // Delete old preview files with thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreview(CMSContext.CurrentSiteName, mli.LibraryID, mfi.FilePath, false);
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                // Save preview file
                                MediaFileInfoProvider.SaveFileToDisk(si.SiteName, mli.LibraryFolder, previewFolder, previewName, previewExt, mfi.FileGUID, binary, false, false);

                                // Log synchronization task
                                SynchronizationHelper.LogObjectChange(mfi, TaskTypeEnum.UpdateObject);
                            }
                        }
                        else
                        {
                            string newExt = null;
                            string newName = null;

                            if (!String.IsNullOrEmpty(extension))
                            {
                                newExt = extension;
                            }
                            if (!String.IsNullOrEmpty(mimetype))
                            {
                                mfi.FileMimeType = mimetype;
                            }

                            mfi.FileTitle = title;
                            mfi.FileDescription = description;

                            if (width > 0)
                            {
                                mfi.FileImageWidth = width;
                            }
                            if (height > 0)
                            {
                                mfi.FileImageHeight = height;
                            }
                            if (binary != null)
                            {
                                mfi.FileBinary = binary;
                                mfi.FileSize = binary.Length;
                            }
                            // Test all parameters to empty values and update new value if available
                            if (!String.IsNullOrEmpty(name))
                            {
                                newName = name;
                            }
                            // If filename changed move preview file and remove all ald thumbnails
                            if ((!String.IsNullOrEmpty(newName) && (mfi.FileName != newName)) || (!String.IsNullOrEmpty(newExt) && (mfi.FileExtension.ToLower() != newExt.ToLower())))
                            {
                                SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                                if (si != null)
                                {
                                    string fileName = (newName != null ? newName : mfi.FileName);
                                    string fileExt = (newExt != null ? newExt : mfi.FileExtension);

                                    string newPath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt);
                                    string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);

                                    // Rename file only if file with same name does not exsists
                                    if (!File.Exists(newPath))
                                    {
                                        // Ensure max length of file path
                                        if (newPath.Length < 260)
                                        {
                                            // Remove old thumbnails
                                            MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);
                                            MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                            // Move media file
                                            MediaFileInfoProvider.MoveMediaFile(si.SiteName, mli.LibraryID, mfi.FilePath, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt, false);

                                            // Set new file name or extension
                                            mfi.FileName = fileName;
                                            mfi.FileExtension = fileExt;

                                            // Ensure new binary
                                            if (binary != null)
                                            {
                                                mfi.FileBinary = binary;
                                                mfi.FileSize = binary.Length;
                                            }
                                        }
                                        else
                                        {
                                            throw new IOExceptions.PathTooLongException();
                                        }
                                    }
                                    else
                                    {
                                        baseImageEditor.LblLoadFailed.Visible = true;
                                        baseImageEditor.LblLoadFailed.ResourceString = "img.errors.fileexists";
                                        SavingFailed = true;
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                // Remove old thumbnails
                                MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);

                                // Remove original media file before save
                                string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);
                                if (File.Exists(filePath))
                                {
                                    File.Delete(filePath);
                                }
                            }

                            // Save new data
                            MediaFileInfoProvider.SetMediaFileInfo(mfi, false);
                        }
                    }
                    catch (Exception e)
                    {
                        // Log exception
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("ImageEditor", "Save file", e);

                        baseImageEditor.LblLoadFailed.Visible = true;
                        baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing";
                        ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, e.Message, "help");
                        this.SavingFailed = true;
                        // Save original media file info
                        MediaFileInfoProvider.SetMediaFileInfo(originalMfi, false);
                    }
                }
            }
        }
    }
Exemple #32
0
    /// <summary>
    /// Internal method for synchronizing current document.
    /// </summary>
    /// <param name="parameter">Parameter</param>
    /// <param name="eventCodeForLog">Event code to set</param>
    /// <param name="finalizeEventLog">Indicates whether to finalize eventlog</param>
    /// <returns>Result of synchronization</returns>
    private string SynchronizeCurrentInternal(object parameter, string eventCodeForLog, bool finalizeEventLog)
    {
        string result = string.Empty;

        eventCode = eventCodeForLog;
        bool finish = ValidationHelper.GetBoolean(parameter, true);

        CanceledString = GetString("Tasks.SynchronizationCanceled");

        int sid = serverId;

        if (sid <= 0)
        {
            sid = SynchronizationInfoProvider.ENABLED_SERVERS;
        }

        AddLog(GetString("Synchronization.LoggingTasks"));

        try
        {
            // Get the tasks
            var settings = new LogMultipleDocumentChangeSettings()
            {
                EnsurePublishTask = true,
                NodeAliasPath     = aliasPath,
                TaskType          = TaskTypeEnum.UpdateDocument,
                ServerID          = sid,
                KeepTaskData      = false,
                RunAsynchronously = false,
                SiteName          = currentSiteName
            };
            IEnumerable <ISynchronizationTask> tasks = DocumentSynchronizationHelper.LogDocumentChange(settings);

            AddLog(GetString("Synchronization.RunningTasks"));

            // Run the synchronization
            result = StagingHelper.RunSynchronization(tasks, serverId, true, currentSiteId, AddLog);

            if (finish)
            {
                // Log possible error
                if (!String.IsNullOrEmpty(result))
                {
                    CurrentError = GetString("Tasks.SynchronizationFailed");
                    AddErrorLog(CurrentError, null);
                }
                else
                {
                    CurrentInfo = GetString("Tasks.SynchronizationOK");
                    AddLog(CurrentInfo);
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // Canceled by user
                CurrentInfo = CanceledString;
                AddLog(CurrentInfo);
            }
            else
            {
                CurrentError = GetString("Tasks.SynchronizationFailed");
                AddErrorLog(CurrentError, result);
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Staging", "SYNCHRONIZE", ex);

            CurrentError = GetString("Tasks.SynchronizationFailed") + ": " + ex.Message;
            AddErrorLog(CurrentError);
        }
        finally
        {
            if (finalizeEventLog)
            {
                // Finalize log context
                FinalizeContext();
            }
        }
        return(result);
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(Request.QueryString["fileid"]) &&
                !string.IsNullOrWhiteSpace(Request.QueryString["containerid"]))
            {
                _fileId      = Request.QueryString["fileid"];
                _containerId = new Guid(Request.QueryString["containerid"]);
            }

            if (!IsPostBack)
            {
                btnProcess.InnerText  = GetString("Kadena.MailingList.ProcessList", string.Empty);
                btnReupload.InnerText = GetString("Kadena.MailingList.ReuploadList", string.Empty);
            }

            if (!string.IsNullOrWhiteSpace(_fileId) && _containerId != Guid.Empty)
            {
                var parsingClient = DIContainer.Resolve <IParsingClient>();
                var parseResult   = parsingClient.GetHeaders(_fileId.ToString()).Result;
                if (parseResult.Success)
                {
                    var headers = parseResult.Payload.ToArray();

                    foreach (var cs in _columnSelectors)
                    {
                        var sel = (FindControl($"sel{cs.Item2}") as HtmlSelect);
                        if (sel != null)
                        {
                            var selectedValue = GetColumnValue(cs.Item2);
                            var valueToSelect = -1;
                            sel.Items.Clear();

                            var emptyItem = new ListItem(GetString("Kadena.MailingList.Empty"), GetString("Kadena.MailingList.Empty"));
                            if (!cs.Item3)
                            {
                                emptyItem.Attributes["disabled"] = string.Empty;
                            }
                            sel.Items.Add(emptyItem);

                            for (int i = 0; i < headers.Length; i++)
                            {
                                sel.Items.Add(new ListItem(headers[i], i.ToString()));
                                if (headers[i].ToLower().Contains(cs.Item1.ToLower()))
                                {
                                    valueToSelect = i;
                                }
                            }
                            if (selectedValue > -1)
                            {
                                valueToSelect = selectedValue;
                            }
                            sel.Value = valueToSelect < 0 ? GetString("Kadena.MailingList.Empty") : valueToSelect.ToString();
                        }
                    }
                }
                else
                {
                    EventLogProvider.LogEvent(EventType.ERROR, GetType().Name, "ParsingHeaders", parseResult.ErrorMessages, siteId: CurrentSite.SiteID);
                }
            }
        }
Exemple #34
0
 /// <summary>
 /// When exception occurs, log it to event log.
 /// </summary>
 private void LogExceptionToEventLog(Exception ex)
 {
     EventLogProvider.LogEvent(EventType.ERROR, "System deployment", "DEPLOYMENT", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, CurrentUser.UserID, CurrentUser.UserName, 0, null, RequestContext.UserHostAddress, SiteContext.CurrentSiteID);
     AddError(ResHelper.GetString("Deployment.DeploymentFailed") + ": " + ex.Message);
 }
Exemple #35
0
    protected void gridHistory_OnAction(string actionName, object actionArgument)
    {
        int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0);

        actionName = actionName.ToLowerCSafe();
        switch (actionName.ToLowerCSafe())
        {
        case "rollback":
        case "fullrollback":
            if (versionHistoryId > 0)
            {
                // Check permissions
                if (CheckPermissions && !AllowModify)
                {
                    ShowError(GetString("History.ErrorNotAllowedToModify"));
                }
                else
                {
                    try
                    {
                        var newVersionId = ObjectVersionManager.RollbackVersion(versionHistoryId, (actionName == "fullrollback"));
                        ObjectVersionHistoryInfo newVersion = ObjectVersionHistoryInfoProvider.GetVersionHistoryInfo(newVersionId);

                        // Set object to null because after rollback it doesn't contain current data
                        Object = null;
                        gridHistory.ReloadData();

                        if (OnAfterRollback != null)
                        {
                            OnAfterRollback(this, null);
                        }

                        ShowConfirmation(GetString("objectversioning.rollbackOK"));

                        ScriptHelper.RegisterStartupScript(this, typeof(string), "RefreshContent", ScriptHelper.GetScript("RefreshRelatedContent_" + ClientID + "();"));

                        ScriptHelper.RefreshTabHeader(Page, newVersion.VersionObjectDisplayName);
                    }
                    catch (CodeNameNotUniqueException ex)
                    {
                        ShowError(String.Format(GetString("objectversioning.restorenotuniquecodename"), (ex.Object != null) ? "('" + ex.Object.ObjectCodeName + "')" : null));
                    }
                    catch (Exception ex)
                    {
                        ShowError(GetString("objectversioning.recyclebin.restorationfailed") + " " + GetString("general.seeeventlog"));

                        // Log to event log
                        EventLogProvider.LogException("Object version list", "OBJECTRESTORE", ex);
                    }
                }
            }
            break;

        case "destroy":
            if (versionHistoryId > 0)
            {
                // Check permissions
                if (CheckPermissions && !AllowDestroy)
                {
                    ShowError(GetString("History.ErrorNotAllowedToDestroy"));
                }
                else
                {
                    ObjectVersionManager.DestroyObjectVersion(versionHistoryId);
                    ShowConfirmation(GetString("objectversioning.destroyOK"));
                }
            }
            break;
        }
    }
    protected void btnClearCache_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Clear the cache
        CacheHelper.ClearCache(null, true);
        Functions.ClearHashtables();

        // Drop the routes
        CMSMvcHandler.DropAllRoutes();

        // Disposes all zip files
        ZipStorageProvider.DisposeAll();

        // Collect the memory
        GC.Collect();
        GC.WaitForPendingFinalizers();

        // Log event
        EventLogProvider eventLog = new EventLogProvider();
        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "CLEARCACHE", null, GetString("Administration-System.ClearCacheSuccess"));

        ShowConfirmation(GetString("Administration-System.ClearCacheSuccess"));

        LoadData();
    }
Exemple #37
0
        public string Execute(TaskInfo ti)
        {
            try
            {
                string        eventName        = string.Empty;
                string        eventStartdate   = string.Empty;
                string        eventEnddate     = string.Empty;
                string        eventDescription = string.Empty;
                string        eventCategory    = string.Empty;
                long          eventProductId;
                StringBuilder documentsAddedStatus = new StringBuilder();//string eventLocation = string.Empty;
                string        eventWebsite         = string.Empty;
                string        eventContact         = string.Empty;
                string        eventFax             = string.Empty;
                string        eventFacilityID      = string.Empty;

                //Communicates with personify web service and gets the list of meetings

                string dataServiceUri      = ConfigurationManager.AppSettings["svcUri_Base"];
                string dataServiceUserName = ConfigurationManager.AppSettings["svcLogin"];
                string dataServicePassword = ConfigurationManager.AppSettings["svcPassword"];

                Uri ServiceUri = new Uri(dataServiceUri);
                PersonifyEntitiesBase DataAccessLayer = new PersonifyEntitiesBase(ServiceUri);
                DataAccessLayer.Credentials = new NetworkCredential(dataServiceUserName, dataServicePassword);
                var eventsListPersonify = DataAccessLayer.WebProductViews.Where(p => p.Subsystem == "MTG" && p.MeetingEndDate >= DateTime.Now.AddDays(-2)).ToList();

                DataSet eventsList = DocumentHelper.GetDocuments("SME.EVENT")
                                     .OnSite(SiteContext.CurrentSiteName)
                                     .Culture("en-us")
                                     .CombineWithDefaultCulture(false)
                                     .All();

                string un  = "smeadmin";
                string pwd = "533@dm1n";

                //authenticates user for publishing documents/pages/events
                AuthenticateUser(un, pwd);

                UserInfo ui = UserInfoProvider.GetUserInfo(un);


                // Create new instance of the Tree provider
                TreeProvider tree = new TreeProvider(ui);

                // Get parent node
                TreeNode parentNode = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/events-professional-development/events", "en-us");

                foreach (var events in eventsListPersonify)
                {
                    eventName        = events.ShortName;
                    eventProductId   = events.ProductId;
                    eventStartdate   = events.MeetingStartDate.ToString();
                    eventEnddate     = events.MeetingEndDate.ToString();
                    eventDescription = events.WebShortDescription;
                    eventCategory    = events.ProductClassCodeString;
                    eventFacilityID  = events.FacilityMasterCustomerId;

                    string[] addressDelimiter = new string[] { "\r\n" };
                    string[] address;
                    string   eventAddress        = string.Empty;
                    string   eventCity           = string.Empty;
                    string   eventCountry        = string.Empty;
                    string   eventStateProvince  = string.Empty;
                    string   eventZipPostalCode  = string.Empty;
                    string   eventLocation       = string.Empty;
                    string   eventEmail          = string.Empty;
                    string   eventPhone          = string.Empty;
                    bool     isAllowSocialEvents = events.ProductClassCodeString.ToLower() != "social_event";

                    if (eventFacilityID != "" && eventFacilityID != null)
                    {
                        var CommuniteeList = DataAccessLayer.AddressInfos.Where(p => p.MasterCustomerId == eventFacilityID).ToList();

                        foreach (var item in CommuniteeList)
                        {
                            address            = item.AddressLabel.Split(addressDelimiter, StringSplitOptions.None);
                            eventAddress       = address[0] + " " + address[1];
                            eventCity          = item.City;
                            eventCountry       = item.CountryCode;
                            eventStateProvince = item.State;
                            eventZipPostalCode = item.PostalCode;
                            eventLocation      = item.City + ", " + item.CountryCode;
                            eventEmail         = item.MailStop;
                            eventPhone         = item.PersonalLine;
                        }
                    }

                    if (parentNode != null)
                    {
                        if (!DocumentExists(events.ProductId, eventsList) && isAllowSocialEvents)
                        {
                            // Create documents

                            var newNode = CMS.DocumentEngine.TreeNode.New("SME.EVENT", tree);
                            newNode.DocumentName    = events.LongName;
                            newNode.NodeAlias       = eventName;
                            newNode.DocumentCulture = "en-us";
                            newNode.SetValue("EventName", eventName);
                            newNode.SetValue("ProductId", eventProductId);
                            newNode.SetValue("StartDate", eventStartdate);
                            newNode.SetValue("EndDate", eventEnddate);
                            newNode.SetValue("EventDetails", eventDescription);
                            newNode.SetValue("EventCategory", eventCategory);
                            newNode.SetValue("Location", eventLocation);
                            //newNode.SetValue("TargetUrl", eventWebsite);
                            //newNode.SetValue("Contact", eventContact);
                            newNode.SetValue("email", eventEmail);
                            newNode.SetValue("Address", eventAddress);
                            newNode.SetValue("City", eventCity);
                            newNode.SetValue("State_Province", eventStateProvince);
                            newNode.SetValue("Zip_PostalCode", eventZipPostalCode);
                            newNode.SetValue("Country", eventCountry);
                            newNode.SetValue("Phone", eventPhone);
                            newNode.SetValue("AllowPersonifyUpdate", true);
                            //newNode.SetValue("Fax", eventFax);
                            newNode.DocumentPageTemplateID = 24357;
                            newNode.Insert(parentNode);
                            //newNode.Publish();
                            documentsAddedStatus.Append("Meeting " + eventName + " added into kentico at " + DateTime.Now + Environment.NewLine);
                        }
                        else
                        {
                            // Update the Document
                            var updateNode = eventsList.Tables[0].AsEnumerable().Where(row => events.ProductId == row.Field <long?>("ProductId")).Select(row => new
                            {
                                ID = row.Field <int>("NodeId"),
                            }).ToList();
                            if (updateNode.Count == 1 && isAllowSocialEvents)
                            {
                                TreeNode node = tree.SelectSingleNode(updateNode[0].ID, "en-us", "SME.Event");

                                if (node.GetBooleanValue("AllowPersonifyUpdate", false))
                                {
                                    //node.DocumentName = events.LongName;
                                    //node.NodeAlias = eventName;
                                    node.DocumentCulture = "en-us";
                                    //node.SetValue("EventName", eventName);
                                    node.SetValue("ProductId", eventProductId);
                                    node.SetValue("StartDate", eventStartdate);
                                    node.SetValue("EndDate", eventEnddate);
                                    //this is the optional field which editors can update from CMS Desk.
                                    //node.SetValue("EventDetails", eventDescription);
                                    node.SetValue("EventCategory", eventCategory);
                                    node.SetValue("Location", eventLocation);
                                    //node.SetValue("TargetUrl", eventWebsite);
                                    //node.SetValue("Contact", eventContact);
                                    node.SetValue("email", eventEmail);
                                    node.SetValue("Address", eventAddress);
                                    node.SetValue("City", eventCity);
                                    node.SetValue("State_Province", eventStateProvince);
                                    node.SetValue("Zip_PostalCode", eventZipPostalCode);
                                    node.SetValue("Country", eventCountry);
                                    node.SetValue("Phone", eventPhone);
                                    //node.SetValue("Fax", eventFax);

                                    node.SetValue("LastUpdate", DateTime.Now);

                                    node.DocumentPageTemplateID = 24357;
                                    node.Update();
                                    DocumentHelper.UpdateDocument(node);
                                    //node.Publish();
                                    documentsAddedStatus.Append("Meeting " + eventName + " updated in kentico at " + DateTime.Now + Environment.NewLine);
                                }
                                else
                                {
                                    documentsAddedStatus.Append("Meeting " + eventName + " skipped due to document setting in document at " + DateTime.Now + Environment.NewLine);
                                }
                            }
                        }
                    }
                }



                EventLogProvider.LogInformation("PersonifyMeeting", "Import", documentsAddedStatus.ToString());
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("PersonifyMeeting", "Import", ex);
            }
            return(null);
        }
    private void DisplayError(Exception ex)
    {
        pnlProgress.Visible = false;
        btnOk.Enabled = false;
        pnlDetails.Visible = false;

        string displayName = null;
        if (exportObj != null)
        {
            displayName = exportObj.ObjectDisplayName;
        }
        lblResult.Text = string.Format(GetString("RestoreObject.Error"), HTMLHelper.HTMLEncode(displayName), ex.Message);
        lblResult.ToolTip = EventLogProvider.GetExceptionLogMessage(ex);
        lblResult.CssClass = "ErrorLabel";

        // Log to the event log
        EventLogProvider ev = new EventLogProvider();
        ev.LogEvent("Export", "RestoreObject", ex);
    }
Exemple #39
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        // New attachment
        DocumentAttachment newAttachment = null;

        string message     = string.Empty;
        bool   fullRefresh = false;
        bool   refreshTree = false;

        try
        {
            // Get the existing document
            if (DocumentID != 0)
            {
                // Get document
                node = DocumentHelper.GetDocument(DocumentID, TreeProvider);
                if (node == null)
                {
                    throw new Exception("Given page doesn't exist!");
                }
            }


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Standard attachments
            if (DocumentID != 0)
            {
                // Check out the document
                if (AutoCheck)
                {
                    // Get original step Id
                    int originalStepId = node.DocumentWorkflowStepID;

                    // Get current step info
                    WorkflowStepInfo si = WorkflowManager.GetStepInfo(node);
                    if (si != null)
                    {
                        // Decide if full refresh is needed
                        bool automaticPublish = wi.WorkflowAutoPublishChanges;
                        // Document is published or archived or uses automatic publish or step is different than original (document was updated)
                        fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID);
                    }

                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckOut(node, node.IsPublished, true);
                    }
                }

                // Handle field attachment
                if (fieldAttachment)
                {
                    // Extension of CMS file before saving
                    string oldExtension = node.DocumentType;

                    newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, TreeProvider);

                    // Different extension
                    if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true))
                    {
                        refreshTree = true;
                    }
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }

                    // Log synchronization task if not under workflow
                    if (wi == null)
                    {
                        DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider);
                    }
                }

                // Check in the document
                if (AutoCheck)
                {
                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckIn(node, null, null);
                    }
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = (DocumentAttachment)AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, SiteContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
            }

            // Ensure properties update
            if ((newAttachment != null) && !InsertMode)
            {
                AttachmentGUID = newAttachment.AttachmentGUID;
            }

            if (newAttachment == null)
            {
                throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied.");
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Content", "UploadAttachment", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;

            // Call aftersave javascript if exists
            if (!String.IsNullOrEmpty(AfterSaveJavascript))
            {
                if ((message == string.Empty) && (newAttachment != null))
                {
                    string url      = null;
                    string safeName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = DocumentURLProvider.UsePermanentUrls(si.SiteName);
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(safeName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    if (!string.IsNullOrEmpty(AfterSaveJavascript))
                    {
                        Hashtable obj = new Hashtable();
                        if (ImageHelper.IsImage(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.IMG_URL]     = url;
                            obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName;
                            obj[DialogParameters.IMG_WIDTH]   = newAttachment.AttachmentImageWidth;
                            obj[DialogParameters.IMG_HEIGHT]  = newAttachment.AttachmentImageHeight;
                        }
                        else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE]  = "flash";
                            obj[DialogParameters.FLASH_URL]    = url;
                            obj[DialogParameters.FLASH_EXT]    = newAttachment.AttachmentExtension;
                            obj[DialogParameters.FLASH_TITLE]  = newAttachment.AttachmentName;
                            obj[DialogParameters.FLASH_WIDTH]  = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT;
                        }
                        else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE] = "audiovideo";
                            obj[DialogParameters.AV_URL]      = url;
                            obj[DialogParameters.AV_EXT]      = newAttachment.AttachmentExtension;
                            obj[DialogParameters.AV_WIDTH]    = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.AV_HEIGHT]   = DEFAULT_OBJECT_HEIGHT;
                        }
                        else
                        {
                            obj[DialogParameters.LINK_URL]  = url;
                            obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName;
                        }

                        // Calling javascript function with parameters attachments url, name, width, height
                        afterSaveScript += ScriptHelper.GetScript(string.Format(@"{5}
                        if (window.{0})
                        {{
                            window.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}
                        else if((window.parent != null) && window.parent.{0})
                        {{
                            window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}", AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj)));
                    }
                }
                else
                {
                    afterSaveScript += ScriptHelper.GetAlertScript(message);
                }
            }

            // Create attachment info string
            string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : "";

            // Ensure message text
            message = TextHelper.EnsureLineEndings(message, " ");

            // Call function to refresh parent window
            afterSaveScript += ScriptHelper.GetScript(String.Format(@"
if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0} != null)){{ 
    window.parent.InitRefresh_{0}({1}, {2}, {3}, {4});
}}",
                                                                    ParentElemID,
                                                                    ScriptHelper.GetString(message.Trim()),
                                                                    (fullRefresh ? "true" : "false"),
                                                                    (refreshTree ? "true" : "false"),
                                                                    attachmentInfo + (InsertMode ? "'insert'" : "'update'")));

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
Exemple #40
0
    /// <summary>
    /// Adds GUID field to form definition.
    /// </summary>
    private void CreateGUID()
    {
        bool success;

        try
        {
            if (FormInfo == null)
            {
                return;
            }

            // Create GUID field
            FormFieldInfo ffiGuid = new FormFieldInfo();

            // Fill FormInfo object
            ffiGuid.Name = "ItemGUID";
            ffiGuid.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "GUID");
            ffiGuid.DataType = FieldDataType.Guid;
            ffiGuid.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, string.Empty);
            ffiGuid.SetPropertyValue(FormFieldPropertyEnum.FieldDescription, String.Empty);
            ffiGuid.FieldType = FormFieldControlTypeEnum.CustomUserControl;
            ffiGuid.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLowerCSafe();
            ffiGuid.PrimaryKey = false;
            ffiGuid.System     = true;
            ffiGuid.Visible    = false;
            ffiGuid.Size       = 0;
            ffiGuid.AllowEmpty = false;

            FormInfo.AddFormItem(ffiGuid);

            // Update definition
            dci.ClassFormDefinition = FormInfo.GetXmlDefinition();

            using (CMSActionContext context = new CMSActionContext())
            {
                // Disable logging into event log
                context.LogEvents = false;

                DataClassInfoProvider.SetDataClassInfo(dci);
            }

            // Clear the default queries
            QueryInfoProvider.ClearDefaultQueries(dci, true, false);

            // Clear the object type hashtable
            AbstractProviderDictionary.ReloadDictionaries(className, true);

            // Clear the classes hashtable
            AbstractProviderDictionary.ReloadDictionaries("cms.class", true);

            // Clear class strucures
            ClassStructureInfo.Remove(className, true);

            // Ensure GUIDs for all items
            using (CMSActionContext ctx = new CMSActionContext())
            {
                ctx.UpdateSystemFields = false;
                ctx.LogSynchronization = false;
                DataSet dsItems = CustomTableItemProvider.GetItems(className);
                if (!DataHelper.DataSourceIsEmpty(dsItems))
                {
                    foreach (DataRow dr in dsItems.Tables[0].Rows)
                    {
                        CustomTableItem item = CustomTableItem.New(className, dr);
                        item.ItemGUID = Guid.NewGuid();
                        item.Update();
                    }
                }
            }

            // Log event
            UserInfo currentUser = MembershipContext.AuthenticatedUser;
            EventLogProvider.LogEvent(EventType.INFORMATION, "Custom table", "GENERATEGUID", string.Format(ResHelper.GetAPIString("customtable.GUIDGenerated", "Field 'ItemGUID' for custom table '{0}' was created and GUID values were generated."), dci.ClassName), null, currentUser.UserID, currentUser.UserName);

            success = true;
        }
        catch (Exception ex)
        {
            success = false;

            FieldEditor.ShowError(GetString("customtable.ErrorGUID"));

            // Log event
            EventLogProvider.LogException("Custom table", "GENERATEGUID", ex);
        }

        if (success)
        {
            URLHelper.Redirect(URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "gen", "1"));
        }
    }
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        if ((GraphImageWidth != 0) && (ComputedWidth == 0))
        {
            // Graph width is computed no need to create graph
            return;
        }

        this.Visible = true;

        // Indicaates whether exception was throw during data loading
        bool errorOccurred = false;
        ReportInfo ri = null;

        try
        {
            this.ReportTableName = this.Parameter;

            this.EnsureTableInfo();
            this.EnsureChildControls();

            //Test security
            if (TableInfo != null)
            {
                ri = ReportInfoProvider.GetReportInfo(TableInfo.TableReportID);
                if (ri != null)
                {
                    if (ri.ReportAccess != ReportAccessEnum.All)
                    {
                        if (!CMSContext.CurrentUser.IsAuthenticated())
                        {
                            this.Visible = false;
                            return;
                        }
                    }

                    //Set default parametrs directly if not set
                    if (this.ReportParameters == null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        this.ReportParameters = fi.GetDataRow();
                        fi.LoadDefaultValues(this.ReportParameters);
                    }

                    ApplyTimeParameters();
                }
            }

            // Only use base parameters in case of stored procedure
            if (this.QueryIsStoredProcedure)
            {
                this.AllParameters = SpecialFunctions.ConvertDataRowToParams(this.ReportParameters, null);
            }

            // Load data
            DataSet ds = this.LoadData();

            // If no data load, set empty dataset
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                string noRecordText = ValidationHelper.GetString(TableInfo.TableSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    GridViewObject.Visible = false;
                    lblInfo.Text = noRecordText;
                    lblInfo.Visible = true;
                    return;
                }

                this.Visible = false;
            }
            else
            {
                GridViewObject.Visible = true;
                // Resolve macros in column names
                int i = 0;
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    if (dc.ColumnName == "Column" + ((int)(i + 1)).ToString())
                    {
                        dc.ColumnName = ResolveMacros(ds.Tables[0].Rows[0][i].ToString());
                    }
                    else
                    {
                        dc.ColumnName = ResolveMacros(dc.ColumnName);
                    }
                    i++;
                }

                // Resolve macros in dataset
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        if (dc.DataType.FullName.ToLower() == "system.string")
                        {
                            dr[dc.ColumnName] = ResolveMacros(ValidationHelper.GetString(dr[dc.ColumnName], ""));
                        }
                    }
                }
            }

            ApplyStyles();

            // Databind to gridview control
            GridViewObject.DataSource = ds;
            this.EnsurePageIndex();
            GridViewObject.DataBind();

            if ((TableFirstColumnWidth != Unit.Empty) && (GridViewObject.Rows.Count > 0))
            {
                GridViewObject.Rows[0].Cells[0].Width = TableFirstColumnWidth;
            }

        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportTable.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report table", "E", ex);
            errorOccurred = true;
        }

        // Export data
        if ((ri != null) && (!errorOccurred))
        {
            ProcessExport(ValidationHelper.GetCodeName(ri.ReportDisplayName));
        }
    }
Exemple #42
0
    /// <summary>
    /// Provides operations necessary to create and store new physical file.
    /// </summary>
    private void HandlePhysicalFilesUpload()
    {
        string message = string.Empty;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            // Prepare the file name
            string extension = Path.GetExtension(ucFileUpload.FileName);
            string fileName  = TargetFileName;
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = Path.GetFileName(ucFileUpload.FileName);
            }
            else if (!fileName.Contains("."))
            {
                fileName += extension;
            }

            // Prepare the path
            if (String.IsNullOrEmpty(TargetFolderPath))
            {
                TargetFolderPath = "~/";
            }

            string filePath = TargetFolderPath;

            // Try to map virtual and relative path to server
            try
            {
                if (!Path.IsPathRooted(filePath))
                {
                    filePath = Server.MapPath(filePath);
                }
            }
            catch
            {
            }

            filePath = DirectoryHelper.CombinePath(filePath, fileName);

            // Ensure directory
            DirectoryHelper.EnsureDiskPath(filePath, SystemContext.WebApplicationPhysicalPath);

            // Ensure unique file name
            if (String.IsNullOrEmpty(TargetFileName) && File.Exists(filePath))
            {
                int    index    = 0;
                string basePath = filePath.Substring(0, filePath.Length - extension.Length);
                string newPath  = filePath;

                do
                {
                    index++;
                    newPath = basePath + "_" + index + extension;
                } while (File.Exists(newPath));

                filePath = newPath;
            }

            // Upload file
            if (ImageHelper.IsImage(extension) && ((ResizeToHeight > 0) || (ResizeToWidth > 0) || (ResizeToMaxSideSize > 0)))
            {
                byte[] data = ucFileUpload.FileBytes;

                // Resize the image
                ImageHelper img     = new ImageHelper(data);
                int[]       newSize = ImageHelper.EnsureImageDimensions(ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, img.ImageWidth, img.ImageHeight);
                if ((newSize[0] != img.ImageWidth) || (newSize[1] != img.ImageHeight))
                {
                    data = img.GetResizedImageData(newSize[0], newSize[1]);
                }

                // Write to file
                File.WriteAllBytes(filePath, data);
            }
            else
            {
                File.WriteAllBytes(filePath, ucFileUpload.FileBytes);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadPhysicalFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (!String.IsNullOrEmpty(message))
            {
                afterSaveScript = "setTimeout(\"alert(" + ScriptHelper.GetString(ScriptHelper.GetString(message), false) + ")\", 1);";
            }
            else
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript = String.Format(
                        @"
if (window.{0} != null) {{
    window.{0}(files)
}} else if ((window.parent != null) && (window.parent.{0} != null)) {{
    window.parent.{0}(files) 
}}
",
                        AfterSaveJavascript
                        );
                }
                else
                {
                    afterSaveScript += "if ((window.parent != null) && (/parentelemid=" + ParentElemID + "/i.test(window.location.href)) && (window.parent.InitRefresh_" + ParentElemID + " != null)){window.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false);}";
                }
            }

            afterSaveScript = ScriptHelper.GetScript(afterSaveScript);

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string result = new Validator().NotEmpty(rfvDisplayName, rfvDisplayName.ErrorMessage).NotEmpty(rfvCodeName, rfvCodeName.ErrorMessage).NotEmpty(rfvURL, rfvURL.ErrorMessage)
            .IsCodeName(txtCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        // Get the object
        WebFarmServerInfo wi = WebFarmServerInfoProvider.GetWebFarmServerInfo(serverid) ?? new WebFarmServerInfo();

        // Check license web farm server limit
        if (String.IsNullOrEmpty(result))
        {
            LicenseKeyInfo lki = LicenseHelper.CurrentLicenseInfo;
            if (lki == null)
            {
                return;
            }

            // Only if server is enabled
            if (chkEnabled.Checked)
            {
                // Enabling or new server as action insert
                VersionActionEnum action = ((wi.ServerID > 0) && wi.ServerEnabled) ? VersionActionEnum.Edit : VersionActionEnum.Insert;
                if (!lki.CheckServerCount(WebSyncHelperClass.ServerCount, action))
                {
                    result = GetString("licenselimitation.infopagemessage");
                }

                // Log the message
                if (!String.IsNullOrEmpty(result))
                {
                    EventLogProvider eventLog = new EventLogProvider();
                    string message = GetString("licenselimitation.serversexceeded");
                    eventLog.LogEvent(EventLogProvider.EVENT_TYPE_WARNING, DateTime.Now, "WebFarms", LicenseHelper.LICENSE_LIMITATION_EVENTCODE, URLHelper.CurrentURL, message);
                }
            }
        }

        if (result == "")
        {
            wi.ServerID = serverid;
            wi.ServerDisplayName = txtDisplayName.Text;
            wi.ServerName = txtCodeName.Text;
            wi.ServerURL = txtURL.Text;
            wi.ServerEnabled = chkEnabled.Checked;
            try
            {
                WebFarmServerInfoProvider.SetWebFarmServerInfo(wi);
                // Clear server list
                URLHelper.Redirect("WebFarm_Server_Edit.aspx?serverid=" + wi.ServerID + "&saved=1");
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.Replace("%%name%%", wi.ServerName);
                lblError.Visible = true;
                lblInfo.Visible = false;
            }
        }
        else
        {
            lblError.Text = result;
            lblError.Visible = true;
            lblInfo.Visible = false;
        }
    }
Exemple #44
0
    private void HandleMetaFileUpload()
    {
        string       message = string.Empty;
        MetaFileInfo mfi     = null;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            if (InsertMode)
            {
                // Create new meta file
                mfi = new MetaFileInfo(FileUploadControl.PostedFile, ObjectID, ObjectType, Category);
                mfi.MetaFileSiteID = SiteID;
            }
            else
            {
                if (MetaFileID > 0)
                {
                    mfi = MetaFileInfoProvider.GetMetaFileInfo(MetaFileID);
                }
                else
                {
                    DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(ObjectID, ObjectType, Category, null, null);
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        mfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                    }
                }

                if (mfi != null)
                {
                    string fileExt = Path.GetExtension(FileUploadControl.FileName);
                    // Init the MetaFile data
                    mfi.MetaFileName      = URLHelper.GetSafeFileName(FileUploadControl.FileName, null);
                    mfi.MetaFileExtension = fileExt;

                    mfi.MetaFileSize     = Convert.ToInt32(FileUploadControl.PostedFile.InputStream.Length);
                    mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(fileExt);
                    mfi.InputStream      = FileUploadControl.PostedFile.InputStream;

                    // Set image properties
                    if (ImageHelper.IsImage(mfi.MetaFileExtension))
                    {
                        // Make MetaFile binary load from InputStream
                        mfi.MetaFileBinary = null;
                        ImageHelper ih = new ImageHelper(mfi.MetaFileBinary);
                        mfi.MetaFileImageHeight = ih.ImageHeight;
                        mfi.MetaFileImageWidth  = ih.ImageWidth;
                    }
                }
            }

            if (mfi != null)
            {
                // Save file to the database
                MetaFileInfoProvider.SetMetaFileInfo(mfi);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadMetaFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (String.IsNullOrEmpty(message))
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript = String.Format(
                        @"
if (window.{0} != null) {{
    window.{0}(files)
}} else if ((window.parent != null) && (window.parent.{0} != null)) {{
    window.parent.{0}(files) 
}}
",
                        AfterSaveJavascript
                        );
                }
                else
                {
                    afterSaveScript = String.Format(@"
                        if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0}))
                        {{
                            window.parent.InitRefresh_{0}('{1}', false, false, {2});
                        }}
                        else {{ 
                            if ('{1}' != '') {{
                                alert('{1}');
                            }}
                        }}", ParentElemID, ScriptHelper.GetString(message.Trim(), false), mfi.MetaFileID.ToString() + (InsertMode ? ",'insert'" : ",'update'"));
                }
            }
            else
            {
                afterSaveScript += ScriptHelper.GetAlertScript(message, false);
            }

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript, true);
        }
    }
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        try
        {
            // Load value info object
            ReportValueInfo rvi = ValueInfo;

            if (rvi != null)
            {
                //Test security
                ReportInfo ri = ReportInfoProvider.GetReportInfo(rvi.ValueReportID);
                if (ri.ReportAccess != ReportAccessEnum.All)
                {
                    if (!CMSContext.CurrentUser.IsAuthenticated())
                    {
                        this.Visible = false;
                        return;
                    }
                }

                ContextResolver resolver = CMSContext.CurrentResolver;
                // Resolve dynamic data macros
                if (DynamicMacros != null)
                {
                    for (int i = 0; i <= this.DynamicMacros.GetUpperBound(0); i++)
                    {
                        resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                    }
                }

                this.QueryIsStoredProcedure = rvi.ValueQueryIsStoredProcedure;
                this.QueryText = resolver.ResolveMacros(rvi.ValueQuery);

                //Set default parametrs directly if not set
                if (this.ReportParameters == null)
                {
                    if (ri != null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        this.ReportParameters = fi.GetDataRow();
                        fi.LoadDefaultValues(this.ReportParameters);
                    }
                }
            }

            // Only use base parameters in case of stored procedure
            if (this.QueryIsStoredProcedure)
            {
                this.AllParameters = SpecialFunctions.ConvertDataRowToParams(this.ReportParameters, null);
            }

            // Load data
            DataSet ds = this.LoadData();

            // If datasource is emptry, create empty dataset
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                // Set literal text
                string value = rvi.ValueFormatString;
                if ((value == null) || (value == ""))
                {
                    value = ValidationHelper.GetString(ds.Tables[0].Rows[0][0], "");
                }
                else
                {
                    value = string.Format(value, ds.Tables[0].Rows[0].ItemArray);
                }

                lblValue.Text = HTMLHelper.HTMLEncode(ResolveMacros(value));
            }
        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportValue.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report value", "E", ex);
        }
    }
    private void LbSubmit_Click(object sender, EventArgs e)
    {
        if (this.Page.IsValid)
        {
            int userId = GetResetRequestID();

            // Check if password expired
            if (pwdExp > 0)
            {
                UserInfo ui = UserInfoProvider.GetUserInfo(userId);
                if (!UserInfoProvider.IsUserPasswordDifferent(ui, txtNewPassword.Text))
                {
                    ShowError(GetString("passreset.newpasswordrequired"));
                    return;
                }
            }

            // Get e-mail address of sender
            string emailFrom = DataHelper.GetNotEmpty(SendEmailFrom, SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSSendPasswordEmailsFrom"));
            // Try to reset password and show result to user
            bool   success;
            string resultText = AuthenticationHelper.ResetPassword(hash, time, userId, interval, txtNewPassword.Text, "Reset password control", emailFrom, siteName, null, out success, InvalidRequestText, ExceededIntervalText);

            if (success)
            {
                try
                {
                    var userInfo = UserInfoProvider.GetFullUserInfo(userId);

                    var userName = userInfo.UserName;

                    var result = ssoClient.SSOCustomerUpdatePasswordByUserName(PersonifyVendorName, PersonifyVendorPassword, userName, txtNewPassword.Text);

                    if (!result.Result)
                    {
                        success = false;

                        if (result.Errors != null && result.Errors.Any())
                        {
                            resultText = result.Errors.First();
                        }
                        else
                        {
                            resultText = "Unknown SSO Error Updating Password.";
                        }

                        EventLogProvider.LogEvent(EventType.WARNING, "CMSWebParts_Personify_ChangePassword", resultText,
                                                  eventDescription: string.Format("Failed to update user credentials in personify SSO with username: {0}", userName),
                                                  userId: userId,
                                                  userName: userName,
                                                  siteId: SiteContext.CurrentSiteID,
                                                  eventTime: DateTime.Now);
                    }
                }
                catch (Exception ex)
                {
                    success    = false;
                    resultText = "Program Error Updating SSO Password";
                    EventLogProvider.LogException("CMSWebParts_Personify_ChangePassword", resultText, ex);
                }
            }

            // If password reset was successful
            if (success)
            {
                ClearResetRequestID();

                // Redirect to specified URL
                if (!string.IsNullOrEmpty(RedirectUrl))
                {
                    URLHelper.Redirect(RedirectUrl);
                }

                // Get proper text
                ShowConfirmation(DataHelper.GetNotEmpty(SuccessText, resultText));
                pnlReset.Visible = false;
            }
            else
            {
                ShowError(resultText);
            }
        }
    }
    public void RaisePostBackEvent(string eventArgument)
    {
        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        // Current Node ID
        int nodeId = ValidationHelper.GetInteger(Param1, 0);

        TreeProvider tree = new TreeProvider(currentUser);
        EventLogProvider log = new EventLogProvider();

        string documentName = string.Empty;
        string action = Action.ToLower();
        string siteName = CMSContext.CurrentSiteName;

        // Process the request
        switch (action)
        {
            case "refresh":
                treeContent.NodeID = nodeId;
                AddScript("currentNodeId = " + nodeId + ";\n");

                break;

            case "moveup":
            case "movedown":
            case "movetop":
            case "movebottom":
                // Move the document up (document order)
                try
                {
                    if (nodeId == 0)
                    {
                        AddAlert(GetString("ContentRequest.ErrorMissingSource"));
                        return;
                    }

                    // Get document to move
                    TreeNode node = tree.SelectSingleNode(nodeId);

                    // Check the permissions for document
                    if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)
                    {
                        switch (action)
                        {
                            case "moveup":
                                node = tree.MoveNodeUp(nodeId);
                                break;

                            case "movedown":
                                node = tree.MoveNodeDown(nodeId);
                                break;

                            case "movetop":
                                node = tree.SelectSingleNode(nodeId);
                                tree.SetNodeOrder(nodeId, DocumentOrderEnum.First);
                                break;

                            case "movebottom":
                                node = tree.SelectSingleNode(nodeId);
                                tree.SetNodeOrder(nodeId, DocumentOrderEnum.Last);
                                break;
                        }

                        if (node != null)
                        {
                            // Log the synchronization tasks for the entire tree level
                            if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges"))
                            {
                                // Log the synchronization tasks for the entire tree level
                                DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, node.NodeAliasPath, tree);
                            }

                            // Select the document in the tree
                            documentName = node.DocumentName;

                            treeContent.ExpandNodeID = node.NodeParentID;
                            treeContent.NodeID = node.NodeID;
                            AddScript("currentNodeId = " + node.NodeID + ";\n");
                        }
                        else
                        {
                            AddAlert(GetString("ContentRequest.MoveFailed"));
                        }
                    }
                    else
                    {
                        // Select the document in the tree
                        treeContent.NodeID = nodeId;

                        AddAlert(GetString("ContentRequest.MoveDenied"));
                    }
                }
                catch (Exception ex)
                {
                    log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "MOVE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.GetUserHostAddress(), EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
                    AddAlert(GetString("ContentRequest.MoveFailed") + " : " + ex.Message);
                }
                break;

            case "setculture":
                // Set the preferred culture code
                try
                {
                    // Set the culture code
                    string language = ValidationHelper.GetString(Param2, "");
                    if (!string.IsNullOrEmpty(language))
                    {
                        CMSContext.PreferredCultureCode = language;
                    }

                    // Refresh the document
                    if (nodeId > 0)
                    {
                        treeContent.NodeID = nodeId;

                        AddScript("SelectNode(" + nodeId + "); \n");
                    }
                }
                catch (Exception ex)
                {
                    log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "SETCULTURE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.GetUserHostAddress(), EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
                    AddAlert(GetString("ContentRequest.ErrorChangeLanguage"));
                }
                break;

            // Sorting
            case "sortalphaasc":
            case "sortalphadesc":
            case "sortdateasc":
            case "sortdatedesc":
                // Set the preferred culture code
                try
                {
                    // Get document to sort
                    TreeNode node = tree.SelectSingleNode(nodeId);

                    // Check the permissions for document
                    if ((currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)
                        && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed))
                    {
                        switch (action)
                        {
                            case "sortalphaasc":
                                tree.OrderNodesAlphabetically(nodeId, true);
                                break;

                            case "sortalphadesc":
                                tree.OrderNodesAlphabetically(nodeId, false);
                                break;

                            case "sortdateasc":
                                tree.OrderNodesByDate(nodeId, true);
                                break;

                            case "sortdatedesc":
                                tree.OrderNodesByDate(nodeId, false);
                                break;
                        }

                        // Log the synchronization tasks for the entire tree level
                        if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges"))
                        {
                            // Log the synchronization tasks for the entire tree level
                            string fakeAlias = node.NodeAliasPath.TrimEnd('/') + "/child";
                            DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, fakeAlias, tree);
                        }
                    }
                    else
                    {
                        AddAlert(GetString("ContentRequest.SortDenied"));
                    }

                    // Refresh the tree
                    if (nodeId > 0)
                    {
                        treeContent.ExpandNodeID = nodeId;
                        treeContent.NodeID = nodeId;
                        AddScript("SelectNode(" + nodeId + "); \n");
                    }
                }
                catch (Exception ex)
                {
                    log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "SORT", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.GetUserHostAddress(), EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
                    AddAlert(GetString("ContentRequest.ErrorSort"));
                }
                break;
        }

        // Maintain scrollbar position
        string script =
        @"var elm = jQuery('#handle_" + nodeId + @"');
          var pnl = jQuery('#" + pnlTreeArea.ClientID + @"');
          var origScroll = " + ScrollPosition + @";
          var elmOff = elm.offset();
          var elmPos = (elmOff == null) ? 0 : elmOff.top;
          var scroll = ((elmPos < origScroll) || (elmPos > (origScroll + pnl.height())));
          pnl.scrollTop(origScroll);
          if(scroll){pnl.animate({ scrollTop: elmPos - 20 }, 300);};";

        ScriptHelper.RegisterStartupScript(Page, typeof(string), "MaintainScrollbar", script, true);
    }
 private void HandleError(Exception exception)
 {
     ErrorControl.Report(exception);
     EventLogProvider.LogException("Facebook integration", "MappingFormControl", exception);
 }
    protected void ctrlImport_OnFinished(object sender, EventArgs e)
    {
        try
        {
            // Convert default culture
            if (!siteType.SelectTemplate)
            {
                TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                tree.ChangeSiteDefaultCulture(SiteName, Culture, "en-US");

                // Change root GUID
                TreeNode root = DocumentHelper.GetDocument(SiteName, "/", Culture, false, "cms.root", null, null, 1, false, null, tree);
                if (root != null)
                {
                    root.NodeGUID = Guid.NewGuid();
                    DocumentHelper.UpdateDocument(root, tree);
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("NewSiteWizard", "FINISH", ex);
        }
        finally
        {
            if (ImportManager.Settings.ProcessCanceled)
            {
                NextButton.Enabled = CancelButton.Enabled = false;
                mImportCanceled = true;
                lblProgress.Text = "<strong>" + ResHelper.GetAPIString("ImportSite.ImportCanceled", "Import process has been cancelled.") + "</strong>";
            }
            else
            {
                if (!ImportManager.Settings.IsWarning() && !ImportManager.Settings.IsError())
                {
                    PreviousButton.Visible = false;
                    CultureHelper.SetPreferredCulture(Culture);
                    if (siteType.SelectTemplate)
                    {
                        // Done
                        finishSite.Domain = Domain;
                        wzdImport.ActiveStepIndex = 7;
                    }
                    else
                    {
                        selectMaster.SiteName = SiteName;
                        wzdImport.ActiveStepIndex += 1;
                        selectMaster.ReloadData();
                    }
                }
            }

            // Stop the timer
            string script = "StopSelectionTimer();";
            ltlScriptAfter.Text += ScriptHelper.GetScript(script);
        }
    }
Exemple #50
0
    /// <summary>
    /// Save selected field.
    /// </summary>
    private void SaveSelectedField()
    {
        // FormFieldInfo structure with data from updated form
        FormFieldInfo ffiUpdated = null;
        // FormCategoryInfo structure with data from updated form
        FormCategoryInfo fciUpdated = null;
        // Determines whether it is a new attribute (or attribute to update)
        bool isNewItem = false;
        string errorMessage = null;
        DataClassInfo dci = null;
        WebPartInfo wpi = null;

        // Variables for changes in DB tables
        string tableName = null;
        string oldColumnName = null;
        string newColumnName = null;
        string newColumnSize = null;
        string newColumnType = null;
        string newColumnDefaultValue = null;  // No default value
        bool newColumnAllowNull = true;

        if (!IsAlternativeForm)
        {
            switch (mMode)
            {
                case FieldEditorModeEnum.WebPartProperties:
                    // Fill WebPartInfo structure with data from database
                    wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId);
                    break;

                case FieldEditorModeEnum.ClassFormDefinition:
                case FieldEditorModeEnum.BizFormDefinition:
                case FieldEditorModeEnum.SystemTable:
                case FieldEditorModeEnum.CustomTable:
                    // Fill ClassInfo structure with data from database
                    dci = DataClassInfoProvider.GetDataClass(mClassName);
                    if (dci != null)
                    {
                        // Set table name
                        tableName = dci.ClassTableName;
                    }
                    else
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "fieldeditor.notablename";
                        return;
                    }
                    break;
            }
        }

        // Load current xml form definition
        LoadFormDefinition();

        if (SelectedItemType == FieldEditorSelectedItemEnum.Field)
        {
            // Fill FormFieldInfo structure with original data
            ffi = fi.GetFormField(SelectedItemName);

            // Fill FormFieldInfo structure with updated form data
            ffiUpdated = FillFormFieldInfoStructure(ffi);

            // Determine whether it is a new attribute or not
            isNewItem = (ffi == null);

            // Check if the attribute name already exists
            if (isNewItem || (ffi.Name.ToLower() != ffiUpdated.Name.ToLower()))
            {
                columnNames = fi.GetColumnNames();

                if (columnNames != null)
                {
                    foreach (string colName in columnNames)
                    {
                        // If name already exists
                        if (ffiUpdated.Name.ToLower() == colName.ToLower())
                        {
                            lblError.Visible = true;
                            lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnName";
                            return;
                        }
                    }
                }

                // Check column name duplicity in JOINed tables
                if (!IsSystemFieldSelected)
                {
                    // Check whether current column already exists in 'View_CMS_Tree_Joined'
                    if (IsDocumentType && DocumentHelper.ColumnExistsInSystemTable(ffiUpdated.Name))
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnInJoinedTable";
                        return;
                    }

                    // Check whether current column is uniquie in tables used to create views - applied only for system tables
                    if ((Mode == FieldEditorModeEnum.SystemTable) && FormHelper.ColumnExistsInView(mClassName, ffiUpdated.Name))
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnInJoinedTable";
                        return;
                    }
                }
            }

            // New node
            if (isNewItem)
            {
                ffiUpdated.PrimaryKey = this.IsPrimaryField;
                newColumnName = ffiUpdated.Name;
                newColumnAllowNull = ffiUpdated.AllowEmpty;

                // Set implicit default value
                if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue)))
                {
                    if (!this.DevelopmentMode)
                    {
                        switch (ffiUpdated.DataType)
                        {
                            case FormFieldDataTypeEnum.Integer:
                            case FormFieldDataTypeEnum.LongInteger:
                            case FormFieldDataTypeEnum.Decimal:
                            case FormFieldDataTypeEnum.Boolean:
                                newColumnDefaultValue = "0";
                                break;

                            case FormFieldDataTypeEnum.Text:
                            case FormFieldDataTypeEnum.LongText:
                            case FormFieldDataTypeEnum.DocumentAttachments:
                                newColumnDefaultValue = "";
                                break;

                            case FormFieldDataTypeEnum.DateTime:
                                newColumnDefaultValue = new DateTime(1970, 1, 1, 0, 0, 0).ToString();
                                break;

                            case FormFieldDataTypeEnum.File:
                            case FormFieldDataTypeEnum.GUID:
                                // 32 digits, empty Guid
                                newColumnDefaultValue = Guid.Empty.ToString();
                                break;

                            case FormFieldDataTypeEnum.Binary:
                                newColumnDefaultValue = null;
                                break;
                        }
                    }
                }
                // Check if default value is in required format
                else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue))
                {
                    // If default value is macro, don't try to ensure the type
                    if (!ffiUpdated.IsMacro)
                    {
                        switch (ffiUpdated.DataType)
                        {
                            case FormFieldDataTypeEnum.Integer:
                                try
                                {
                                    int i = Int32.Parse(ffiUpdated.DefaultValue);
                                    newColumnDefaultValue = i.ToString();
                                }
                                catch
                                {
                                    newColumnDefaultValue = "0";
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger");
                                }
                                break;

                            case FormFieldDataTypeEnum.LongInteger:
                                try
                                {
                                    long longInt = long.Parse(ffiUpdated.DefaultValue);
                                    newColumnDefaultValue = longInt.ToString();
                                }
                                catch
                                {
                                    newColumnDefaultValue = "0";
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger");
                                }
                                break;

                            case FormFieldDataTypeEnum.Decimal:
                                if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue))
                                {
                                    newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue);
                                }
                                else
                                {
                                    newColumnDefaultValue = "0";
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble");
                                }
                                break;

                            case FormFieldDataTypeEnum.DateTime:
                                if ((ffiUpdated.DefaultValue.ToLower() == DateTimePicker.DATE_TODAY.ToLower()) || (ffiUpdated.DefaultValue.ToLower() == DateTimePicker.TIME_NOW.ToLower()))
                                {
                                    newColumnDefaultValue = ffiUpdated.DefaultValue;
                                }
                                else
                                {
                                    try
                                    {
                                        DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = dat.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = DateTime.Now.ToString();
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime");
                                    }
                                }
                                break;

                            case FormFieldDataTypeEnum.File:
                            case FormFieldDataTypeEnum.GUID:
                                try
                                {
                                    Guid g = new Guid(ffiUpdated.DefaultValue);
                                    newColumnDefaultValue = g.ToString();
                                }
                                catch
                                {
                                    newColumnDefaultValue = Guid.Empty.ToString();
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid");
                                }
                                break;

                            case FormFieldDataTypeEnum.LongText:
                            case FormFieldDataTypeEnum.Text:
                            case FormFieldDataTypeEnum.Boolean:

                                newColumnDefaultValue = ffiUpdated.DefaultValue;
                                break;
                        }
                    }
                }

                // Set column type and size
                LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize);

                if (string.IsNullOrEmpty(errorMessage))
                {
                    if (!IsAlternativeForm)
                    {
                        switch (mMode)
                        {
                            case FieldEditorModeEnum.ClassFormDefinition:
                            case FieldEditorModeEnum.BizFormDefinition:
                            case FieldEditorModeEnum.SystemTable:
                            case FieldEditorModeEnum.CustomTable:

                                // Add new column to specified table
                                try
                                {
                                    string newDBDefaultValue = null;

                                    // Check if it is not a macro
                                    if (ffiUpdated.IsMacro)
                                    {
                                        newDBDefaultValue = newColumnDefaultValue;
                                    }
                                    else
                                    {
                                        switch (ffiUpdated.DataType)
                                        {
                                            case FormFieldDataTypeEnum.Decimal:
                                                newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue);
                                                break;

                                            case FormFieldDataTypeEnum.DateTime:
                                                newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue);
                                                break;
                                            default:
                                                newDBDefaultValue = newColumnDefaultValue;
                                                break;
                                        }
                                    }

                                    if (!ffiUpdated.External)
                                    {
                                        if (this.DevelopmentMode)
                                        {
                                            TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue, false);
                                        }
                                        else
                                        {
                                            TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue);
                                        }

                                        // Recreate the table PK constraint
                                        if (IsPrimaryField)
                                        {
                                            int pos = 0;
                                            FormFieldInfo[] pkFields = fi.GetFields(true, true, false, true);
                                            string[] primaryKeys = new string[pkFields.Length + 1];
                                            foreach (FormFieldInfo pk in pkFields)
                                            {
                                                if (pk != null)
                                                {
                                                    primaryKeys[pos++] = "[" + pk.Name + "]";
                                                }
                                            }
                                            primaryKeys[pos] = "[" + newColumnName + "]";
                                            TableManager.RecreatePKConstraint(tableName, primaryKeys, null);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lblError.Visible = true;
                                    lblError.Text = ex.Message;
                                    return;
                                }

                                break;
                        }
                    }
                }
                // Some error has occurred
                else
                {
                    lblError.Visible = true;
                    lblError.Text = errorMessage;
                    return;
                }
            }
            // Existing node
            else
            {
                // Get info whether it is a primary key or system fild
                ffiUpdated.PrimaryKey = ffi.PrimaryKey;

                // If attribute is a primary key
                if (ffi.PrimaryKey)
                {
                    // Check if the attribute type is integer number
                    if (ffiUpdated.DataType != FormFieldDataTypeEnum.Integer)
                    {
                        errorMessage += GetString("TemplateDesigner.ErrorPKNotInteger") + " ";
                    }

                    // Check if allow empty is disabled
                    if (ffiUpdated.AllowEmpty)
                    {
                        errorMessage += GetString("TemplateDesigner.ErrorPKAllowsNulls") + " ";
                    }

                    // Check that the field type is label
                    string labelControlName = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLower();
                    if ((ffiUpdated.FieldType != FormFieldControlTypeEnum.LabelControl) && ((ffiUpdated.FieldType != FormFieldControlTypeEnum.CustomUserControl) && (ffiUpdated.Settings["controlname"].ToString().ToLower() != labelControlName)))
                    {
                        errorMessage += GetString("TemplateDesigner.ErrorPKisNotLabel") + " ";
                    }

                    // Some error has occurred
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        lblError.Visible = true;
                        lblError.Text = GetString("TemplateDesigner.ErrorPKThisIsPK") + " " + errorMessage;
                        return;
                    }
                }

                // If table column update is needed
                if (((ffi.PrimaryKey) && (ffi.Name != ffiUpdated.Name)) ||
                     ((!ffi.PrimaryKey) &&
                        ((ffi.Name != ffiUpdated.Name) ||
                         (ffi.DataType != ffiUpdated.DataType) ||
                         (ffi.AllowEmpty != ffiUpdated.AllowEmpty) ||
                         (ffi.Size != ffiUpdated.Size) ||
                         ((ffi.DefaultValue != ffiUpdated.DefaultValue) || (ffiUpdated.DataType == FormFieldDataTypeEnum.Decimal)))
                     )
                   )
                {
                    // Set variables needed for changes in DB
                    oldColumnName = ffi.Name;
                    newColumnName = ffiUpdated.Name;
                    newColumnAllowNull = ffiUpdated.AllowEmpty;

                    // Set implicit default value
                    if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue)))
                    {
                        switch (ffiUpdated.DataType)
                        {
                            case FormFieldDataTypeEnum.Integer:
                            case FormFieldDataTypeEnum.LongInteger:
                            case FormFieldDataTypeEnum.Decimal:
                            case FormFieldDataTypeEnum.Boolean:
                                newColumnDefaultValue = "0";
                                break;

                            case FormFieldDataTypeEnum.Text:
                            case FormFieldDataTypeEnum.LongText:
                                newColumnDefaultValue = "";
                                break;

                            case FormFieldDataTypeEnum.DateTime:
                                newColumnDefaultValue = DateTime.Now.ToString();
                                break;

                            case FormFieldDataTypeEnum.File:
                            case FormFieldDataTypeEnum.GUID:
                                // 32 digits, empty Guid
                                newColumnDefaultValue = Guid.Empty.ToString();
                                break;

                            case FormFieldDataTypeEnum.Binary:
                                newColumnDefaultValue = null;
                                break;
                        }
                    }

                    // Check if default value is in required format
                    else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue))
                    {
                        // If default value is macro, don't try to ensure the type
                        if (!ffiUpdated.IsMacro)
                        {
                            switch (ffiUpdated.DataType)
                            {
                                case FormFieldDataTypeEnum.Integer:
                                    try
                                    {
                                        int i = Int32.Parse(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = i.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = "0";
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.LongInteger:
                                    try
                                    {
                                        long longInt = long.Parse(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = longInt.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = "0";
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.Decimal:
                                    if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue))
                                    {
                                        newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue);
                                    }
                                    else
                                    {
                                        newColumnDefaultValue = "0";
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.DateTime:
                                    if ((ffiUpdated.DefaultValue.ToLower() == DateTimePicker.DATE_TODAY.ToLower()) || (ffiUpdated.DefaultValue.ToLower() == DateTimePicker.TIME_NOW.ToLower()))
                                    {
                                        newColumnDefaultValue = ffiUpdated.DefaultValue;
                                    }
                                    else
                                    {
                                        try
                                        {
                                            DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue);
                                            newColumnDefaultValue = dat.ToString();
                                        }
                                        catch
                                        {
                                            newColumnDefaultValue = DateTime.Now.ToString();
                                            errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime");
                                        }
                                    }
                                    break;

                                case FormFieldDataTypeEnum.File:
                                case FormFieldDataTypeEnum.GUID:
                                    try
                                    {
                                        Guid g = new Guid(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = g.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = Guid.Empty.ToString();
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.LongText:
                                case FormFieldDataTypeEnum.Text:
                                case FormFieldDataTypeEnum.Boolean:

                                    newColumnDefaultValue = ffiUpdated.DefaultValue;
                                    break;
                            }
                        }
                    }

                    // Set column type and size
                    LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize);

                    if (string.IsNullOrEmpty(errorMessage))
                    {
                        if (!IsAlternativeForm)
                        {
                            switch (mMode)
                            {
                                case FieldEditorModeEnum.ClassFormDefinition:
                                case FieldEditorModeEnum.BizFormDefinition:
                                case FieldEditorModeEnum.SystemTable:
                                case FieldEditorModeEnum.CustomTable:

                                    try
                                    {
                                        string newDBDefaultValue = null;

                                        // Check if it is not a macro
                                        if (ffiUpdated.IsMacro)
                                        {
                                            newDBDefaultValue = newColumnDefaultValue;
                                        }
                                        else
                                        {
                                            switch (ffiUpdated.DataType)
                                            {
                                                case FormFieldDataTypeEnum.Decimal:
                                                    newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue);
                                                    break;

                                                case FormFieldDataTypeEnum.DateTime:
                                                    newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue);
                                                    break;
                                                default:
                                                    newDBDefaultValue = newColumnDefaultValue;
                                                    break;
                                            }
                                        }

                                        if (ffiUpdated.External)
                                        {
                                            if (!ffi.External)
                                            {
                                                // Drop old column from table
                                                TableManager.DropTableColumn(tableName, ffi.Name);
                                            }
                                        }
                                        else
                                        {
                                            if (ffi.External)
                                            {
                                                // Add table column
                                                TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue);
                                            }
                                            else
                                            {
                                                // Change table column
                                                TableManager.AlterTableColumn(tableName, oldColumnName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue);
                                                if (OnFieldNameChanged != null)
                                                {
                                                    OnFieldNameChanged(this, oldColumnName, newColumnName);
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        // User friendly message for not null setting of column
                                        if (ffi.AllowEmpty && !newColumnAllowNull)
                                        {
                                            lblError.Visible = true;
                                            lblError.ResourceString = "FieldEditor.ColumnNotAcceptNull";
                                            lblError.ToolTip = ex.Message;
                                        }
                                        else
                                        {
                                            lblError.Visible = true;
                                            lblError.Text = ex.Message;
                                        }
                                        return;
                                    }

                                    break;
                            }
                        }
                    }
                    // Some error has occurred
                    else
                    {
                        lblError.Visible = true;
                        lblError.Text = errorMessage;
                        return;
                    }
                } // End update needed
            } // End existing node

            // Insert new field
            if (isNewItem)
            {
                InsertFormItem(ffiUpdated);
            }
            // Update current field
            else
            {
                fi.UpdateFormField(ffi.Name, ffiUpdated);
            }
        }
        else if (SelectedItemType == FieldEditorSelectedItemEnum.Category)
        {
            // Fill FormCategoryInfo structure with original data
            fci = fi.GetFormCategory(SelectedItemName);
            // Determine whether it is a new attribute or not
            isNewItem = (fci == null);

            // Fill FormCategoryInfo structure with updated form data
            fciUpdated = new FormCategoryInfo();
            fciUpdated.CategoryCaption = categoryEdit.Value.Replace("'", "");

            // Check if the category caption is empty
            if (string.IsNullOrEmpty(fciUpdated.CategoryCaption))
            {
                lblError.Visible = true;
                lblError.ResourceString = "TemplateDesigner.ErrorCategoryNameEmpty";
                return;
            }

            if (isNewItem)
            {
                // Use category caption for name attribut
                fciUpdated.CategoryName = fciUpdated.CategoryCaption;
            }
            else
            {
                fciUpdated.CategoryName = SelectedItemName;
            }

            if (isNewItem)
            {
                // Get form category names
                string[] categoryNames = fi.GetCategoryNames();

                if (categoryNames != null)
                {
                    // Check if the category name is unique
                    foreach (string name in categoryNames)
                    {
                        // If name already exists return error
                        if (fciUpdated.CategoryName == name)
                        {
                            lblError.Visible = true;
                            lblError.ResourceString = "TemplateDesigner.ErrorExistingCategoryName";
                            return;
                        }
                    }
                }

                // Insert new category
                InsertFormItem(fciUpdated);
            }
            else
            {
                // Update current
                fi.UpdateFormCategory(fci.CategoryName, fciUpdated);
            }
        }

        // Make changes in database
        if (SelectedItemType != 0)
        {
            // Get updated definition
            FormDefinition = fi.GetXmlDefinition();

            string error = null;

            if (!IsAlternativeForm)
            {
                switch (mMode)
                {
                    case FieldEditorModeEnum.WebPartProperties:
                        if (wpi != null)
                        {
                            // Update xml definition
                            wpi.WebPartProperties = FormDefinition;

                            try
                            {
                                WebPartInfoProvider.SetWebPartInfo(wpi);
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                            }
                        }
                        else
                        {
                            error = GetString("FieldEditor.WebpartNotFound");
                        }
                        break;

                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:
                        if (dci != null)
                        {
                            // Update xml definition
                            dci.ClassFormDefinition = FormDefinition;

                            // Update xml schema
                            dci.ClassXmlSchema = TableManager.GetXmlSchema(dci.ClassTableName);

                            // When updating existing field
                            if (ffi != null)
                            {
                                // Update ClassNodeNameSource field
                                if (dci.ClassNodeNameSource == ffi.Name)
                                {
                                    dci.ClassNodeNameSource = ffiUpdated.Name;
                                }
                            }

                            bool fieldType = (SelectedItemType == FieldEditorSelectedItemEnum.Field);

                            // Update changes in DB
                            try
                            {
                                // Save the data class
                                DataClassInfoProvider.SetDataClass(dci);

                                // Generate the class code
                                GenerateCode();

                                // Update inherited classes with new fields
                                FormHelper.UpdateInheritedClasses(dci);
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                            }

                            if (fieldType)
                            {
                                // Generate default view
                                if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                {
                                    SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName);
                                }
                                else
                                {
                                    SqlGenerator.GenerateDefaultView(dci, null);
                                }

                                // Regenerate queries
                                SqlGenerator.GenerateDefaultQueries(dci, true, true);
                            }

                            // Updates custom views
                            if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition))
                            {
                                try
                                {
                                    TableManager.RefreshCustomViews(dci.ClassTableName);

                                    string lowClassName = dci.ClassName.ToLower();
                                    if (lowClassName == "cms.document" || lowClassName == "cms.tree")
                                    {
                                        TableManager.RefreshDocumentViews();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    error = ResHelper.GetString("fieldeditor.refreshingviewsfailed");
                                    EventLogProvider ev = new EventLogProvider();
                                    ev.LogEvent("Field Editor", "EXCEPTION", ex);
                                }
                            }
                        }
                        else
                        {
                            error = GetString("FieldEditor.ClassNotFound");
                        }
                        break;
                }
            }

            if (!string.IsNullOrEmpty(error))
            {
                lblError.Visible = true;
                lblError.Text = "[FieldEditor.SaveSelectedField()]: " + error;
            }
            else
            {
                IsNewItemEdited = false;

                if (SelectedItemType == FieldEditorSelectedItemEnum.Category)
                {
                    Reload(categPreffix + fciUpdated.CategoryName);
                }
                else if (SelectedItemType == FieldEditorSelectedItemEnum.Field)
                {
                    Reload(fieldPreffix + ffiUpdated.Name);
                }

                lblError.Visible = false;
                lblInfo.Visible = true;
                lblInfo.ResourceString = "general.changessaved";
            }
        }

        // All done and new item, fire OnFieldCreated  event
        if (isNewItem && (ffiUpdated != null))
        {
            RaiseOnFieldCreated(ffiUpdated);
        }
    }
    public static void Update60()
    {
        EventLogProvider evp = new EventLogProvider();
        evp.LogEvent("I", DateTime.Now, "Upgrade to 6.0", "Upgrade - Start");

        DataClassInfo dci = null;

        #region "CMS.UserSettings"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("cms.usersettings");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "UserAuthenticationGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserBounces";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl;
                    ffi.Visible = false;
                    ffi.Caption = "UserBounces";

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserLinkedInID";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserLogActivities";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserPasswordRequestHash";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("CMS_UserSettings");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("CMS_UserSettings");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("CMS.UserSettings - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Customer"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.customer");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "CustomerSiteID";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    TableManager tm = new TableManager(dci.ClassConnectionString);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_Customer");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);

                    tm.RefreshCustomViews("COM_Customer");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.Customer - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Order"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.order");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "OrderCulture";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 10;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderIsPaid";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderTotalPriceInMainCurrency";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("OrderStatusID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("OrderStatusID", ffi);
                    }

                    ffi = fi.GetFormField("OrderShippingAddressID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("OrderShippingAddressID", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_Order");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_Order");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.Order - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - OrderItem"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.orderitem");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemBundleGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemIsPrivate";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemSendNotification";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemSKU";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemText";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemTotalPriceInMainCurrency";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemValidTo";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_OrderItem");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_OrderItem");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.OrderItem - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Shopping cart item"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.shoppingcartitem");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "CartItemBundleGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemIsPrivate";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemText";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemValidTo";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("CartItemGuid");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("CartItemGuid", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_ShoppingCartSKU");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_ShoppingCartSKU");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.ShoppingCartItem - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - SKU"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.sku");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "SKUBundleInventoryType";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUConversionName";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUConversionValue";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 200;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxDownloads";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxItemsInOrder";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMembershipGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMinPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUNeedsShipping";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUPrivateDonation";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUProductType";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUSiteID";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidFor";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidity";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidUntil";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("SKUDepartmentID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("SKUDepartmentID", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_SKU");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_SKU");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.SKU - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Community - Group"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("Community.Group");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "GroupLogActivity";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.CheckBoxControl;
                    ffi.Visible = true;
                    ffi.DefaultValue = "true";
                    ffi.Caption = "GroupLogActivity";

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("Community_Group");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("Community_Group");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Community.Group - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Newsletter - Subscriber"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("newsletter.subscriber");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "SubscriberBounces";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("Newsletter_Subscriber");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("Newsletter_Subscriber");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Newsletter.Subscriber - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "CMS.Document"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("cms.document");
            if (dci != null)
            {
                SearchSettings ss = dci.ClassSearchSettingsInfos;
                SearchSettingsInfo ssi = ss.GetSettingsInfo("42f446ee-9818-4596-8124-54a38f64aa05");
                if (ssi != null)
                {
                    ssi.Searchable = true;
                    ss.SetSettingsInfo(ssi);
                }

                DataClassInfoProvider.SetDataClass(dci);
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("CMS.Document - Upgrade", "Upgrade", ex);
        }

        #endregion

        // Set the path to the upgrade package
        mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/upgrade_55R2_60.zip");

        mWebsitePath = HttpContext.Current.Server.MapPath("~/");

        TableManager dtm = new TableManager(null);

        // Update all views
        dtm.RefreshDocumentViews();

        // Set data version
        ObjectHelper.SetSettingsKeyValue("CMSDataVersion", "6.0");

        // Clear hashtables
        CMSObjectHelper.ClearHashtables();

        // Clear the cache
        CacheHelper.ClearCache(null, true);

        // Drop the routes
        CMSMvcHandler.DropAllRoutes();

        // Init the Mimetype helper (required for the Import)
        MimeTypeHelper.LoadMimeTypes();

        CMSThread thread = new CMSThread(Upgrade60Import);
        thread.Start();
    }
    /// <summary>
    /// OnSaveData event handler. Sets security properties.
    /// </summary>
    protected void DocumentManager_OnSaveData(object sender, DocumentManagerEventArgs e)
    {
        TreeNode node = e.Node;

        if (node != null)
        {
            string message    = null;
            bool   clearCache = false;

            // Authentication
            if (!pnlAuth.IsHidden)
            {
                int isSecuredNode = node.IsSecuredNode;

                if (radYes.Checked)
                {
                    isSecuredNode = 1;
                }
                else if (radNo.Checked)
                {
                    isSecuredNode = 0;
                }
                else if (radParent.Checked)
                {
                    isSecuredNode = -1;
                }

                // Set secured areas settings
                if (isSecuredNode != node.IsSecuredNode)
                {
                    node.IsSecuredNode = isSecuredNode;
                    clearCache         = true;
                    message           += ResHelper.GetAPIString("security.documentaccessauthchanged", "Page authentication settings have been modified.");
                }
            }

            // SSL
            if (!pnlSSL.IsHidden)
            {
                int requiresSSL = node.RequiresSSL;

                if (radYesSSL.Checked)
                {
                    requiresSSL = 1;
                }
                else if (radNoSSL.Checked)
                {
                    requiresSSL = 0;
                }
                else if (radParentSSL.Checked)
                {
                    requiresSSL = -1;
                }
                else if (radNeverSSL.Checked)
                {
                    requiresSSL = 2;
                }

                // Set SSL settings
                if (requiresSSL != node.RequiresSSL)
                {
                    node.RequiresSSL = requiresSSL;
                    clearCache       = true;
                    if (message != null)
                    {
                        message += "<br />";
                    }
                    message += ResHelper.GetAPIString("security.documentaccesssslchanged", "Page SSL settings have been modified.");
                }
            }

            // Insert information about this event to event log.
            if (DocumentManager.Tree.LogEvents && (message != null))
            {
                EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DOCACCESSMODIFIED", message, eventUrl, currentUser.UserID, currentUser.UserName, node.NodeID, DocumentName, ipAddress, node.NodeSiteID);
            }

            // Clear cache if security settings changed
            if (clearCache)
            {
                CacheHelper.ClearPageInfoCache(node.NodeSiteName);
                CacheHelper.ClearFileNodeCache(node.NodeSiteName);
            }

            // Clear ACL settings
            securityElem.InvalidateAcls();
        }
    }
    /// <summary>
    /// Initializes common properties used for processing image.
    /// </summary>
    void baseImageEditor_InitializeProperties()
    {
        // Process media file
        if (baseImageEditor.ImageType == ImageHelper.ImageTypeEnum.MediaFile)
        {

            // Get mediafile
            mfi = MediaFileInfoProvider.GetMediaFileInfo(mediafileGuid, this.CurrentSiteName);
            // If file is not null
            if (mfi != null)
            {
                MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(mfi.FileLibraryID);

                if ((mli != null) && (MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filemodify")))
                {
                    // Load media file thumbnail
                    if (isPreview)
                    {
                        PreviewPath = MediaFileInfoProvider.GetPreviewFilePath(mfi);
                        if (PreviewPath != null)
                        {
                            OldPreviewExt = Path.GetExtension(PreviewPath);
                            try
                            {
                                // Get file contents from file system
                                previewFile = File.ReadAllBytes(PreviewPath);
                            }
                            catch (Exception ex)
                            {
                                EventLogProvider ev = new EventLogProvider();
                                ev.LogEvent("ImageEditor", "GetPreviewFile", ex);
                            }
                            if (previewFile != null)
                            {
                                baseImageEditor.ImgHelper = new ImageHelper(previewFile);
                            }
                            else
                            {
                                baseImageEditor.LoadingFailed = true;
                                baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
                            }
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
                        }
                    }
                    // Load media file
                    else
                    {
                        mfi.FileBinary = MediaFileInfoProvider.GetFile(mfi, mli.LibraryFolder, this.CurrentSiteName);
                        // Ensure metafile binary data
                        if (mfi.FileBinary != null)
                        {
                            baseImageEditor.ImgHelper = new ImageHelper(mfi.FileBinary);
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
                        }
                    }
                }
                else
                {
                    baseImageEditor.LoadingFailed = true;
                    baseImageEditor.LblLoadFailed.ResourceString = "img.errors.filemodify";
                }
            }
            else
            {
                baseImageEditor.LoadingFailed = true;
                baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
            }
        }

        // Check that image is in supported formats
        if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null))
        {
            baseImageEditor.LoadingFailed = true;
            baseImageEditor.LblLoadFailed.ResourceString = "img.errors.format";
        }
    }
    /// <summary>
    /// Resets permission inheritance of node and its children.
    /// </summary>
    /// <param name="siteName">Name of site</param>
    /// <param name="nodeAliasPath">Alias path</param>
    /// <param name="recursive">Indicates whether to recursively reset all nodes below the current node</param>
    /// <param name="user">Current user</param>
    /// <param name="tr">Tree provider</param>
    /// <returns>Whether TRUE if no permission conflict has occurred</returns>
    private bool ResetNodePermission(string siteName, string nodeAliasPath, bool recursive, UserInfo user, TreeProvider tr)
    {
        // Check permissions
        bool permissionsResult = false;

        try
        {
            if (tr == null)
            {
                tr = new TreeProvider(user);
            }
            // Get node by alias path
            TreeNode treeNode = tr.SelectSingleNode(siteName, nodeAliasPath, null, true, null, false);
            permissionsResult = CanModifyPermission(!recursive, treeNode, user);

            if (treeNode != null)
            {
                // If user has permissions
                if (permissionsResult)
                {
                    // Break inheritance of a node
                    if (!AclInfoProvider.DoesNodeInheritPermissions(treeNode))
                    {
                        // Restore inheritance of a node
                        AclInfoProvider.RestoreInheritance(treeNode);

                        // Log current encoded alias path
                        AddLog(HTMLHelper.HTMLEncode(nodeAliasPath));

                        // Log staging task and flush cache
                        DocumentSynchronizationHelper.LogDocumentChange(treeNode, TaskTypeEnum.RestoreACLInheritance, treeNode.TreeProvider, SynchronizationInfoProvider.ENABLED_SERVERS, null, treeNode.TreeProvider.AllowAsyncActions);
                        Node.ClearCache();

                        // Insert information about this event to event log.
                        if (DocumentManager.Tree.LogEvents)
                        {
                            if (recursive)
                            {
                                LogContext.LogEventToCurrent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", string.Format(ResHelper.GetAPIString("security.documentpermissionsrestoredfordoc", "Permissions of the page '{0}' have been restored to the parent page permissions."), nodeAliasPath), null, user.UserID, user.UserName, treeNode.NodeID, treeNode.GetDocumentName(), ipAddress, Node.NodeSiteID, null, null, null, DateTime.Now);
                            }
                            else
                            {
                                EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", ResHelper.GetAPIString("security.documentpermissionsrestored", "Permissions have been restored to the parent page permissions."), eventUrl, user.UserID, user.UserName, treeNode.NodeID, treeNode.GetDocumentName(), ipAddress, Node.NodeSiteID);
                            }
                        }
                    }
                    else
                    {
                        AddLog(string.Format(GetString("cmsdesk.skippingrestoring"), HTMLHelper.HTMLEncode(nodeAliasPath)));
                    }
                }

                // Recursively reset node inheritance
                if (recursive)
                {
                    // Get child nodes of current node
                    DataSet ds = DocumentManager.Tree.SelectNodes(siteName, treeNode.NodeAliasPath.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, null, null, null, 1, false, -1, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",NodeAliasPath");
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            string childNodeAliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty);

                            if (!string.IsNullOrEmpty(childNodeAliasPath))
                            {
                                bool tempPermissionsResult = ResetNodePermission(siteName, childNodeAliasPath, true, user, tr);
                                permissionsResult = tempPermissionsResult && permissionsResult;
                            }
                        }
                    }
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                CurrentInfo = GetString("cmsdesk.restoringcanceled");
                AddLog(CurrentInfo);
            }
            else
            {
                // Log error
                CurrentError = GetString("cmsdesk.restoringfailed") + ": " + ex.Message;
                AddLog(CurrentError);
            }
        }
        catch (Exception ex)
        {
            // Log error
            CurrentError = GetString("cmsdesk.restoringfailed") + ": " + ex.Message;
            AddLog(CurrentError);
        }
        return(permissionsResult);
    }
    /// <summary>
    /// Render override.
    /// </summary>
    protected override void Render(HtmlTextWriter writer)
    {
        // if everything ok, email should be send
        if (mSendEmail)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            Html32TextWriter mwriter = new Html32TextWriter(sw);
            repItems.RenderControl(mwriter);

            repItems.Visible = false;

            // Prepare the macro resolver
            ContextResolver resolver = ContextResolver.CreateContextChild();

            string[,] replacements = new string[2, 2];
            // Prepare macro replacements
            replacements[0, 0] = "message";
            replacements[0, 1] = txtMessageText.Text;
            replacements[1, 0] = "document";
            replacements[1, 1] = URLHelper.MakeLinksAbsolute(sb.ToString());

            resolver.SourceParameters = replacements;

            if (EmailTemplate != null)
            {
                EmailMessage message = new EmailMessage();
                message.EmailFormat = EmailFormatEnum.Html;

                message.From = EmailFrom;
                message.Recipients = txtEmailTo.Text;

                // Get current css stylesheet
                string styleSheet = URLHelper.MakeLinksAbsolute(GetCssFileLink());

                // resolve EmailSubject here
                message.Subject = resolver.ResolveMacros(EmailSubject);
                // resolve EmailTemplate, wrap to HTML code and add the CSS files
                message.Body = "<html><head>" + styleSheet + "</head><body class=\"EmailBody\">" + resolver.ResolveMacros(EmailTemplate) + "</body></html>";

                // check recipients
                if ((message.Recipients != null) && (message.Recipients.Trim() != ""))
                {
                    try
                    {
                        EmailSender.SendEmail(CMSContext.CurrentSiteName, message);

                        // Display message, email was sent successfully
                        lblInfo.Text = GetString("sendtofriend.emailsent");
                        txtEmailTo.Text = "";
                        txtMessageText.Text = "";
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = GetString("SendToFriend.SendEmailError");
                        try
                        {
                            EventLogProvider eventLog = new EventLogProvider();
                            eventLog.LogEvent("Send email", "SendToFriend", ex);
                        }
                        catch
                        {
                            // Unable to log the event
                        }
                    }
                }
            }
        }

        base.Render(writer);
    }
Exemple #56
0
    /// <summary>
    /// Bind tree view.
    /// </summary>
    /// <param name="dirPath">Directory path</param>
    /// <param name="parentNode">Parent node</param>
    /// <param name="isRoot">Indicates if current parentNode is root</param>
    private void BindTreeView(string dirPath, TreeNode parentNode, bool isRoot = false)
    {
        if (Directory.Exists(dirPath))
        {
            string hidenFolder = "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName);

            // Get directories
            string[] dirs = null;
            try
            {
                dirs = Directory.GetDirectories(dirPath);
            }
            catch (Exception exception)
            {
                // Ignore directories that are not accessible
                if (!(exception is UnauthorizedAccessException || exception is IOExceptions.PathTooLongException))
                {
                    EventLogProvider.LogException("Media library", "READOBJ", exception);
                }
            }
            if (dirs != null)
            {
                int index = 1;
                foreach (string dir in dirs)
                {
                    if (!dir.EndsWithCSafe(hidenFolder, true))
                    {
                        int      dirCount    = 0;
                        string[] directories = null;
                        string[] files       = null;

                        string text = dir.Substring(dir.LastIndexOfCSafe('\\')).Trim('\\');

                        // Get the files and directories
                        try
                        {
                            if (DisplayFilesCount)
                            {
                                files = Directory.GetFiles(dir);
                            }

                            directories = Directory.GetDirectories(dir);
                            if (directories != null)
                            {
                                dirCount = directories.Length;
                            }
                        }
                        catch (Exception exception)
                        {
                            // Ignore files and directories that are not accessible
                            if (!(exception is UnauthorizedAccessException || exception is IOExceptions.PathTooLongException))
                            {
                                EventLogProvider.LogException("Media library", "READOBJ", exception);
                            }
                        }

                        TreeNode node;
                        if (ShowFolder(index))
                        {
                            if (DisplayFilesCount && (files != null))
                            {
                                node = CreateNode("<span class=\"Name\">" + text + " (" + files.Length + ")</span>", text, parentNode, dirCount, index);
                            }
                            else
                            {
                                node = CreateNode("<span class=\"Name\">" + text + "</span>", text, parentNode, dirCount, index);
                            }

                            if (dirCount == 1)
                            {
                                node.PopulateOnDemand = !directories[0].EndsWithCSafe(hidenFolder);
                            }
                            else
                            {
                                node.PopulateOnDemand = (dirCount > 0);
                            }

                            // Check if there is node within the current path to be selected
                            if (!string.IsNullOrEmpty(PathToSelect))
                            {
                                EnsureNodeExpand(parentNode, node);
                            }

                            parentNode.ChildNodes.Add(node);
                        }
                        else
                        {
                            node = CreateNode("<span class=\"Name\">" + GetString("general.seelisting") + "</span>", "", parentNode, 0, index);
                            parentNode.ChildNodes.Add(node);

                            RootHasMore = (isRoot && !CloseListing);
                        }

                        if (ShowFolder(index))
                        {
                            index++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
    /// <summary>
    /// Did you mean suggestion.
    /// </summary>
    private static string DidYouMean(string dictionaryFile, string searchQuery, IEnumerable <string> searchTerms)
    {
        if (searchTerms != null)
        {
            Spelling       SpellChecker   = null;
            WordDictionary WordDictionary = null;


            #region "Word dictionary"

            // If not in cache, create new
            WordDictionary = new WordDictionary();
            WordDictionary.EnableUserFile = false;

            // Getting folder for dictionaries
            string folderName = HttpContext.Current.Request.MapPath("~/App_Data/Dictionaries/");

            // Check if dictionary file exists
            string fileName = Path.Combine(folderName, dictionaryFile);
            if (!File.Exists(fileName))
            {
                EventLogProvider.LogEvent(EventType.ERROR, "DidYouMean webpart", "Dictionary file not found!");

                return(String.Empty);
            }

            WordDictionary.DictionaryFolder = folderName;
            WordDictionary.DictionaryFile   = dictionaryFile;

            // Load and initialize the dictionary
            WordDictionary.Initialize();

            #endregion


            #region "SpellCheck"

            // Prepare spellchecker
            SpellChecker                = new Spelling();
            SpellChecker.Dictionary     = WordDictionary;
            SpellChecker.SuggestionMode = Spelling.SuggestionEnum.NearMiss;

            bool suggest = false;

            // Check all searched terms
            foreach (string term in searchTerms)
            {
                if (term.Length > 2)
                {
                    SpellChecker.Suggest(term);
                    ArrayList al = SpellChecker.Suggestions;

                    // If there are some suggestions
                    if ((al != null) && (al.Count > 0))
                    {
                        suggest = true;

                        // Expression to find term
                        Regex regex = RegexHelper.GetRegex("([\\+\\-\\s\\(]|^)" + term + "([\\s\\)]|$)");

                        // Change term in original search query
                        string suggestion = "$1" + startTag + al[0] + endTag + "$2";
                        searchQuery = regex.Replace(searchQuery, suggestion);
                    }
                }
            }

            #endregion


            if (suggest)
            {
                return(searchQuery);
            }
        }

        return(String.Empty);
    }
Exemple #58
0
 /// <summary>
 /// When exception occurs, log it to event log.
 /// </summary>
 /// <param name="ex">Exception to log</param>
 private void LogExceptionToEventLog(Exception ex)
 {
     EventLogProvider.LogException("Contact management", "DELETECONTACT", ex);
     AddError(GetString("om.contact.deletefailed") + ": " + ex.Message);
 }
Exemple #59
0
    /// <summary>
    /// Delete attribute button clicked.
    /// </summary>
    protected void btnDeleteItem_Click(Object sender, System.Web.UI.ImageClickEventArgs e)
    {
        if (Mode == FieldEditorModeEnum.BizFormDefinition)
        {
            // Check 'EditForm' permission
            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm"))
            {
                RedirectToAccessDenied("cms.form", "EditForm");
            }
        }

        // Raise on before definition update event
        if (OnBeforeDefinitionUpdate != null)
        {
            OnBeforeDefinitionUpdate(this, EventArgs.Empty);
        }

        FormFieldInfo ffiSelected = null;
        DataClassInfo dci = null;
        WebPartInfo wpi = null;
        string errorMessage = null;
        string newSelectedValue = null;
        string deletedItemPreffix = null;

        // Clear settings
        simpleMode.Settings = new Hashtable();
        controlSettings.Settings = new Hashtable();

        // Load current xml form definition
        LoadFormDefinition();

        if ((!string.IsNullOrEmpty(SelectedItemName)) && (!IsNewItemEdited))
        {
            if (SelectedItemType == FieldEditorSelectedItemEnum.Field)
            {
                ffiSelected = fi.GetFormField(SelectedItemName);
                deletedItemPreffix = fieldPreffix;

                if (ffiSelected != null)
                {
                    // Do not allow deleting of the primary key except for external fields
                    if (ffiSelected.PrimaryKey && !ffiSelected.External)
                    {
                        if (!this.DevelopmentMode)
                        {
                            lblError.Visible = true;
                            lblError.ResourceString = "TemplateDesigner.ErrorCannotDeletePK";
                            return;
                        }
                        else
                        {
                            // Check if at least one primary key stays
                            if (fi.GetFields(true, true, false, true).Length < 2)
                            {
                                lblError.Visible = true;
                                lblError.ResourceString = "TemplateDesigner.ErrorCannotDeletePK";
                                return;
                            }
                        }
                    }

                    // Check if at least two fields stay in document type definition
                    if ((this.Mode == FieldEditorModeEnum.ClassFormDefinition) && (fi.GetFields(true, true, true).Length < 3))
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorCannotDeleteAllCustomFields";
                        return;
                    }

                    // Do not allow deleting of the system field
                    if (ffiSelected.System && !ffiSelected.External && !DevelopmentMode)
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorCannotDeleteSystemField";
                        return;
                    }

                    // Remove specifield field from xml form definition
                    fi.RemoveFormField(SelectedItemName);

                    // Get updated definition
                    FormDefinition = fi.GetXmlDefinition();

                    switch (mMode)
                    {
                        case FieldEditorModeEnum.WebPartProperties:
                            // Web part properties
                            {
                                wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId);
                                if (wpi != null)
                                {
                                    wpi.WebPartProperties = FormDefinition;
                                    try
                                    {
                                        WebPartInfoProvider.SetWebPartInfo(wpi);
                                    }
                                    catch (Exception ex)
                                    {
                                        errorMessage = ex.Message;
                                    }
                                }
                                else
                                {
                                    errorMessage = GetString("FieldEditor.WebpartNotFound");
                                }
                            }
                            break;

                        case FieldEditorModeEnum.ClassFormDefinition:
                        case FieldEditorModeEnum.BizFormDefinition:
                        case FieldEditorModeEnum.SystemTable:
                        case FieldEditorModeEnum.CustomTable:
                            {
                                // Standard classes
                                dci = DataClassInfoProvider.GetDataClass(mClassName);
                                if (dci != null)
                                {
                                    // If document type is edited AND field that should be removed is FILE
                                    if ((mMode == FieldEditorModeEnum.ClassFormDefinition) && (!string.IsNullOrEmpty(ClassName)) &&
                                        (ffiSelected.DataType == FormFieldDataTypeEnum.File))
                                    {
                                        DocumentHelper.DeleteDocumentAttachments(ClassName, ffiSelected.Name, null);
                                    }

                                    // If bizform is edited AND field that should be removed is FILE
                                    if ((mMode == FieldEditorModeEnum.BizFormDefinition) && (!string.IsNullOrEmpty(ClassName)) &&
                                        (ffiSelected.FieldType == FormFieldControlTypeEnum.UploadControl))
                                    {
                                        BizFormInfoProvider.DeleteBizFormFiles(ClassName, ffiSelected.Name, CMSContext.CurrentSiteID);
                                    }

                                    // Update xml definition
                                    dci.ClassFormDefinition = FormDefinition;

                                    try
                                    {
                                        if (!ffiSelected.External)
                                        {
                                            // Remove corresponding column from table
                                            TableManager.DropTableColumn(dci.ClassTableName, SelectedItemName);

                                            // Update xml schema
                                            dci.ClassXmlSchema = TableManager.GetXmlSchema(dci.ClassTableName);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        errorMessage = ex.Message;
                                    }

                                    // Deleted field is used as ClassNodeNameSource -> remove node name source
                                    if (dci.ClassNodeNameSource == SelectedItemName)
                                    {
                                        dci.ClassNodeNameSource = "";
                                    }

                                    // Update changes in database
                                    try
                                    {
                                        using (CMSActionContext context = new CMSActionContext())
                                        {
                                            // Do not log synchronization for BizForm
                                            if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                            {
                                                context.DisableLogging();
                                            }

                                            // Save the data class
                                            DataClassInfoProvider.SetDataClass(dci);

                                            // Update inherited classes with new fields
                                            FormHelper.UpdateInheritedClasses(dci);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        errorMessage = ex.Message;
                                    }

                                    // Refresh views and quries only if changes to DB were made
                                    if (!ffiSelected.External)
                                    {
                                        // Generate default view
                                        if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                        {
                                            SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName);
                                        }
                                        else
                                        {
                                            SqlGenerator.GenerateDefaultView(dci, null);
                                        }

                                        // Regenerate queries
                                        SqlGenerator.GenerateDefaultQueries(dci, true, true);

                                        // Updates custom views
                                        if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition))
                                        {
                                            try
                                            {
                                                TableManager.RefreshCustomViews(dci.ClassTableName);

                                                string lowClassName = dci.ClassName.ToLower();
                                                if (lowClassName == "cms.document" || lowClassName == "cms.tree")
                                                {
                                                    TableManager.RefreshDocumentViews();
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                errorMessage = ResHelper.GetString("fieldeditor.refreshingviewsfailed");
                                                EventLogProvider ev = new EventLogProvider();
                                                ev.LogEvent("Field Editor", "EXCEPTION", ex);
                                            }
                                        }
                                    }

                                    // Clear hashtables
                                    ClearHashtables();
                                }
                                else
                                {
                                    errorMessage = GetString("FieldEditor.ClassNotFound");
                                }
                            }
                            break;
                    }
                }
            }
            else if (SelectedItemType == FieldEditorSelectedItemEnum.Category)
            {
                deletedItemPreffix = categPreffix;

                // Remove specifield category from xml form definition
                fi.RemoveFormCategory(SelectedItemName);

                // Get updated form definition
                FormDefinition = fi.GetXmlDefinition();

                switch (mMode)
                {
                    case FieldEditorModeEnum.WebPartProperties:
                        wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId);
                        if (wpi != null)
                        {
                            wpi.WebPartProperties = FormDefinition;
                            try
                            {
                                WebPartInfoProvider.SetWebPartInfo(wpi);
                            }
                            catch (Exception ex)
                            {
                                errorMessage = ex.Message;
                            }
                        }
                        else
                        {
                            errorMessage = GetString("FieldEditor.WebpartNotFound");
                        }
                        break;

                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:
                        dci = DataClassInfoProvider.GetDataClass(mClassName);

                        if (dci != null)
                        {
                            // Update xml definition
                            dci.ClassFormDefinition = FormDefinition;

                            // Update changes in database
                            try
                            {
                                using (CMSActionContext context = new CMSActionContext())
                                {
                                    // Do not log synchronization for BizForm
                                    if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                    {
                                        context.DisableLogging();
                                    }

                                    // Save the data class
                                    DataClassInfoProvider.SetDataClass(dci);

                                    // Update inherited classes with new fields
                                    FormHelper.UpdateInheritedClasses(dci);
                                }
                            }
                            catch (Exception ex)
                            {
                                errorMessage = ex.Message;
                            }
                        }
                        else
                        {
                            errorMessage = GetString("FieldEditor.ClassNotFound");
                        }
                        break;
                }
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                lblError.Visible = true;
                lblError.Text = "[ FieldEditor.btnDeleteItem_Click() ]: " + errorMessage;
            }
        }
        else
        {
            // "delete" new item from the list
            IsNewItemEdited = false;
        }

        // Set new selected value
        ListItem deletedItem = lstAttributes.Items.FindByValue(deletedItemPreffix + SelectedItemName);
        int deletedItemIndex = lstAttributes.Items.IndexOf(deletedItem);

        if ((deletedItemIndex > 0) && (lstAttributes.Items[deletedItemIndex - 1] != null))
        {
            newSelectedValue = lstAttributes.Items[deletedItemIndex - 1].Value;
        }

        // Reload data
        Reload(newSelectedValue);

        // Raise on after definition update event
        if (OnAfterDefinitionUpdate != null)
        {
            OnAfterDefinitionUpdate(this, EventArgs.Empty);
        }
    }
    /// <summary>
    /// Gets FormEngineUserControl instance for the input SettingsKeyInfo object.
    /// </summary>
    /// <param name="key">SettingsKeyInfo</param>
    /// <param name="groupNo">Number representing index of the processing settings group</param>
    /// <param name="keyNo">Number representing index of the processing SettingsKeyInfo</param>
    private FormEngineUserControl GetFormEngineUserControl(SettingsKeyInfo key, int groupNo, int keyNo)
    {
        string controlNameOrPath = key.KeyEditingControlPath;

        if (string.IsNullOrEmpty(controlNameOrPath))
        {
            return(null);
        }

        // Try to get form control by its name
        FormEngineUserControl control = null;
        var formUserControl           = FormUserControlInfoProvider.GetFormUserControlInfo(controlNameOrPath);

        if (formUserControl != null)
        {
            var formProperties = formUserControl.UserControlMergedParameters;

            if (formUserControl.UserControlParentID > 0)
            {
                // Get parent user control
                var parentFormUserControl = FormUserControlInfoProvider.GetFormUserControlInfo(formUserControl.UserControlParentID);
                if (parentFormUserControl != null)
                {
                    formUserControl = parentFormUserControl;
                }
            }

            // Create FormInfo and load control
            control = Page.LoadUserControl(FormUserControlInfoProvider.GetFormUserControlUrl(formUserControl)) as FormEngineUserControl;
            if (control != null)
            {
                FormInfo fi = FormHelper.GetFormControlParameters(controlNameOrPath, formProperties, false);
                control.LoadDefaultProperties(fi);

                if (!string.IsNullOrEmpty(key.KeyFormControlSettings))
                {
                    control.FieldInfo = FormHelper.GetFormControlSettingsFromXML(key.KeyFormControlSettings);
                    control.LoadControlFromFFI();
                }
            }
        }
        else
        {
            // Try to load the control
            try
            {
                control = Page.LoadUserControl(controlNameOrPath) as FormEngineUserControl;
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("Settings", "LoadControl", ex);
            }
        }

        if (control == null)
        {
            return(null);
        }

        control.ID         = string.Format(@"key{0}{1}", groupNo, keyNo);
        control.IsLiveSite = false;

        return(control);
    }