/// <summary>
    /// Generate control output.
    /// </summary>
    public void GenerateContent()
    {
        string templatePath = DepartmentTemplatePath;

        if (String.IsNullOrEmpty(templatePath))
        {
            ltlContent.Text    = ResHelper.GetString("departmentsectionsmanager.notemplate");
            ltlContent.Visible = true;
        }
        else
        {
            if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
            {
                int   counter = 0;
                Table tb      = new Table();

                string value      = ValidationHelper.GetString(mSelectedValue, "");
                string docAliases = ";" + value.ToLower() + ";";

                TreeNode editedNode    = Form.EditedObject as TreeNode;
                int      targetClassId = ValidationHelper.GetInteger(editedNode.GetValue("NodeClassID"), 0);

                TableRow tr = new TableRow();
                foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
                {
                    // For each section td element is generated
                    TableCell td     = new TableCell();
                    CheckBox  cbCell = new CheckBox();
                    cbCell.ID   = "chckSection" + counter;
                    cbCell.Text = drDoc["NodeAlias"].ToString();
                    cbCell.Attributes.Add("Value", drDoc["NodeAlias"].ToString());

                    // Check if child allowed
                    int sourceClassId = ValidationHelper.GetInteger(drDoc["NodeClassID"], 0);
                    if (!DataClassInfoProvider.IsChildClassAllowed(targetClassId, sourceClassId))
                    {
                        cbCell.Enabled = false;
                        cbCell.ToolTip = ResHelper.GetString("departmentsectionsmanager.notallowedchild");
                    }

                    // Disable default hidden documents
                    if (HIDDEN_DOCUMENT_ALIAS.Contains(";" + drDoc["NodeAlias"].ToString().ToLower() + ";"))
                    {
                        cbCell.Checked = cbCell.Enabled;
                        cbCell.Enabled = false;
                    }


                    // Check for selected value
                    string docAlias = ValidationHelper.GetString(drDoc["NodeAlias"], "");

                    if (docAliases.Contains(";" + docAlias.ToLower() + ";") || ((mSelectedValue == null) && (Form.Mode == FormModeEnum.Insert)))
                    {
                        if (cbCell.Enabled)
                        {
                            cbCell.Checked = true;
                        }
                    }

                    // If editing existing document register alert script
                    if ((Form.Mode != FormModeEnum.Insert) && cbCell.Checked)
                    {
                        cbCell.Attributes.Add("OnClick", "if(!this.checked){alert(" + ScriptHelper.GetString(ResHelper.GetString("departmentsectionsmanagerformcontrol.removesectionwarning")) + ");}");
                    }

                    // Add reference to checkbox arraylist
                    CheckboxReferences.Add(cbCell);
                    counter++;

                    td.Controls.Add(cbCell);
                    tr.Cells.Add(td);

                    // If necessary create new row
                    if ((counter % ITEMS_PER_ROW) == 0)
                    {
                        tr.CssClass = "Row";
                        tb.Rows.Add(tr);
                        tr = new TableRow();
                    }
                }
                // If last row contains data add it
                if (counter > 0)
                {
                    tb.Rows.Add(tr);
                }
                pnlContent.Controls.Add(tb);
            }
            else
            {
                ltlContent.Text    = ResHelper.GetString("departmentsectionsmanager.notemplate");
                ltlContent.Visible = true;
            }
        }
    }
Пример #2
0
 /// <summary>
 /// Returns link to "add to shoppingcart".
 /// </summary>
 /// <param name="productId">Product ID</param>
 /// <param name="enabled">Indicates whether product is enabled or not</param>
 /// <param name="imageUrl">Image URL</param>
 public static string GetAddToShoppingCartLink(object productId, object enabled, string imageUrl)
 {
     if (ValidationHelper.GetBoolean(enabled, false) && (ValidationHelper.GetInteger(productId, 0) != 0))
     {
         // Get default image URL
         imageUrl = imageUrl ?? "CMSModules/CMS_Ecommerce/addorder.png";
         return("<img src=\"" + UIHelper.GetImageUrl(null, imageUrl) + "\" alt=\"Add to cart\" /><a href=\"" + ShoppingCartURL(CMSContext.CurrentSiteName) + "?productId=" + Convert.ToString(productId) + "&amp;quantity=1\">" + ResHelper.GetString("EcommerceFunctions.AddToShoppingCart") + "</a>");
     }
     else
     {
         return("");
     }
 }
Пример #3
0
 /// <summary>
 /// Returns link to remove specified product from the user's wishlist.
 /// </summary>
 /// <param name="productId">Product ID</param>
 public static string GetRemoveFromWishListLink(object productId)
 {
     if ((productId != DBNull.Value) && (!CMSContext.CurrentUser.IsPublic()))
     {
         return("<a href=\"javascript:onclick=RemoveFromWishlist(" + Convert.ToString(productId) + ")\" class=\"RemoveFromWishlist\">" + ResHelper.GetString("Wishlist.RemoveFromWishlist") + "</a>");
     }
     else
     {
         return("");
     }
 }
Пример #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CopyValues(postTreeElem);

        // Hide selected area if forum is AdHoc
        if (IsAdHocForum)
        {
            plcHeader.Visible = false;
        }

        // Handle the Move topic mode
        if (ForumContext.CurrentMode != ForumMode.TopicMove)
        {
            plcMoveThread.Visible = false;
        }
        else
        {
            plcMoveThread.Visible  = true;
            threadMove.TopicMoved += new EventHandler(TopicMoved);
        }

        if ((hdnSelected.Value == String.Empty) && (QueryHelper.Contains("moveto")))
        {
            hdnSelected.Value = QueryHelper.GetString("moveto", "");
            mSelectedPost     = ValidationHelper.GetInteger(hdnSelected.Value, 0);
        }

        bool newThread       = base.IsAvailable(null, ForumActionType.NewThread);
        bool newSubscription = base.IsAvailable(null, ForumActionType.SubscribeToForum);
        bool newFavorites    = base.IsAvailable(null, ForumActionType.AddForumToFavorites);
        bool newBreadCrumbs  = (ForumBreadcrumbs1.GenerateBreadcrumbs() != "");

        // Hide separators according to the link visibility
        // Each separator is hidden if the item preceeding the separator is invisible or
        // no item is behind the separator.
        if (!newThread || (!newSubscription && !newFavorites && !newBreadCrumbs))
        {
            plcActionSeparator.Visible = false;
        }
        if (!newSubscription || (!newFavorites && !newBreadCrumbs))
        {
            plcAddToFavoritesSeparator.Visible = false;
        }
        if (!newFavorites || !newBreadCrumbs)
        {
            plcBreadcrumbsSeparator.Visible = false;
        }

        // postTreeElem.ForumID = ForumContext.CurrentForum.ForumID;
        //postTreeElem.ShowMode = ShowModeEnum.TreeMode;

        // Unapproved posts are shown only if onsite mangement is enabled and user is moderator
        ForumInfo fi = ForumContext.CurrentForum;

        postTreeElem.SelectOnlyApproved = !((fi != null) && EnableOnSiteManagement && fi.ForumModerated && ForumContext.UserIsModerator(ForumContext.CurrentForum.ForumID, CommunityGroupID));

        if (postTreeElem.ShowMode == ShowModeEnum.DynamicDetailMode)
        {
            // Set javascript for selected mode
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ForumTreeDynamic", ScriptHelper.GetScript("function SelectForumNode(nodeElem, selElem) { if (document.getElementById(nodeElem) != null) { document.getElementById(nodeElem).style.display = 'block';} " +
                                                                                                                    "if (document.getElementById(selElem) != null) {document.getElementById(selElem).style.display = 'none';} return false;}\n "));
        }
        else
        {
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ForumTreeNormal", ScriptHelper.GetScript("function SelectForumNode(nodeElem) { return false; }\n "));
        }

        // Show post javascript
        string showScript = "function ShowPost(id){ document.getElementById('" + hdnSelected.ClientID + "').value = id; " + ControlsHelper.GetPostBackEventReference(this, "") + " }";

        //Register show post javascript code
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ShowForumPost", ScriptHelper.GetScript(showScript));

        // Don't use redirection after action
        UseRedirectAfterAction = false;

        int selected = ValidationHelper.GetInteger(hdnSelected.Value, ValidationHelper.GetInteger(Request[hdnSelected.UniqueID], 0));

        if (selected > 0)
        {
            ForumPostInfo fpi = ForumPostInfoProvider.GetForumPostInfo(selected);
            if (fpi != null)
            {
                ucAbuse.ReportObjectID            = fpi.PostId;
                ucAbuse.ReportTitle               = ResHelper.GetString("Forums_WebInterface_ForumPost.AbuseReport", CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName)) + fpi.PostText;
                ucAbuse.CMSPanel.CommunityGroupID = CommunityGroupID;
                ucAbuse.CMSPanel.SecurityAccess   = AbuseReportAccess;
                ucAbuse.CMSPanel.Roles            = AbuseReportRoles;
            }
        }
    }
Пример #5
0
    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);
        RequireSite = false;

        // Check for UI permissions
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Content", new string[] { "Properties", "Properties.General", "General.Design", "Design.NewCSSStylesheets" }, CMSContext.CurrentSiteName))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "Properties;Properties.General;General.Design;Design.NewCSSStylesheets");
        }

        // Check hash
        if (!QueryHelper.ValidateHash("hash", "saved;selectorid"))
        {
            URLHelper.Redirect(ResolveUrl(string.Format("~/CMSMessages/Error.aspx?title={0}&text={1}", ResHelper.GetString("dialogs.badhashtitle"), ResHelper.GetString("dialogs.badhashtext"))));
        }

        // Page has been opened from CMSDesk
        dialogMode = QueryHelper.GetBoolean("usedialog", false);

        if (dialogMode)
        {
            MasterPageFile = "~/CMSMasterPages/UI/Dialogs/ModalDialogPage.master";

            // Check 'Design Web site' permission if opened from CMS Desk
            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Design", "Design"))
            {
                RedirectToCMSDeskAccessDenied("CMS.Design", "Design");
            }
        }
    }
