Example #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Init
        ICMSMasterPage currentMaster = Page.Master as ICMSMasterPage;

        previewState = GetPreviewStateFromCookies(THEME);
        InitHeaderActions();
        ScriptHelper.RegisterClientScriptBlock(Page, typeof(String), "performAction", ScriptHelper.GetScript("function actionPerformed(action) { " + Page.ClientScript.GetPostBackEventReference(btnAction, "#").Replace("'#'", "action") + ";}"));

        txtContent.ShowBookmarks             = true;
        txtContent.FullScreenParentElementID = "divContent";

        if (QueryHelper.ValidateHash("hash"))
        {
            identifier = QueryHelper.GetString("identifier", null);
            if (!String.IsNullOrEmpty(identifier))
            {
                prop = WindowHelper.GetItem(identifier) as Hashtable;
                if (prop != null)
                {
                    lblName.Text = GetString("general.filename");

                    filePath  = Server.MapPath(ValidationHelper.GetString(prop["filepath"], ""));
                    extension = ValidationHelper.GetString(prop["newfileextension"], "");

                    if (!String.IsNullOrEmpty(extension))
                    {
                        // New file
                        newFile = true;

                        if (!extension.StartsWith("."))
                        {
                            extension = "." + extension;
                        }

                        filePath = ValidationHelper.GetString(prop["targetpath"], "");

                        if (currentMaster != null)
                        {
                            currentMaster.Title.TitleText = GetString("filemanagernew.header.file");
                        }
                    }
                    else
                    {
                        // Edit file
                        if (!File.Exists(filePath))
                        {
                            // Redirect to error page
                            URLHelper.Redirect(UIHelper.GetErrorPageUrl("Error.Header", "general.filedoesntexist", true));
                        }

                        fileName = Path.GetFileNameWithoutExtension(filePath);

                        // Setup the controls
                        if (!RequestHelper.IsPostBack())
                        {
                            txtName.Text    = fileName;
                            txtContent.Text = File.ReadAllText(filePath);

                            if (QueryHelper.GetBoolean("saved", false))
                            {
                                ShowChangesSaved();
                                String script = "wopener.SetRefreshAction();";
                                ScriptHelper.RegisterStartupScript(Page, typeof(String), "refreshScript", ScriptHelper.GetScript(script));
                            }
                        }

                        extension = Path.GetExtension(filePath);

                        if (currentMaster != null)
                        {
                            currentMaster.Title.TitleText = GetString("filemanageredit.header.file");
                        }
                    }

                    // Setup the syntax highlighting
                    switch (extension.TrimStart('.').ToLowerCSafe())
                    {
                    case "css":
                        txtContent.Language = LanguageEnum.CSS;
                        break;

                    case "skin":
                        txtContent.Language = LanguageEnum.ASPNET;
                        break;

                    case "xml":
                        txtContent.Language = LanguageEnum.XML;
                        break;

                    case "html":
                        txtContent.Language = LanguageEnum.HTMLMixed;
                        break;

                    case "cs":
                        txtContent.Language = LanguageEnum.CSharp;
                        break;

                    case "js":
                        txtContent.Language = LanguageEnum.JavaScript;
                        break;
                    }

                    // Setup the labels
                    lblExt.Text = extension;
                }
            }
        }

        RegisterInitScripts(pnlContent.ClientID, pnlMenu.ClientID, ((previewState != 0) && !newFile));
    }
    /// <summary>
    /// Click event of btnOk.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Arguments</param>
    protected void btnReset_Click(object sender, EventArgs e)
    {
        if ((passStrength.Text.Length > 0) && rfvConfirmPassword.IsValid)
        {
            if (passStrength.Text == txtConfirmPassword.Text)
            {
                // Check policy
                if (passStrength.IsValid())
                {
                    int userId = GetResetRequestID();

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

                    // Get e-mail address of sender
                    string emailFrom = DataHelper.GetNotEmpty(SendEmailFrom, SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName));

                    // Try to reset password and show result to user
                    bool   success;
                    string resultText = AuthenticationHelper.ResetPassword(hash, time, userId, interval, passStrength.Text, "Reset password control", emailFrom, siteName, null, out success, InvalidRequestText, ExceededIntervalText);

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

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

                        // Get proper text
                        ShowConfirmation(DataHelper.GetNotEmpty(SuccessText, resultText));
                        pnlReset.Visible  = false;
                        returnUrl         = URLHelper.IsLocalUrl(returnUrl) ? ResolveUrl(returnUrl) : securedAreasLogonUrl;
                        lblLogonLink.Text = String.Format(GetString("memberhsip.logonlink"), HTMLHelper.EncodeForHtmlAttribute(returnUrl));
                    }
                    else
                    {
                        ShowError(resultText);
                    }
                }
                else
                {
                    ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                }
            }
            else
            {
                ShowError(GetString("passreset.notmatch"));
            }
        }
        else
        {
            ShowError(GetString("general.requiresvalue"));
        }
    }
    /// <summary>
    /// Reloads the data of the forum control.
    /// </summary>
    public override void ReloadData()
    {
        base.ReloadData();

        // Enable Inline macros resolving only if the dialogs are allowed
        if (ForumContext.CurrentForum != null)
        {
            if (ForumContext.CurrentForum.ForumEnableAdvancedImage)
            {
                allowedInlineControls = ControlsHelper.ALLOWED_FORUM_CONTROLS;
            }
        }

        UniPager1.Enabled  = EnablePostsPaging;
        UniPager1.PageSize = PostsPageSize;

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

        ForumViewModeSelector1.Text = "<span>" + GetString("flatforum.modeslabel") + "</span>&nbsp;";

        if (ForumContext.CurrentMode != ForumMode.TopicMove)
        {
            plcMoveThread.Visible = false;
        }
        else
        {
            plcMoveThread.Visible  = true;
            threadMove.TopicMoved += TopicMoved;
        }

        listForums.OuterData = ForumContext.CurrentForum;
        onlyPublish          = !ForumContext.UserIsModerator(ForumID, CommunityGroupID);

        // Retrieve data just for the current page
        int currentOffset = EnablePostsPaging ? PostsPageSize * (UniPager1.CurrentPage - 1) : 0;
        int maxRecords    = EnablePostsPaging ? PostsPageSize : 0;
        int totalRecords  = 0;

        listForums.DataSource = ForumPostInfoProvider.SelectForumPosts(ForumID, "/%", "PostIDPath Like '" + ForumPostInfoProvider.GetPath(null, ThreadID) + "%'", ThreadOrderBy, MaxRelativeLevel, onlyPublish, -1, null, currentOffset, maxRecords, ref totalRecords);

        // Set the total number of records to the pager
        UniPager1.PagedControl.PagerForceNumberOfResults = totalRecords;

        // Redirect to the upper level if there is no post
        if (DataHelper.DataSourceIsEmpty(listForums.DataSource))
        {
            ForumInfo fi = ForumContext.CurrentForum;
            if (fi != null)
            {
                string url = GetURL(fi, ForumActionType.Forum);
                if (!String.IsNullOrEmpty(url))
                {
                    URLHelper.Redirect(UrlResolver.ResolveUrl(url));
                }
            }

            URLHelper.Redirect(URLHelper.RemoveParameterFromUrl(RequestContext.CurrentURL, "threadid"));
        }

        listForums.DataBind();
    }
    /// <summary>
    /// Actions handler.
    /// </summary>
    private void Validate()
    {
        mErrorText      = null;
        pnlLog.Visible  = true;
        DataSource      = null;
        pnlGrid.Visible = false;

        CurrentError = string.Empty;

        // Get the full domain
        ctlAsyncLog.EnsureLog();
        ctlAsyncLog.Parameter = RequestContext.FullDomain + ";" + URLHelper.GetFullApplicationUrl() + ";" + URLHelper.RemoveProtocolAndDomain(Url);
        ctlAsyncLog.RunAsync(CheckLinks, WindowsIdentity.GetCurrent());
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        const string CONTENT_CMSDESK_FOLDER = "~/CMSModules/Content/CMSDesk/";

        // Register script files
        ScriptHelper.RegisterScriptFile(this, CONTENT_CMSDESK_FOLDER + "EditTabs.js");

        bool   checkCulture       = false;
        bool   splitViewSupported = false;
        string action             = QueryHelper.GetString("action", "edit").ToLowerCSafe();

        switch (action)
        {
        // New dialog / new page form
        case "new":
            int classId = QueryHelper.GetInteger("classid", 0);
            if (classId <= 0)
            {
                // Get by class name if specified
                string className = QueryHelper.GetString("classname", string.Empty);
                if (className != string.Empty)
                {
                    classInfo = DataClassInfoProvider.GetDataClassInfo(className);
                    if (classInfo != null)
                    {
                        classId = classInfo.ClassID;
                    }
                }
            }

            const string EC_PRODUCTS_FOLDER = "~/CMSModules/Ecommerce/Pages/Tools/Products/";

            if (classId > 0)
            {
                viewpage = ResolveUrl(CONTENT_CMSDESK_FOLDER + "Edit/Edit.aspx");

                // Check if document type is allowed under parent node
                if (parentNodeID > 0)
                {
                    // Get the node
                    TreeNode = Tree.SelectSingleNode(parentNodeID, TreeProvider.ALL_CULTURES);
                    if (TreeNode != null)
                    {
                        if (!DocumentHelper.IsDocumentTypeAllowed(TreeNode, classId))
                        {
                            viewpage = CONTENT_CMSDESK_FOLDER + "NotAllowed.aspx?action=child";
                        }
                    }
                }

                // Use product page when product type is selected
                classInfo = classInfo ?? DataClassInfoProvider.GetDataClassInfo(classId);
                if ((classInfo != null) && (classInfo.ClassIsProduct))
                {
                    viewpage = ResolveUrl(EC_PRODUCTS_FOLDER + "Product_New.aspx");
                }
            }
            else
            {
                if (parentNodeID > 0)
                {
                    viewpage = EC_PRODUCTS_FOLDER + "New_ProductOrSection.aspx";
                }
                else
                {
                    viewpage = EC_PRODUCTS_FOLDER + "Product_New.aspx?parentNodeId=0";
                }
            }
            break;

        case "delete":
            // Delete dialog
            viewpage = CONTENT_CMSDESK_FOLDER + "Delete.aspx";
            break;

        default:
            // Edit mode
            viewpage           = CONTENT_CMSDESK_FOLDER + "Edit/edit.aspx?mode=editform";
            splitViewSupported = true;

            // Ensure class info
            if ((classInfo == null) && (Node != null))
            {
                classInfo = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName);
            }

            // Check explicit editing page url
            if ((classInfo != null) && !string.IsNullOrEmpty(classInfo.ClassEditingPageURL))
            {
                viewpage = URLHelper.AppendQuery(ResolveUrl(classInfo.ClassEditingPageURL), RequestContext.CurrentQueryString);
            }

            checkCulture = true;
            break;
        }

        // If culture version should be checked, check
        if (checkCulture)
        {
            // Check (and ensure) the proper content culture
            if (!CheckPreferredCulture())
            {
                RefreshParentWindow();
            }

            // Check split mode
            bool isSplitMode = PortalUIHelper.DisplaySplitMode;
            bool combineWithDefaultCulture = !isSplitMode && SiteInfoProvider.CombineWithDefaultCulture(SiteContext.CurrentSiteName);

            var nodeId = QueryHelper.GetInteger("nodeid", 0);
            TreeNode = Tree.SelectSingleNode(nodeId, CultureCode, combineWithDefaultCulture);
            if (TreeNode == null)
            {
                // Document does not exist -> redirect to new culture version creation dialog
                viewpage = ProductUIHelper.GetNewCultureVersionPageUrl();
            }
        }

        // Apply the additional transformations to the view page URL
        viewpage = URLHelper.AppendQuery(viewpage, RequestContext.CurrentQueryString);
        viewpage = URLHelper.RemoveParameterFromUrl(viewpage, "mode");
        viewpage = URLHelper.AddParameterToUrl(viewpage, "mode", "productssection");
        viewpage = ResolveUrl(viewpage);
        viewpage = URLHelper.AddParameterToUrl(viewpage, "hash", QueryHelper.GetHash(viewpage));

        // Split mode enabled
        if (splitViewSupported && PortalUIHelper.DisplaySplitMode && (TreeNode != null) && (action == "edit" || action == "preview" || (TreeNode.IsPublished && action == "livesite")))
        {
            viewpage = DocumentUIHelper.GetSplitViewUrl(viewpage);
        }

        URLHelper.Redirect(UrlResolver.ResolveUrl(viewpage));
    }
