Ejemplo n.º 1
0
    protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        sourceName = sourceName.ToLowerCSafe();
        DataRowView drv = null;
        bool        modifyPermission = true;
        string      documentCulture  = null;

        switch (sourceName)
        {
        case "documentname":
            drv = parameter as DataRowView;
            string documentName        = null;
            string encodedDocumentName = null;
            string documentType        = null;
            documentCulture = ValidationHelper.GetString(drv.Row["DocumentCulture"], string.Empty);
            string alias           = ValidationHelper.GetString(drv.Row["NodeAlias"], string.Empty);
            int    nodeId          = ValidationHelper.GetInteger(drv.Row["NodeID"], 0);
            int    documentId      = ValidationHelper.GetInteger(drv.Row["DocumentID"], 0);
            bool   isLinked        = (ValidationHelper.GetInteger(drv["NodeLinkedNodeID"], 0) != 0);
            Guid   nodeGuid        = ValidationHelper.GetGuid(drv.Row["NodeGUID"], Guid.Empty);
            string fileDescription = ValidationHelper.GetString(drv.Row["FileDescription"], string.Empty);
            Guid   fileAttachment  = ValidationHelper.GetGuid(drv.Row["FileAttachment"], Guid.Empty);

            // Get permissions flags
            modifyPermission = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Modify, documentCulture);
            bool modifyCulturePermission     = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Modify, PreferredCultureCode);
            bool deletePermission            = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Delete, documentCulture);
            bool modifyPermissionsPermission = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.ModifyPermissions, documentCulture);
            bool readPermission = !CheckPermissions || TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Read, documentCulture);

            if (modifyPermission)
            {
                documentName = ValidationHelper.GetString(drv.Row["DocumentName"], string.Empty);
                documentType = ValidationHelper.GetString(drv.Row["DocumentType"], string.Empty);
            }
            else
            {
                documentName = ValidationHelper.GetString(drv.Row["PublishedDocumentName"], string.Empty);
                documentType = ValidationHelper.GetString(drv.Row["PublishedDocumentType"], string.Empty);
            }

            encodedDocumentName = HTMLHelper.HTMLEncode(documentName);

            string fileTypeIcon = UIHelper.GetFileIcon(Page, documentType, tooltip: HTMLHelper.HTMLEncode(documentType));
            string flagIcon     = null;
            if (documentCulture.ToLowerCSafe() != PreferredCultureCode.ToLowerCSafe())
            {
                flagIcon = "<img class=\"Icon\" src=\"" + GetFlagIconUrl(documentCulture, "16x16") + "\" alt=\"" + HTMLHelper.HTMLEncode(documentCulture) + "\" />";
            }

            string menuParameter = ScriptHelper.GetString(nodeId + "|" + documentCulture);

            string attachmentName = encodedDocumentName;

            string toolTip = UIHelper.GetTooltipAttributes(null, 0, 0, null, null, null, fileDescription, null, 300);

            // Generate link to open document
            if (fileAttachment != Guid.Empty)
            {
                // Get document URL
                string attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(nodeGuid, alias));
                if (modifyPermission)
                {
                    attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(documentId, string.Empty));
                    attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + documentId));
                }
                attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                if (!string.IsNullOrEmpty(attachmentUrl))
                {
                    attachmentName = "<a href=\"" + URLHelper.EncodeQueryString(attachmentUrl) + "\" " + toolTip + ">" + encodedDocumentName + "</a> ";
                }
            }
            else
            {
                attachmentName = "<span" + toolTip + ">" + encodedDocumentName + "</span>";
            }

            // Add linked flag
            if (isLinked)
            {
                attachmentName += DocumentHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
            }

            bool showContextMenu = readPermission && (modifyPermission || modifyPermissionsPermission || deletePermission || (IsAuthorizedToCreate && modifyCulturePermission));
            // Generate row with icons, hover action and context menu
            StringBuilder contextMenuString = new StringBuilder();
            contextMenuString.Append("<table>");
            contextMenuString.Append("<tr>");

            if (showContextMenu)
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + arrowContextMenu.ClientID, menuParameter, false, HtmlTextWriterTag.Td, "ArrowIcon", null));
                contextMenuString.Append("<a class=\"btn-unigrid-action\"><i class=\"icon-ellipsis\"></i></a>");
                contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));
            }
            else
            {
                contextMenuString.Append("<td class=\"NoIcon\">&nbsp;</td>");
            }

            if (showContextMenu)
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + rowContextMenu.ClientID, menuParameter, true, HtmlTextWriterTag.Td, "FileTypeIcon", null));
            }
            else
            {
                contextMenuString.Append("<td class=\"FileTypeIcon\">");
            }
            contextMenuString.Append(fileTypeIcon);
            contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));

            if (showContextMenu)
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + rowContextMenu.ClientID, menuParameter, true, HtmlTextWriterTag.Td, "RowContent", "width: 100%;"));
            }
            else
            {
                contextMenuString.Append("<td class=\"RowContent\" style=\"width: 100%;\">");
            }
            contextMenuString.Append(attachmentName);
            contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));

            if (!string.IsNullOrEmpty(flagIcon))
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + rowContextMenu.ClientID, menuParameter, true, HtmlTextWriterTag.Td, "FlagIcon", null));
                contextMenuString.Append(flagIcon);
                contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));
            }
            contextMenuString.Append("  </tr>");
            contextMenuString.Append("</table>");
            return(contextMenuString.ToString());

        case "modifiedwhen":
        case "modifiedwhentooltip":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return(string.Empty);
            }
            else
            {
                // Handle time zones
                DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);

                if (sourceName == "modifiedwhen")
                {
                    if (IsLiveSite)
                    {
                        return(TimeZoneMethods.ConvertDateTime(modifiedWhen, this));
                    }
                    else
                    {
                        return(TimeZoneHelper.GetCurrentTimeZoneDateTimeString(modifiedWhen, CurrentUser, CurrentSite, out usedTimeZone));
                    }
                }
                else
                {
                    if (!IsLiveSite)
                    {
                        if (TimeZoneHelper.TimeZonesEnabled && (usedTimeZone == null))
                        {
                            TimeZoneHelper.GetCurrentTimeZoneDateTimeString(modifiedWhen, CurrentUser, CurrentSite, out usedTimeZone);
                        }
                        return(TimeZoneHelper.GetUTCLongStringOffset(usedTimeZone));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

        case "status":
            string stepName = string.Empty;
            string toReturn = string.Empty;

            // Extract datarow
            drv = parameter as DataRowView;

            stepName = GetString("general.dash");
            TreeNode node = DocumentHelper.GetDocument(ValidationHelper.GetInteger(drv["DocumentID"], 0), TreeProvider);
            if (node != null)
            {
                var step = node.WorkflowStep;
                if (step != null)
                {
                    stepName = step.StepDisplayName;
                }
            }

            // Gain desired values from datarow view
            int checkedOutByUserId = ValidationHelper.GetInteger(drv["DocumentCheckedOutByUserID"], 0);
            documentCulture  = ValidationHelper.GetString(drv.Row["DocumentCulture"], string.Empty);
            modifyPermission = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Modify, documentCulture);

            // Add 'checked out' icon
            if ((checkedOutByUserId > 0) && modifyPermission)
            {
                toReturn = " " + DocumentHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.CheckedOut);
            }

            toReturn = stepName + toReturn;
            return(toReturn);
        }
        return(parameter);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsAdHocForum)
        {
            plcHeader.Visible = false;
        }

        forumEdit.OnPreview            += new EventHandler(forumEdit_OnPreview);
        forumEdit.OnModerationRequired += new EventHandler(forumEdit_OnModerationRequired);

        // Check whether subscription is for forum or post
        if (ForumContext.CurrentReplyThread == null)
        {
            ltrTitle.Text = GetString("Forums_ForumNewPost_Header.NewThread");

            if (ForumContext.CurrentPost != null && ForumContext.CurrentMode == ForumMode.Edit)
            {
                ltrTitle.Text = GetString("Forums_ForumNewPost_Header.EditPost");
            }
        }
        else
        {
            plcPreview.Visible = true;

            ltrTitle.Text = GetString("Forums_ForumNewPost_Header.Reply");

            ltrAvatar.Text  = AvatarImage(ForumContext.CurrentReplyThread);
            ltrSubject.Text = HTMLHelper.HTMLEncode(ForumContext.CurrentReplyThread.PostSubject);
            if (ForumContext.CurrentForum != null)
            {
                if (ForumContext.CurrentForum.ForumEnableAdvancedImage)
                {
                    ltrText.AllowedControls = ControlsHelper.ALLOWED_FORUM_CONTROLS;
                }
                else
                {
                    ltrText.AllowedControls = "none";
                }
                ltrText.Text = ResolvePostText(ForumContext.CurrentReplyThread.PostText);
            }
            ltrUserName.Text = HTMLHelper.HTMLEncode(ForumContext.CurrentReplyThread.PostUserName);
            ltrTime.Text     = TimeZoneUIMethods.ConvertDateTime(ForumContext.CurrentReplyThread.PostTime, this).ToString();

            UserSettingsInfo usi           = UserSettingsInfoProvider.GetUserSettingsInfoByUser(ForumContext.CurrentReplyThread.PostUserID);
            BadgeInfo        bi            = null;
            string           badgeName     = null;
            string           badgeImageUrl = null;

            if (usi != null)
            {
                bi = BadgeInfoProvider.GetBadgeInfo(usi.UserBadgeID);
                if (bi != null)
                {
                    badgeName     = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(bi.BadgeDisplayName));
                    badgeImageUrl = HTMLHelper.HTMLEncode(bi.BadgeImageURL);
                }
            }

            ltrBadge.Text = GetNotEmpty(badgeName, "<div class=\"Badge\">" + badgeName + "</div>", "<div class=\"Badge\">" + GetString("Forums.PublicBadge") + "</div>", ForumActionType.Badge) +
                            GetNotEmpty(badgeImageUrl, "<div class=\"BadgeImage\"><img alt=\"" + badgeName + "\" src=\"" + GetImageUrl(ValidationHelper.GetString(badgeImageUrl, "")) + "\" /></div>", "", ForumActionType.Badge);
        }
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Import files.
    /// </summary>
    private void Import(object parameter)
    {
        try
        {
            object[]        parameters  = (object[])parameter;
            string[]        items       = (string[])parameters[0];
            CurrentUserInfo currentUser = (CurrentUserInfo)parameters[3];

            if ((items.Length > 0) && (currentUser != null))
            {
                resultListIndex   = null;
                resultListValues  = null;
                errorFiles        = null;
                hdnValue.Value    = null;
                hdnSelected.Value = null;
                string siteName        = CMSContext.CurrentSiteName;
                string targetAliasPath = ValidationHelper.GetString(parameters[1], null);

                bool imported    = false; // Flag - true if one file was imported at least
                bool importError = false; // Flag - true when import failed

                TreeProvider tree = new TreeProvider(currentUser);
                TreeNode     tn   = tree.SelectSingleNode(siteName, targetAliasPath, TreeProvider.ALL_CULTURES, true, null, false);
                if (tn != null)
                {
                    // Check if CMS.File document type exist and check if document contains required columns (FileName, FileAttachment)
                    DataClassInfo fileClassInfo = DataClassInfoProvider.GetDataClass("CMS.File");
                    if (fileClassInfo == null)
                    {
                        AddError(GetString("newfile.classcmsfileismissing"));
                        return;
                    }
                    else
                    {
                        FormInfo      fi        = new FormInfo(fileClassInfo.ClassFormDefinition);
                        FormFieldInfo fileFfi   = null;
                        FormFieldInfo attachFfi = null;
                        if (fi != null)
                        {
                            fileFfi   = fi.GetFormField("FileName");
                            attachFfi = fi.GetFormField("FileAttachment");
                        }
                        if ((fi == null) || (fileFfi == null) || (attachFfi == null))
                        {
                            AddError(GetString("newfile.someofrequiredfieldsmissing"));
                            return;
                        }
                    }

                    DataClassInfo dci = DataClassInfoProvider.GetDataClass(tn.NodeClassName);

                    if (dci != null)
                    {
                        // Check if "file" and "folder" are allowed as a child document under selected document type
                        bool          fileAllowed     = false;
                        bool          folderAllowed   = false;
                        DataClassInfo folderClassInfo = DataClassInfoProvider.GetDataClass("CMS.Folder");
                        if ((fileClassInfo != null) || (folderClassInfo != null))
                        {
                            string[] paths;
                            foreach (string fullFileName in items)
                            {
                                paths = fullFileName.Substring(rootPath.Length).Split('\\');
                                // Check file
                                if (paths.Length == 1)
                                {
                                    if (!fileAllowed && (fileClassInfo != null) && !DataClassInfoProvider.IsChildClassAllowed(dci.ClassID, fileClassInfo.ClassID))
                                    {
                                        AddError(GetString("Tools.FileImport.NotAllowedChildClass"));
                                        return;
                                    }
                                    else
                                    {
                                        fileAllowed = true;
                                    }
                                }

                                // Check folder
                                if (paths.Length > 1)
                                {
                                    if (!folderAllowed && (folderClassInfo != null) && !DataClassInfoProvider.IsChildClassAllowed(dci.ClassID, folderClassInfo.ClassID))
                                    {
                                        AddError(GetString("Tools.FileImport.FolderNotAllowedChildClass"));
                                        return;
                                    }
                                    else
                                    {
                                        folderAllowed = true;
                                    }
                                }

                                if (fileAllowed && folderAllowed)
                                {
                                    break;
                                }
                            }
                        }

                        // Check if user is allowed to create new file document
                        if (fileAllowed && !currentUser.IsAuthorizedToCreateNewDocument(tn, "CMS.File"))
                        {
                            AddError(GetString("accessdenied.notallowedtocreatedocument"));
                            return;
                        }

                        // Check if user is allowed to create new folder document
                        if (folderAllowed && !currentUser.IsAuthorizedToCreateNewDocument(tn, "CMS.Folder"))
                        {
                            AddError(GetString("accessdenied.notallowedtocreatedocument"));
                            return;
                        }
                    }

                    string   cultureCode      = ValidationHelper.GetString(parameters[2], "");
                    string[] fileList         = new string[1];
                    string[] relativePathList = new string[1];

                    // Begin log
                    AddLog(GetString("tools.fileimport.importingprogress"));

                    if (items.Length > 0)
                    {
                        // Initialize output arrays - we have atleast 1 file
                        if (resultListIndex == null)
                        {
                            resultListIndex = new ArrayList();
                        }
                        if (resultListValues == null)
                        {
                            resultListValues = new ArrayList();
                        }
                    }

                    string msgImported = GetString("Tools.FileImport.Imported");
                    string msgFailed   = GetString("Tools.FileImport.Failed");

                    // Insert files selected in datagrid to list of files to import
                    foreach (string fullFileName in items)
                    {
                        // Import selected files only
                        fileList[0]         = fullFileName;
                        relativePathList[0] = fullFileName.Substring(rootPath.Length);

                        // Remove extension if needed
                        if (!chkIncludeExtension.Checked)
                        {
                            relativePathList[0] = Regex.Replace(relativePathList[0], "(.*)\\..*", "$1");
                        }

                        try
                        {
                            FileImport.ImportFiles(siteName, targetAliasPath, cultureCode, fileList, relativePathList, currentUser.UserID, chkDeleteImported.Checked);

                            // Import of a file succeeded, fill the output lists
                            resultListIndex.Add(fullFileName);
                            resultListValues.Add(new string[] { fullFileName, msgImported, true.ToString() });

                            imported = true; // One file was imported
                            AddLog(HTMLHelper.HTMLEncode(fullFileName));
                        }
                        catch (Exception ex)
                        {
                            // File import failed
                            if (errorFiles == null)
                            {
                                errorFiles = new ArrayList();
                            }
                            errorFiles.Add(fullFileName);
                            importError = true;

                            // Fill the output lists
                            resultListIndex.Add(fullFileName);
                            resultListValues.Add(new string[] { fullFileName, msgFailed + " (" + HTMLHelper.HTMLEncode(ex.Message) + ")", false.ToString() });

                            AddError(msgFailed + " (" + HTMLHelper.HTMLEncode(ex.Message) + ")");

                            // Abort importing the rest of files for serious exceptions
                            if (!(ex is UnauthorizedAccessException))
                            {
                                return;
                            }
                        }
                    }
                }
                // Specified alias path not found
                else
                {
                    AddError(GetString("Tools.FileImport.AliasPathNotFound"));
                    return;
                }

                if (filesList.Count > 0)
                {
                    if (!importError)
                    {
                        if (imported)
                        {
                            AddError(GetString("Tools.FileImport.FilesWereImported"));
                            return;
                        }
                    }
                    else
                    {
                        AddError(GetString("Tools.FileImport.FilesNotImported"));
                        return;
                    }
                }
            }
            // No items selected to import
            else
            {
                AddError(GetString("Tools.FileImport.FilesNotImported"));
                return;
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
    }
    /// <summary>
    /// Initializes menu.
    /// </summary>
    protected void InitalizeMenu()
    {
        if (webpartId != "")
        {
            // get pageinfo
            PageInfo pi = GetPageInfo(aliasPath, templateId);
            if (pi == null)
            {
                this.Visible = false;
                return;
            }

            PageTemplateInfo pti = pi.PageTemplateInfo;
            if (pti != null)
            {
                WebPartInfo wi = null;

                // Get web part
                WebPartInstance webPart = pti.GetWebPart(instanceGuid, webpartId);
                if (webPart != null)
                {
                    wi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType);
                    if (ValidationHelper.GetString(webPart.GetValue("WebPartCode"), "").Trim() != "")
                    {
                        showCodeTab = true;
                    }
                    if (webPart.Bindings.Count > 0)
                    {
                        showBindingTab = true;
                    }
                }
                else
                {
                    wi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0));
                }

                if (wi != null)
                {
                    // Generate documentation link
                    Literal ltr = new Literal();
                    PageTitle.RightPlaceHolder.Controls.Add(ltr);

                    string docScript = "NewWindow('" + ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/WebPartDocumentationPage.aspx") + "?webpartid=" + ScriptHelper.GetString(wi.WebPartName, false) + "', 'WebPartPropertiesDocumentation', 800, 800); return false;";

                    ltr.Text  = "<table cellpadding=\"0\" cellspacing=\"0\"><tr><td>";
                    ltr.Text += "<a onclick=\"" + docScript + "\" href=\"#\"><img src=\"" + ResolveUrl(GetImageUrl("CMSModules/CMS_PortalEngine/Documentation.png")) + "\" style=\"border-width: 0px;\"></a>";
                    ltr.Text += "</td>";
                    ltr.Text += "<td>";
                    ltr.Text += "<a onclick=\"" + docScript + "\" href=\"#\">" + GetString("WebPartPropertie.DocumentationLink") + "</a>";
                    ltr.Text += "</td></tr></table>";

                    PageTitle.TitleText = GetString("WebpartProperties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WebPartDisplayName)) + ")";
                }
            }
        }

        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        tabsElem.UrlTarget = "webpartpropertiescontent";
    }