Пример #6
0
    protected object listElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        CMSGridActionButton btn;

        switch (sourceName.ToLowerCSafe())
        {
        // Set visibility for edit button
        case "edit":
            if (IsWidget)
            {
                btn = sender as CMSGridActionButton;
                if (btn != null)
                {
                    btn.Visible = false;
                }
            }
            break;

        // Set visibility for dialog edit button
        case "dialogedit":
            btn = sender as CMSGridActionButton;
            if (btn != null)
            {
                btn.Visible = IsWidget;
            }
            break;

        case "view":
            btn = (CMSGridActionButton)sender;
            // Ensure accountID parameter value;
            var objectID = ValidationHelper.GetInteger(btn.CommandArgument, 0);
            // Contact detail URL
            string contactURL = ApplicationUrlHelper.GetElementDialogUrl(ModuleName.CONTACTMANAGEMENT, "EditContact", objectID);
            // Add modal dialog script to onClick action
            btn.OnClientClick = ScriptHelper.GetModalDialogScript(contactURL, "ContactDetail");
            break;

        // Delete action
        case "delete":

            btn = (CMSGridActionButton)sender;
            btn.OnClientClick = "if(!confirm(" + ScriptHelper.GetString(string.Format(ResHelper.GetString("autoMenu.RemoveStateConfirmation"), HTMLHelper.HTMLEncode(TypeHelper.GetNiceObjectTypeName(ContactInfo.OBJECT_TYPE).ToLowerCSafe()))) + ")) { return false; }" + btn.OnClientClick;
            if (!mCanRemoveAutomationProcesses)
            {
                btn.Enabled = false;
            }
            break;
        }

        return(null);
    }
Пример #7
0
    protected object listElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        CMSGridActionButton btn;

        switch (sourceName.ToLowerCSafe())
        {
        // Delete action
        case "delete":
            btn = (CMSGridActionButton)sender;
            btn.OnClientClick = "if(!confirm(" + ScriptHelper.GetString(string.Format(ResHelper.GetString("autoMenu.RemoveStateConfirmation"), HTMLHelper.HTMLEncode(TypeHelper.GetNiceObjectTypeName(ContactInfo.OBJECT_TYPE).ToLowerCSafe()))) + ")) { return false; }" + btn.OnClientClick;
            if (!WorkflowStepInfoProvider.CanUserRemoveAutomationProcess(CurrentUser, SiteContext.CurrentSiteName))
            {
                if (btn != null)
                {
                    btn.Enabled = false;
                }
            }
            break;

        case "view":
            btn = (CMSGridActionButton)sender;
            // Ensure accountID parameter value;
            var objectID = ValidationHelper.GetInteger(btn.CommandArgument, 0);
            // Contact detail URL
            string contactURL = ApplicationUrlHelper.GetElementDialogUrl(ModuleName.CONTACTMANAGEMENT, "EditContact", objectID);
            // Add modal dialog script to onClick action
            btn.OnClientClick = ScriptHelper.GetModalDialogScript(contactURL, "ContactDetail");
            break;

        // Process status column
        case "statestatus":
            return(AutomationHelper.GetProcessStatus((ProcessStatusEnum)ValidationHelper.GetInteger(parameter, 0)));
        }

        return(null);
    }
    /// <summary>
    /// Renders script for custom transformation.
    /// </summary>
    /// <param name="renderer">Instance of Strands script renderer</param>
    /// <param name="template">Selected template</param>
    /// <exception cref="StrandsException">Transformation does not exist</exception>
    private void RenderCustomTransformation(StrandsScriptRenderer renderer, StrandsWebTemplateData template)
    {
        var transformation = TransformationInfoProvider.GetTransformation(CustomTransformation);

        if (transformation == null)
        {
            throw new StrandsException("[StrandsRecommendations.ParseRecommendationTemplate]: Cannot load the transformation specified in the web part.", ResHelper.GetString("strands.recommendations.transformations.errorloadingtransformation"));
        }
        if (transformation.TransformationType != TransformationTypeEnum.jQuery)
        {
            throw new StrandsException("[StrandsRecommendations.ParseRecommendationTemplate]: Transformation type has to be of type jQuery.", ResHelper.GetString("strands.recommendations.transformations.wrongtype"));
        }

        renderer.RenderCustomizedRendererScript(transformation, template.ID, strandsRecs.ClientID);
    }
Пример #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get parameters from query string
        GetParameters();

        if (saved)
        {
            ShowChangesSaved();
        }

        lblEnglishText.Text = string.Format(GetString("Administration-UICulture_String_New.EnglishText"), CultureHelper.DefaultUICulture);
        rfvKey.ErrorMessage = GetString("Administration-UICulture_String_New.EmptyKey");

        ResourceStringInfo ri = SqlResourceManager.GetResourceStringInfo(stringID, uiCultureID);

        EditedObject = ri;

        string defaultCulture = CultureHelper.DefaultUICulture;

        uic = UICultureInfoProvider.GetUICultureInfo(uiCultureID);
        if (uic.UICultureCode == defaultCulture)
        {
            // Default culture
            plcDefaultText.Visible = false;
            txtKey.Visible         = true;
            lblKeyEng.Visible      = false;

            if (!RequestHelper.IsPostBack())
            {
                txtKey.Text  = ri.StringKey;
                txtText.Text = SqlResourceManager.GetStringStrictly(ri.StringKey, CultureHelper.DefaultUICulture);
            }
        }
        else
        {
            // Other cultures
            plcDefaultText.Visible = true;
            txtKey.Visible         = false;
            rfvKey.Enabled         = false;
            lblKeyEng.Visible      = true;

            lblKeyEng.Text       = ri.StringKey;
            lblEnglishValue.Text = HTMLHelper.HTMLEncode(MacroResolver.RemoveSecurityParameters(SqlResourceManager.GetStringStrictly(ri.StringKey, CultureHelper.DefaultUICulture), true, null));

            if (!RequestHelper.IsPostBack())
            {
                txtKey.Text  = ri.StringKey;
                txtText.Text = SqlResourceManager.GetStringStrictly(ri.StringKey, uic.UICultureCode);
            }

            // Set default culture text to translate
            txtText.AllowTranslationServices  = true;
            txtText.TranslationSourceText     = ResHelper.GetString(ri.StringKey, defaultCulture);
            txtText.TranslationSourceLanguage = defaultCulture;
            txtText.TranslationTargetLanguage = uic.UICultureCode;
        }

        if (!DialogMode)
        {
            // Initialize master page
            InitializeMasterPage(ri, plcDefaultText.Visible);
        }
        else
        {
            txtKey.Enabled    = false;
            plcCustom.Visible = false;
        }

        if (!RequestHelper.IsPostBack() && (!DialogMode))
        {
            chkCustomString.Checked = ri.StringIsCustom;
        }
    }
Пример #10
0
    /// <summary>
    /// Empties recycle bin.
    /// </summary>
    private void EmptyBin(BinSettingsContainer settings)
    {
        // Begin log
        AddLog(ResHelper.GetString("Recyclebin.EmptyingBin", mCurrentCulture));

        try
        {
            DataSet recycleBin = GetRecycleBinSeletedItems(settings, "VersionID, VersionObjectType, VersionObjectID, VersionObjectDisplayName, VersionObjectSiteID");
            if (!DataHelper.DataSourceIsEmpty(recycleBin))
            {
                foreach (DataRow dr in recycleBin.Tables[0].Rows)
                {
                    string   versionObjType = Convert.ToString(dr["VersionObjectType"]);
                    string   objName        = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(dr["VersionObjectDisplayName"], string.Empty)));
                    SiteInfo currentSite    = settings.Site;

                    string siteName;
                    if (currentSite != null)
                    {
                        siteName = currentSite.SiteName;
                    }
                    else
                    {
                        int siteId = ValidationHelper.GetInteger(dr["VersionObjectSiteID"], 0);
                        siteName = SiteInfoProvider.GetSiteName(siteId);
                    }

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

                        // Destroy the version
                        int versionObjId = ValidationHelper.GetInteger(dr["VersionObjectID"], 0);
                        ObjectVersionManager.DestroyObjectHistory(versionObjType, versionObjId);
                        LogContext.LogEvent(EventType.INFORMATION, "Objects", "DESTROYOBJECT", ResHelper.GetString("objectversioning.Recyclebin.objectdestroyed"), RequestContext.RawURL, currentUserInfo.UserID, currentUserInfo.UserName, 0, null, RequestContext.UserHostAddress, (currentSite != null) ? currentSite.SiteID : 0, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now);
                    }
                }
                if (!String.IsNullOrEmpty(CurrentError))
                {
                    CurrentError = ResHelper.GetString("objectversioning.recyclebin.errorsomenotdestroyed", mCurrentCulture);
                    AddLog(CurrentError);
                }
                else
                {
                    CurrentInfo = ResHelper.GetString("ObjectVersioning.Recyclebin.DestroyOK", mCurrentCulture);
                    AddLog(CurrentInfo);
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            if (!CMSThread.Stopped(ex))
            {
                // Log error
                CurrentError = "Error occurred: " + ResHelper.GetString("general.seeeventlog", mCurrentCulture);
                AddLog(CurrentError);

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

            // Log to event log
            LogException("EMPTYINGBIN", ex);
        }
    }
Пример #11
0
    /// <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 (MembershipContext.AuthenticatedUser.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, SiteContext.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);
            if (verInfo != null)
            {
                // Get object site name
                string siteName = (CurrentSite != null) ? CurrentSite.SiteName : SiteInfoProvider.GetSiteName(verInfo.VersionObjectSiteID);

                if (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(doPostback: false);
    }
Пример #12
0
    /// <summary>
    /// Restores set of given version histories.
    /// </summary>
    /// <param name="recycleBin">DataSet with nodes to restore</param>
    /// <param name="action">Action to be performed</param>
    private void RestoreDataSet(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, SiteContext.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", mCurrentCulture) + " '" + taskTitle + "'");
                    }
                    else
                    {
                        // Set result flag
                        if (resultOK)
                        {
                            resultOK = false;
                        }
                    }
                }
            }
        }

        if (resultOK)
        {
            CurrentInfo = ResHelper.GetString("ObjectVersioning.Recyclebin.RestorationOK", mCurrentCulture);
            AddLog(CurrentInfo);
        }
        else
        {
            CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", mCurrentCulture);
            AddLog(CurrentError);
        }
    }