Example #6
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string errorMessage = "";
        string siteName     = SiteContext.CurrentSiteName;

        if ((txtCustomerCompany.Text.Trim() == "" || !IsBusiness) &&
            ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == "")))
        {
            errorMessage = GetString("Customers_Edit.errorInsert");
        }

        // At least company name has to be filled when company account is selected
        if (errorMessage == "" && IsBusiness)
        {
            errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text, GetString("customers_edit.errorCompany")).Result;
        }

        // Check the following items if complete company info is required for company account
        if (errorMessage == "" && ECommerceSettings.RequireCompanyInfo(siteName) && IsBusiness)
        {
            errorMessage = new Validator().NotEmpty(txtOraganizationID.Text, GetString("customers_edit.errorOrganizationID"))
                           .NotEmpty(txtTaxRegistrationID.Text, GetString("customers_edit.errorTaxRegID")).Result;
        }

        if (errorMessage == "")
        {
            errorMessage = new Validator().IsEmail(txtCustomerEmail.Text.Trim(), GetString("customers_edit.erroremailformat"))
                           .MatchesCondition(txtCustomerEmail.Text.Trim(), k => k.Length < 50, GetString("customers_edit.erroremailformat"))
                           .MatchesCondition(txtCustomerPhone.Text.Trim(), k => k.Length < 50, GetString("customers_edit.errorphoneformat")).Result;
        }

        plcCompanyInfo.Visible = IsBusiness;

        if (errorMessage == "")
        {
            // If customer doesn't already exist, create new one
            if (mCustomer == null)
            {
                mCustomer = new CustomerInfo();
                mCustomer.CustomerEnabled = true;
                mCustomer.CustomerUserID  = MembershipContext.AuthenticatedUser.UserID;
            }

            int currencyId = selectCurrency.SelectedID;

            if (ECommerceContext.CurrentShoppingCart != null)
            {
                ECommerceContext.CurrentShoppingCart.ShoppingCartCurrencyID = currencyId;
            }

            mCustomer.CustomerEmail     = txtCustomerEmail.Text.Trim();
            mCustomer.CustomerLastName  = txtCustomerLastName.Text.Trim();
            mCustomer.CustomerPhone     = txtCustomerPhone.Text.Trim();
            mCustomer.CustomerFirstName = txtCustomerFirstName.Text.Trim();
            mCustomer.CustomerCreated   = DateTime.Now;

            // Set customer's preferences
            mCustomer.CustomerPreferredCurrencyID       = (currencyId > 0) ? currencyId : 0;
            mCustomer.CustomerPreferredPaymentOptionID  = drpPayment.SelectedID;
            mCustomer.CustomerPreferredShippingOptionID = drpShipping.SelectedID;

            // Check if customer is registered
            if (mCustomer.CustomerIsRegistered)
            {
                // Find user-site binding
                UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(Customer.CustomerUserID, SiteContext.CurrentSiteID);
                if (userSite != null)
                {
                    // Set user's preferences
                    userSite.UserPreferredCurrencyID       = mCustomer.CustomerPreferredCurrencyID;
                    userSite.UserPreferredPaymentOptionID  = mCustomer.CustomerPreferredPaymentOptionID;
                    userSite.UserPreferredShippingOptionID = mCustomer.CustomerPreferredShippingOptionID;

                    UserSiteInfoProvider.SetUserSiteInfo(userSite);
                }
            }

            if (IsBusiness)
            {
                mCustomer.CustomerCompany           = txtCustomerCompany.Text.Trim();
                mCustomer.CustomerOrganizationID    = txtOraganizationID.Text.Trim();
                mCustomer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim();
            }
            else
            {
                mCustomer.CustomerCompany           = "";
                mCustomer.CustomerOrganizationID    = "";
                mCustomer.CustomerTaxRegistrationID = "";
            }

            // Update customer data
            CustomerInfoProvider.SetCustomerInfo(mCustomer);

            // Update corresponding contact data
            ModuleCommands.OnlineMarketingUpdateContactFromExternalData(mCustomer, DataClassInfoProvider.GetDataClassInfo(CustomerInfo.TYPEINFO.ObjectClassName).ClassContactOverwriteEnabled,
                                                                        ModuleCommands.OnlineMarketingGetCurrentContactID());

            // Let others now that customer was created
            if (OnCustomerCrated != null)
            {
                OnCustomerCrated();

                ShowChangesSaved();
            }
            else
            {
                URLHelper.Redirect(URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "saved", "1"));
            }
        }
        else
        {
            //Show error
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Adds parameter to current URL and Redirects to it.
    /// </summary>
    /// <param name="parameter">Parameter to be added.</param>
    /// <param name="value">Value of parameter to be added.</param>
    private void RedirectTo(string parameter, string value)
    {
        string urlToRedirect = URLHelper.AddParameterToUrl(RequestContext.CurrentURL, parameter, value);

        URLHelper.Redirect(urlToRedirect);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for tooltips
        ScriptHelper.RegisterTooltip(Page);

        string refreshScript =
            @"function RefreshUpdatePanel(hiddenFieldID, action) {
                var hiddenField = document.getElementById(hiddenFieldID);
                if (hiddenField) {
                    __doPostBack(hiddenFieldID, action);
                }
            }

            function FullRefresh(hiddenFieldID, action) {
                if(RefreshTree != null)
                {
                    RefreshTree();
                }

                RefreshUpdatePanel(hiddenFieldID, action);
            }

            function FullPageRefresh_" + ClientID + @"(guid) {
                if(RefreshTree != null)
                {
                    RefreshTree();
                }

                var hiddenField = document.getElementById('" + hdnFullPostback.ClientID + "');" +
            @"if (hiddenField) {
                    __doPostBack('" + hdnFullPostback.ClientID + "', 'refresh|' + guid);" +
            @"}
            }";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "RefreshUpdatePanel", ScriptHelper.GetScript(refreshScript));

        // Initialize refresh script for update panel
        string initRefreshScript =
            "function InitRefresh_" + ClientID + "(msg, fullRefresh, guid, action)\n" +
            "{\n" +
            "   if((msg != null) && (msg != \"\")){ alert(msg); action='error'; }\n" +
            "   if(fullRefresh) { FullRefresh('" + hdnFullPostback.ClientID + "', action + '|' + guid); }\n" +
            "   else { RefreshUpdatePanel('" + hdnPostback.ClientID + "', action + '|' + guid); }\n" +
            "}\n";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "AfterUploadRefresh", ScriptHelper.GetScript(initRefreshScript));

        // Register dialog script
        ScriptHelper.RegisterDialogScript(Page);

        string editorUrl = null;

        if (IsLiveSite)
        {
            if (CMSContext.CurrentUser.IsAuthenticated())
            {
                editorUrl = URLHelper.ResolveUrl("~/CMS/Dialogs/CMSModules/MediaLibrary/CMSPages/ImageEditor.aspx");
            }
            else
            {
                editorUrl = URLHelper.ResolveUrl("~/CMSModules/MediaLibrary/CMSPages/ImageEditor.aspx");
            }
        }
        else
        {
            editorUrl = URLHelper.ResolveUrl("~/CMSModules/MediaLibrary/Controls/MediaLibrary/ImageEditor.aspx");
        }

        // Dialog for editing image
        ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "EditThumbnailImage",
                                               ScriptHelper.GetScript("function EditThumbnailImage(query) { " +
                                                                      "modalDialog('" + editorUrl + "' + query, 'imageEditorDialog', 905, 670); " +
                                                                      " } "
                                                                      ));

        // Initialize deletion confirmation
        ScriptHelper.RegisterClientScriptBlock(this, GetType(), "DeleteConfirmation",
                                               ScriptHelper.GetScript(
                                                   "function DeleteConfirmation(){var conf = confirm('" + GetString("media.thumb.deleteconfirmation") + "'); return conf;}"
                                                   ));

        // Grid initialization
        gridAttachments.IsLiveSite           = IsLiveSite;
        gridAttachments.Visible              = true;
        gridAttachments.GridName             = "~/CMSModules/MediaLibrary/Controls/MediaLibrary/MediaFileUpload.xml";
        gridAttachments.OnExternalDataBound += GridOnExternalDataBound;
        gridAttachments.OnAction            += GridOnAction;
        pnlGrid.Attributes.Add("style", "padding-top: 2px;");

        // Load data
        ReloadData();
    }
    /// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object GridOnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "update":
            PlaceHolder plcUpd = new PlaceHolder();
            plcUpd.ID = "plcUdateAction";

            // Add disabled image
            ImageButton imgUpdate = new ImageButton();
            imgUpdate.ID = "imgUpdate";

            if (!Enabled || !EnableUpdate)
            {
                imgUpdate.ImageUrl = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/uploaddisabled.png", IsLiveSite));
                imgUpdate.Style.Add("cursor", "default");
                imgUpdate.Enabled = false;
            }
            else
            {
                imgUpdate.Visible = false;
            }

            plcUpd.Controls.Add(imgUpdate);

            // Dynamically load uploader control
            DirectFileUploader dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader;

            // Set uploader's properties
            if (dfuElem != null)
            {
                if (Enabled && EnableUpdate)
                {
                    dfuElem.ID                = "dfuElem" + LibraryID;
                    dfuElem.DisplayInline     = true;
                    dfuElem.SourceType        = MediaSourceEnum.MediaLibraries;
                    dfuElem.MediaFileID       = MediaFileID;
                    dfuElem.LibraryID         = LibraryID;
                    dfuElem.LibraryFolderPath = LibraryFolderPath;
                    dfuElem.ParentElemID      = ClientID;
                    dfuElem.IsMediaThumbnail  = IsMediaThumbnail;
                    dfuElem.ImageUrl          = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload.png", IsLiveSite));
                    dfuElem.ImageHeight       = 16;
                    dfuElem.ImageWidth        = 16;
                    dfuElem.InsertMode        = false;
                    dfuElem.ForceLoad         = true;
                    dfuElem.IsLiveSite        = IsLiveSite;
                    // New settings added
                    dfuElem.UploadMode        = MultifileUploaderModeEnum.DirectSingle;
                    dfuElem.Height            = 16;
                    dfuElem.Width             = 16;
                    dfuElem.MaxNumberToUpload = 1;
                }
                else
                {
                    dfuElem.Visible = false;
                }

                plcUpd.Controls.Add(dfuElem);
            }
            return(plcUpd);

        case "edit":
            // Get file extension
            if ((FileInfo != null) && (LibraryInfo != null))
            {
                ImageButton img = (ImageButton)sender;

                if (CMSContext.CurrentUser.IsAuthenticated())
                {
                    string fileExt = (IsMediaThumbnail ? previewExt : FileInfo.FileExtension);

                    // If the file is not an image don't allow image editing
                    if (!ImageHelper.IsSupportedByImageEditor(fileExt) || !Enabled)
                    {
                        // Disable edit icon in case that attachment is not an image
                        img.ImageUrl = ResolveUrl(GetImageUrl("Design/editdisabled.png", IsLiveSite));
                        img.Enabled  = false;
                        img.Style.Add("cursor", "default");
                    }
                    else
                    {
                        string query = string.Format("?refresh=1&siteid={0}&MediaFileGUID={1}{2}", LibraryInfo.LibrarySiteID, FileInfo.FileGUID, (IsMediaThumbnail ? "&isPreview=1" : ""));
                        query             = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));
                        img.OnClientClick = "EditThumbnailImage('" + query + "'); return false;";
                    }
                    img.AlternateText = GetString("general.edit");
                }
                else
                {
                    img.Visible = false;
                }
            }
            break;

        case "delete":
            ImageButton imgDelete = (ImageButton)sender;

            if (!Enabled)
            {
                // Disable delete icon in case that editing is not allowed
                imgDelete.ImageUrl = ResolveUrl(GetImageUrl("Design/deletedisabled.png", IsLiveSite));
                imgDelete.Enabled  = false;
                imgDelete.Style.Add("cursor", "default");
            }
            else
            {
                // Turn off validation
                imgDelete.CausesValidation = false;

                // Explicitly initialize confirmation
                imgDelete.OnClientClick = "if (DeleteConfirmation() == false) { return false; }";
            }

            break;

        case "filename":
            if ((LibraryInfo != null) && (FileInfo != null))
            {
                string fileUrl  = "";
                string fileExt  = "";
                string fileName = "";

                // Get file extension
                if (IsMediaThumbnail)
                {
                    fileName = previewName;
                    fileExt  = previewExt;
                    fileUrl  = ResolveUrl("~/CMSPages/GetMediaFile.aspx?preview=1&fileguid=" + FileInfo.FileGUID.ToString());
                }
                else
                {
                    fileExt  = FileInfo.FileExtension;
                    fileName = FileInfo.FileName;
                    fileUrl  = MediaFileInfoProvider.GetMediaFileAbsoluteUrl(FileInfo.FileGUID, FileInfo.FileName);
                }
                fileUrl = URLHelper.UpdateParameterInUrl(fileUrl, "chset", Guid.NewGuid().ToString());

                string tooltip = null;
                string iconUrl = GetFileIconUrl(fileExt, "List");
                bool   isImage = ImageHelper.IsImage(fileExt);

                if (isImage)
                {
                    tooltip = "";

                    if (File.Exists(previewPath))
                    {
                        FileStream file = FileStream.New(previewPath, FileMode.Open, FileAccess.Read);
                        Image      img  = Image.FromStream(file.SystemStream);
                        file.Close();
                        if (img != null)
                        {
                            int[]  imgDims = ImageHelper.EnsureImageDimensions(0, 0, 150, img.Width, img.Height);
                            string setRTL  = (CultureHelper.IsUICultureRTL() ? ", LEFT, true" : "");
                            tooltip = "onmouseout=\"UnTip()\" onmouseover=\"Tip('<div style=\\'width:" + imgDims[0] + "px; text-align:center;\\'><img src=\\'" + URLHelper.AddParameterToUrl(fileUrl, "maxsidesize", "150") + "\\' alt=\\'" + fileName + "\\' /></div>'" + setRTL + ")\"";
                            // Dispose image
                            img.Dispose();
                        }
                    }
                }

                string imageTag = "<img class=\"Icon\" src=\"" + iconUrl + "\" alt=\"" + fileName + "\" />";
                if (isImage)
                {
                    return("<a href=\"#\" onclick=\"javascript: window.open('" + fileUrl + "'); return false;\"><span " + tooltip + ">" + imageTag + fileName + "</span></a>");
                }
                else
                {
                    return("<a href=\"" + fileUrl + "\">" + imageTag + fileName + "</a>");
                }
            }

            return("");

        case "filesize":
            return(DataHelper.GetSizeString(ValidationHelper.GetLong(parameter, 0)));
        }

        return(parameter);
    }