Ejemplo n.º 5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Security test
        if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
        {
            RedirectToAccessDenied(GetString("attach.actiondenied"));
        }

        // Add link to external stylesheet
        CSSHelper.RegisterCSSLink(this, "Default", "/CMSDesk.css");

        // Get current resolver
        resolver = MacroContext.CurrentResolver.CreateChild();

        DataSet ds  = null;
        DataSet cds = null;

        // Check init settings
        bool allWidgets    = QueryHelper.GetBoolean("allWidgets", false);
        bool allWebParts   = QueryHelper.GetBoolean("allWebparts", false);
        bool allWireframes = QueryHelper.GetBoolean("allwireframes", false);

        // Get webpart (widget) from querystring - only if no allwidget or allwebparts set
        bool   isWebpartInQuery  = false;
        bool   isWidgetInQuery   = false;
        String webpartQueryParam = String.Empty;

        //If not show all widgets or webparts - check if any widget or webpart is present
        if (!allWidgets && !allWebParts && !allWireframes)
        {
            webpartQueryParam = QueryHelper.GetString("webpart", "");
            if (!string.IsNullOrEmpty(webpartQueryParam))
            {
                isWebpartInQuery = true;
            }
            else
            {
                webpartQueryParam = QueryHelper.GetString("widget", "");
                if (!string.IsNullOrEmpty(webpartQueryParam))
                {
                    isWidgetInQuery = true;
                }
            }
        }

        // Set development option if is required
        if (QueryHelper.GetString("details", "0") == "1")
        {
            development = true;
        }

        // Generate all webparts
        if (allWebParts)
        {
            // Get all webpart categories
            cds = WebPartCategoryInfoProvider.GetCategories();
        }
        // Generate all widgets
        else if (allWidgets)
        {
            // Get all widget categories
            cds = WidgetCategoryInfoProvider.GetWidgetCategories();
        }
        else if (allWireframes)
        {
            WebPartCategoryInfo wpci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoByCodeName("Wireframes");
            if (wpci != null)
            {
                cds = WebPartCategoryInfoProvider.GetCategories(wpci.CategoryID);
            }
        }
        // Generate single webpart
        else if (isWebpartInQuery)
        {
            // Split weparts
            string[] webparts = webpartQueryParam.Split(';');
            if (webparts.Length > 0)
            {
                string webpartWhere = SqlHelper.GetWhereCondition("WebpartName", webparts);
                ds = WebPartInfoProvider.GetWebParts().Where(webpartWhere);

                // If any webparts found
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    StringBuilder categoryWhere = new StringBuilder("");
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        categoryWhere.Append(ValidationHelper.GetString(dr["WebpartCategoryID"], "NULL") + ",");
                    }

                    string ctWhere = "CategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                    cds = WebPartCategoryInfoProvider.GetCategories().Where(ctWhere);
                }
            }
        }
        // Generate single widget
        else if (isWidgetInQuery)
        {
            string[] widgets = webpartQueryParam.Split(';');
            if (widgets.Length > 0)
            {
                string widgetsWhere = SqlHelper.GetWhereCondition("WidgetName", widgets);
                ds = WidgetInfoProvider.GetWidgets().Where(widgetsWhere);
            }

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                StringBuilder categoryWhere = new StringBuilder("");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    categoryWhere.Append(ValidationHelper.GetString(dr["WidgetCategoryID"], "NULL") + ",");
                }

                string ctWhere = "WidgetCategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                cds = WidgetCategoryInfoProvider.GetWidgetCategories().Where(ctWhere);
            }
        }

        if (allWidgets || isWidgetInQuery)
        {
            documentationTitle = "Kentico Widgets";
            Page.Header.Title  = "Widgets documentation";
        }

        if (!allWebParts && !allWidgets && !allWireframes && !isWebpartInQuery && !isWidgetInQuery)
        {
            pnlContent.Visible = false;
            pnlInfo.Visible    = true;
        }

        // Check whether at least one category is present
        if (!DataHelper.DataSourceIsEmpty(cds))
        {
            string namePrefix = ((isWidgetInQuery) || (allWidgets)) ? "Widget" : String.Empty;

            // Loop through all web part categories
            foreach (DataRow cdr in cds.Tables[0].Rows)
            {
                // Get all webpart in the categories
                if (allWebParts || allWireframes)
                {
                    ds = WebPartInfoProvider.GetAllWebParts(Convert.ToInt32(cdr["CategoryId"]));
                }
                // Get all widgets in the category
                else if (allWidgets)
                {
                    int categoryID = Convert.ToInt32(cdr["WidgetCategoryId"]);
                    ds = WidgetInfoProvider.GetWidgets().WhereEquals("WidgetCategoryID", categoryID);
                }

                // Check whether current category contains at least one webpart
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Generate category name code
                    menu += "<br /><strong>" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "</strong><br /><br />";

                    // Loop through all web web parts in categories
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // Init
                        isImagePresent         = false;
                        undocumentedProperties = 0;
                        documentation          = 0;

                        // Webpart (Widget) information
                        string itemDisplayName   = String.Empty;
                        string itemDescription   = String.Empty;
                        string itemDocumentation = String.Empty;
                        string itemType          = String.Empty;
                        int    itemID            = 0;

                        WebPartInfo wpi = null;
                        WidgetInfo  wi  = null;

                        // Set webpart info
                        if (isWebpartInQuery || allWebParts || allWireframes)
                        {
                            wpi = new WebPartInfo(dr);
                            if (wpi != null)
                            {
                                itemDisplayName   = wpi.WebPartDisplayName;
                                itemDescription   = wpi.WebPartDescription;
                                itemDocumentation = wpi.WebPartDocumentation;
                                itemID            = wpi.WebPartID;
                                itemType          = WebPartInfo.OBJECT_TYPE;

                                if (wpi.WebPartCategoryID != ValidationHelper.GetInteger(cdr["CategoryId"], 0))
                                {
                                    wpi = null;
                                }
                            }
                        }
                        // Set widget info
                        else if ((isWidgetInQuery) || (allWidgets))
                        {
                            wi = new WidgetInfo(dr);
                            if (wi != null)
                            {
                                itemDisplayName   = wi.WidgetDisplayName;
                                itemDescription   = wi.WidgetDescription;
                                itemDocumentation = wi.WidgetDocumentation;
                                itemType          = WidgetInfo.OBJECT_TYPE;
                                itemID            = wi.WidgetID;

                                if (wi.WidgetCategoryID != ValidationHelper.GetInteger(cdr["WidgetCategoryId"], 0))
                                {
                                    wi = null;
                                }
                            }
                        }

                        // Check whether web part (widget) exists
                        if ((wpi != null) || (wi != null))
                        {
                            // Link GUID
                            Guid mguid = Guid.NewGuid();

                            // Whether description is present in webpart
                            bool isDescription = false;

                            // Image url
                            string wimgurl = GetItemImage(itemID, itemType);

                            // Set description text
                            string descriptionText = itemDescription;

                            // Parent webpart info
                            WebPartInfo pwpi = null;

                            // If webpart look for parent's description and documentation
                            if (wpi != null)
                            {
                                // Get parent description if webpart is inherited
                                if (wpi.WebPartParentID > 0)
                                {
                                    pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                                    if (pwpi != null)
                                    {
                                        if ((descriptionText == null || descriptionText.Trim() == ""))
                                        {
                                            // Set description from parent
                                            descriptionText = pwpi.WebPartDescription;
                                        }

                                        // Set documentation text from parent if WebPart is inherited
                                        if ((wpi.WebPartDocumentation == null) || (wpi.WebPartDocumentation.Trim() == ""))
                                        {
                                            itemDocumentation = pwpi.WebPartDocumentation;
                                            if (!String.IsNullOrEmpty(itemDocumentation))
                                            {
                                                documentation = 2;
                                            }
                                        }
                                    }
                                }
                            }

                            // Set description as present
                            if (descriptionText.Trim().Length > 0)
                            {
                                isDescription = true;
                            }

                            // Generate HTML for menu and content
                            menu += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a>&nbsp;";

                            // Generate webpart header
                            content += "<table style=\"width:100%;\"><tr><td><h1><a name=\"_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(cdr[namePrefix + "CategoryDisplayName"].ToString())) + "&nbsp;>&nbsp;" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(itemDisplayName)) + "</a></h1></td><td style=\"text-align:right;\">&nbsp;<a href=\"#top\" class=\"noprint\">top</a></td></tr></table>";

                            // Generate WebPart content
                            content +=
                                @"<table style=""width: 100%; height: 200px; border: solid 1px #DDDDDD;"">
                                   <tr> 
                                     <td style=""width: 50%; text-align:center; border-right: solid 1px #DDDDDD; vertical-align: middle;margin-left: auto; margin-right:auto; text-align:center;"">
                                         <img src=""" + wimgurl + @""" alt=""imageTeaser"">
                                     </td>
                                     <td style=""width: 50%; vertical-align: center;text-align:center;"">"
                                + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(descriptionText)) + @"
                                     </td>
                                   </tr>
                                </table>";

                            // Properties content
                            content += "<div class=\"DocumentationWebPartsProperties\">";

                            // Generate content
                            if (wpi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wpi));
                            }
                            else if (wi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wi));
                            }

                            // Close content area
                            content += "</div>";

                            // Generate documentation text content
                            content += "<br /><div style=\"border: solid 1px #dddddd;width: 100%;\">" +
                                       DataHelper.GetNotEmpty(HTMLHelper.ResolveUrls(itemDocumentation, null), "<strong>Additional documentation text is not provided.</strong>") +
                                       "</div>";

                            // Set page break tag for print
                            content += "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />";

                            // If development is required - highlight missing description, images and doc. text
                            if (development)
                            {
                                // Check image
                                if (!isImagePresent)
                                {
                                    menu += "<span style=\"color:Brown;\">image&nbsp;</span>";
                                }

                                // Check properties
                                if (undocumentedProperties > 0)
                                {
                                    menu += "<span style=\"color:Red;\">properties(" + undocumentedProperties + ")&nbsp;</span>";
                                }

                                // Check properties
                                if (!isDescription)
                                {
                                    menu += "<span style=\"color:#37627F;\">description&nbsp;</span>";
                                }

                                // Check documentation text
                                if (String.IsNullOrEmpty(itemDocumentation))
                                {
                                    documentation = 1;
                                }

                                switch (documentation)
                                {
                                // Display information about missing documentation
                                case 1:
                                    menu += "<span style=\"color:Green;\">documentation&nbsp;</span>";
                                    break;

                                // Display information about inherited documentation
                                case 2:
                                    menu += "<span style=\"color:Green;\">documentation (inherited)&nbsp;</span>";
                                    break;
                                }
                            }

                            menu += "<br />";
                        }
                    }
                }
            }
        }

        ltlContent.Text = menu + "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />" + content;
    }