Пример #13
0
    /// <summary>
    /// Restores objects selected in UniGrid.
    /// </summary>
    private void Restore(BinSettingsContainer settings, Action action)
    {
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("objectversioning.recyclebin.restoringobjects", mCurrentCulture));

            if (settings.User.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects"))
            {
                DataSet recycleBin = GetRecycleBinSeletedItems(settings, "VersionID, VersionObjectDisplayName, VersionObjectType, VersionObjectID");

                if (!DataHelper.DataSourceIsEmpty(recycleBin))
                {
                    RestoreDataSet(recycleBin, action);
                }
            }
            else
            {
                CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailedpermissions");
                AddLog(CurrentError);
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                CurrentInfo = ResHelper.GetString("Recyclebin.RestorationCanceled", mCurrentCulture);
                AddLog(CurrentInfo);
            }
            else
            {
                // Log error
                CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", mCurrentCulture) + ": " + ResHelper.GetString("general.seeeventlog", mCurrentCulture);
                AddLog(CurrentError);

                // Log to event log
                LogException("OBJECTRESTORE", ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", mCurrentCulture) + ": " + ResHelper.GetString("general.seeeventlog", mCurrentCulture);
            AddLog(CurrentError);

            // Log to event log
            LogException("OBJECTRESTORE", ex);
        }
    }
 private void SetExplanationText()
 {
     litExplanationText.Text = String.Format(ResHelper.GetString("deleteinactivecontacts.settings.description"), DocumentationHelper.GetDocumentationTopicUrl("contacts_automatic_deletion"));
 }
Пример #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Ensure, that it is going to be rendered
        pnlRole.Visible = true;

        ScriptHelper.RegisterWOpenerScript(Page);
        ScriptHelper.RegisterJQuery(Page);

        // Try to get parameters
        string    identifier = QueryHelper.GetString("params", null);
        Hashtable parameters = (Hashtable)WindowHelper.GetItem(identifier);

        // Validate hash
        if ((QueryHelper.ValidateHash("hash", "selectedvalue")) && (parameters != null))
        {
            int siteID = ValidationHelper.GetInteger(parameters["SiteID"], -1);
            if (siteID != -1)
            {
                // Check permissions
                ContactHelper.AuthorizedReadContact(siteID, true);
                if (AccountHelper.AuthorizedModifyAccount(siteID, false) || ContactHelper.AuthorizedModifyContact(siteID, false))
                {
                    contactRoleSelector.SiteID     = siteID;
                    contactRoleSelector.IsLiveSite = false;
                    contactRoleSelector.UniSelector.DialogWindowName = "SelectContactRole";
                    contactRoleSelector.IsSiteManager = ValidationHelper.GetBoolean(parameters["IsSiteManager"], false);

                    selectionDialog.LocalizeItems = QueryHelper.GetBoolean("localize", true);

                    // Load resource prefix
                    string resourcePrefix = ValidationHelper.GetString(parameters["ResourcePrefix"], "general");

                    // Set the page title
                    string titleText = GetString(resourcePrefix + ".selectitem|general.selectitem");

                    // Validity group text
                    lblAddAccounts.ResourceString = resourcePrefix + ".contactsrole";
                    pnlRoleHeading.Visible        = true;

                    PageTitle.TitleText = titleText;
                    Page.Title          = titleText;
                }
                // No permission modify
                else
                {
                    RedirectToAccessDenied(ModuleName.CONTACTMANAGEMENT, "ModifyAccount");
                }
            }
            else
            {
                // Redirect to error page
                URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("dialogs.badhashtitle") + "&text=" + ResHelper.GetString("dialogs.badhashtext")));
            }
        }

        CurrentMaster.PanelContent.RemoveCssClass("dialog-content");
    }