Example #10
0
    /// <summary>
    /// Loads data of specific activity.
    /// </summary>
    protected void LoadData()
    {
        if (activityId <= 0)
        {
            return;
        }

        // Load and check if object exists
        ActivityInfo ai = ActivityInfoProvider.GetActivityInfo(activityId);

        EditedObject = ai;

        ActivityTypeInfo ati = ActivityTypeInfoProvider.GetActivityTypeInfo(ai.ActivityType);

        plcActivityValue.Visible = (ati == null) || ati.ActivityTypeIsCustom || (ati.ActivityTypeName == PredefinedActivityType.PAGE_VISIT) && !String.IsNullOrEmpty(ai.ActivityValue);

        string dispName = (ati != null ? ati.ActivityTypeDisplayName : GetString("general.na"));

        lblTypeVal.Text    = String.Format("{0}", HTMLHelper.HTMLEncode(dispName));
        lblContactVal.Text = HTMLHelper.HTMLEncode(ContactInfoProvider.GetContactFullName(ai.ActivityContactID));

        // Init contact detail link
        string contactURL = ApplicationUrlHelper.GetElementDialogUrl(ModuleName.CONTACTMANAGEMENT, "EditContact", ai.ActivityContactID);

        btnContact.Attributes.Add("onClick", ScriptHelper.GetModalDialogScript(contactURL, "ContactDetail"));
        btnContact.ToolTip = GetString("general.edit");

        lblDateVal.Text = (ai.ActivityCreated == DateTimeHelper.ZERO_TIME ? GetString("general.na") : HTMLHelper.HTMLEncode(ai.ActivityCreated.ToString()));

        // Get site display name
        string siteName = SiteInfoProvider.GetSiteName(ai.ActivitySiteID);

        if (String.IsNullOrEmpty(siteName))
        {
            siteName = GetString("general.na");
        }
        else
        {
            // Retrieve site info and its display name
            SiteInfo si = SiteInfoProvider.GetSiteInfo(siteName);
            if (si != null)
            {
                siteName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(si.DisplayName));
            }
            else
            {
                siteName = GetString("general.na");
            }
        }
        lblSiteVal.Text = siteName;

        string url = ai.ActivityURL;

        plcCampaign.Visible = !String.IsNullOrEmpty(ai.ActivityCampaign);
        lblCampaignVal.Text = HTMLHelper.HTMLEncode(ai.ActivityCampaign);
        lblValue.Text       = HTMLHelper.HTMLEncode(String.IsNullOrEmpty(ai.ActivityValue) ? GetString("general.na") : ai.ActivityValue);

        // Init textboxes only for the first time
        if (!RequestHelper.IsPostBack())
        {
            txtComment.Value = ai.ActivityComment;
            txtTitle.Text    = ai.ActivityTitle;
            txtURLRef.Text   = ai.ActivityURLReferrer;
            if (ai.ActivityType != PredefinedActivityType.NEWSLETTER_CLICKTHROUGH)
            {
                txtURL.Text = url;
            }
        }

        cDetails.ActivityID = activityId;

        // Init link button URL
        if (ai.ActivitySiteID > 0)
        {
            SiteInfo si = SiteInfoProvider.GetSiteInfo(ai.ActivitySiteID);
            if (si != null)
            {
                // Hide view button if URL is blank
                string activityUrl = ai.ActivityURL;
                if ((activityUrl != null) && !String.IsNullOrEmpty(activityUrl.Trim()))
                {
                    string appUrl = URLHelper.GetApplicationUrl(si.DomainName);
                    url                 = URLHelper.GetAbsoluteUrl(activityUrl, appUrl, appUrl, "");
                    url                 = URLHelper.AddParameterToUrl(url, URLHelper.SYSTEM_QUERY_PARAMETER, "1");
                    btnView.ToolTip     = GetString("general.view");
                    btnView.NavigateUrl = url;
                    btnView.Visible     = true;
                }
                else
                {
                    btnView.Visible = false;
                }
            }
        }
    }