Ejemplo n.º 6
0
        /// <summary>
        /// Generates an A tag with a "mailto" link.
        /// </summary>
        /// <param name="htmlHelper">HTML helper.</param>
        /// <param name="email">Email address.</param>
        public static MvcHtmlString MailTo(this HtmlHelper htmlHelper, string email)
        {
            if (string.IsNullOrEmpty(email))
            {
                return(MvcHtmlString.Empty);
            }

            var link = string.Format("<a href=\"mailto:{0}\">{1}</a>", HTMLHelper.EncodeForHtmlAttribute(email), HTMLHelper.HTMLEncode(email));

            return(MvcHtmlString.Create(link));
        }
    /// <summary>
    /// Restores set of given version histories.
    /// </summary>
    /// <param name="currentUserInfo">Current user info</param>
    /// <param name="recycleBin">DataSet with nodes to restore</param>
    private void RestoreDataSet(BinSettingsContainer settings, DataSet recycleBin, Action action)
    {
        // Result flags
        bool resultOK = true;

        if (!DataHelper.DataSourceIsEmpty(recycleBin))
        {
            // Restore all objects
            foreach (DataRow dataRow in recycleBin.Tables[0].Rows)
            {
                int versionId = ValidationHelper.GetInteger(dataRow["VersionID"], 0);

                // Log current event
                string taskTitle = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(dataRow["VersionObjectDisplayName"], string.Empty)));

                // Restore object
                if (versionId > 0)
                {
                    GeneralizedInfo restoredObj = null;
                    try
                    {
                        switch (action)
                        {
                        case Action.Restore:
                            restoredObj = ObjectVersionManager.RestoreObject(versionId, true);
                            break;

                        case Action.RestoreToCurrentSite:
                            restoredObj = ObjectVersionManager.RestoreObject(versionId, CMSContext.CurrentSiteID);
                            break;

                        case Action.RestoreWithoutSiteBindings:
                            restoredObj = ObjectVersionManager.RestoreObject(versionId, 0);
                            break;
                        }
                    }
                    catch (CodeNameNotUniqueException ex)
                    {
                        CurrentError = String.Format(GetString("objectversioning.restorenotuniquecodename"), (ex.Object != null) ? "('" + ex.Object.ObjectCodeName + "')" : null);
                        AddLog(CurrentError);
                    }

                    if (restoredObj != null)
                    {
                        AddLog(ResHelper.GetString("general.object", currentCulture) + " '" + taskTitle + "'");
                    }
                    else
                    {
                        // Set result flag
                        if (resultOK)
                        {
                            resultOK = false;
                        }
                    }
                }
            }
        }

        if (resultOK)
        {
            CurrentInfo = ResHelper.GetString("ObjectVersioning.Recyclebin.RestorationOK", currentCulture);
            AddLog(CurrentInfo);
        }
        else
        {
            CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", currentCulture);
            AddLog(CurrentError);
        }
    }