Пример #16
0
    /// <summary>
    /// Deletes document(s).
    /// </summary>
    private void Delete(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Blogs, VersionActionEnum.Edit))
        {
            AddError(ResHelper.GetString("cmsdesk.blogdeletelicenselimitations", currentCulture));
            return;
        }

        if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Edit))
        {
            AddError(ResHelper.GetString("cmsdesk.documentdeletelicenselimitations", currentCulture));
            return;
        }
        int refreshId = 0;

        TreeProvider tree = new TreeProvider(currentUser);

        tree.AllowAsyncActions = false;

        try
        {
            string[] parameters = ((string)parameter).Split(';');

            string siteName         = parameters[1];
            bool   isMultipleAction = ValidationHelper.GetBoolean(parameters[2], false);

            // Prepare the where condition
            string where = SqlHelperClass.GetWhereCondition("NodeID", (int[])nodeIds.ToArray(typeof(int)));
            string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture, NodeParentID");

            bool   combineWithDefaultCulture = chkAllCultures.Checked;
            string cultureCode = combineWithDefaultCulture ? TreeProvider.ALL_CULTURES : parameters[0];

            // Begin log
            AddLog(ResHelper.GetString("ContentDelete.DeletingDocuments", currentCulture));

            // Get the documents
            DataSet ds = tree.SelectNodes(siteName, "/%", cultureCode, combineWithDefaultCulture, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                string   altPath = Convert.ToString(selAltPath.Value);
                TreeNode altNode = null;
                if (chkUseDeletedPath.Checked && !String.IsNullOrEmpty(altPath))
                {
                    NodeSelectionParameters nsp = new NodeSelectionParameters();
                    nsp.AliasPath   = altPath;
                    nsp.CultureCode = TreeProvider.ALL_CULTURES;
                    nsp.ClassNames  = TreeProvider.ALL_CLASSNAMES;
                    nsp.CombineWithDefaultCulture = true;
                    nsp.SiteName         = siteName;
                    nsp.MaxRelativeLevel = TreeProvider.ALL_LEVELS;
                    nsp.TopN             = 1;

                    altNode = DocumentHelper.GetDocument(nsp, tree);

                    // Check whether user is authorized to use alternating document
                    if (altNode != null)
                    {
                        if (currentUser.IsAuthorizedPerDocument(altNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
                        {
                            throw new Exception(GetString("contentdelete.notallowedalternating"));
                        }
                    }
                }

                // Delete the documents
                foreach (DataRow nodeRow in ds.Tables[0].Rows)
                {
                    // Get the current document
                    string className  = nodeRow["ClassName"].ToString();
                    string aliasPath  = nodeRow["NodeAliasPath"].ToString();
                    string docCulture = nodeRow["DocumentCulture"].ToString();
                    refreshId = ValidationHelper.GetInteger(nodeRow["NodeParentID"], 0);
                    if (refreshId == 0)
                    {
                        refreshId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0);
                    }
                    TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, tree);

                    if (node == null)
                    {
                        AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath)));
                        continue;
                    }

                    // Ensure current parent ID
                    int parentId = node.NodeParentID;

                    // Check if bound SKU can be deleted (if any)
                    bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node);

                    // Check delete permissions
                    if (IsUserAuthorizedToDeleteDocument(node) && (CanDestroy(node) || !chkDestroy.Checked) && authorizedToDeleteSKU)
                    {
                        // Delete the document
                        if (parentId <= 0)
                        {
                            parentId = node.NodeID;
                        }

                        // Prepare action for affected products
                        DeleteProductActionEnum deleteSKUsAction = DeleteProductActionEnum.NoAction;

                        switch (rblSKUAction.SelectedValue)
                        {
                        case "delete":
                            deleteSKUsAction = DeleteProductActionEnum.DeleteSKU;
                            break;

                        case "disable":
                            deleteSKUsAction = DeleteProductActionEnum.DisableSKU;
                            break;

                        case "deleteordisable":
                            deleteSKUsAction = DeleteProductActionEnum.DeleteOrDisableSKU;
                            break;
                        }

                        // Prepare settings for delete
                        DeleteDocumentSettings settings = new DeleteDocumentSettings(node, tree, chkAllCultures.Checked, chkDestroy.Checked, deleteSKUsAction);

                        // Add additional settings if alternating document is specified
                        if (altNode != null)
                        {
                            settings.AlternatingDocument             = altNode;
                            settings.AlternatingDocumentCopyAllPaths = chkAltAliases.Checked;
                            settings.AlternatingDocumentMaxLevel     = chkAltSubNodes.Checked ? -1 : node.NodeLevel;
                        }

                        // Delete document
                        refreshId = DocumentHelper.DeleteDocument(settings) || isMultipleAction ? parentId : node.NodeID;
                    }
                    // Access denied - not authorized to delete the document
                    else
                    {
                        AddError(string.Format(ResHelper.GetString("cmsdesk.notauthorizedtodeletedocument", currentCulture), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                    }
                }
            }
            else
            {
                AddError(ResHelper.GetString("DeleteDocument.CultureNotExists", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                ShowError(ResHelper.GetString("DeleteDocument.DeletionCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (string.IsNullOrEmpty(CurrentError))
            {
                // Refresh tree or page (on-site editing)
                if (!RequiresDialog)
                {
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    // Go to the root by default
                    string url = URLHelper.ResolveUrl("~/");

                    // Update the refresh node id when set in the parent dialog
                    if (Parameters != null)
                    {
                        int refreshNodeId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                        if (refreshNodeId > 0)
                        {
                            refreshId = refreshNodeId;
                        }
                    }

                    // Try go to the parent document
                    if (refreshId > 0)
                    {
                        TreeProvider tp = new TreeProvider(CMSContext.CurrentUser);
                        TreeNode     tn = DocumentHelper.GetDocument(refreshId, TreeProvider.ALL_CULTURES, tp);
                        if (tn != null)
                        {
                            url = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(tn.NodeAliasPath));
                        }
                    }

                    ctlAsync.Parameter = "window.refreshPageOnClose = true; window.reloadPageUrl = " + ScriptHelper.GetString(url) + "; CloseDialog();";
                }
            }
            else
            {
                ctlAsync.Parameter = "RefreshTree(null, null);";
            }
        }
    }
Пример #17
0
    /// <summary>
    /// Initializes header actions.
    /// </summary>
    protected void InitHeaderActions()
    {
        bool isAuthorized = CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm");

        int attachCount = 0;

        if (isAuthorized)
        {
            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(FormInfo.FormID, BizFormInfo.OBJECT_TYPE, ObjectAttachmentsCategories.LAYOUT, null, null, "MetafileID", -1);
            attachCount = ds.Items.Count;

            // Register attachments count update module
            ScriptHelper.RegisterModule(this, "CMS/AttachmentsCountUpdater", new { Selector = "." + mAttachmentsActionClass, Text = ResHelper.GetString("general.attachments") });

            // Register dialog scripts
            ScriptHelper.RegisterDialogScript(Page);
        }

        // Prepare metafile dialog URL
        string metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
        string query             = string.Format("?objectid={0}&objecttype={1}", FormInfo.FormID, BizFormInfo.OBJECT_TYPE);

        metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, ObjectAttachmentsCategories.LAYOUT, QueryHelper.GetHash(query));

        // Init attachment button
        attachments = new HeaderAction
        {
            Text          = GetString("general.attachments") + ((attachCount > 0) ? " (" + attachCount + ")" : string.Empty),
            Tooltip       = GetString("general.attachments"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
            Enabled       = isAuthorized,
            Visible       = !layoutElem.IsEditedObjectLocked(),
            CssClass      = mAttachmentsActionClass,
            ButtonStyle   = ButtonStyle.Default,
        };
        layoutElem.AddExtraHeaderAction(attachments);
    }
        /// <summary>
        /// Prepares the layout of the web part.
        /// </summary>
        protected override void PrepareLayout()
        {
            //make a unique id for the div, this is to deal with multiple instances of the control on the same page
            Random ran = new Random();

            UniqueHtmlId = "vectorTabAccordion" + ran.Next(10000, 999999);
            IsMobileView = Request.IsMobileBrowser();

            StartLayout();
            StringBuilder result = new StringBuilder();

            result.Append("<div ");
            // Width
            string width = Width;

            if (!string.IsNullOrEmpty(width))
            {
                result.Append(" style=\"width: ", width, "\"");
            }

            if (IsDesign)
            {
                result.Append(" id=\"", ShortClientID, "_env\">");

                result.Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">");

                switch (ViewMode)
                {
                case ViewModeEnum.Design:
                case ViewModeEnum.DesignDisabled:
                {
                    result.Append("<tr><td class=\"LayoutHeader\" colspan=\"2\">");

                    // Add header container
                    AddHeaderContainer();

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

                result.Append("<tr><td style=\"width: 100%;\">");
            }
            else
            {
                result.Append(">");
            }

            // Add the tabs
            tabs    = new TabContainer();
            tabs.ID = "tabs";

            if (IsDesign)
            {
                result.Append("</td>");

                // Resizers
                if (AllowDesignMode)
                {
                    // Width resizer
                    result.Append("<td class=\"HorizontalResizer\" onmousedown=\"", GetHorizontalResizerScript("env", "Width", false, "tabs_body"), " return false;\">&nbsp;</td></tr>");

                    // Height resizer
                    result.Append("<tr><td class=\"VerticalResizer\" onmousedown=\"", GetVerticalResizerScript("tabs_body", "Height"), " return false;\">&nbsp;</td>");
                    result.Append("<td class=\"BothResizer\" onmousedown=\"", GetHorizontalResizerScript("env", "Width", false, "tabs_body"), " ", GetVerticalResizerScript("tabs_body", "Height"), " return false;\">&nbsp;</td>");
                }

                result.Append("</tr>");
            }

            // Tab headers
            string[] headers = TextHelper.EnsureLineEndings(TabHeaders, "\n").Split('\n');

            if ((ActiveTabIndex >= 1) && (ActiveTabIndex <= Tabs))
            {
                tabs.ActiveTabIndex = ActiveTabIndex - 1;
            }

            bool hideEmpty = HideEmptyTabs;

            for (int i = 1; i <= Tabs; i++)
            {
                // Create new tab
                CMSTabPanel tab = new CMSTabPanel();
                tab.ID = "tab" + i;

                // Prepare the header
                string header = null;
                if (headers.Length >= i)
                {
                    header = ResHelper.LocalizeString(headers[i - 1]);
                    header = HTMLHelper.HTMLEncode(header);
                }
                if (String.IsNullOrEmpty(header))
                {
                    header = "Tab " + i;
                }

                tab.HeaderText      = header;
                tab.HideIfZoneEmpty = hideEmpty;

                tabs.Tabs.Add(tab);

                tab.WebPartZone = AddZone(ID + "_" + i, header, tab);
            }

            if (IsDesign || !IsMobileView)
            {
                //show tabs in design mode
                AddControl(tabs);
            }
            else
            {
                //show tab content in view mode
                ShowTabContent();
            }

            // Setup the tabs
            tabs.ScrollBars = ControlsHelper.GetScrollbarsEnum(Scrollbars);

            if (!String.IsNullOrEmpty(TabsCSSClass))
            {
                tabs.CssClass = TabsCSSClass;
            }

            tabs.TabStripPlacement = GetTabStripPlacement(TabStripPlacement);

            if (!String.IsNullOrEmpty(Height))
            {
                tabs.Height = new Unit(Height);
            }

            if (IsDesign)
            {
                // Footer
                if (AllowDesignMode)
                {
                    result.Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">");

                    result.Append("<div class=\"LayoutLeftActions\">");

                    // Pane actions
                    AppendAddAction(ResHelper.GetString("Layout.AddTab"), "Tabs");
                    if (Tabs > 1)
                    {
                        AppendRemoveAction(ResHelper.GetString("Layout.RemoveTab"), "Tabs");
                    }

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

                result.Append("</table>");
            }

            result.Append("</div>");

            //Append(result.ToString());
            FinishLayout();
        }
    /// <summary>
    /// Setups control for authenticated users.
    /// </summary>
    private void SetupControlForAuthenticatedUser()
    {
        EnsureBackwardCompatibility();

        // If signout should not be visible or user has not FacebookID registered
        if ((ShowSignOutAs == ShowSignOutEnum.DoNotShow) || String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.UserFacebookID))
        {
            Visible = false;
            return;
        }

        RegisterFacebookScript();

        // Get logout script for FB connect
        string currentUrlLogout = URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "logout", "1");

        currentUrlLogout = URLHelper.AddParameterToUrl(currentUrlLogout, "logout_hash", QueryHelper.GetHash(currentUrlLogout));
        string additionalScript = "window.location.href=" + ScriptHelper.GetString(URLHelper.GetAbsoluteUrl(currentUrlLogout)) + "; return false;";
        string logoutScript     = FacebookConnectHelper.GetFacebookLogoutScriptForSignOut(RequestContext.CurrentURL, FacebookConnectHelper.GetFacebookApiKey(SiteContext.CurrentSiteName), additionalScript);

        // Hide Facebook Connect button
        plcFBButton.Visible = false;
        if (String.IsNullOrEmpty(SignOutText))
        {
            SignOutText = ResHelper.GetString("webparts_membership_signoutbutton.signout");
        }

        switch (ShowSignOutAs)
        {
        // Show as image
        case ShowSignOutEnum.Image:
            string signOutImageUrl = SignOutImageURL;

            // Use default image if none is specified
            if (String.IsNullOrEmpty(signOutImageUrl))
            {
                signOutImageUrl = GetImageUrl("Others/FacebookConnect/signout.gif");
            }
            imgSignOut.ImageUrl        = ResolveUrl(signOutImageUrl);
            imgSignOut.Visible         = true;
            imgSignOut.AlternateText   = GetString("webparts_membership_signoutbutton.signout");
            lnkSignOutImageBtn.Visible = true;
            lnkSignOutImageBtn.Attributes.Add("onclick", logoutScript);
            lnkSignOutImageBtn.Attributes.Add("style", "cursor:pointer;");
            break;

        // Show as link
        case ShowSignOutEnum.Link:
            lnkSignOutLink.Text    = SignOutText;
            lnkSignOutLink.Visible = true;
            lnkSignOutLink.Attributes.Add("onclick", logoutScript);
            lnkSignOutLink.Attributes.Add("style", "cursor:pointer;");
            break;

        // Show as button
        case ShowSignOutEnum.Button:
            btnSignOut.OnClientClick = logoutScript;
            btnSignOut.Text          = SignOutText;
            btnSignOut.Visible       = true;
            break;
        }
    }
Пример #20
0
    /// <summary>
    /// Prepares the layout of the web part.
    /// </summary>
    protected override void PrepareLayout()
    {
        StartLayout();

        Append("<div");

        // Width
        string width = Width;

        if (!string.IsNullOrEmpty(width))
        {
            Append(" style=\"width: ", width, "\"");
        }

        if (IsDesign)
        {
            Append(" id=\"", ShortClientID, "_env\">");

            Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">");

            if (ViewModeIsDesign())
            {
                Append("<tr><td class=\"LayoutHeader\" colspan=\"2\">");

                // Add header container
                AddHeaderContainer();

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

            Append("<tr><td id=\"", ShortClientID, "_info\" style=\"width: 100%;\">");
        }
        else
        {
            Append(">");
        }

        // Add the tabs
        var acc = new CMSAccordion();

        acc.ID = "acc";
        AddControl(acc);

        if (IsDesign)
        {
            Append("</td>");

            if (AllowDesignMode)
            {
                // Width resizer
                Append("<td class=\"HorizontalResizer\" onmousedown=\"" + GetHorizontalResizerScript("env", "Width", false, "info") + " return false;\">&nbsp;</td>");
            }

            Append("</tr>");
        }

        // Pane headers
        string[] headers = TextHelper.EnsureLineEndings(PaneHeaders, "\n").Split('\n');

        for (int i = 1; i <= Panes; i++)
        {
            // Create new pane
            var pane = new CMSAccordionPane();
            pane.ID = "pane" + i;

            // Prepare the header
            string header = null;
            if (headers.Length >= i)
            {
                header = ResHelper.LocalizeString(headers[i - 1]);
                header = HTMLHelper.HTMLEncode(header);
            }
            if (String.IsNullOrEmpty(header))
            {
                header = "Pane " + i;
            }

            pane.Header = new TextTransformationTemplate(header);
            acc.Panes.Add(pane);

            pane.WebPartZone = AddZone(ID + "_" + i, header, pane.ContentContainer);
        }

        // Setup the accordion
        if ((ActivePaneIndex >= 1) && (ActivePaneIndex <= acc.Panes.Count))
        {
            acc.SelectedIndex = ActivePaneIndex - 1;
        }

        acc.ContentCssClass        = ContentCSSClass;
        acc.HeaderCssClass         = HeaderCSSClass;
        acc.HeaderSelectedCssClass = SelectedHeaderCSSClass;

        acc.FadeTransitions    = FadeTransitions;
        acc.TransitionDuration = TransitionDuration;
        acc.RequireOpenedPane  = RequireOpenedPane;

        // If no active pane is selected and doesn't require opened one, do not preselect any
        if (!acc.RequireOpenedPane && (ActivePaneIndex < 0))
        {
            acc.SelectedIndex = -1;
        }

        if (IsDesign)
        {
            if (AllowDesignMode)
            {
                Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">");

                // Pane actions
                Append("<div class=\"LayoutLeftActions\">");

                AppendAddAction(ResHelper.GetString("Layout.AddPane"), "Panes");
                if (Panes > 1)
                {
                    AppendRemoveAction(ResHelper.GetString("Layout.RemoveLastPane"), "Panes");
                }

                Append("</div></div></td></tr>");
            }

            Append("</table>");
        }

        Append("</div>");

        FinishLayout();
    }