Example #11
0
    /// <summary>
    /// OnSave event handler.
    /// </summary>
    private void PollNew_OnSaved(object sender, EventArgs e)
    {
        string error = null;

        // Show possible license limitation error
        if (!String.IsNullOrEmpty(PollNew.LicenseError))
        {
            error = "&error=" + PollNew.LicenseError;
        }

        string editActionUrl = URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(
                                                                                           URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.Polls", "EditPoll"), "objectid", PollNew.ItemID.ToString()), "siteid", siteId.ToString()), "displaytitle", "false"), "saved", "1");

        URLHelper.Redirect(editActionUrl + error);
    }
Example #12
0
 protected void btnNext_Click(object sender, EventArgs e)
 {
     URLHelper.Redirect(URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "activityid", nextId.ToString()));
 }
Example #13
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!RequestHelper.IsPostBack())
            {
                // If user is public
                if (CMSContext.CurrentUser.IsPublic())
                {
                    // Get logon url
                    string logonUrl = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSecuredAreasLogonPage");
                    logonUrl = DataHelper.GetNotEmpty(LoginURL, logonUrl);

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

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

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

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

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

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

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

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

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

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

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

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

                                            if (SendDefaultGroupEmails)
                                            {
                                                if (group.GroupSendJoinLeaveNotification &&
                                                    (groupMember.MemberStatus == GroupMemberStatus.Approved))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoin", CMSContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedConfirmation", CMSContext.CurrentSiteName, groupMember, false);
                                                }
                                                if (group.GroupSendWaitingForApprovalNotification && (groupMember.MemberStatus == GroupMemberStatus.WaitingForApproval))
                                                {
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberWaitingForApproval", CMSContext.CurrentSiteName, groupMember, true);
                                                    GroupMemberInfoProvider.SendNotificationMail("Groups.MemberJoinedWaitingForApproval", CMSContext.CurrentSiteName, groupMember, false);
                                                }
                                            }
                                        }

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

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

                                        // Delete this invitation
                                        InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                    }
                                }
                                else
                                {
                                    lblInfo.Text     = GroupNoLongerExists;
                                    lblInfo.CssClass = "InvitationErrorLabel";
                                    // Delete this invitation
                                    InvitationInfoProvider.DeleteInvitationInfo(invitation);
                                }
                            }
                            else
                            {
                                lblInfo.Text     = InvitationIsNotValid;
                                lblInfo.CssClass = "InvitationErrorLabel";
                                // Delete this invitation
                                InvitationInfoProvider.DeleteInvitationInfo(invitation);
                            }
                        }
                        else
                        {
                            lblInfo.Text     = InvitationNoLongerExists;
                            lblInfo.CssClass = "InvitationErrorLabel";
                        }
                        lblInfo.Visible = true;
                    }
                    else
                    {
                        Visible = false;
                    }
                }
            }
        }
    }
Example #14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for unimenu button selection
        CMSDeskPage.AddMenuButtonSelectScript(this, "Contacts", null, "menu");

        // Get current user info
        CurrentUserInfo user = CMSContext.CurrentUser;

        // Get contact info object
        ContactInfo ci = (ContactInfo)EditedObject;

        if (ci == null)
        {
            return;
        }

        // Check permission read
        ContactHelper.AuthorizedReadContact(ci.ContactSiteID, true);

        // Check if running under site manager (and distribute "site manager" flag to other tabs)
        string siteManagerParam = string.Empty;

        if (this.IsSiteManager)
        {
            siteManagerParam = "&issitemanager=1";

            // Hide title
            CurrentMaster.Title.TitleText = CurrentMaster.Title.TitleImage = string.Empty;
        }
        else
        {
            // Set title
            CurrentMaster.Title.TitleImage = GetImageUrl("Objects/OM_Contact/object.png");
            CurrentMaster.Title.TitleText  = GetString("om.contact.edit");
        }

        // Set default help topic
        SetHelp("onlinemarketing_contact_general", "helpTopic");

        string append = null;

        if (ci.ContactMergedWithContactID != 0)
        {
            // Append '(merged)' behind contact name in breadcrumbs
            append = " " + GetString("om.contact.mergedsuffix");
        }
        else if (ci.ContactSiteID == 0)
        {
            // Append '(global)' behind contact name in breadcrumbs
            append = " " + GetString("om.contact.globalsuffix");
        }

        // Modify header appearance in modal dialog (display title instead of breadcrumbs)
        if (QueryHelper.GetBoolean("dialogmode", false))
        {
            CurrentMaster.Title.TitleText  = GetString("om.contact.edit") + " - " + HTMLHelper.HTMLEncode(ContactInfoProvider.GetContactFullName(ci)) + append;
            CurrentMaster.Title.TitleImage = GetImageUrl("Objects/OM_Contact/object.png");
        }
        else
        {
            // Get url for breadcrumbs
            string url = ResolveUrl("~/CMSModules/ContactManagement/Pages/Tools/Contact/List.aspx");
            url = URLHelper.AddParameterToUrl(url, "siteid", this.SiteID.ToString());
            if (this.IsSiteManager)
            {
                url = URLHelper.AddParameterToUrl(url, "issitemanager", "1");
            }

            CurrentPage.InitBreadcrumbs(2);
            CurrentPage.SetBreadcrumb(0, GetString("om.contact.list"), url, "_parent", null);
            CurrentPage.SetBreadcrumb(1, ContactInfoProvider.GetContactFullName(ci) + append, null, null, null);
        }

        // Check if contact has any custom fields
        int i = 0;

        FormInfo formInfo = FormHelper.GetFormInfo(ci.Generalized.DataClass.ClassName, false);

        if (formInfo.GetFormElements(true, false, true).Count > 0)
        {
            i = 1;
        }

        int  contactId      = ci.ContactID;
        bool ipTabAvailable = ActivitySettingsHelper.IPLoggingEnabled(CMSContext.CurrentSiteName) || ContactHelper.IsSiteManager;
        int  counter        = 0;

        // Initialize tabs
        this.InitTabs(7 + (ipTabAvailable ? 1 : 0) + i, "content");

        this.SetTab(counter++, GetString("general.general"), "Tab_General.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_general');");

        if (i > 0)
        {
            // Add tab for custom fields
            this.SetTab(counter++, GetString("general.customfields"), "Tab_CustomFields.aspx?contactid=" + ci.ContactID + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_customfields');");
        }

        if (AccountHelper.AuthorizedReadAccount(ci.ContactSiteID, false) || ContactHelper.AuthorizedReadContact(ci.ContactSiteID, false))
        {
            this.SetTab(counter++, GetString("om.account.list"), "Tab_Accounts.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_accounts');");
        }

        this.SetTab(counter++, GetString("om.membership.list"), "Membership/Tab_Membership.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_membership');");

        this.SetTab(counter++, GetString("om.activity.list"), "Tab_Activities.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_activities');");

        if (ipTabAvailable)
        {
            this.SetTab(counter++, GetString("om.activity.iplist"), "Tab_IPs.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_ips');");
        }

        // Show contact groups
        this.SetTab(counter++, GetString("om.contactgroup.list"), "Tab_ContactGroups.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_contactgroups');");

        // Show scoring tab for site contacts
        if (ci.ContactSiteID > 0)
        {
            this.SetTab(counter++, GetString("om.score.list"), "Tab_Scoring.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_scoring');");
        }

        // Hide last 3 tabs if the contact is merged
        if (ci.ContactMergedWithContactID == 0)
        {
            this.SetTab(counter++, GetString("om.contact.merge"), "Tab_Merge.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_merge');");
        }
    }