Ejemplo n.º 8
0
    /// <summary>
    /// Creates node.
    /// </summary>
    /// <param name="uniNode">Node to create</param>
    protected TreeNode CreateNode(UniTreeNode uniNode)
    {
        var data = (DataRow)uniNode.ItemData;

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

        TreeNode node = new TreeNode();

        // Get data
        int childNodesCount = 0;

        if (!String.IsNullOrEmpty(ProviderObject.ChildCountColumn))
        {
            childNodesCount = ValidationHelper.GetInteger(data[ProviderObject.ChildCountColumn], 0);
        }

        // Node ID
        int nodeId = 0;

        if (!String.IsNullOrEmpty(ProviderObject.IDColumn))
        {
            nodeId = ValidationHelper.GetInteger(data[ProviderObject.IDColumn], 0);
        }

        // Node value
        string nodeValue = String.Empty;

        if (!String.IsNullOrEmpty(ProviderObject.ValueColumn))
        {
            nodeValue = nodeId.ToString();
        }

        string objectType = String.Empty;

        if (!String.IsNullOrEmpty(ProviderObject.ObjectTypeColumn))
        {
            objectType = ValidationHelper.GetString(data[ProviderObject.ObjectTypeColumn], "");

            // Add object type to value
            nodeValue += "_" + objectType;
        }

        // Caption
        string displayName = String.Empty;

        if (!String.IsNullOrEmpty(ProviderObject.CaptionColumn))
        {
            displayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(data[ProviderObject.CaptionColumn], "")));
        }

        // Display name, if caption is empty (or non existent)
        if (!String.IsNullOrEmpty(ProviderObject.DisplayNameColumn) && String.IsNullOrEmpty(displayName))
        {
            displayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(data[ProviderObject.DisplayNameColumn], "")));
        }

        // Path
        string nodePath = String.Empty;

        if (!String.IsNullOrEmpty(ProviderObject.PathColumn))
        {
            nodePath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(data[ProviderObject.PathColumn], "")).ToLowerCSafe();
        }

        // Parent ID
        int parentId = 0;

        if (!String.IsNullOrEmpty(ProviderObject.ParentIDColumn))
        {
            parentId = ValidationHelper.GetInteger(data[ProviderObject.ParentIDColumn], 0);
        }

        // Parameter
        string parameter = String.Empty;

        if (!String.IsNullOrEmpty(ProviderObject.ParameterColumn))
        {
            parameter = HTMLHelper.HTMLEncode(ValidationHelper.GetString(data[ProviderObject.ParameterColumn], "")).ToLowerCSafe();
        }

        int nodeLevel = 0;

        if (!String.IsNullOrEmpty(ProviderObject.LevelColumn))
        {
            nodeLevel = ValidationHelper.GetInteger(data[ProviderObject.LevelColumn], 0);
        }

        // Set navigation URL to current page
        node.NavigateUrl = RequestContext.CurrentURL + "#";

        // Set value
        node.Value = nodeValue;

        // Get tree icon
        var treeIcon = GetNodeIconMarkup(uniNode, data);

        // Set text
        string text;

        string selectedItem      = ValidationHelper.GetString(SelectedItem, "");
        string selectPathLowered = SelectPath.ToLowerCSafe();

        if (nodeValue.EqualsCSafe(selectedItem, true) || ((selectPathLowered == nodePath) && String.IsNullOrEmpty(selectedItem)))
        {
            text = ReplaceMacros(SelectedNodeTemplate, nodeId, childNodesCount, displayName, treeIcon, parentId, objectType, parameter);
        }
        else
        {
            text = ReplaceMacros(NodeTemplate, nodeId, childNodesCount, displayName, treeIcon, parentId, objectType, parameter);
        }

        if (UsePostBack)
        {
            text = "<span onclick=\"" + ControlsHelper.GetPostBackEventReference(this, nodeValue + ";" + nodePath) + "\">" + text + "</span>";
        }

        node.Text = text;

        // Set populate node automatically
        if (childNodesCount != 0)
        {
            node.PopulateOnDemand = true;
        }

        // Expand tree
        if (ExpandAll)
        {
            node.Expanded = true;
        }
        else if (CollapseAll)
        {
            node.Expanded = false;
        }
        else
        {
            // Handle expand path
            if (!nodePath.EndsWith("/"))
            {
                nodePath += "/";
            }

            string expandPathLowered = ExpandPath.ToLowerCSafe();

            if (selectPathLowered.StartsWithCSafe(nodePath) && (selectPathLowered != nodePath))
            {
                node.Expanded = true;
            }
            else if ((expandPathLowered.StartsWithCSafe(nodePath)))
            {
                node.Expanded = true;
            }
            else
            // Path expanded by user
            if (selectedPath.StartsWithCSafe(nodePath) && (selectedPath != nodePath))
            {
                node.Expanded = true;
            }
            // Expand all roots for multiple roots tree
            else if ((parentId == 0) && MultipleRoots)
            {
                node.Expanded = true;
            }
            else
            {
                node.Expanded = false;
            }
        }

        // Expand level
        if ((ExpandLevel != 0) && !CollapseAll)
        {
            node.Expanded = nodeLevel <= ExpandLevel;
        }

        return(node);
    }
    /// <summary>
    /// Initializes the control properties
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            // Register JQuery
            ScriptHelper.RegisterJQuery(Page);

            treeElemG.StopProcessing = !DisplayGlobalCategories && !DisplaySiteCategories;
            treeElemP.StopProcessing = !DisplayPersonalCategories;

            // Use images according to culture
            if (CultureHelper.IsPreferredCultureRTL())
            {
                treeElemG.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false);
                treeElemP.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false);
            }
            else
            {
                treeElemG.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false);
                treeElemP.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false);
            }

            // Prepare node templates
            treeElemP.SelectedNodeTemplate = treeElemG.SelectedNodeTemplate = "<span id=\"" + ClientID + "node_##NODECODENAME##\" class=\"CategoryTreeItem " + SelectedItemCSS + "\">##BEFORENAME####ICON##<span class=\"Name\">##NODECUSTOMNAME##</span>##AFTERNAME##</span>";
            treeElemP.NodeTemplate         = treeElemG.NodeTemplate = "<span id=\"" + ClientID + "node_##NODECODENAME##\" class=\"CategoryTreeItem\">##BEFORENAME####ICON##<span class=\"Name\">##NODECUSTOMNAME##</span>##AFTERNAME##</span>";

            // Init tree provider objects
            treeElemG.ProviderObject = CreateTreeProvider(CMSContext.CurrentSiteID, 0);
            if (!treeElemP.StopProcessing && (CMSContext.CurrentUser != null))
            {
                treeElemP.ProviderObject = CreateTreeProvider(0, CMSContext.CurrentUser.UserID);
            }

            // Expand first level by default
            treeElemP.ExpandPath = treeElemG.ExpandPath = "/";

            // Create root node for global and site categories
            string rootIcon    = "";
            string rootCatName = CategoriesRoot;
            string rootId      = "NULL";
            string before      = "";
            string after       = "";

            if (StartingCategoryObj != null)
            {
                rootId      = StartingCategoryObj.CategoryID.ToString();
                rootCatName = HTMLHelper.HTMLEncode(StartingCategoryObj.CategoryDisplayName);

                before = string.Format("<a href=\"{0}\">", URLHelper.EncodeQueryString(GetUrl(StartingCategoryObj)));
                after  = "</a>";
            }

            string rootName = "<span class=\"TreeRoot\">" + ResHelper.LocalizeString(rootCatName) + "</span>";
            string rootText = treeElemG.ReplaceMacros(treeElemG.NodeTemplate, 0, 6, rootName, rootIcon, 0, null, null);

            // Replace macros
            rootText = rootText.Replace("##NODECUSTOMNAME##", rootName);
            rootText = rootText.Replace("##NODECODENAME##", "CategoriesRoot");
            rootText = rootText.Replace("##PARENTID##", CATEGORIES_ROOT_PARENT_ID.ToString());
            rootText = rootText.Replace("##BEFORENAME##", before);
            rootText = rootText.Replace("##AFTERNAME##", after);

            string itemImg = CategoriesRootImageUrl;
            if (!string.IsNullOrEmpty(itemImg) && itemImg.StartsWithCSafe("~/"))
            {
                itemImg = ResolveUrl(itemImg);
            }

            if (string.IsNullOrEmpty(itemImg))
            {
                itemImg = null;
            }

            treeElemG.SetRoot(rootText, rootId, itemImg, null, null);

            rootName = "<span class=\"TreeRoot\">" + ResHelper.LocalizeString(PersonalCategoriesRoot) + "</span>";
            rootText = treeElemP.ReplaceMacros(treeElemP.NodeTemplate, 0, 6, rootName, rootIcon, 0, null, null);

            // Replace macros
            rootText = rootText.Replace("##NODECUSTOMNAME##", rootName);
            rootText = rootText.Replace("##NODECODENAME##", "PersonalCategoriesRoot");
            rootText = rootText.Replace("##PARENTID##", PERSONAL_CATEGORIES_ROOT_PARENT_ID.ToString());
            rootText = rootText.Replace("##BEFORENAME##", "");
            rootText = rootText.Replace("##AFTERNAME##", "");

            itemImg = PersonalCategoriesRootImageUrl;
            if (!string.IsNullOrEmpty(itemImg) && itemImg.StartsWithCSafe("~/"))
            {
                itemImg = ResolveUrl(itemImg);
            }

            if (string.IsNullOrEmpty(itemImg))
            {
                itemImg = null;
            }

            treeElemP.SetRoot(rootText, "NULL", itemImg, null, null);
        }
    }
Ejemplo n.º 10
0
    protected void memberListElem_GridOnAction(object sender, CommandEventArgs args)
    {
        switch (args.CommandName.ToLowerCSafe())
        {
        case "approve":
            lblInfo.Text    = GetString("group.member.userhasbeenapproved");
            lblInfo.Visible = true;
            break;

        case "reject":
            lblInfo.Text    = GetString("group.member.userhasbeenrejected");
            lblInfo.Visible = true;
            break;

        case "edit":
            int memberId = ValidationHelper.GetInteger(args.CommandArgument, 0);
            memberEditElem.MemberID = memberId;
            memberEditElem.GroupID  = GroupID;
            plcList.Visible         = false;
            plcEdit.Visible         = true;
            memberEditElem.Visible  = true;
            memberEditElem.ReloadData();

            GroupMemberInfo gmi = GroupMemberInfoProvider.GetGroupMemberInfo(memberId);
            if (gmi != null)
            {
                UserInfo ui = UserInfoProvider.GetUserInfo(gmi.MemberUserID);
                if (ui != null)
                {
                    lblEditBack.Text = " <span class=\"TitleBreadCrumbSeparator\">&nbsp;</span> " + HTMLHelper.HTMLEncode(ui.FullName);
                }
            }
            break;
        }
    }
Ejemplo n.º 11
0
    /// <summary>
    /// Page PreRender.
    /// </summary>
    /// <param name="e">Arguments</param>
    protected override void OnPreRender(EventArgs e)
    {
        int index = 0;

        foreach (object item in defaultItems)
        {
            string[] defaultItem = (string[])item;

            if (defaultItem != null)
            {
                // Generate link HTML tag
                string selectedItem = ValidationHelper.GetString(SelectedItem, "").ToLowerCSafe();
                string template     = (selectedItem == defaultItem[2].ToLowerCSafe()) ? SelectedDefaultItemTemplate : DefaultItemTemplate;

                string link = ReplaceMacros(template, 0, 0, defaultItem[0], defaultItem[1], 0, "", "");

                // Add complete HTML code to page
                if (UsePostBack)
                {
                    link = "<span onclick=\"" + ControlsHelper.GetPostBackEventReference(this, HTMLHelper.HTMLEncode(defaultItem[2])) + "\">" + link + "</span>";
                }

                TreeNode tn = new TreeNode();
                tn.Text        = link;
                tn.NavigateUrl = RequestContext.CurrentURL + "#";
                TreeView.Nodes.AddAt(index, tn);
                index++;
            }
        }

        if (DisplayPopulatingIndicator && !RequestHelper.IsCallback())
        {
            // Register tree progress icon
            ScriptHelper.RegisterTreeProgress(Page);
        }

        base.OnPreRender(e);
    }
Ejemplo n.º 12
0
    /// <summary>
    /// Saves the data.
    /// </summary>
    private bool Save(string newsletterName, ContactInfo contact)
    {
        bool toReturn = false;
        int  siteId   = SiteContext.CurrentSiteID;

        // Check if subscriber info object exists
        if (string.IsNullOrEmpty(newsletterName) || (contact == null))
        {
            return(false);
        }

        // Get newsletter info
        NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterName, siteId);

        if (newsletter != null)
        {
            try
            {
                // Check if contact is not marketable
                if (!mSubscriptionService.IsMarketable(contact, newsletter))
                {
                    toReturn = true;

                    mSubscriptionService.Subscribe(contact, newsletter, new SubscribeSettings()
                    {
                        SendConfirmationEmail = SendConfirmationEmail,
                        AllowOptIn            = true,
                        RemoveAlsoUnsubscriptionFromAllNewsletters = true,
                    });

                    // Info message
                    if (!chooseMode)
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("NewsletterSubscription.Subscribed");
                    }

                    // Track successful subscription conversion
                    if (TrackConversionName != string.Empty)
                    {
                        string siteName = SiteContext.CurrentSiteName;

                        if (AnalyticsHelper.AnalyticsEnabled(siteName) && Service.Resolve <IAnalyticsConsentProvider>().HasConsentForLogging() && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress))
                        {
                            // Log conversion
                            HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                        }
                    }
                }
                else
                {
                    // Info message - subscriber is allready in site
                    if (!chooseMode)
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed");
                    }
                    else
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text   += GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY") + " " + HTMLHelper.HTMLEncode(newsletter.NewsletterDisplayName) + ".<br />";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("NewsletterSubscription.NewsletterDoesNotExist");
        }

        return(toReturn);
    }
Ejemplo n.º 13
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            return;
        }

        // Hide info label of the captcha control because the newsletter subscription web part has its own
        scCaptcha.ShowInfoLabel = false;

        lblFirstName.Text         = FirstNameText;
        lblLastName.Text          = LastNameText;
        lblEmail.Text             = EmailText;
        lblCaptcha.ResourceString = CaptchaText;
        plcCaptcha.Visible        = DisplayCaptcha;

        if ((UseImageButton) && (!String.IsNullOrEmpty(ImageButtonURL)))
        {
            pnlButtonSubmit.Visible = false;
            pnlImageSubmit.Visible  = true;
            btnImageSubmit.ImageUrl = ImageButtonURL;
        }
        else
        {
            pnlButtonSubmit.Visible = true;
            pnlImageSubmit.Visible  = false;
            btnSubmit.Text          = ButtonText;
        }

        // Display labels only if user is logged in and property AllowUserSubscribers is set to true
        if (AllowUserSubscribers && AuthenticationHelper.IsAuthenticated())
        {
            visibleFirstName = false;
            visibleLastName  = false;
            visibleEmail     = false;
        }
        // Otherwise display text-boxes
        else
        {
            visibleFirstName = true;
            visibleLastName  = true;
            visibleEmail     = true;
        }

        // Hide first name field if not required
        if (!DisplayFirstName)
        {
            visibleFirstName = false;
        }
        // Hide last name field if not required
        if (!DisplayLastName)
        {
            visibleLastName = false;
        }

        // Show/hide newsletter list
        plcNwsList.Visible = NewsletterName.EqualsCSafe("nwsletuserchoose", true);
        if (plcNwsList.Visible)
        {
            chooseMode = true;

            if ((!ExternalUse || !RequestHelper.IsPostBack()) && (chklNewsletters.Items.Count == 0))
            {
                DataSet ds = null;

                // Try to get data from cache
                using (var cs = new CachedSection <DataSet>(ref ds, CacheMinutes, true, CacheItemName, "newslettersubscription", SiteContext.CurrentSiteName))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        ds = NewsletterInfoProvider.GetNewslettersForSite(SiteContext.CurrentSiteID).WhereEquals("NewsletterType", (int)EmailCommunicationTypeEnum.Newsletter).OrderBy("NewsletterDisplayName").Columns("NewsletterDisplayName", "NewsletterName");

                        // Add data to the cache
                        if (cs.Cached)
                        {
                            // Prepare cache dependency
                            cs.CacheDependency = CacheHelper.GetCacheDependency("newsletter.newsletter|all");
                        }

                        cs.Data = ds;
                    }
                }

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    ListItem li          = null;
                    string   displayName = null;

                    // Fill checkbox list with newsletters
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        displayName = ValidationHelper.GetString(dr["NewsletterDisplayName"], string.Empty);

                        li = new ListItem(HTMLHelper.HTMLEncode(displayName), ValidationHelper.GetString(dr["NewsletterName"], string.Empty));
                        chklNewsletters.Items.Add(li);
                    }
                }
            }
        }

        // Set SkinID properties
        if (!StandAlone && (PageCycle < PageCycleEnum.Initialized) && (string.IsNullOrEmpty(ValidationHelper.GetString(Page.StyleSheetTheme, string.Empty))))
        {
            string skinId = SkinID;
            if (!string.IsNullOrEmpty(skinId))
            {
                lblFirstName.SkinID = skinId;
                lblLastName.SkinID  = skinId;
                lblEmail.SkinID     = skinId;
                txtFirstName.SkinID = skinId;
                txtLastName.SkinID  = skinId;
                txtEmail.SkinID     = skinId;
                btnSubmit.SkinID    = skinId;
            }
        }
    }