Пример #21
0
    /// <summary>
    /// Moves document.
    /// </summary>
    private void PerformAction(object parameter)
    {
        AddLog(GetString(CopyMoveAction.ToLowerCSafe() == "copy" ? "media.copy.startcopy" : "media.move.startmove"));

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

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

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

            // Original path in DB
            string origDBPath = Path.EnsureSlashes(FolderPath);

            // New path in DB
            string newDBPath;

            AddLog(NewPath);

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

            string origFolderName = Path.GetFileName(origPath);

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

            // New path on disk
            string newPath = NewPath;

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

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

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

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

                    // Get new DB path
                    newDBPath = Path.EnsureSlashes(newPath.Replace(Path.EnsureEndBackslash(libPath), ""));
                }
                catch (Exception ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                    EventLogProvider.LogException("MediaFolder", CopyMoveAction, ex);
                    AddLog(CurrentError);
                    return;
                }
            }
            else
            {
                origDBPath = Path.EnsureSlashes(FolderPath);
                newDBPath  = Path.EnsureSlashes(newPath.Replace(libPath, "")).Trim('/');
            }

            // Error if moving folder into its subfolder
            if ((String.IsNullOrEmpty(Files) && !AllFiles) && (CopyMoveAction.ToLowerCSafe() == "move") && newPath.StartsWithCSafe(Path.EnsureEndBackslash(FolderPath)))
            {
                CurrentError = GetString("media.move.parenttochild");
                AddLog(CurrentError);
                return;
            }

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

            NewPath       = newPath;
            refreshScript = @"
var topWin = GetTop();
if (topWin) {
    if ((topWin.opener) && (typeof(topWin.opener.RefreshLibrary) != 'undefined')) {
        topWin.opener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + @");
    } 
    else if ((topWin.wopener) && (typeof(topWin.wopener.RefreshLibrary) != 'undefined')) { 
        topWin.wopener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + @"); 
    } 
    CloseDialog();
}";

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

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

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

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

                                AddLog(fileName);

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

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

                                try
                                {
                                    CopyMove(origDBFilePath, newDBFilePath);
                                }
                                catch (UnauthorizedAccessException ex)
                                {
                                    CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied");
                                    EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                                    AddLog(CurrentError);
                                    return;
                                }
                                catch (ThreadAbortException ex)
                                {
                                    string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                                    if (state == CMSThread.ABORT_REASON_STOP)
                                    {
                                        // When canceled
                                        CurrentInfo = GetString("general.actioncanceled");
                                        AddLog(CurrentInfo);
                                    }
                                    else
                                    {
                                        // Log error
                                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                        EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                                        AddLog(CurrentError);
                                        return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                    EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                                    AddLog(CurrentError);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
Пример #22
0
    /// <summary>
    /// Initializes header action control.
    /// </summary>
    private void InitHeaderActions()
    {
        bool isNew          = (IssueId == 0);
        var  issue          = IssueInfoProvider.GetIssueInfo(IssueId);
        bool isIssueVariant = !isNew && (issue != null) && issue.IssueIsABTest;

        hdrActions.ActionsList.Clear();

        // Init save button
        hdrActions.ActionsList.Add(new SaveAction(this)
        {
            OnClientClick = "if (GetContent != null) {return GetContent();} else {return false;}"
        });

        // Ensure spell check action
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("EditMenu.IconSpellCheck"),
            Tooltip       = GetString("EditMenu.SpellCheck"),
            OnClientClick = "var frame = GetFrame(); if ((frame != null) && (frame.contentWindow.SpellCheck_" + ClientID + " != null)) {frame.contentWindow.SpellCheck_" + ClientID + "();} return false;"
        });

        // Init send draft button
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("newsletterissue_content.senddraft"),
            Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : GetString("newsletterissue_content.senddraft"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}?objectid={1}', 'SendDraft', '700', '300');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_SendDraft.aspx"), IssueId) + " return false;",
            Enabled       = !isNew
        });

        // Init preview button
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("general.preview"),
            Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : GetString("general.preview"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}?objectid={1}', 'Preview', '90%', '90%');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_Preview.aspx"), IssueId) + " return false;",
            Enabled       = !isNew
        });

        int    attachCount       = 0;
        string metaFileDialogUrl = null;

        if (!isNew)
        {
            ScriptHelper.RegisterDialogScript(Page);

            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(IssueId,
                                                                              (isIssueVariant ? IssueInfo.OBJECT_TYPE_VARIANT : IssueInfo.OBJECT_TYPE),
                                                                              ObjectAttachmentsCategories.ISSUE, null, null, "MetafileID", -1);
            attachCount = ds.Items.Count;

            // Register attachments count update module
            ScriptHelper.RegisterModule(this, "CMS/AttachmentsCountUpdater", new { Selector = "." + mAttachmentsActionClass, Text = ResHelper.GetString("general.attachments") });

            // Prepare metafile dialog URL
            metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
            string query = string.Format("?objectid={0}&objecttype={1}", IssueId, (isIssueVariant ? IssueInfo.OBJECT_TYPE_VARIANT : IssueInfo.OBJECT_TYPE));
            metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, ObjectAttachmentsCategories.ISSUE, QueryHelper.GetHash(query));
        }

        // Init attachment button
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("general.attachments") + ((attachCount > 0) ? " (" + attachCount + ")" : string.Empty),
            Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : GetString("general.attachments"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
            Enabled       = !isNew,
            CssClass      = mAttachmentsActionClass
        });

        // Init create A/B test button - online marketing, open email and click through tracking are required
        if (isNew || !isIssueVariant)
        {
            if (NewsletterHelper.IsABTestingAvailable())
            {
                // Check that trackings are enabled
                NewsletterInfo news             = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
                bool           trackingsEnabled = (news != null) && news.NewsletterTrackOpenEmails && news.NewsletterTrackClickedLinks;

                hdrActions.ActionsList.Add(new HeaderAction
                {
                    Text          = GetString("newsletterissue_content.createabtest"),
                    Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : (trackingsEnabled ? GetString("newsletterissue_content.createabtest") : GetString("newsletterissue_content.abtesttooltip")),
                    OnClientClick = (isNew || !trackingsEnabled) ? "return false;" : "ShowVariantDialog_" + ucVariantDialog.ClientID + "('addvariant', ''); return false;",
                    Enabled       = !isNew && trackingsEnabled
                });
                ucVariantDialog.IssueID       = IssueId;
                ucVariantDialog.OnAddVariant += ucVariantSlider_OnVariantAdded;
            }
        }

        hdrActions.ActionPerformed += HeaderActions_ActionPerformed;
        hdrActions.ReloadData();
        pnlActions.Attributes.Add("onmouseover", "if (RememberFocusedRegion) {RememberFocusedRegion();}");
    }