Example #15
0
    protected void ViewControl_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        DataRowView    drv  = (DataRowView)e.Item.DataItem;
        IDataContainer data = new DataRowContainer(drv);

        string fileNameColumn = FileNameColumn;

        // Get information on file
        string fileName = HTMLHelper.HTMLEncode(data.GetValue(fileNameColumn).ToString());
        string ext      = HTMLHelper.HTMLEncode(data.GetValue(FileExtensionColumn).ToString());

        // Load file type
        Label lblType = e.Item.FindControl("lblTypeValue") as Label;

        if (lblType != null)
        {
            fileName     = fileName.Substring(0, fileName.Length - ext.Length);
            lblType.Text = ResHelper.LocalizeString(ext);
        }

        // Load file name
        Label lblName = e.Item.FindControl("lblFileName") as Label;

        if (lblName != null)
        {
            lblName.Text = fileName;
        }

        // Load file size
        Label lblSize = e.Item.FindControl("lblSizeValue") as Label;

        if (lblSize != null)
        {
            long size = ValidationHelper.GetLong(data.GetValue(FileSizeColumn), 0);
            lblSize.Text = DataHelper.GetSizeString(size);
        }

        string argument     = RaiseOnGetArgumentSet(drv.Row);
        string selectAction = GetSelectScript(drv, argument);

        // Initialize EDIT button
        var btnEdit = e.Item.FindControl("btnEdit") as CMSAccessibleButton;

        if (btnEdit != null)
        {
            btnEdit.ToolTip = GetString("general.edit");

            string path       = data.GetValue("Path").ToString();
            string editScript = GetEditScript(path, ext);

            if (!String.IsNullOrEmpty(editScript))
            {
                btnEdit.OnClientClick = editScript;
            }
            else
            {
                btnEdit.Visible = false;
            }
        }

        // Initialize DELETE button
        var btnDelete = e.Item.FindControl("btnDelete") as CMSAccessibleButton;

        if (btnDelete != null)
        {
            btnDelete.ToolTip       = GetString("general.delete");
            btnDelete.OnClientClick = GetDeleteScript(argument);
        }

        // Image area
        Image fileImage = e.Item.FindControl("imgElem") as Image;

        if (fileImage != null)
        {
            string url;
            if (ImageHelper.IsImage(ext))
            {
                url = URLHelper.UnMapPath(data.GetValue("Path").ToString());

                // Generate new tooltip command
                if (!String.IsNullOrEmpty(url))
                {
                    url = String.Format("{0}?chset={1}", url, Guid.NewGuid());

                    UIHelper.EnsureTooltip(fileImage, ResolveUrl(url), 0, 0, null, null, ext, null, null, 300);
                }

                fileImage.ImageUrl = ResolveUrl(url);
            }
            else
            {
                fileImage.Visible = false;

                Literal literalImage = e.Item.FindControl("ltrImage") as Literal;
                if (literalImage != null)
                {
                    literalImage.Text = UIHelper.GetFileIcon(Page, ext, FontIconSizeEnum.Dashboard);
                }
            }
        }

        // Selectable area
        Panel pnlItemInageContainer = e.Item.FindControl("pnlThumbnails") as Panel;

        if (pnlItemInageContainer != null)
        {
            pnlItemInageContainer.Attributes["onclick"] = selectAction;
            pnlItemInageContainer.Attributes["style"]   = "cursor:pointer;";
        }
    }
Example #16
0
    /// <summary>
    /// Handles btnOK's OnClick event.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Finds whether required fields are not empty
        string result = new Validator().NotEmpty(txtControlName.Text, rfvControlName.ErrorMessage).NotEmpty(txtControlDisplayName, rfvControlDisplayName.ErrorMessage).Result;

        // Check input file validity
        if (String.IsNullOrEmpty(result) && radNewControl.Checked)
        {
            if (!tbFileName.IsValid())
            {
                result = tbFileName.ValidationError;
            }
        }

        // Try to create new form control if everything is OK
        if (String.IsNullOrEmpty(result))
        {
            FormUserControlInfo fi = new FormUserControlInfo();
            fi.UserControlDisplayName       = txtControlDisplayName.Text.Trim();
            fi.UserControlCodeName          = txtControlName.Text.Trim();
            fi.UserControlType              = drpTypeSelector.ControlType;
            fi.UserControlForText           = false;
            fi.UserControlForLongText       = false;
            fi.UserControlForInteger        = false;
            fi.UserControlForLongInteger    = false;
            fi.UserControlForDecimal        = false;
            fi.UserControlForDateTime       = false;
            fi.UserControlForBoolean        = false;
            fi.UserControlForFile           = false;
            fi.UserControlForDocAttachments = false;
            fi.UserControlForGUID           = false;
            fi.UserControlForVisibility     = false;
            fi.UserControlShowInBizForms    = false;
            fi.UserControlDefaultDataType   = "Text";

            // Inherited user control
            if (radInheritedControl.Checked)
            {
                fi.UserControlParentID = ValidationHelper.GetInteger(drpFormControls.Value, 0);

                // Create empty default values definition
                fi.UserControlParameters = "<form></form>";
                fi.UserControlFileName   = "inherited";
            }
            else
            {
                fi.UserControlFileName = tbFileName.Value.ToString();
            }

            try
            {
                FormUserControlInfoProvider.SetFormUserControlInfo(fi);

                // If control was successfully created then redirect to editing page
                URLHelper.Redirect("Frameset.aspx?controlId=" + Convert.ToString(fi.UserControlID));
            }
            catch (Exception ex)
            {
                ShowError(ex.Message.Replace("%%name%%", fi.UserControlCodeName));
            }
        }
        else
        {
            ShowError(result);
        }
    }
 void boardSubscription_OnSaved(object sender, EventArgs e)
 {
     URLHelper.Redirect("~/CMSModules/Groups/Tools/MessageBoards/Boards/Board_Edit_Subscription_Edit.aspx?subscriptionid=" + this.boardSubscription.SubscriptionID + "&boardid=" + boardId + "&saved=1&groupid=" + this.groupId);
 }
Example #18
0
 /// <summary>
 /// AnswerList edit action handler.
 /// </summary>
 private void AnswerList_OnEdit(object sender, EventArgs e)
 {
     URLHelper.Redirect(UrlResolver.ResolveUrl("Polls_Edit_Answer_Edit.aspx?answerId=" + AnswerList.SelectedItemID.ToString() + "&groupId=" + groupId));
 }
Example #19
0
    /// <summary>
    /// Returns URL of the media item according site settings.
    /// </summary>
    /// <param name="nodeGuid">Node GUID of the current attachment node</param>
    /// <param name="documentUrlPath">URL path of the current attachment document</param>
    /// <param name="maxSideSize">Maximum dimension for images displayed for tile and thumbnails view</param>
    /// <param name="nodeAlias">Node alias of the current attachment node</param>
    /// <param name="nodeAliasPath">Node alias path of the current attachment node</param>
    /// <param name="nodeIsLink">Indicates if node is linked node.</param>
    public string GetContentItemUrl(Guid nodeGuid, string documentUrlPath, string nodeAlias, string nodeAliasPath, bool nodeIsLink, int height, int width, int maxSideSize, bool notAttachment, string documentExtension)
    {
        string result = "";

        if (documentExtension.Contains(";"))
        {
            documentExtension = documentExtension.Split(';')[0];
        }

        // Generate URL
        if (UsePermanentUrls)
        {
            bool isLink = ((OutputFormat == OutputFormatEnum.BBLink) || (OutputFormat == OutputFormatEnum.HTMLLink)) ||
                          ((OutputFormat == OutputFormatEnum.URL) && (SelectableContent == SelectableContentEnum.AllContent));

            if (String.IsNullOrEmpty(nodeAlias))
            {
                nodeAlias = "default";
            }

            if (notAttachment || isLink)
            {
                result = TreePathUtils.GetPermanentDocUrl(nodeGuid, nodeAlias, SiteObj.SiteName, null, documentExtension);
            }
            else
            {
                result = AttachmentManager.GetPermanentAttachmentUrl(nodeGuid, nodeAlias, documentExtension);
            }
        }
        else
        {
            string docUrlPath = nodeIsLink ? null : documentUrlPath;
            result = TreePathUtils.GetUrl(nodeAliasPath, docUrlPath, null, null, documentExtension);
        }

        // Make URL absolute if required
        int currentSiteId = CMSContext.CurrentSiteID;

        if (Config.UseFullURL || (currentSiteId != SiteObj.SiteID) || (currentSiteId != GetCurrentSiteId()))
        {
            result = URLHelper.GetAbsoluteUrl(result, SiteObj.DomainName, URLHelper.GetApplicationUrl(SiteObj.DomainName), null);
        }

        // Image dimensions to URL
        if (maxSideSize > 0)
        {
            result = URLHelper.AddParameterToUrl(result, "maxsidesize", maxSideSize.ToString());
        }
        if (height > 0)
        {
            result = URLHelper.AddParameterToUrl(result, "height", height.ToString());
        }
        if (width > 0)
        {
            result = URLHelper.AddParameterToUrl(result, "width", width.ToString());
        }

        // Media selctor should returns non-resolved URL in all cases
        bool isMediaSelector = (OutputFormat == OutputFormatEnum.URL) && (SelectableContent == SelectableContentEnum.OnlyMedia);

        return(isMediaSelector ? result : URLHelper.ResolveUrl(result, true, false));
    }