Ejemplo n.º 14
0
    /// <summary>
    /// Saves webpart properties.
    /// </summary>
    public bool Save()
    {
        // Check MVT/CP security
        if (VariantID > 0)
        {
            // Check OnlineMarketing permissions.
            if (!CheckPermissions("Manage"))
            {
                ShowError("general.modifynotallowed");
                return(false);
            }
        }

        // Save the data
        if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(form))
        {
            if (SynchronizationHelper.IsCheckedOutByOtherUser(pti))
            {
                string   userName = null;
                UserInfo ui       = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID);
                if (ui != null)
                {
                    userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite));
                }

                ShowError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.TypeInfo.ObjectType, pti.DisplayName, userName));
                return(false);
            }

            // Add web part if new
            if (IsNewWebPart)
            {
                int webpartId = ValidationHelper.GetInteger(WebPartID, 0);

                // Ensure layout zone flag
                if (QueryHelper.GetBoolean("layoutzone", false))
                {
                    WebPartZoneInstance zone = pti.TemplateInstance.EnsureZone(ZoneID);
                    zone.LayoutZone = true;
                }

                webPartInstance = PortalHelper.AddNewWebPart(webpartId, ZoneID, false, ZoneVariantID, Position, templateInstance);

                // Set default layout
                if (wpi.WebPartParentID > 0)
                {
                    WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetDefaultLayout(wpi.WebPartID);
                    if (wpli != null)
                    {
                        webPartInstance.SetValue("WebPartLayout", wpli.WebPartLayoutCodeName);
                    }
                }
            }

            webPartInstance.XMLVersion = 1;
            if (IsNewVariant)
            {
                webPartInstance             = webPartInstance.Clone();
                webPartInstance.VariantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", String.Empty).ToLowerCSafe());
            }

            // Get basic form's data row and update web part
            SaveFormToWebPart(form);

            // Set new position if set
            if (PositionLeft > 0)
            {
                webPartInstance.SetValue("PositionLeft", PositionLeft);
            }
            if (PositionTop > 0)
            {
                webPartInstance.SetValue("PositionTop", PositionTop);
            }

            // Ensure the data source web part instance in the main web part
            if (NestedWebPartID > 0)
            {
                webPartInstance.WebPartType = wpi.WebPartName;
                mainWebPartInstance.NestedWebParts[NestedWebPartKey] = webPartInstance;
            }

            bool isWebPartVariant = (VariantID > 0) || (ZoneVariantID > 0) || IsNewVariant;
            if (!isWebPartVariant)
            {
                // Save the changes
                CMSPortalManager.SaveTemplateChanges(pi, templateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree);
            }
            else
            {
                Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable;
                // Save changes to the web part variant
                VariantHelper.SaveWebPartVariantChanges(webPartInstance, VariantID, ZoneVariantID, VariantMode, varProperties);
            }

            // Reload the form (because of macro values set only by JS)
            form.ReloadData();

            // Clear the cached web part
            CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe());

            ShowChangesSaved();

            return(true);
        }
        else if ((mainWebPartInstance != null) && (mainWebPartInstance.ParentZone != null) && (mainWebPartInstance.ParentZone.ParentTemplateInstance != null))
        {
            // Reload the zone/web part variants when saving of the form fails
            mainWebPartInstance.ParentZone.ParentTemplateInstance.LoadVariants(true, VariantModeEnum.None);
        }

        return(false);
    }
    /// <summary>
    /// Handles the PreRender event of the Page control.
    /// </summary>
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (stopProcessing)
        {
            Visible = false;
            return;
        }

        // Check permissions
        if (!CheckPermissions("Manage"))
        {
            // Hide add/remove variant buttons when the Manage permission is not allowed
            plcRemoveVariant.Visible = false;
            plcAddVariant.Visible    = false;
        }

        // Hide buttons in the template edit in the site manager
        if (DocumentContext.CurrentDocument == null)
        {
            plcRemoveVariant.Visible = false;
            plcAddVariant.Visible    = false;
            plcVariantList.Visible   = false;
        }

        // Get the sum of all variants
        int totalVariants = 0;

        switch (SliderMode)
        {
        case VariantTypeEnum.Zone:
            // Zone
            if ((WebPartZoneControl != null) &&
                (WebPartZoneControl.HasVariants) &&
                (WebPartZoneControl.ZoneInstance != null) &&
                (WebPartZoneControl.ZoneInstance.ZoneInstanceVariants != null))
            {
                totalVariants = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Count;
            }
            break;

        case VariantTypeEnum.WebPart:
        case VariantTypeEnum.Widget:
            // Web part
            // Widget
            if ((WebPartControl != null) &&
                (WebPartControl.HasVariants) &&
                (WebPartControl.PartInstance != null) &&
                (WebPartControl.PartInstance.PartInstanceVariants != null))
            {
                totalVariants = WebPartControl.PartInstance.PartInstanceVariants.Count;
            }
            break;
        }

        // Increase by 1 to include the original webpart
        totalVariants++;

        // Reset the slider state (correct variant for the current combination is chosen by javascript in window.onload)
        txtSlider.Text = "1";
        if (isRTL)
        {
            // Reverse position index when in RTL
            txtSlider.Text = totalVariants.ToString();
        }

        // Change the slider CSS class if used for widgets
        if ((WebPartControl != null) &&
            WebPartControl.IsWidget)
        {
            pnlVariations.CssClass = "WidgetVariantSlider";
        }

        // Setup the variant slider extender
        sliderExtender.Minimum        = 1;
        sliderExtender.Maximum        = totalVariants;
        sliderExtender.Steps          = totalVariants;
        sliderExtender.HandleImageUrl = GetImageUrl("Design/Controls/VariantSlider/slider.png");

        if (isRTL)
        {
            // RTL culture - set the javascript variable
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "VariantSliderRTL", ScriptHelper.GetScript("variantSliderIsRTL = true;"));
        }

        // Change the arrows design for MVT
        if ((VariantMode == VariantModeEnum.MVT) || !PortalContext.ContentPersonalizationEnabled)
        {
            //pnlLeft.CssClass = "SliderLeftMVT";
            //pnlRight.CssClass = "SliderRightMVT";
        }

        CssRegistration.RegisterBootstrap(Page);

        sliderExtender.HandleCssClass = "slider-horizontal-handle";
        sliderExtender.RailCssClass   = "slider-horizontal-rail";
        lblTotal.Text = totalVariants.ToString();

        txtSlider.Attributes.Add("onchange", "$cmsj('#" + hdnSliderPosition.ClientID + "').change();");
        txtSlider.Style.Add("display", "none");

        // Prepare the parameters
        string zoneId = string.Empty;

        PageInfo pi = PagePlaceholder.PageInfo;

        string aliasPath  = pi.NodeAliasPath;
        string templateId = pi.GetUsedPageTemplateId().ToString();

        string webPartName        = string.Empty;
        string instanceGuidString = string.Empty;

        switch (SliderMode)
        {
        case VariantTypeEnum.Zone:
            // Zone
            zoneId = WebPartZoneControl.ZoneInstance.ZoneID;
            break;

        case VariantTypeEnum.WebPart:
        case VariantTypeEnum.Widget:
            // Web part
            zoneId             = WebPartControl.PartInstance.ParentZone.ZoneID;
            instanceGuidString = WebPartControl.InstanceGUID.ToString();
            webPartName        = WebPartControl.PartInstance.ControlID;
            break;
        }

        // Setup tooltips
        pnlLeft.ToolTip          = ResHelper.GetString("variantslider.btnleft", UICulture);
        pnlRight.ToolTip         = ResHelper.GetString("variantslider.btnright", UICulture);
        imgRemoveVariant.ToolTip = ResHelper.GetString("variantslider.btnremove", UICulture);
        imgVariantList.ToolTip   = ResHelper.GetString("variantslider.btnlist", UICulture);

        // Setup default behaviour - no action executed
        imgRemoveVariantDisabled.Attributes.Add("onclick", "return false;");
        imgVariantList.Attributes.Add("onclick", "return false;");

        // Cancel propagation of the double-click event (skips opening the web part properties dialog)
        pnlVariations.Attributes.Add("ondblclick", "CancelEventPropagation(event)");

        // Hidden field used for changing the slider position. The position of the slider is stored also here because of the usage of the slider arrows.
        hdnSliderPosition.Style.Add("display", "none");
        hdnSliderPosition.Attributes.Add("onchange", "OnHiddenChanged(this, document.getElementById('" + lblPart.ClientID + "'), '" + uniqueCode + "', '" + sliderExtender.BehaviorID + @"' );");

        String zoneIdPar    = (WebPartControl != null) ? "GetActualZoneId('wp_" + WebPartControl.InstanceGUID.ToString("N") + "')" : "'" + zoneId + "'";
        string dialogParams = zoneIdPar + ", '" + webPartName + "', '" + aliasPath + "', '" + instanceGuidString + "', " + templateId + ", '" + VariantTypeFunctions.GetVariantTypeString(SliderMode) + "'";

        // Allow edit actions
        if (totalVariants == 1)
        {
            if (SliderMode == VariantTypeEnum.Widget)
            {
                plcRemoveVariant.Visible = false;
                plcVariantList.Visible   = false;
                plcSliderPanel.Visible   = false;
                var  cui       = MembershipContext.AuthenticatedUser;
                bool manageMVT = cui.IsAuthorizedPerResource("cms.mvtest", "manage") && cui.IsAuthorizedPerResource("cms.mvtest", "read");
                bool manageCP  = cui.IsAuthorizedPerResource("cms.contentpersonalization", "manage") && cui.IsAuthorizedPerResource("cms.contentpersonalization", "read");

                if (PortalContext.MVTVariantsEnabled && PortalContext.ContentPersonalizationEnabled && manageMVT && manageCP)
                {
                    pnlAddVariantWrapper.Attributes.Add("onclick", "OpenMenuAddWidgetVariant(this, '" + WebPartControl.ShortClientID + "'); return false;");
                    imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnadd", UICulture);

                    // Script for opening a new variant dialog window and activating widget border to prevent to widget border from hiding
                    // when the user moves his mouse to the 'add widget' context menu.
                    string script = @"
function OpenMenuAddWidgetVariant(menuPositionEl, targetId) {
    currentContextMenuId = targetId;
    ContextMenu('addWidgetVariantMenu', menuPositionEl, webPartLocation[targetId + '_container'], true);
    AutoPostitionContextMenu('addWidgetVariantMenu');
}";
                    ScriptHelper.RegisterStartupScript(this, typeof(string), "OpenMenuAddWidgetVariantScript", ScriptHelper.GetScript(script));
                }
                else
                {
                    if (PortalContext.MVTVariantsEnabled && manageMVT)
                    {
                        imgAddVariant.Attributes.Add("onclick", "AddMVTVariant(" + dialogParams + "); return false;");
                        imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddmvt", UICulture);
                    }
                    else if (PortalContext.ContentPersonalizationEnabled && manageCP)
                    {
                        imgAddVariant.Attributes.Add("onclick", "AddPersonalizationVariant(" + dialogParams + "); return false;");
                        imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddpesronalization", UICulture);
                    }
                }
            }
        }
        else
        {
            if (VariantMode == VariantModeEnum.MVT)
            {
                imgAddVariant.Attributes.Add("onclick", "AddMVTVariant(" + dialogParams + "); return false;");
                imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddmvt", UICulture);
            }
            else
            {
                imgAddVariant.Attributes.Add("onclick", "AddPersonalizationVariant(" + dialogParams + "); return false;");
                imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddpesronalization", UICulture);
            }
        }

        if ((totalVariants > 1) || (SliderMode == VariantTypeEnum.Widget))
        {
            // Register only for full postback or first page load
            if (!RequestHelper.IsAsyncPostback())
            {
                if ((VariantMode == VariantModeEnum.MVT))
                {
                    // Activate the variant list button fot MVT
                    imgVariantList.Attributes.Add("onclick", "ListMVTVariants(" + dialogParams + ", '" + uniqueCode + "'); return false;");
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    // Activate the variant list button for Content personalization
                    imgVariantList.Attributes.Add("onclick", "ListPersonalizationVariants(" + dialogParams + ", '" + uniqueCode + "'); return false;");
                }

                // Assign the onclick event for he Remove variant button
                imgRemoveVariant.Attributes.Add("onclick", "RemoveVariantPostBack_" + uniqueCode + @"(); return false");

                // Register Remove variant script
                string removeVariantScript = @"
                function RemoveVariantPostBack_" + uniqueCode + @"() {
                    if (confirm(" + ScriptHelper.GetLocalizedString("variantslider.removeconfirm") + @")) {" +
                                             DocumentManager.GetAllowSubmitScript() + @"
                        var postBackCode = '" + uniqueCode + ":remove:' + GetCurrentVariantId('" + uniqueCode + @"');
                        SetVariant('" + uniqueCode + @"', 0);"
                                             + ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "postBackCode") + @";
                    }
                }";

                ScriptHelper.RegisterStartupScript(Page, typeof(string), "removeVariantScript_" + uniqueCode, ScriptHelper.GetScript(removeVariantScript));

                int step = 1;
                if (isRTL)
                {
                    // Reverse step direction
                    step = -1;
                }
                // Assign the onclick events for the slider arrows
                pnlLeft.Attributes.Add("onclick", "OnSliderChanged(event, '" + hdnSliderPosition.ClientID + "', " + totalVariants + ", " + step * (-1) + ");");
                pnlRight.Attributes.Add("onclick", "OnSliderChanged(event, '" + hdnSliderPosition.ClientID + "', " + totalVariants + ", " + step + ");");

                // Get all variants GUIDs
                List <string> variantIDsArray        = new List <string>();
                List <string> variantControlIDsArray = new List <string>();
                List <string> divIDsArray            = new List <string>();

                switch (SliderMode)
                {
                case VariantTypeEnum.Zone:
                    // Zone
                    if ((WebPartZoneControl != null) &&
                        (WebPartZoneControl.ZoneInstance != null) &&
                        (WebPartZoneControl.ZoneInstance.ZoneInstanceVariants != null))
                    {
                        // Fill the variant IDs array
                        variantIDsArray = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Select(zone => zone.VariantID.ToString()).ToList <string>();
                        // First item is the original zone (variantid=0)
                        variantIDsArray.Insert(0, "0");

                        // Fill the variant control IDs array
                        variantControlIDsArray = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Select(zone => "\"" + (!string.IsNullOrEmpty(ValidationHelper.GetString(zone.Properties["zonetitle"], string.Empty)) ? HTMLHelper.HTMLEncode(zone.Properties["zonetitle"].ToString()) : zone.ZoneID) + "\"").ToList <string>();
                        // First item is the original web part/widget
                        variantControlIDsArray.Insert(0, "\"" + (!string.IsNullOrEmpty(WebPartZoneControl.ZoneTitle) ? HTMLHelper.HTMLEncode(WebPartZoneControl.ZoneTitle) : WebPartZoneControl.ZoneInstance.ZoneID) + "\"");

                        // Fill the DIV tag IDs array
                        divIDsArray = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Select(zone => "\"Variant_" + VariantModeFunctions.GetVariantModeString(zone.VariantMode) + "_" + zone.VariantID.ToString() + "\"").ToList <string>();
                        // First item is the original web part
                        divIDsArray.Insert(0, "\"" + uniqueCode + "\"");
                    }
                    break;

                case VariantTypeEnum.WebPart:
                case VariantTypeEnum.Widget:
                    // Web part or widget
                    if ((WebPartControl != null) &&
                        (WebPartControl.PartInstance != null) &&
                        (WebPartControl.PartInstance.PartInstanceVariants != null))
                    {
                        // Fill the variant IDs array
                        variantIDsArray = WebPartControl.PartInstance.PartInstanceVariants.Select(webpart => webpart.VariantID.ToString()).ToList <string>();
                        // First item is the original web part/widget (variantid=0)
                        variantIDsArray.Insert(0, "0");

                        // Fill the variant control IDs array
                        variantControlIDsArray = WebPartControl.PartInstance.PartInstanceVariants.Select(webpart => "\"" + (!string.IsNullOrEmpty(ValidationHelper.GetString(webpart.Properties["webparttitle"], string.Empty)) ? HTMLHelper.HTMLEncode(webpart.Properties["webparttitle"].ToString()) : webpart.ControlID) + "\"").ToList <string>();
                        // First item is the original web part/widget
                        variantControlIDsArray.Insert(0, "\"" + (!string.IsNullOrEmpty(ValidationHelper.GetString(WebPartControl.PartInstance.Properties["webparttitle"], string.Empty)) ? HTMLHelper.HTMLEncode(WebPartControl.PartInstance.Properties["webparttitle"].ToString()) : WebPartControl.PartInstance.ControlID) + "\"");

                        // Fill the DIV tag IDs array
                        divIDsArray = WebPartControl.PartInstance.PartInstanceVariants.Select(webpart => "\"Variant_" + VariantModeFunctions.GetVariantModeString(webpart.VariantMode) + "_" + webpart.VariantID + "\"").ToList <string>();
                        // First item is the original web part/widget
                        divIDsArray.Insert(0, "\"" + uniqueCode + "\"");
                    }
                    break;
                }

                // Create a javascript arrays:
                // Fill the following javascript array: itemCodesArray.push([variantIDs], [divIDs], actualSliderPosition, totalVariants, variantSliderId, sliderElement, hiddenElem_SliderPosition, zoneId, webPartInstanceGuid)
                StringBuilder sb = new StringBuilder();
                sb.Append("itemIDs = [");
                sb.Append(String.Join(",", variantIDsArray.ToArray()));
                sb.Append("]; divIDs = [");
                sb.Append(String.Join(",", divIDsArray.ToArray()));
                sb.Append("]; itemControlIDs = [");
                sb.Append(String.Join(",", variantControlIDsArray.ToArray()));
                sb.Append("];");
                sb.Append("itemCodes = [itemIDs, divIDs, itemControlIDs, 1, "); // 0, 1, 2, 3 (see the details in the 'variants.js' file)
                sb.Append(totalVariants);                                       // 4
                sb.Append(", \"");
                sb.Append(pnlVariations.ClientID);                              // 5
                sb.Append("\", \"");
                sb.Append(sliderExtender.ClientID);                             // 6
                sb.Append("_handleImage\", \"");
                sb.Append(hdnSliderPosition.ClientID);                          // 7
                sb.Append("\", \"");
                if (SliderMode == VariantTypeEnum.Zone)                         // 8
                {
                    sb.Append(WebPartZoneControl.TitleLabel.ClientID);
                }
                else
                {
                    // Display label only for web parts (editor widgets have title hidden)
                    if (WebPartControl.TitleLabel != null)
                    {
                        sb.Append(WebPartControl.TitleLabel.ClientID);
                    }
                }
                sb.Append("\", \"");
                sb.Append(zoneId);                      // 9
                sb.Append("\", \"");
                if (SliderMode != VariantTypeEnum.Zone) // 10
                {
                    sb.Append(instanceGuidString);
                }
                sb.Append("\", \"");
                sb.Append(VariantModeFunctions.GetVariantModeString(VariantMode)); // 11
                sb.Append("\", \"");
                sb.Append(pnlVariations.ClientID);                                 // 12
                sb.Append("\"]; itemCodesAssociativeArray[\"");
                sb.Append(uniqueCode);
                sb.Append("\"] = itemCodes;");

                ScriptHelper.RegisterStartupScript(Page, typeof(string), sliderExtender.ClientID + "_InitScript", sb.ToString(), true);
            }
        }
        else
        {
            Visible = false;
        }
    }
    /// <summary>
    /// Invoked when new treenode is created.
    /// </summary>
    /// <param name="itemData">Category data.</param>
    /// <param name="defaultNode">Default node.</param>
    protected TreeNode treeElem_OnNodeCreated(DataRow itemData, TreeNode defaultNode)
    {
        defaultNode.Selected     = false;
        defaultNode.SelectAction = TreeNodeSelectAction.None;
        defaultNode.NavigateUrl  = "";

        if (itemData != null)
        {
            CategoryInfo category = new CategoryInfo(itemData);

            // Ensure name
            string catName     = ValidationHelper.GetString(itemData["CategoryName"], "");
            string caption     = ValidationHelper.GetString(itemData["CategoryDisplayName"], "");
            int    catParentId = ValidationHelper.GetInteger(itemData["CategoryParentID"], 0);
            int    catId       = ValidationHelper.GetInteger(itemData["CategoryID"], 0);
            int    catLevel    = ValidationHelper.GetInteger(itemData["CategoryLevel"], 0);
            string catIDPath   = ValidationHelper.GetString(itemData["CategoryIDPath"], "");

            if ((StartingCategoryObj != null) && (catIDPath.StartsWithCSafe(StartingCategoryObj.CategoryIDPath)))
            {
                catLevel = catLevel - StartingCategoryObj.CategoryLevel - 1;
            }

            string cssClass = GetCssClass(catLevel);

            if (String.IsNullOrEmpty(caption))
            {
                caption = catName;
            }

            // Get target url
            string url = GetUrl(category);
            caption = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(caption));

            StringBuilder attrs = new StringBuilder();

            // Append target sttribute
            if (!string.IsNullOrEmpty(CategoriesPageTarget))
            {
                attrs.Append(" target=\"").Append(CategoriesPageTarget).Append("\"");
            }

            // Append title attribute
            if (RenderLinkTitle)
            {
                attrs.Append(" title=\"").Append(caption).Append("\"");
            }

            // Append CSS class
            if (!string.IsNullOrEmpty(cssClass))
            {
                attrs.Append(" class=\"" + cssClass + "\"");
            }

            // Append before/after texts
            caption  = (CategoryContentBefore ?? "") + caption;
            caption += CategoryContentAfter ?? "";

            // Set caption
            defaultNode.Text = defaultNode.Text.Replace("##NODECUSTOMNAME##", caption);
            defaultNode.Text = defaultNode.Text.Replace("##NODECODENAME##", HTMLHelper.HTMLEncode(catName));
            defaultNode.Text = defaultNode.Text.Replace("##PARENTID##", catParentId.ToString());
            defaultNode.Text = defaultNode.Text.Replace("##ID##", catId.ToString());
            defaultNode.Text = defaultNode.Text.Replace("##BEFORENAME##", string.Format("<a href=\"{0}\" {1}>", URLHelper.EncodeQueryString(url), attrs.ToString()));
            defaultNode.Text = defaultNode.Text.Replace("##AFTERNAME##", "</a>");

            // Expand node if all nodes are to be expanded
            if (ExpandAll)
            {
                defaultNode.Expand();
            }
            else
            {
                // Check if selected category exists
                if (Category != null)
                {
                    if ((Category.CategoryID != catId) || RenderSubItems)
                    {
                        // Expand whole path to selected category
                        string strId = catId.ToString().PadLeft(CategoryInfoProvider.CategoryIDLength, '0');
                        if (Category.CategoryIDPath.Contains(strId))
                        {
                            defaultNode.Expand();
                        }
                    }
                }
            }

            return(defaultNode);
        }

        return(null);
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!RequestHelper.IsPostBack())
            {
                // If user is public
                if (CMSContext.CurrentUser.IsPublic())
                {
                    // Get logon URL
                    string logonUrl = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSecuredAreasLogonPage");
                    logonUrl = DataHelper.GetNotEmpty(LoginURL, logonUrl);

                    // Create redirect URL
                    logonUrl = URLHelper.ResolveUrl(logonUrl) + "?ReturnURL=" + HttpUtility.UrlEncode(URLHelper.CurrentURL);
                    URLHelper.Redirect(logonUrl);
                }
                else
                {
                    // Get invitation by GUID
                    Guid invitationGuid = QueryHelper.GetGuid("invitationguid", Guid.Empty);
                    if (invitationGuid != Guid.Empty)
                    {
                        InvitationInfo invitation = InvitationInfoProvider.GetInvitationInfo(invitationGuid);
                        if (invitation != null)
                        {
                            // Check if invitation is valid
                            if ((invitation.InvitationValidTo == DateTimeHelper.ZERO_TIME) ||
                                (invitation.InvitationValidTo >= DateTime.Now))
                            {
                                GroupInfo group = GroupInfoProvider.GetGroupInfo(invitation.InvitationGroupID);

                                if (group != null)
                                {
                                    // Check whether current user is the user who should be invited
                                    if ((invitation.InvitedUserID > 0) && (invitation.InvitedUserID != CMSContext.CurrentUser.UserID))
                                    {
                                        lblInfo.CssClass = "InvitationErrorLabel";
                                        lblInfo.Text     = InvitationIsNotValid;
                                        lblInfo.Visible  = true;
                                        return;
                                    }

                                    // If user was invited by e-mail
                                    if (invitation.InvitedUserID == 0)
                                    {
                                        invitation.InvitedUserID = CMSContext.CurrentUser.UserID;
                                    }

                                    if (!GroupMemberInfoProvider.IsMemberOfGroup(invitation.InvitedUserID, invitation.InvitationGroupID))
                                    {
                                        // Create group member info object
                                        GroupMemberInfo groupMember = new GroupMemberInfo();
                                        groupMember.MemberInvitedByUserID = invitation.InvitedByUserID;
                                        groupMember.MemberUserID          = CMSContext.CurrentUser.UserID;
                                        groupMember.MemberGroupID         = invitation.InvitationGroupID;
                                        groupMember.MemberJoined          = DateTime.Now;

                                        // Set proper status depending on grouo settings
                                        switch (group.GroupApproveMembers)
                                        {
                                        // Only approved members can join
                                        case GroupApproveMembersEnum.ApprovedCanJoin:
                                            groupMember.MemberStatus = GroupMemberStatus.WaitingForApproval;
                                            lblInfo.Text             = MemberWaiting.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName));
                                            break;

                                        // Only invited members
                                        case GroupApproveMembersEnum.InvitedWithoutApproval:
                                        // Any site members can join
                                        case GroupApproveMembersEnum.AnyoneCanJoin:
                                            groupMember.MemberApprovedWhen = DateTime.Now;
                                            groupMember.MemberStatus       = GroupMemberStatus.Approved;
                                            lblInfo.Text = MemberJoined.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName));
                                            break;
                                        }
                                        // Store info object to database
                                        GroupMemberInfoProvider.SetGroupMemberInfo(groupMember);

                                        // Handle sending e-mails
                                        if (SendEmailToInviter || SendDefaultGroupEmails)
                                        {
                                            UserInfo sender    = UserInfoProvider.GetFullUserInfo(groupMember.MemberUserID);
                                            UserInfo recipient = UserInfoProvider.GetFullUserInfo(groupMember.MemberInvitedByUserID);

                                            if (SendEmailToInviter)
                                            {
                                                EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Groups.MemberAcceptedInvitation", CMSContext.CurrentSiteName);

                                                // Resolve macros
                                                MacroResolver resolver = CMSContext.CurrentResolver;
                                                resolver.SourceData = new object[] { sender, recipient, group, groupMember };
                                                resolver.SetNamedSourceData("Sender", sender);
                                                resolver.SetNamedSourceData("Recipient", recipient);
                                                resolver.SetNamedSourceData("Group", group);
                                                resolver.SetNamedSourceData("GroupMember", groupMember);

                                                if (!String.IsNullOrEmpty(recipient.Email) && !String.IsNullOrEmpty(sender.Email))
                                                {
                                                    // Send e-mail
                                                    EmailMessage message = new EmailMessage();
                                                    message.Recipients    = recipient.Email;
                                                    message.From          = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                                                    message.Subject       = resolver.ResolveMacros(template.TemplateSubject);
                                                    message.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                                                    // Enable macro encoding for body
                                                    resolver.EncodeResolvedValues = true;
                                                    message.Body          = resolver.ResolveMacros(template.TemplateText);
                                                    message.CcRecipients  = template.TemplateCc;
                                                    message.BccRecipients = template.TemplateBcc;
                                                    message.EmailFormat   = EmailFormatEnum.Default;

                                                    MetaFileInfoProvider.ResolveMetaFileImages(message, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                                                    EmailSender.SendEmail(CMSContext.CurrentSiteName, message);
                                                }
                                            }

                                            if (SendDefaultGroupEmails)
                                            {
                                                // Send join or leave notification
                                                if (group.GroupSendJoinLeaveNotification &&
                                                    (groupMember.MemberStatus == GroupMemberStatus.Approved))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoin", CMSContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedConfirmation", CMSContext.CurrentSiteName, groupMember, false);
                                                }

                                                // Send 'waiting for approval' notification
                                                if (group.GroupSendWaitingForApprovalNotification && (groupMember.MemberStatus == GroupMemberStatus.WaitingForApproval))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberWaitingForApproval", CMSContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval", CMSContext.CurrentSiteName, groupMember, false);
                                                }
                                            }
                                        }

                                        // Delete all invitations to specified group for specified user (based on e-mail or userId)
                                        string whereCondition = "InvitationGroupID = " + invitation.InvitationGroupID + " AND (InvitedUserID=" + CMSContext.CurrentUser.UserID + " OR InvitationUserEmail = N'" + SqlHelperClass.GetSafeQueryString(CMSContext.CurrentUser.Email, false) + "')";
                                        InvitationInfoProvider.DeleteInvitations(whereCondition);

                                        // Log activity
                                        LogJoinActivity(groupMember, group);
                                    }
                                    else
                                    {
                                        lblInfo.Text     = UserIsAlreadyMember.Replace("##GROUPNAME##", HTMLHelper.HTMLEncode(group.GroupDisplayName));
                                        lblInfo.CssClass = "InvitationErrorLabel";

                                        // Delete this invitation
                                        InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                    }
                                }
                                else
                                {
                                    lblInfo.Text     = GroupNoLongerExists;
                                    lblInfo.CssClass = "InvitationErrorLabel";
                                    // Delete this invitation
                                    InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                }
                            }
                            else
                            {
                                lblInfo.Text     = InvitationIsNotValid;
                                lblInfo.CssClass = "InvitationErrorLabel";
                                // Delete this invitation
                                InvitationInfoProvider.DeleteInvitationInfo(invitation);
                            }
                        }
                        else
                        {
                            lblInfo.Text     = InvitationNoLongerExists;
                            lblInfo.CssClass = "InvitationErrorLabel";
                        }
                        lblInfo.Visible = true;
                    }
                    else
                    {
                        // Hide control if invitation GUID isn't set
                        Visible = false;
                    }
                }
            }
        }
    }