Пример #23
0
    /// <summary>
    /// Logged in handler.
    /// </summary>
    private void Login1_LoggedIn(object sender, EventArgs e)
    {
        // Set view mode to live site after login to prevent bar with "Close preview mode"
        CMSContext.ViewMode = ViewModeEnum.LiveSite;

        // Ensure response cookie
        CookieHelper.EnsureResponseCookie(FormsAuthentication.FormsCookieName);

        // Set cookie expiration
        if (Login1.RememberMeSet)
        {
            CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddYears(1), false);
        }
        else
        {
            // Extend the expiration of the authentication cookie if required
            if (!AuthenticationHelper.UseSessionCookies && (HttpContext.Current != null) && (HttpContext.Current.Session != null))
            {
                CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddMinutes(Session.Timeout), false);
            }
        }

        // Current username
        string userName = Login1.UserName;

        // Get user name (test site prefix too)
        UserInfo ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, CMSContext.CurrentSite);

        // Check whether safe user name is required and if so get safe username
        if (RequestHelper.IsMixedAuthentication() && UserInfoProvider.UseSafeUserName)
        {
            // Get info on the authenticated user
            if (ui == null)
            {
                // User stored with safe name
                userName = ValidationHelper.GetSafeUserName(Login1.UserName, CMSContext.CurrentSiteName);

                // Find user by safe name
                ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, CMSContext.CurrentSite);
                if (ui != null)
                {
                    // Authenticate user by site or global safe username
                    CMSContext.AuthenticateUser(ui.UserName, Login1.RememberMeSet);
                }
            }
        }

        if (ui != null)
        {
            // If user name is site prefixed, authenticate user manually
            if (UserInfoProvider.IsSitePrefixedUser(ui.UserName))
            {
                CMSContext.AuthenticateUser(ui.UserName, Login1.RememberMeSet);
            }

            // Log activity
            int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
            Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables);
            activityLogin.Log();
        }

        // Redirect user to the return url, or if is not defined redirect to the default target url
        string url = QueryHelper.GetString("ReturnURL", string.Empty);

        if (!string.IsNullOrEmpty(url))
        {
            if (url.StartsWithCSafe("~") || url.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))
            {
                URLHelper.Redirect(ResolveUrl(ValidationHelper.GetString(Request.QueryString["ReturnURL"], "")));
            }
            else
            {
                URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
            }
        }
        else
        {
            if (DefaultTargetUrl != "")
            {
                URLHelper.Redirect(ResolveUrl(DefaultTargetUrl));
            }
            else
            {
                URLHelper.Redirect(URLRewriter.CurrentURL);
            }
        }
    }
    private void InitAttachmentAction()
    {
        EmailTemplateInfo emailTemplate = Control.EditedObject as EmailTemplateInfo;

        if ((emailTemplate != null) && (emailTemplate.TemplateID > 0))
        {
            int  siteId = emailTemplate.TemplateSiteID;
            Page page   = Control.Page;

            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(emailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE,
                                                                              siteId > 0 ? "MetaFileSiteID=" + siteId : "MetaFileSiteID IS NULL", null, "MetafileID", -1);
            int attachCount = ds.Items.Count;

            // Register attachments count update module
            ScriptHelper.RegisterModule(page, "CMS/AttachmentsCountUpdater", new { Selector = "." + mAttachmentsActionClass, Text = ResHelper.GetString("general.attachments") });

            // Register dialog scripts
            ScriptHelper.RegisterDialogScript(page);

            // Prepare metafile dialog URL
            string metaFileDialogUrl = URLHelper.ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
            string query             = String.Format("?objectid={0}&objecttype={1}&siteid={2}", emailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, siteId);
            metaFileDialogUrl += String.Format("{0}&category={1}&hash={2}", query, ObjectAttachmentsCategories.TEMPLATE, QueryHelper.GetHash(query));

            ObjectEditMenu menu = (ObjectEditMenu)ControlsHelper.GetChildControl(page, typeof(ObjectEditMenu));
            if (menu != null)
            {
                menu.AddExtraAction(new HeaderAction()
                {
                    Text          = ResHelper.GetString("general.attachments") + ((attachCount > 0) ? " (" + attachCount.ToString() + ")" : String.Empty),
                    OnClientClick = String.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
                    Enabled       = !SynchronizationHelper.UseCheckinCheckout || emailTemplate.Generalized.IsCheckedOutByUser(MembershipContext.AuthenticatedUser),
                    CssClass      = mAttachmentsActionClass
                });
            }
        }
    }
Пример #25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterDialogScript(this.Page);
        ScriptHelper.RegisterApplicationConstants(this.Page);

        // Get the object type
        string param       = this.ContextMenu.Parameter;
        string objectType  = null;
        bool   groupObject = false;

        if (param != null)
        {
            string[] parms = param.Split(';');
            objectType = parms[0];
            if (parms.Length == 2)
            {
                groupObject = ValidationHelper.GetBoolean(parms[1], false);
            }
        }

        // Get empty info
        GeneralizedInfo obj = null;

        if (objectType != null)
        {
            obj = CMSObjectHelper.GetReadOnlyObject(objectType);
            // Get correct info for listings
            if (obj.TypeInfo.Inherited)
            {
                obj = CMSObjectHelper.GetReadOnlyObject(obj.TypeInfo.OriginalObjectType);
            }
            obj.ObjectGroupID = groupObject ? 1 : 0;
        }

        if (obj == null)
        {
            this.Visible = false;
            return;
        }

        CurrentUserInfo curUser     = CMSContext.CurrentUser;
        string          curSiteName = CMSContext.CurrentSiteName;

        string menuId = this.ContextMenu.MenuID;

        // Relationships
        if (obj.TypeInfo.HasObjectRelationships)
        {
            this.iRelationships.ImageUrl = UIHelper.GetImageUrl(this.Page, "Design/Controls/UniGrid/Actions/Relationships.png");
            this.iRelationships.Text     = ResHelper.GetString("General.Relationships");
            this.iRelationships.Attributes.Add("onclick", "ContextRelationships(GetContextMenuParameter('" + menuId + "'));");
        }
        else
        {
            this.iRelationships.Visible = false;
        }

        // Export
        if (obj.TypeInfo.AllowSingleExport)
        {
            if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "ExportObjects", curSiteName))
            {
                this.iExport.ImageUrl = UIHelper.GetImageUrl(this.Page, "Design/Controls/UniGrid/Actions/ExportObject.png");
                this.iExport.Text     = ResHelper.GetString("General.Export");
                this.iExport.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), false);");
            }
            else
            {
                this.iExport.Visible = false;
            }

            if (obj.GUIDColumn != TypeInfo.COLUMN_NAME_UNKNOWN)
            {
                if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "BackupObjects", curSiteName))
                {
                    this.iBackup.ImageUrl = UIHelper.GetImageUrl(this.Page, "Design/Controls/UniGrid/Actions/BackupObject.png");
                    this.iBackup.Text     = ResHelper.GetString("General.Backup");
                    this.iBackup.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), true);");
                }
                else
                {
                    this.iBackup.Visible = false;
                }

                if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects", curSiteName))
                {
                    this.iRestore.ImageUrl = UIHelper.GetImageUrl(this.Page, "Design/Controls/UniGrid/Actions/RestoreObject.png");
                    this.iRestore.Text     = ResHelper.GetString("General.Restore");
                    this.iRestore.Attributes.Add("onclick", "ContextRestoreObject(GetContextMenuParameter('" + menuId + "'), true);");
                }
                else
                {
                    this.iRestore.Visible = false;
                }
            }
            else
            {
                this.iBackup.Visible  = false;
                this.iRestore.Visible = false;
            }
        }
        else
        {
            this.iExport.Visible  = false;
            this.iBackup.Visible  = false;
            this.iRestore.Visible = false;
        }

        // Versioning
        if (obj.AllowRestore && UniGridFunctions.ObjectSupportsDestroy(obj) && curUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, obj.TypeInfo.OriginalObjectType, curSiteName))
        {
            iDestroy.ImageUrl = UIHelper.GetImageUrl(Page, "Design/Controls/UniGrid/Actions/Delete.png");
            iDestroy.Text     = ResHelper.GetString("security.destroy");
            iDestroy.Attributes.Add("onclick", "ContextDestroyObject_" + ClientID + "(GetContextMenuParameter('" + menuId + "'))");
        }
        else
        {
            iDestroy.Visible = false;
        }

        bool ancestor = iRelationships.Visible;

        sep1.Visible = iExport.Visible && ancestor;
        ancestor    |= iExport.Visible;
        sep2.Visible = (iBackup.Visible || iRestore.Visible) && ancestor;
        ancestor    |= (iBackup.Visible || iRestore.Visible);
        sep3.Visible = iDestroy.Visible && ancestor;

        this.Visible = iRelationships.Visible || iExport.Visible || iBackup.Visible || iDestroy.Visible;

        if (Visible)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
function ContextRelationships(definition) {
   var url = applicationUrl + 'CMSModules/AdminControls/Pages/ObjectRelationships.aspx?objecttype=' + escape(definition[0]) + '&objectid=' + escape(definition[1]);
        modalDialog(url, ""relationships"", 900, 600);
    }
    
function ContextExportObject(definition, backup) {
   var query = ''; 
   if (backup) {
       query += '&backup=true';
   }
   modalDialog(applicationUrl + 'CMSModules/ImportExport/SiteManager/ExportObject.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1] + query, 'ExportObject', 750, 200);
}

function ContextRestoreObject(definition, backup) {
    var query = '';
    if (backup) {
       query += '&backup=true';
    }
    modalDialog(applicationUrl + 'CMSModules/ImportExport/SiteManager/RestoreObject.aspx?objectType=' + escape(definition[0]) + '&objectId=' + definition[1] + query, 'RestoreObject', 750, 350);
}");
            // Register general export scripts
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ObjectMenuExportScripts", sb.ToString(), true);

            sb = new StringBuilder();
            sb.Append(@"
function ContextDestroyObject_", ClientID, @"(definition)
{
   if(confirm('", ResHelper.GetString("objectversioning.destroyobjectconfirmation"), @"')) {
      if(UG_DestroyObj_", ContextMenu.ParentElementClientID, @") {
          var param = definition.toString().split(',');
          if((param != null) && (param.length == 2)) {
              UG_DestroyObj_", ContextMenu.ParentElementClientID, @"(param[1]);
          }
      }
   }
}");
            // Register destroy script for particular menu
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ObjectMenuDestroyScript_" + ClientID, sb.ToString(), true);
        }
    }