Example #20
0
 protected void editElem_OnSaved(object sender, EventArgs e)
 {
     URLHelper.Redirect("Edit.aspx?saved=1&projecttaskstatusid=" + editElem.ItemID);
 }
    /// <summary>
    /// Saves the changed settings
    /// </summary>
    /// <param name="isSite">Indicates whether changed settings is global or site</param>
    private void Save(bool isSite)
    {
        // This action is permitted only for global administrators
        if (MembershipContext.AuthenticatedUser.IsGlobalAdministrator)
        {
            if (!String.IsNullOrEmpty(SettingsKeys))
            {
                String[] keys = SettingsKeys.Split(';');
                foreach (String key in keys)
                {
                    if (key != String.Empty)
                    {
                        String objectKey    = ";" + key + ";";
                        String siteKeyName  = SiteName + "." + key;
                        bool   globalObject = (GlobalObjects.Contains(objectKey) || KeyScope == DisabledModuleScope.Global);
                        bool   siteObject   = SiteObjects.Contains(objectKey);

                        // If setting is global or site (or both), set global(site) settings no matter what button (site or global) was clicked
                        if (globalObject || siteObject)
                        {
                            if (globalObject)
                            {
                                if (!SettingsKeyInfoProvider.GetBoolValue(key))
                                {
                                    SettingsKeyInfoProvider.SetValue(key, true);
                                }
                            }

                            if (siteObject)
                            {
                                if (!SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                                {
                                    SettingsKeyInfoProvider.SetValue(siteKeyName, true);
                                }
                            }

                            continue;
                        }

                        // Test first if settings is disabled
                        if (!SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                        {
                            String keyName = isSite ? siteKeyName : key;
                            try
                            {
                                SettingsKeyInfoProvider.SetValue(keyName, true);
                            }
                            catch (Exception)
                            {
                                if (isSite)
                                {
                                    // Site settings does not exists. Save as global then
                                    SettingsKeyInfoProvider.SetValue(key, true);
                                }
                            }

                            // If global enabled and site still disabled - enable it also
                            if (!isSite && (KeyScope != DisabledModuleScope.Global))
                            {
                                // If settings not enabled, inherit from global
                                if (!SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                                {
                                    SettingsKeyInfoProvider.SetValue(siteKeyName, null);
                                }
                            }
                        }
                    }
                }
            }

            // Reload UI if necessary
            if (ReloadUIWhenModuleEnabled)
            {
                URLHelper.Redirect(RequestContext.CurrentURL);
            }
        }
    }
Example #22
0
    /// <summary>
    /// Handles reset button click. Resets zones of specified type to default settings.
    /// </summary>
    protected void btnReset_Click(object sender, EventArgs e)
    {
        // Disable the reset action when document editing is not allowed (i.e. non-editable workflow step)
        if (!WidgetActionsEnabled)
        {
            resetAllowed = false;
        }

        // Security check
        if (!DisplayResetButton || !resetAllowed)
        {
            return;
        }

        PageInfo pi = CurrentPageInfo;

        if (pi == null)
        {
            return;
        }

        if ((zoneType == WidgetZoneTypeEnum.Editor) || (zoneType == WidgetZoneTypeEnum.Group))
        {
            // Clear document webparts/group webparts
            TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);

            if (node != null)
            {
                bool updateDocument = true;

                if (zoneType == WidgetZoneTypeEnum.Editor)
                {
                    if (ViewMode.IsEdit(true) || ViewMode.IsEditLive())
                    {
                        // Do not save the document to the database, keep it in only in the memory
                        updateDocument = false;

                        // Get the default template widgets
                        PortalContext.SaveEditorWidgets(pi.DocumentID, pi.UsedPageTemplateInfo.TemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor));
                    }
                    else
                    {
                        node.SetValue("DocumentWebParts", String.Empty);
                    }

                    ClearEditorWidgetsContent(node, pi.UsedPageTemplateInfo.TemplateInstance, updateDocument);

                    // Delete all variants
                    if (pi.UsedPageTemplateInfo != null)
                    {
                        foreach (WebPartZoneInstance zoneInstance in zoneInstances)
                        {
                            if (zoneInstance.WebPartsContainVariants)
                            {
                                VariantHelper.DeleteWidgetVariants(zoneInstance.ZoneID, pi.UsedPageTemplateInfo.PageTemplateId, node.DocumentID);
                            }
                        }
                    }
                }
                else if (zoneType == WidgetZoneTypeEnum.Group)
                {
                    node.SetValue("DocumentGroupWebParts", String.Empty);
                }

                if (updateDocument)
                {
                    // Save the document
                    DocumentHelper.UpdateDocument(node, TreeProvider);
                }
            }
        }
        else if (zoneType == WidgetZoneTypeEnum.User)
        {
            // Delete user personalization info
            PersonalizationInfo up = PersonalizationInfoProvider.GetUserPersonalization(MembershipContext.AuthenticatedUser.UserID, pi.DocumentID);
            PersonalizationInfoProvider.DeletePersonalizationInfo(up);

            // Clear cached values
            TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);
            if (node != null)
            {
                node.ClearCache();
            }
        }
        else if (zoneType == WidgetZoneTypeEnum.Dashboard)
        {
            // Delete user personalization info
            PersonalizationInfo up = PersonalizationInfoProvider.GetDashBoardPersonalization(MembershipContext.AuthenticatedUser.UserID, PortalContext.DashboardName, PortalContext.DashboardSiteName);
            PersonalizationInfoProvider.DeletePersonalizationInfo(up);

            // Clear cached page template
            if (pi.UsedPageTemplateInfo != null)
            {
                CacheHelper.TouchKey("cms.pagetemplate|byid|" + pi.UsedPageTemplateInfo.PageTemplateId);
            }
        }

        // Make redirect to see changes after load
        string url = RequestContext.CurrentURL;

        if (ViewMode.IsEdit(true) || ViewMode.IsEditLive())
        {
            // Ensure that the widgets will be loaded from the session layer (not from database)
            url = URLHelper.UpdateParameterInUrl(url, "cmscontentchanged", "true");
        }

        URLHelper.Redirect(url);
    }