Ejemplo n.º 18
0
    protected void WriteTablesContent()
    {
        foreach (object[] table in tables)
        {
            // Prepare the components
            DataTable         dt            = (DataTable)table[0];
            LiteralControl    ltlContent    = (LiteralControl)table[1];
            UIPager           pagerElem     = (UIPager)table[2];
            UniPagerConnector connectorElem = (UniPagerConnector)table[3];

            // Handle the different types of direct page selector
            int currentPageSize = pagerElem.CurrentPageSize;
            if (currentPageSize > 0)
            {
                if (connectorElem.PagerForceNumberOfResults / (float)currentPageSize > 20.0f)
                {
                    pagerElem.DirectPageControlID = "txtPage";
                }
                else
                {
                    pagerElem.DirectPageControlID = "drpPage";
                }
            }

            // Bind the pager first
            connectorElem.RaiseOnPageBinding(null, null);

            // Prepare the string builder
            StringBuilder sb = new StringBuilder();

            // Prepare the indexes for paging
            int pageSize = pagerElem.CurrentPageSize;

            int startIndex = (pagerElem.CurrentPage - 1) * pageSize + 1;
            int endIndex   = startIndex + pageSize;

            // Process all items
            int  index = 0;
            bool all   = (endIndex <= startIndex);

            if (dt.Columns.Count > 6)
            {
                // Write all rows
                foreach (DataRow dr in dt.Rows)
                {
                    index++;
                    if (all || (index >= startIndex) && (index < endIndex))
                    {
                        sb.Append("<table class=\"table table-hover\">");

                        // Add header
                        sb.AppendFormat("<thead><tr class=\"unigrid-head\"><th>{0}</th><th class=\"main-column-100\">{1}</th></tr></thead><tbody>", GetString("General.FieldName"), GetString("General.Value"));

                        // Add values
                        foreach (DataColumn dc in dt.Columns)
                        {
                            object value = dr[dc.ColumnName];

                            // Binary columns
                            string content;
                            if ((dc.DataType == typeof(byte[])) && (value != DBNull.Value))
                            {
                                byte[] data = (byte[])value;
                                content = "<" + GetString("General.BinaryData") + ", " + DataHelper.GetSizeString(data.Length) + ">";
                            }
                            else
                            {
                                content = ValidationHelper.GetString(value, String.Empty);
                            }

                            if (!String.IsNullOrEmpty(content))
                            {
                                sb.AppendFormat("<tr><td><strong>{0}</strong></td><td class=\"wrap-normal\">", dc.ColumnName);

                                // Possible DataTime columns
                                if ((dc.DataType == typeof(DateTime)) && (value != DBNull.Value))
                                {
                                    DateTime    dateTime    = Convert.ToDateTime(content);
                                    CultureInfo cultureInfo = CultureHelper.GetCultureInfo(MembershipContext.AuthenticatedUser.PreferredUICultureCode);
                                    content = dateTime.ToString(cultureInfo);
                                }

                                // Process content
                                ProcessContent(sb, dr, dc.ColumnName, ref content);

                                sb.Append("</td></tr>");
                            }
                        }

                        sb.Append("</tbody></table>\n");
                    }
                }
            }
            else
            {
                sb.Append("<table class=\"table table-hover\">");

                // Add header
                sb.Append("<thead><tr class=\"unigrid-head\">");
                int h = 1;
                foreach (DataColumn column in dt.Columns)
                {
                    sb.AppendFormat("<th{0}>{1}</th>", (h == dt.Columns.Count) ? " class=\"main-column-100\"" : String.Empty, column.ColumnName);
                    h++;
                }
                sb.Append("</tr></thead><tbody>");

                // Write all rows
                foreach (DataRow dr in dt.Rows)
                {
                    index++;
                    if (all || (index >= startIndex) && (index < endIndex))
                    {
                        sb.Append("<tr>");

                        // Add values
                        foreach (DataColumn dc in dt.Columns)
                        {
                            object value = dr[dc.ColumnName];
                            // Possible DataTime columns
                            if ((dc.DataType == typeof(DateTime)) && (value != DBNull.Value))
                            {
                                DateTime    dateTime    = Convert.ToDateTime(value);
                                CultureInfo cultureInfo = CultureHelper.GetCultureInfo(MembershipContext.AuthenticatedUser.PreferredUICultureCode);
                                value = dateTime.ToString(cultureInfo);
                            }

                            string content = ValidationHelper.GetString(value, String.Empty);
                            content = HTMLHelper.HTMLEncode(content);

                            sb.AppendFormat("<td{0}>{1}</td>", (content.Length >= 100) ? " class=\"wrap-normal\"" : String.Empty, content);
                        }
                        sb.Append("</tr>");
                    }
                }
                sb.Append("</tbody></table>\n");
            }

            ltlContent.Text = sb.ToString();
        }
    }
    /// <summary>
    /// Handles the UniGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void ugRecycleBin_OnAction(string actionName, object actionArgument)
    {
        int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0);

        actionName = actionName.ToLowerCSafe();

        switch (actionName)
        {
        case "restorechilds":
        case "restorewithoutbindings":
        case "restorecurrentsite":
            try
            {
                if (CMSContext.CurrentUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects"))
                {
                    switch (actionName)
                    {
                    case "restorechilds":
                        ObjectVersionManager.RestoreObject(versionHistoryId, true);
                        break;

                    case "restorewithoutbindings":
                        ObjectVersionManager.RestoreObject(versionHistoryId, 0);
                        break;

                    case "restorecurrentsite":
                        ObjectVersionManager.RestoreObject(versionHistoryId, CMSContext.CurrentSiteID);
                        break;
                    }

                    ShowConfirmation(GetString("ObjectVersioning.Recyclebin.RestorationOK"));
                }
                else
                {
                    ShowError(ResHelper.GetString("objectversioning.recyclebin.restorationfailedpermissions"));
                }
            }
            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
                LogException("OBJECTRESTORE", ex);
            }
            break;

        case "destroy":

            ObjectVersionHistoryInfo verInfo = ObjectVersionHistoryInfoProvider.GetVersionHistoryInfo(versionHistoryId);

            // Get object site name
            string siteName = null;
            if (CurrentSite != null)
            {
                siteName = CurrentSite.SiteName;
            }
            else
            {
                siteName = SiteInfoProvider.GetSiteName(verInfo.VersionObjectSiteID);
            }

            if ((verInfo != null) && CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, verInfo.VersionObjectType, siteName))
            {
                ObjectVersionManager.DestroyObjectHistory(verInfo.VersionObjectType, verInfo.VersionObjectID);
                ShowConfirmation(GetString("ObjectVersioning.Recyclebin.DestroyOK"));
            }
            else
            {
                ShowError(String.Format(ResHelper.GetString("objectversioning.recyclebin.destructionfailedpermissions"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(verInfo.VersionObjectDisplayName))));
            }
            break;
        }

        ugRecycleBin.ResetSelection();
        ReloadFilter((CurrentSite != null) ? CurrentSite.SiteID : -1, IsSingleSite, false);
    }