Пример #26
0
    private void ReloadMenu()
    {
        if (StopProcessing)
        {
            return;
        }

        // Handle several reloads
        ClearProperties();

        if (!HideStandardButtons)
        {
            // If content should be refreshed
            if (AutomationManager.RefreshActionContent)
            {
                // Display action message
                WorkflowActionInfo action = WorkflowActionInfoProvider.GetWorkflowActionInfo(Step.StepActionID);
                string             name   = (action != null) ? action.ActionDisplayName : Step.StepDisplayName;
                string             str    = (action != null) ? "workflow.actioninprogress" : "workflow.stepinprogress";
                string             text   = string.Format(ResHelper.GetString(str, ResourceCulture), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(name)));
                text = ScriptHelper.GetLoaderInlineHtml(text);

                InformationText = text;
                EnsureRefreshScript();
            }

            // Object update
            if (AutomationManager.Mode == FormModeEnum.Update)
            {
                if (InfoObject != null)
                {
                    // Get current process
                    WorkflowInfo process    = AutomationManager.Process;
                    string       objectName = HTMLHelper.HTMLEncode(InfoObject.TypeInfo.GetNiceObjectTypeName().ToLowerCSafe());

                    // Next step action
                    if (AutomationManager.IsActionAllowed(ComponentEvents.AUTOMATION_MOVE_NEXT))
                    {
                        next = new NextStepAction(Page)
                        {
                            Tooltip       = string.Format(ResHelper.GetString("EditMenu.NextStep", ResourceCulture), objectName),
                            OnClientClick = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_MOVE_NEXT, null),
                        };
                    }

                    // Move to specific step action
                    if (AutomationManager.IsActionAllowed(ComponentEvents.AUTOMATION_MOVE_SPEC))
                    {
                        var steps = WorkflowStepInfoProvider.GetWorkflowSteps()
                                    .Where("StepWorkflowID = " + process.WorkflowID + " AND StepType <> " + (int)WorkflowStepTypeEnum.Start)
                                    .OrderBy("StepDisplayName");

                        specific = new NextStepAction(Page)
                        {
                            Text        = GetString("AutoMenu.SpecificStepIcon"),
                            Tooltip     = string.Format(ResHelper.GetString("AutoMenu.SpecificStepMultiple", ResourceCulture), objectName),
                            CommandName = ComponentEvents.AUTOMATION_MOVE_SPEC,
                            EventName   = ComponentEvents.AUTOMATION_MOVE_SPEC,
                            CssClass    = "scrollable-menu",

                            // Make action inactive
                            OnClientClick = null,
                            Inactive      = true
                        };

                        foreach (var s in steps)
                        {
                            string         stepName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.StepDisplayName));
                            NextStepAction spc      = new NextStepAction(Page)
                            {
                                Text            = string.Format(ResHelper.GetString("AutoMenu.SpecificStepTo", ResourceCulture), stepName),
                                Tooltip         = string.Format(ResHelper.GetString("AutoMenu.SpecificStep", ResourceCulture), objectName),
                                CommandName     = ComponentEvents.AUTOMATION_MOVE_SPEC,
                                EventName       = ComponentEvents.AUTOMATION_MOVE_SPEC,
                                CommandArgument = s.StepID.ToString(),
                                OnClientClick   = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_MOVE_SPEC, "if(!confirm(" + ScriptHelper.GetString(string.Format(ResHelper.GetString("autoMenu.MoveSpecificConfirmation"), objectName, ResHelper.LocalizeString(s.StepDisplayName))) + ")) { return false; }"),
                            };

                            // Process action appearance
                            ProcessAction(spc, Step, s);

                            // Add step
                            specific.AlternativeActions.Add(spc);
                        }

                        // Add comment
                        AddCommentAction(ComponentEvents.AUTOMATION_MOVE_SPEC, specific, objectName);
                    }

                    // Previous step action
                    if (AutomationManager.IsActionAllowed(ComponentEvents.AUTOMATION_MOVE_PREVIOUS))
                    {
                        var prevSteps      = Manager.GetPreviousSteps(InfoObject, StateObject);
                        int prevStepsCount = prevSteps.Count;

                        if (prevStepsCount > 0)
                        {
                            previous = new PreviousStepAction(Page)
                            {
                                Tooltip       = string.Format(ResHelper.GetString("EditMenu.PreviousStep", ResourceCulture), objectName),
                                OnClientClick = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_MOVE_PREVIOUS, null)
                            };

                            // For managers allow move to specified step
                            if (WorkflowStepInfoProvider.CanUserManageAutomationProcesses(MembershipContext.AuthenticatedUser, InfoObject.Generalized.ObjectSiteName))
                            {
                                if (prevStepsCount > 1)
                                {
                                    foreach (var s in prevSteps)
                                    {
                                        previous.AlternativeActions.Add(new PreviousStepAction(Page)
                                        {
                                            Text            = string.Format(ResHelper.GetString("EditMenu.PreviousStepTo", ResourceCulture), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.StepDisplayName))),
                                            Tooltip         = string.Format(ResHelper.GetString("EditMenu.PreviousStep", ResourceCulture), objectName),
                                            OnClientClick   = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_MOVE_PREVIOUS, null),
                                            CommandArgument = s.RelatedHistoryID.ToString()
                                        });
                                    }
                                }
                            }

                            // Add comment
                            AddCommentAction(ComponentEvents.AUTOMATION_MOVE_PREVIOUS, previous, objectName);
                        }
                    }

                    if (AutomationManager.IsActionAllowed(ComponentEvents.AUTOMATION_REMOVE))
                    {
                        delete = new HeaderAction
                        {
                            CommandName   = ComponentEvents.AUTOMATION_REMOVE,
                            EventName     = ComponentEvents.AUTOMATION_REMOVE,
                            Text          = ResHelper.GetString("autoMenu.RemoveState", ResourceCulture),
                            Tooltip       = string.Format(ResHelper.GetString("autoMenu.RemoveStateDesc", ResourceCulture), objectName),
                            OnClientClick = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_REMOVE, "if(!confirm(" + ScriptHelper.GetString(string.Format(ResHelper.GetString("autoMenu.RemoveStateConfirmation"), objectName)) + ")) { return false; }"),
                            ButtonStyle   = ButtonStyle.Default
                        };
                    }

                    // Handle multiple next steps
                    if (next != null)
                    {
                        // Get next step info
                        List <WorkflowStepInfo> steps = AutomationManager.NextSteps;
                        int stepsCount = steps.Count;
                        if (stepsCount > 0)
                        {
                            var nextS = steps[0];

                            // Only one next step
                            if (stepsCount == 1)
                            {
                                if (nextS.StepIsFinished)
                                {
                                    next.Text    = ResHelper.GetString("EditMenu.IconFinish", ResourceCulture);
                                    next.Tooltip = string.Format(ResHelper.GetString("EditMenu.Finish", ResourceCulture), objectName);
                                }

                                // Process action appearance
                                ProcessAction(next, Step, nextS);
                            }
                            // Multiple next steps
                            else
                            {
                                // Check if not all steps finish steps
                                if (steps.Exists(s => !s.StepIsFinished))
                                {
                                    next.Tooltip = string.Format(ResHelper.GetString("EditMenu.NextStepMultiple", ResourceCulture), objectName);
                                }
                                else
                                {
                                    next.Text    = ResHelper.GetString("EditMenu.IconFinish", ResourceCulture);
                                    next.Tooltip = string.Format(ResHelper.GetString("EditMenu.NextStepMultiple", ResourceCulture), objectName);
                                }

                                // Make action inactive
                                next.OnClientClick = null;
                                next.Inactive      = true;

                                // Process action appearance
                                ProcessAction(next, Step, null);

                                string itemText = "EditMenu.NextStepTo";
                                string itemDesc = "EditMenu.NextStep";

                                foreach (var s in steps)
                                {
                                    NextStepAction nxt = new NextStepAction(Page)
                                    {
                                        Text            = string.Format(ResHelper.GetString(itemText, ResourceCulture), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.StepDisplayName))),
                                        Tooltip         = string.Format(ResHelper.GetString(itemDesc, ResourceCulture), objectName),
                                        OnClientClick   = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_MOVE_NEXT, null),
                                        CommandArgument = s.StepID.ToString()
                                    };

                                    if (s.StepIsFinished)
                                    {
                                        nxt.Text    = string.Format(ResHelper.GetString("EditMenu.FinishTo", ResourceCulture), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.StepDisplayName)));
                                        nxt.Tooltip = string.Format(ResHelper.GetString("EditMenu.Finish", ResourceCulture), objectName);
                                    }

                                    // Process action appearance
                                    ProcessAction(nxt, Step, s);

                                    // Add step
                                    next.AlternativeActions.Add(nxt);
                                }
                            }

                            // Add comment
                            AddCommentAction(ComponentEvents.AUTOMATION_MOVE_NEXT, next, objectName);
                        }
                        else
                        {
                            bool displayAction = false;
                            if (!Step.StepAllowBranch)
                            {
                                // Transition exists, but condition doesn't match
                                var transitions = Manager.GetStepTransitions(Step);
                                if (transitions.Count > 0)
                                {
                                    WorkflowStepInfo s = WorkflowStepInfoProvider.GetWorkflowStepInfo(transitions[0].TransitionEndStepID);

                                    // Finish text
                                    if (s.StepIsFinished)
                                    {
                                        next.Text    = ResHelper.GetString("EditMenu.IconFinish", ResourceCulture);
                                        next.Tooltip = string.Format(ResHelper.GetString("EditMenu.Finish", ResourceCulture), objectName);
                                    }

                                    // Inform user
                                    displayAction = true;
                                    next.Enabled  = false;

                                    // Process action appearance
                                    ProcessAction(next, Step, null);
                                }
                            }

                            if (!displayAction)
                            {
                                // There is not next step
                                next = null;
                            }
                        }
                    }

                    // Handle start button
                    if (AutomationManager.IsActionAllowed(ComponentEvents.AUTOMATION_START) && (process.WorkflowRecurrenceType != ProcessRecurrenceTypeEnum.NonRecurring))
                    {
                        start = new HeaderAction
                        {
                            CommandName     = ComponentEvents.AUTOMATION_START,
                            EventName       = ComponentEvents.AUTOMATION_START,
                            Text            = ResHelper.GetString("autoMenu.StartState", ResourceCulture),
                            Tooltip         = process.WorkflowEnabled ? ResHelper.GetString("autoMenu.StartStateDesc", ResourceCulture) : ResHelper.GetString("autoMenu.DisabledStateDesc", ResourceCulture),
                            CommandArgument = process.WorkflowID.ToString(),
                            Enabled         = process.WorkflowEnabled,
                            OnClientClick   = RaiseGetClientValidationScript(ComponentEvents.AUTOMATION_START, "if(!confirm(" + ScriptHelper.GetString(string.Format(ResHelper.GetString("autoMenu.startSameProcessConfirmation", ResourceCulture), objectName)) + ")) { return false; }"),
                            ButtonStyle     = ButtonStyle.Default
                        };
                    }
                }
            }
        }

        // Add actions in correct order
        menu.ActionsList.Clear();

        AddAction(previous);
        AddAction(next);
        AddAction(specific);
        AddAction(delete);
        AddAction(start);

        // Set the information text
        if (!String.IsNullOrEmpty(InformationText))
        {
            lblInfo.Text     = InformationText;
            lblInfo.CssClass = "LeftAlign EditMenuInfo";
            lblInfo.Visible  = true;
        }

        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterModule(Page, "CMS/ScrollPane", new { selector = ".scrollable-menu ul" });

        CssRegistration.RegisterCssLink(Page, "~/CMSScripts/jquery/jquery-jscrollpane.css");
    }