Example #23
0
    /// <summary>
    /// Check URLs contained in document. Returns DataSet with validation results.
    /// </summary>
    /// <param name="urls">List of URLs to be processed</param>
    /// <param name="parameter">Parameter containing data to resolve relative URLs to absolute</param>
    private void CheckUrls(List <string> urls, string parameter)
    {
        int index       = 0;
        int indexOffset = 0;

        // Initialize DataTable
        DataTable tbErrors = new DataTable();

        tbErrors.Columns.Add("statuscode");
        tbErrors.Columns.Add("type");
        tbErrors.Columns.Add("message");
        tbErrors.Columns.Add("url");
        tbErrors.Columns.Add("time");

        // Store table to DataSet
        DataSource = new DataSet();
        DataSource.Tables.Add(tbErrors);

        // Prepare variables
        string[]       urlParams         = parameter.Split(';');
        string         message           = null;
        int            firstResponseCode = 0;
        Uri            reqUri            = null;
        HttpStatusCode statusCode        = HttpStatusCode.OK;
        string         statusDescription = null;

        string[] exceptions = UrlRequestExceptions.ToLowerCSafe().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

        // Process URLs
        while (index < urls.Count)
        {
            string          url  = urls[index + indexOffset];
            string          type = "E";
            bool            cont = false;
            bool            loadDataFromResponse = true;
            string          time;
            HttpWebResponse response;
            bool            sslWarning = false;

            try
            {
                AddLog(urls[index + indexOffset], false);

                // Create HEAD web request for each URL
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URLHelper.GetAbsoluteUrl(url, urlParams[0], urlParams[1], urlParams[2]));
                req.Method            = "HEAD";
                req.UserAgent         = "CMS-LinkChecker";
                req.AllowAutoRedirect = false;

                // If exception use GET request instead
                foreach (string exception in exceptions)
                {
                    if (url.ToLowerCSafe().Contains(exception))
                    {
                        req.Method = "GET";
                        break;
                    }
                }

                // Sleep thread for specified time
                Thread.Sleep(ValidationDelay);

                // Initialize watcher to get time required to access URL
                Stopwatch sw = new Stopwatch();
                sw.Start();

                try
                {
                    response = (HttpWebResponse)req.GetResponse();
                }
                catch (WebException e)
                {
                    response = (HttpWebResponse)e.Response;

                    if (e.InnerException is AuthenticationException)
                    {
                        statusDescription    = e.InnerException.Message;
                        statusCode           = HttpStatusCode.SwitchingProtocols;
                        loadDataFromResponse = false;
                        sslWarning           = true;
                    }
                }

                sw.Stop();
                time   = "(" + sw.ElapsedMilliseconds + " ms)";
                reqUri = req.RequestUri;
            }
            catch
            {
                time     = "(0 ms)";
                response = null;
            }

            // Store response values
            if (loadDataFromResponse)
            {
                if (response != null)
                {
                    statusCode        = response.StatusCode;
                    statusDescription = response.StatusDescription;
                    response.Close();
                }
                else
                {
                    statusCode        = HttpStatusCode.NotFound;
                    statusDescription = HttpWorkerRequest.GetStatusDescription((int)statusCode);
                }
            }

            // Process response status code
            switch (statusCode)
            {
            // Response OK status
            case HttpStatusCode.Accepted:
            case HttpStatusCode.Continue:
            case HttpStatusCode.Created:

            case HttpStatusCode.NoContent:
            case HttpStatusCode.NonAuthoritativeInformation:
            case HttpStatusCode.NotModified:
            case HttpStatusCode.OK:
            case HttpStatusCode.PartialContent:

            case HttpStatusCode.ResetContent:
            case HttpStatusCode.SwitchingProtocols:
            case HttpStatusCode.Unused:
            case HttpStatusCode.UseProxy:
                message = statusDescription;
                break;

            // Moved, follow redirection
            case HttpStatusCode.MultipleChoices:
            case HttpStatusCode.MovedPermanently:
            case HttpStatusCode.Found:
            case HttpStatusCode.RedirectMethod:
            case HttpStatusCode.RedirectKeepVerb:
                indexOffset++;
                cont = true;
                if (firstResponseCode == 0)
                {
                    firstResponseCode = (int)statusCode;
                }

                string newLocation = response.Headers["Location"];
                string redirectUrl = URLHelper.ContainsProtocol(newLocation) ? newLocation : URLHelper.GetAbsoluteUrl(newLocation, urlParams[0], urlParams[1], urlParams[2]);
                urls.Insert(index + indexOffset, redirectUrl);
                break;

            // Client errors
            case HttpStatusCode.BadRequest:
            case HttpStatusCode.Unauthorized:
            case HttpStatusCode.PaymentRequired:
            case HttpStatusCode.Forbidden:
            case HttpStatusCode.NotFound:
            case HttpStatusCode.MethodNotAllowed:
            case HttpStatusCode.NotAcceptable:
            case HttpStatusCode.ProxyAuthenticationRequired:
            case HttpStatusCode.RequestTimeout:
            case HttpStatusCode.Conflict:
            case HttpStatusCode.Gone:
            case HttpStatusCode.LengthRequired:
            case HttpStatusCode.PreconditionFailed:
            case HttpStatusCode.RequestEntityTooLarge:
            case HttpStatusCode.RequestUriTooLong:
            case HttpStatusCode.UnsupportedMediaType:
            case HttpStatusCode.RequestedRangeNotSatisfiable:
            case HttpStatusCode.ExpectationFailed:
                message = ResHelper.GetString("validation.link.clienterror", currentCulture) + " " + statusDescription;
                break;

            // Internal server errors
            case HttpStatusCode.InternalServerError:
            case HttpStatusCode.NotImplemented:
            case HttpStatusCode.BadGateway:
            case HttpStatusCode.ServiceUnavailable:
            case HttpStatusCode.GatewayTimeout:
            case HttpStatusCode.HttpVersionNotSupported:
                message = ResHelper.GetString("validation.link.servererror", currentCulture) + " " + statusDescription;
                break;
            }

            string statusCodeText = ((int)statusCode).ToString();

            // Add log describing link validation result
            AddLog(" " + time + " <b>" + DocumentValidationHelper.GetStatusCodeDescription((int)statusCode, currentCulture) + "</b> ");

            if (!cont)
            {
                // Store link validation result if link broken or final target of redirection found
                if (LinkBroken(response) || (indexOffset > 0))
                {
                    if (!LinkBroken(response) || sslWarning)
                    {
                        type = "W";
                    }

                    // Check if redirection was present
                    if (indexOffset > 0)
                    {
                        statusCodeText    = firstResponseCode + "->" + (int)statusCode;
                        firstResponseCode = 0;

                        message = EnsureMaximumLineLength(urls[index]) + "<br />" + ResHelper.GetString("validation.link.permanentredir") + "<br />" + EnsureMaximumLineLength(urls[index + indexOffset]) + " <b>" + message + "</b>";
                    }

                    // Add validation result to result table
                    tbErrors.Rows.Add(statusCodeText, type, message, EnsureMaximumLineLength(urls[index + indexOffset]), time);
                }

                // Move to next url
                index      += indexOffset + 1;
                indexOffset = 0;
            }
        }
    }
Example #24
0
 protected void btnNext_Click(object sender, EventArgs e)
 {
     // Redirect to next
     URLHelper.Redirect(URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "emailId", mNextId.ToString()));
 }
    /// <summary>
    /// Page load.
    /// </summary>
    /// <param name="sender">Sender.</param>
    /// <param name="e">Arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        hash      = QueryHelper.GetString("hash", string.Empty);
        time      = QueryHelper.GetString("datetime", string.Empty);
        policyReq = QueryHelper.GetInteger("policyreq", 0);
        pwdExp    = QueryHelper.GetInteger("exp", 0);

        // Prepare URL of logon page
        securedAreasLogonUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName);
        securedAreasLogonUrl = UrlResolver.ResolveUrl(securedAreasLogonUrl);

        returnUrl = QueryHelper.GetString("returnurl", securedAreasLogonUrl);

        rfvConfirmPassword.Text = GetString("general.requiresvalue");

        siteName = SiteContext.CurrentSiteName;

        // Get interval from settings
        interval = SettingsKeyInfoProvider.GetDoubleValue("CMSResetPasswordInterval", siteName);

        // Prepare failed message
        string invalidRequestMessage = DataHelper.GetNotEmpty(InvalidRequestText, String.Format(ResHelper.GetString("membership.passwresetfailed"), URLHelper.AddParameterToUrl(securedAreasLogonUrl, "forgottenpassword", "1")));

        // Reset password cancellation
        if (IsCancellationRequest())
        {
            // Get user info
            UserInfo ui = UserInfoProvider.GetUsersDataWithSettings()
                          .WhereEquals("UserPasswordRequestHash", hash)
                          .TopN(1)
                          .FirstOrDefault();

            if (ui != null)
            {
                ui.UserPasswordRequestHash = null;
                UserInfoProvider.SetUserInfo(ui);
                ClearResetRequestID();

                ShowInformation(GetString("membership.passwresetcancelled"));
            }
            else
            {
                ShowError(invalidRequestMessage);
            }

            pnlReset.Visible = false;
            return;
        }

        // Reset password request
        if (!RequestHelper.IsPostBack())
        {
            if (policyReq > 0)
            {
                ShowInformation(GetString("passwordpolicy.policynotmet") + "<br />" + passStrength.GetPasswordPolicyHint());
            }

            UserInfo ui;

            // Get user info
            int userId = GetResetRequestID();
            if (userId > 0)
            {
                // Invalidation forces user info to load user settings from DB and not use cached values.
                ui = UserInfoProvider.GetUserInfo(userId);
                ui?.Generalized.Invalidate(false);
            }
            else
            {
                ui = UserInfoProvider.GetUsersDataWithSettings()
                     .WhereEquals("UserPasswordRequestHash", hash).TopN(1).FirstOrDefault();
            }

            // There is nobody to reset password for
            if (ui == null)
            {
                return;
            }

            // Validate request
            ResetPasswordResultEnum result = AuthenticationHelper.ValidateResetPassword(ui, hash, time, interval, "Reset password control");

            // Prepare messages
            string resultMessage = string.Empty;

            // Check result
            switch (result)
            {
            case ResetPasswordResultEnum.Success:
                // Save user to session
                SetResetRequestID(ui.UserID);

                // Delete it from user info
                ui.UserPasswordRequestHash = null;
                UserInfoProvider.SetUserInfo(ui);

                break;

            case ResetPasswordResultEnum.TimeExceeded:
                resultMessage = DataHelper.GetNotEmpty(ExceededIntervalText, String.Format(ResHelper.GetString("membership.passwreqinterval"), URLHelper.AddParameterToUrl(securedAreasLogonUrl, "forgottenpassword", "1")));
                break;

            default:
                resultMessage = invalidRequestMessage;
                break;
            }

            if (!string.IsNullOrEmpty(resultMessage))
            {
                // Show error message
                ShowError(resultMessage);

                pnlReset.Visible = false;
            }
        }
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (customerObj == null)
        {
            return;
        }

        if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
        }

        if (customerId != 0)
        {
            string errorMessage = new Validator().NotEmpty(txtAddressLine1.Text, "Customer_Edit_Address_Edit.rqvLine")
                                  .NotEmpty(txtAddressCity.Text, "Customer_Edit_Address_Edit.rqvCity")
                                  .NotEmpty(txtAddressZip.Text, "Customer_Edit_Address_Edit.rqvZipCode")
                                  .NotEmpty(txtPersonalName.Text, "Customer_Edit_Address_Edit.rqvPersonalName").Result;

            // Check country presence
            if (errorMessage == "" && (ucCountrySelector.CountryID <= 0))
            {
                errorMessage = GetString("countryselector.selectedcountryerr");
            }

            if (errorMessage == "")
            {
                // Get object
                AddressInfo addressObj = AddressInfoProvider.GetAddressInfo(addressId);
                if (addressObj == null)
                {
                    addressObj = new AddressInfo();
                }

                // Set address object data
                addressObj.AddressIsBilling    = chkAddressIsBilling.Checked;
                addressObj.AddressIsShipping   = chkAddressIsShipping.Checked;
                addressObj.AddressZip          = txtAddressZip.Text.Trim();
                addressObj.AddressPhone        = txtAddressDeliveryPhone.Text.Trim();
                addressObj.AddressPersonalName = txtPersonalName.Text.Trim();
                addressObj.AddressLine1        = txtAddressLine1.Text.Trim();
                addressObj.AddressEnabled      = chkAddressEnabled.Checked;
                addressObj.AddressLine2        = txtAddressLine2.Text.Trim();
                addressObj.AddressCity         = txtAddressCity.Text.Trim();
                addressObj.AddressCountryID    = ucCountrySelector.CountryID;
                addressObj.AddressStateID      = ucCountrySelector.StateID;
                addressObj.AddressIsCompany    = chkAddressIsCompany.Checked;
                addressObj.AddressName         = AddressInfoProvider.GetAddressName(addressObj);
                addressObj.AddressCustomerID   = customerId;

                AddressInfoProvider.SetAddressInfo(addressObj);

                // Redirect to editing UI
                URLHelper.Redirect("Customer_Edit_Address_Edit.aspx?customerId=" + customerId + "&addressId=" + Convert.ToString(addressObj.AddressID) + "&saved=1");
            }
            else
            {
                // Show error message
                ShowError(errorMessage);
            }
        }
    }