Ejemplo n.º 20
0
    /// <summary>
    /// Processes the content.
    /// </summary>
    /// <param name="sb">StringBuilder to write</param>
    /// <param name="source">Source object</param>
    /// <param name="column">Column</param>
    /// <param name="content">Content</param>
    protected void ProcessContent(StringBuilder sb, object source, string column, ref string content)
    {
        bool standard = true;

        switch (column.ToLowerCSafe())
        {
        // Document content
        case "documentcontent":
            EditableItems items = new EditableItems();
            items.LoadContentXml(content);

            // Add regions
            foreach (DictionaryEntry region in items.EditableRegions)
            {
                sb.Append("<span class=\"VersionEditableRegionTitle\">" + (string)region.Key + "</span>");

                string regionContent = HTMLHelper.ResolveUrls((string)region.Value, SystemContext.ApplicationPath);

                sb.Append("<span class=\"VersionEditableRegionText\">" + regionContent + "</span>");
            }

            // Add web parts
            foreach (DictionaryEntry part in items.EditableWebParts)
            {
                sb.Append("<span class=\"VersionEditableWebPartTitle\">" + (string)part.Key + "</span>");

                string regionContent = HTMLHelper.ResolveUrls((string)part.Value, SystemContext.ApplicationPath);
                sb.Append("<span class=\"VersionEditableWebPartText\">" + regionContent + "</span>");
            }

            standard = false;
            break;

        // XML columns
        case "pagetemplatewebparts":
        case "webpartproperties":
        case "reportparameters":
        case "classformdefinition":
        case "classxmlschema":
        case "classformlayout":
        case "userdialogsconfiguration":
            content = HTMLHelper.ReformatHTML(content);
            break;

        // File columns
        case "metafilename":
        {
            Guid metaFileGuid = ValidationHelper.GetGuid(GetValueFromSource(source, "MetaFileGuid"), Guid.Empty);
            if (metaFileGuid != Guid.Empty)
            {
                string metaFileName = ValidationHelper.GetString(GetValueFromSource(source, "MetaFileName"), "");

                content = "<a href=\"" + ResolveUrl(MetaFileInfoProvider.GetMetaFileUrl(metaFileGuid, metaFileName)) + "\" target=\"_blank\" >" + HTMLHelper.HTMLEncode(metaFileName) + "</a>";
                sb.Append(content);

                standard = false;
            }
        }
        break;
        }

        // Standard rendering
        if (standard)
        {
            if (content.Length > 500)
            {
                content = TextHelper.EnsureMaximumLineLength(content, 50, "&#x200B;", true);
            }
            else
            {
                content = HTMLHelper.HTMLEncode(content);
            }

            content = HTMLHelper.EnsureHtmlLineEndings(content);
            content = content.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
            sb.Append("<div style=\"max-height: 300px; overflow: auto;\">" + content + "</div>");
        }
    }
    /// <summary>
    /// Empties recycle bin.
    /// </summary>
    private void EmptyBin(object parameter)
    {
        // Begin log
        AddLog(ResHelper.GetString("Recyclebin.EmptyingBin", currentCulture));
        BinSettingsContainer settings        = (BinSettingsContainer)parameter;
        CurrentUserInfo      currentUserInfo = settings.User;
        SiteInfo             currentSite     = settings.Site;

        DataSet recycleBin = null;

        string where = IsSingleSite ? "VersionObjectSiteID IS NULL" : null;

        switch (settings.CurrentWhat)
        {
        case What.AllObjects:
            if (currentSite != null)
            {
                where = SqlHelperClass.AddWhereCondition(where, "VersionObjectSiteID = " + currentSite.SiteID, "OR");
            }
            where = GetWhereCondition(where);
            break;

        case What.SelectedObjects:
            List <string> toRestore = ugRecycleBin.SelectedItems;
            // Restore selected objects
            if (toRestore.Count > 0)
            {
                where = SqlHelperClass.GetWhereCondition("VersionID", toRestore);
            }
            break;
        }
        recycleBin = ObjectVersionHistoryInfoProvider.GetRecycleBin(where, null, -1, "VersionID, VersionObjectType, VersionObjectID, VersionObjectDisplayName, VersionObjectSiteID");

        try
        {
            if (!DataHelper.DataSourceIsEmpty(recycleBin))
            {
                foreach (DataRow dr in recycleBin.Tables[0].Rows)
                {
                    int    versionHistoryId = Convert.ToInt32(dr["VersionID"]);
                    string versionObjType   = Convert.ToString(dr["VersionObjectType"]);
                    string objName          = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(dr["VersionObjectDisplayName"], string.Empty)));
                    string siteName         = null;
                    if (currentSite != null)
                    {
                        siteName = currentSite.SiteName;
                    }
                    else
                    {
                        int siteId = ValidationHelper.GetInteger(dr["VersionObjectSiteID"], 0);
                        siteName = SiteInfoProvider.GetSiteName(siteId);
                    }

                    // Check permissions
                    if (!currentUserInfo.IsAuthorizedPerObject(PermissionsEnum.Destroy, versionObjType, siteName))
                    {
                        CurrentError = String.Format(ResHelper.GetString("objectversioning.Recyclebin.DestructionFailedPermissions", currentCulture), objName);
                        AddLog(CurrentError);
                    }
                    else
                    {
                        AddLog(ResHelper.GetString("general.object", currentCulture) + " '" + objName + "'");

                        // Destroy the version
                        int versionObjId = ValidationHelper.GetInteger(dr["VersionObjectID"], 0);
                        ObjectVersionManager.DestroyObjectHistory(versionObjType, versionObjId);
                        LogContext.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Objects", "DESTROYOBJECT", currentUserInfo.UserID, currentUserInfo.UserName, 0, null, HTTPHelper.UserHostAddress, ResHelper.GetString("objectversioning.Recyclebin.objectdestroyed"), (currentSite != null) ? currentSite.SiteID : 0, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent());
                    }
                }
                if (!String.IsNullOrEmpty(CurrentError))
                {
                    CurrentError = ResHelper.GetString("objectversioning.recyclebin.errorsomenotdestroyed", currentCulture);
                    AddLog(CurrentError);
                }
                else
                {
                    CurrentInfo = ResHelper.GetString("ObjectVersioning.Recyclebin.DestroyOK", currentCulture);
                    AddLog(CurrentInfo);
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state != CMSThread.ABORT_REASON_STOP)
            {
                // Log error
                CurrentError = "Error occurred: " + ResHelper.GetString("general.seeeventlog", currentCulture);
                AddLog(CurrentError);

                // Log to event log
                LogException("EMPTYINGBIN", ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            CurrentError = "Error occurred: " + ResHelper.GetString("general.seeeventlog", currentCulture);
            AddLog(CurrentError);

            // Log to event log
            LogException("EMPTYINGBIN", ex);
        }
    }
Ejemplo n.º 22
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with liveid token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (liveUser != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.liveid.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.liveid.fillvalidemail")).Result;

            string password = passStrength.Text.Trim();

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (errorMessage == String.Empty))
            {
                if (password == String.Empty)
                {
                    errorMessage = GetString("mem.liveid.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                }
            }

            string siteName = CMSContext.CurrentSiteName;

            // Check whether email is unique if it is required
            if ((errorMessage == String.Empty) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if ((errorMessage == String.Empty) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (errorMessage == String.Empty)
            {
                string userName = txtUserNameNew.Text.Trim();
                // Check if user with given username already exists
                UserInfo ui     = UserInfoProvider.GetUserInfo(userName);
                UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, CMSContext.CurrentSite));

                // User with given username is already registered
                if ((ui != null) || (siteui != null))
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = DisplayMessage;
                    ui             = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, false, ref error);
                    DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = ui.FullName = userName;

                        // Ensure site prefixes
                        if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
                        {
                            ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, CMSContext.CurrentSite);
                        }

                        ui.Email = txtEmail.Text;

                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        Session.Remove("windowsliveloginuser");

                        // Send registration e-mails
                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, password, true, SendWelcomeEmail);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Track registration into analytics
                        AuthenticationHelper.TrackUserRegistration(TrackConversionName, ConversionValue, siteName, ui);

                        Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        // Display error message
                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
Ejemplo n.º 23
0
 /// <summary>
 /// Resolve text.
 /// </summary>
 /// <param name="value">Input value</param>
 public string ResolveText(object value)
 {
     return(HTMLHelper.HTMLEncode(ValidationHelper.GetString(value, "")));
 }
Ejemplo n.º 24
0
    /// <summary>
    /// Generate document content.
    /// </summary>
    /// <param name="wpi">WebPart info</param>
    /// <param name="gd">Guid</param>
    /// <param name="category">Category</param>
    protected void GenerateDocContent(FormInfo fi)
    {
        if (fi == null)
        {
            return;
        }
        // Get defintion elements
        var infos = fi.GetFormElements(true, false);

        bool isOpenSubTable = false;

        string currentGuid = "";

        // Used for filter empty categories
        String categoryHeader = String.Empty;

        // Check all items in object array
        foreach (object contrl in infos)
        {
            // Generate row for form category
            if (contrl is FormCategoryInfo)
            {
                // Load castegory info
                FormCategoryInfo fci = contrl as FormCategoryInfo;
                if (fci != null)
                {
                    // Close table from last category
                    if (isOpenSubTable)
                    {
                        content       += "<tr class=\"PropertyBottom\"><td class=\"PropertyLeftBottom\">&nbsp;</td><td colspan=\"2\" class=\"Center\">&nbsp;</td><td class=\"PropertyRightBottom\">&nbsp;</td></tr></table>";
                        isOpenSubTable = false;
                    }

                    if (currentGuid == "")
                    {
                        currentGuid = Guid.NewGuid().ToString().Replace("-", "_");
                    }

                    // Generate table for current category
                    categoryHeader = @"<br />
                        <table cellpadding=""0"" cellspacing=""0"" class=""CategoryTable"">
                          <tr>
                           <td class=""CategoryLeftBorder"">&nbsp;</td>
                           <td class=""CategoryTextCell"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(fci.CategoryName)) + @"</td>
                           <td class=""CategoryRightBorder"">&nbsp;</td>
                         </tr>
                       </table>";
                }
            }
            else
            {
                // Get form field info
                FormFieldInfo ffi = contrl as FormFieldInfo;

                if (ffi != null)
                {
                    if (categoryHeader != String.Empty)
                    {
                        content       += categoryHeader;
                        categoryHeader = String.Empty;
                    }

                    if (!isOpenSubTable)
                    {
                        // Generate table for properties under one category
                        isOpenSubTable = true;
                        content       += "" +
                                         "<table cellpadding=\"0\" cellspacing=\"0\" id=\"_" + currentGuid + "\" class=\"PropertiesTable\" >";
                        currentGuid = "";
                    }

                    // Add ':' to caption
                    string doubleDot = "";
                    if (!ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver).EndsWithCSafe(":"))
                    {
                        doubleDot = ":";
                    }

                    string fieldDescription = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldDescription, resolver);

                    content +=
                        @"<tr>
                            <td class=""PropertyLeftBorder"" >&nbsp;</td>
                            <td class=""PropertyContent"" style=""width:200px;"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver))) + doubleDot + @"</td>
                            <td class=""PropertyRow"">" + HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(ResHelper.LocalizeString(fieldDescription), GetString("WebPartDocumentation.DescriptionNoneAvailable"))) + @"</td>
                            <td class=""PropertyRightBorder"">&nbsp;</td>
                        </tr>";

                    if (fieldDescription == null || fieldDescription.Trim() == "")
                    {
                        undocumentedProperties++;
                    }
                }
            }
        }

        // Close last category (if has any properties)
        if (isOpenSubTable)
        {
            content += "<tr class=\"PropertyBottom\"><td class=\"PropertyLeftBottom\">&nbsp;</td><td colspan=\"2\" class=\"Center\">&nbsp;</td><td class=\"PropertyRightBottom\">&nbsp;</td></tr></table>";
        }
    }