Пример #27
0
 /// <summary>
 /// Returns link to add specified product to the user's wishlist.
 /// </summary>
 /// <param name="productId">Product ID</param>
 /// <param name="imageUrl">Image URL</param>
 public static string GetAddToWishListLink(object productId, string imageUrl)
 {
     if (ValidationHelper.GetInteger(productId, 0) != 0)
     {
         // Get default image URL
         imageUrl = imageUrl ?? "CMSModules/CMS_Ecommerce/addtowishlist.png";
         return("<img src=\"" + UIHelper.GetImageUrl(null, imageUrl) + "\" alt=\"Add to wishlist\" /><a href=\"" + WishlistURL(CMSContext.CurrentSiteName) + "?productId=" + Convert.ToString(productId) + "\">" + ResHelper.GetString("EcommerceFunctions.AddToWishlist") + "</a>");
     }
     else
     {
         return("");
     }
 }
Пример #28
0
    /// <summary>
    /// Validate values in textboxes.
    /// </summary>
    public override bool IsValid()
    {
        Validator val    = new Validator();
        string    result = null;

        if (this.plcAccount.Visible)
        {
            // Validate registration data
            if (radSignIn.Checked)
            {
                ScriptHelper.RegisterStartupScript(this, this.GetType(), "checkSignIn", ScriptHelper.GetScript("showHideForm('tblSignIn','" + radSignIn.ClientID + "');"));

                // Check banned IP
                if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Login))
                {
                    result = GetString("banip.ipisbannedlogin");
                }

                // Check user name
                if (string.IsNullOrEmpty(result))
                {
                    result = val.NotEmpty(txtUsername.Text.Trim(), GetString("ShoppingCartCheckRegistration.ErrorMissingUsername")).Result;
                }

                if (!string.IsNullOrEmpty(result))
                {
                    lblError.Text    = result;
                    lblError.Visible = true;
                    return(false);
                }
            }
            // Check 'New registration' section
            else if (radNewReg.Checked)
            {
                ScriptHelper.RegisterStartupScript(this, this.GetType(), "checkRegistration", ScriptHelper.GetScript("showHideForm('tblRegistration','" + radNewReg.ClientID + "');"));

                // Check banned IP
                if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Registration))
                {
                    result = GetString("banip.ipisbannedregistration");
                }

                if (string.IsNullOrEmpty(result) && !BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Login))
                {
                    result = GetString("banip.ipisbannedlogin");
                }

                // Check registration form
                if (string.IsNullOrEmpty(result))
                {
                    result = val.NotEmpty(txtFirstName1.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr"))
                             .NotEmpty(txtLastName1.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr"))
                             .NotEmpty(txtEmail2.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr"))
                             .NotEmpty(passStrength.Text.Trim(), GetString("ShoppingCartCheckRegistration.PsswdErr")).Result;
                }

                // Check company properties
                if (string.IsNullOrEmpty(result) && mRequireOrgTaxRegIDs && chkCorporateBody.Checked)
                {
                    result = val.NotEmpty(txtCompany1.Text.Trim(), GetString("ShoppingCartCheckRegistration.CompanyErr")).Result;
                    if ((result == "") && plcOrganizationID.Visible)
                    {
                        result = val.NotEmpty(txtOrganizationID.Text.Trim(), GetString("ShoppingCartCheckRegistration.OrganizationIDErr")).Result;
                    }

                    if ((result == "") && plcTaxRegistrationID.Visible)
                    {
                        result = val.NotEmpty(txtTaxRegistrationID.Text.Trim(), GetString("ShoppingCartCheckRegistration.TaxRegistrationIDErr")).Result;
                    }
                }
                if (result == "")
                {
                    if (!ValidationHelper.IsEmail(txtEmail2.Text.Trim()))
                    {
                        lblEmail2Err.Text    = GetString("ShoppingCartCheckRegistration.EmailErr");
                        lblEmail2Err.Visible = true;
                    }
                    // Password and confirmed password must be same
                    if (passStrength.Text != txtConfirmPsswd.Text)
                    {
                        lblPsswdErr.Text    = GetString("ShoppingCartCheckRegistration.DifferentPsswds");
                        lblPsswdErr.Visible = true;
                    }

                    // Check policy
                    if (!passStrength.IsValid())
                    {
                        lblPsswdErr.Text    = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                        lblPsswdErr.Visible = true;
                    }


                    if ((!DataHelper.IsEmpty(lblEmail2Err.Text.Trim())) || (!DataHelper.IsEmpty(lblPsswdErr.Text.Trim())))
                    {
                        return(false);
                    }
                }
                else
                {
                    lblError.Text    = result;
                    lblError.Visible = true;
                    return(false);
                }
            }
            // Check 'Continue as anonymous customer' section
            else if (radAnonymous.Checked)
            {
                ScriptHelper.RegisterStartupScript(this, this.GetType(), "checkAnonymous", ScriptHelper.GetScript("showHideForm('tblAnonymous','" + radAnonymous.ClientID + "');"));

                result = val.NotEmpty(txtFirstName2.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr"))
                         .NotEmpty(txtLastName2.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr"))
                         .NotEmpty(txtEmail3.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr")).Result;

                if (result == "" && mRequireOrgTaxRegIDs)
                {
                    result = val.NotEmpty(txtCompany2.Text.Trim(), ResHelper.GetString("ShoppingCartCheckRegistration.CompanyErr")).Result;
                    // Check organization ID only if visible
                    if ((result == "") && plcOrganizationID2.Visible)
                    {
                        result = val.NotEmpty(txtOrganizationID2.Text.Trim(), ResHelper.GetString("ShoppingCartCheckRegistration.OrganizationIDErr")).Result;
                    }
                    // Check tax ID only if visible
                    if ((result == "") && plcTaxRegistrationID2.Visible)
                    {
                        result = val.NotEmpty(txtTaxRegistrationID2.Text.Trim(), ResHelper.GetString("ShoppingCartCheckRegistration.TaxRegistrationIDErr")).Result;
                    }
                }

                if (result == "")
                {
                    if (!ValidationHelper.IsEmail(txtEmail3.Text.Trim()))
                    {
                        lblEmail3Err.Text    = GetString("ShoppingCartCheckRegistration.EmailErr");
                        lblEmail3Err.Visible = true;
                        return(false);
                    }
                }
                else
                {
                    lblError.Text    = result;
                    lblError.Visible = true;
                    return(false);
                }
            }
        }
        else
        {
            // Validate customer data
            result = val.NotEmpty(txtEditFirst.Text.Trim(), GetString("ShoppingCartCheckRegistration.FirstNameErr"))
                     .NotEmpty(txtEditLast.Text.Trim(), GetString("ShoppingCartCheckRegistration.LastNameErr"))
                     .IsEmail(txtEditEmail.Text.Trim(), GetString("ShoppingCartCheckRegistration.EmailErr")).Result;

            if (result == "" && mRequireOrgTaxRegIDs && chkEditCorpBody.Checked)
            {
                result = val.NotEmpty(txtEditCompany.Text.Trim(), GetString("ShoppingCartCheckRegistration.CompanyErr")).Result;
                // Check organization id only if visible
                if ((result == "") && plcEditOrgID.Visible)
                {
                    result = val.NotEmpty(txtEditOrgID.Text.Trim(), GetString("ShoppingCartCheckRegistration.OrganizationIDErr")).Result;
                }
                // Check tax id only if visible
                if ((result == "") && plcEditTaxRegID.Visible)
                {
                    result = val.NotEmpty(txtEditTaxRegID.Text.Trim(), GetString("ShoppingCartCheckRegistration.TaxRegistrationIDErr")).Result;
                }
            }
            if (result == "")
            {
                return(true);
            }
            else
            {
                lblError.Text    = result;
                lblError.Visible = true;
                return(false);
            }
        }

        return(true);
    }
    private void PublishAndFinish(object parameter)
    {
        TreeNode node = null;

        Tree.AllowAsyncActions = false;
        CanceledString         = ResHelper.GetString("content.publishcanceled", mCurrentCulture);
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("content.preparingdocuments", mCurrentCulture));

            string where = parameter as string;

            // Get the documents
            DataSet documents = GetDocumentsToProcess(where);

            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                // Create instance of workflow manager class
                WorkflowManager wm = WorkflowManager.GetInstance(Tree);

                // Begin publishing
                AddLog(ResHelper.GetString("content.publishingdocuments", mCurrentCulture));
                foreach (DataTable classTable in documents.Tables)
                {
                    foreach (DataRow nodeRow in classTable.Rows)
                    {
                        // Get the current document
                        string className  = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty);
                        string aliasPath  = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty);
                        string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty);
                        string siteName   = SiteInfoProvider.GetSiteName(nodeRow["NodeSiteID"].ToInteger(0));

                        node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, Tree);

                        // Publish document
                        if (Publish(node, wm))
                        {
                            return;
                        }
                    }
                }

                CurrentInfo = GetString("workflowdocuments.publishcomplete");
            }
            else
            {
                AddError(ResHelper.GetString("content.nothingtopublish", mCurrentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                CurrentInfo = CanceledString;
            }
            else
            {
                int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
                // Log error
                LogExceptionToEventLog("PUBLISHDOC", "content.publishfailed", ex, siteId);
            }
        }
        catch (Exception ex)
        {
            int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
            // Log error
            LogExceptionToEventLog("PUBLISHDOC", "content.publishfailed", ex, siteId);
        }
    }
Пример #30
0
 /// <summary>
 /// Gets resource string.
 /// </summary>
 /// <param name="stringKey">Resource string key.</param>
 private string GetString(string stringKey)
 {
     return(ResHelper.GetString(stringKey));
 }