Example #27
0
    void btnGUID_Click(object sender, EventArgs e)
    {
        try
        {
            // Create GUID field
            FormFieldInfo ffiGuid = new FormFieldInfo();

            // Fill FormInfo object
            ffiGuid.Name                    = "ItemGUID";
            ffiGuid.Caption                 = "GUID";
            ffiGuid.DataType                = FormFieldDataTypeEnum.GUID;
            ffiGuid.DefaultValue            = "";
            ffiGuid.Description             = "";
            ffiGuid.FieldType               = FormFieldControlTypeEnum.CustomUserControl;
            ffiGuid.Settings["controlname"] = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLower();
            ffiGuid.PrimaryKey              = false;
            ffiGuid.System                  = true;
            ffiGuid.Visible                 = false;
            ffiGuid.Size                    = 0;
            ffiGuid.AllowEmpty              = false;

            FormInfo.AddFormField(ffiGuid);

            // Update table structure - columns could be added
            bool old = TableManager.UpdateSystemFields;
            TableManager.UpdateSystemFields = true;
            string schema = FormInfo.GetXmlDefinition();
            TableManager.UpdateTableBySchema(dci.ClassTableName, schema);
            TableManager.UpdateSystemFields = old;

            // Update xml schema and form definition
            dci.ClassFormDefinition = schema;
            dci.ClassXmlSchema      = TableManager.GetXmlSchema(dci.ClassTableName);

            dci.Generalized.LogEvents = false;

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

            dci.Generalized.LogEvents = true;

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

            // Clear cached data
            CMSObjectHelper.RemoveReadOnlyObjects(CustomTableItemProvider.GetObjectType(className), true);
            CustomTableItemProvider.Remove(className, true);
            // Clear the object type hashtable
            ProviderStringDictionary.ReloadDictionaries(className, true);

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

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

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

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

            URLHelper.Redirect(URLHelper.AddParameterToUrl(URLRewriter.CurrentURL, "gen", "1"));
        }
        catch (Exception ex)
        {
            lblError.Visible = true;
            lblError.Text    = GetString("customtable.ErrorGUID") + ex.Message;

            // Log event
            EventLog.LogEvent("Custom table", "GENERATEGUID", ex);
        }
    }
Example #28
0
    /// <summary>
    /// On external databound event.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="sourceName">Action what is called</param>
    /// <param name="parameter">Parameter</param>
    /// <returns>Result object</returns>
    protected object ListViewControl_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        // Initializing variables
        object result = null;

        string argument = string.Empty;
        string ext      = string.Empty;

        switch (sourceName.ToLowerCSafe())
        {
        // Select event
        case "select":
            GridViewRow         gvr = (parameter as GridViewRow);
            DataRowView         drv = (DataRowView)gvr.DataItem;
            CMSGridActionButton btn = ((CMSGridActionButton)sender);

            // Get item extension
            ext = drv[FileExtensionColumn].ToString().Trim('.');
            bool isSelectable = IsItemSelectable(ValidationHelper.GetBoolean(drv["isfile"], true));

            // Check if item is selectable, if not remove select action button
            if (!isSelectable)
            {
                btn.ToolTip = "";
                btn.Enabled = false;
            }
            else
            {
                argument = RaiseOnGetArgumentSet(drv.Row);

                // Initialize command
                btn.OnClientClick = GetSelectScript(drv, argument);

                result = btn;
            }
            break;

        // Select subdocs event
        case "selectsubdocs":
            btn = sender as CMSGridActionButton;
            if (btn != null)
            {
                drv = (DataRowView)(parameter as GridViewRow).DataItem;
                string nodeId     = ValidationHelper.GetString(drv[FileIdColumn], "");
                int    childCount = ValidationHelper.GetInteger(drv["childscount"], 0);

                if ((IsDisplayMore || Configuration.ShowFolders) && !ValidationHelper.GetBoolean(drv["isfile"], true))
                {
                    // Check if item is selectable, if not remove select action button
                    if (childCount > 0)
                    {
                        // Initialize command
                        btn.OnClientClick = "SetParentAction('" + nodeId.Replace("\\", "\\\\").Replace("'", "\\'") + "'); return false;";
                    }
                    else
                    {
                        btn.ToolTip = GetString("dialogs.list.actions.showsubfolders");
                        btn.Enabled = false;
                    }
                }
                else
                {
                    // Hide subdocs button
                    btn.Attributes["style"] = "display:none;";
                }
            }
            break;

        // Edit action
        case "edit":
        {
            btn = sender as CMSGridActionButton;
            if (btn != null)
            {
                if (editAllowed && Configuration.AllowManage)
                {
                    drv = (DataRowView)(parameter as GridViewRow).DataItem;

                    ext = drv[FileExtensionColumn].ToString();
                    string path = drv["Path"].ToString();

                    string editScript = GetEditScript(path, ext);

                    // Assign the onclick script
                    if (!String.IsNullOrEmpty(editScript))
                    {
                        btn.OnClientClick = editScript;

                        return(result);
                    }
                }

                btn.Visible = false;
            }
        }
        break;

        // Delete event
        case "delete":
        {
            btn = ((CMSGridActionButton)sender);

            if (editAllowed && Configuration.AllowManage)
            {
                gvr = (parameter as GridViewRow);
                drv = (DataRowView)gvr.DataItem;

                argument = RaiseOnGetArgumentSet(drv.Row);

                // Initialize command
                btn.OnClientClick = GetDeleteScript(argument);

                return(result);
            }

            btn.Visible = false;
        }
        break;

        // Name event
        case "name":
        {
            drv = (DataRowView)parameter;

            // Get name and extension
            string name = drv[FileNameColumn].ToString();
            ext = drv[FileExtensionColumn].ToString();

            bool isFile = ValidationHelper.GetBoolean(drv["isfile"], true);

            // Remove extension if available
            if (isFile)
            {
                name = HTMLHelper.HTMLEncode(Path.GetFileNameWithoutExtension(name));
            }

            string url = null;
            if (ImageHelper.IsImage(ext))
            {
                url = URLHelper.UnMapPath(drv["Path"].ToString());
            }

            // Check if item is selectable
            if (!IsItemSelectable(isFile))
            {
                LiteralControl ltlName = new LiteralControl(name);

                // Get final panel
                result = GetListItem(ext, url, isFile, ltlName, false);
            }
            else
            {
                // Make a file name link
                LinkButton lnkBtn = new LinkButton();

                // Escape chars for post back JavaScript event
                lnkBtn.ID   = name.Replace("'", "").Replace("$", "");
                lnkBtn.Text = HTMLHelper.HTMLEncode(name);

                argument = RaiseOnGetArgumentSet(drv.Row);

                // Initialize command
                lnkBtn.Attributes["onclick"] = GetSelectScript(drv, argument);

                // Get final panel
                result = GetListItem(ext, url, isFile, lnkBtn, true);
            }
        }
        break;

        // Type event
        case "type":
            drv = (DataRowView)parameter;

            // Remove starting dot
            result = drv[FileExtensionColumn].ToString().ToLowerCSafe();
            break;

        // Size event
        case "size":
            drv = (DataRowView)parameter;

            // Get formatted size string
            if (ValidationHelper.GetBoolean(drv["isfile"], true))
            {
                long size = ValidationHelper.GetLong(drv[FileSizeColumn], 0);
                result = DataHelper.GetSizeString(size);
            }
            else
            {
                return("");
            }
            break;

        // File modified event
        case "filemodified":
            drv    = (DataRowView)parameter;
            result = drv["filemodified"].ToString();
            break;
        }

        return(result);
    }
Example #29
0
 protected override void OnPreInit(EventArgs e)
 {
     LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.OnlineUsers);
     base.OnPreInit(e);
     FrameHeight = SessionManager.StoreOnlineUsersInDatabase ? TabsBreadFrameHeight : 0;
 }
Example #30
0
    /// <summary>
    /// Saves the item
    /// </summary>
    /// <param name="saveAndClose">Close dialog after save</param>
    private void Save(bool saveAndClose)
    {
        //Check valid input
        string errMsg = new Validator().
                        NotEmpty(txtName.Text, GetString("img.errors.filename")).
                        IsFolderName(txtName.Text, GetString("img.errors.filename")).
                        Result;

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

        // Prepare the path
        string path = filePath;

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

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

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

        bool success         = true;
        bool fileNameChanged = false;

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

        if (success)
        {
            ShowChangesSaved();

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

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

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

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

            RegisterRefreshScript();
        }
    }