Esempio n. 1
0
    /// <summary>
    /// Removes document content for all editor widgets in a given document.
    /// </summary>
    /// <param name="treeNode">Document to update</param>
    /// <param name="pti">Page template instance</param>
    /// <param name="omitUpdate">Indicates whether update on a given document should be omitted</param>
    private void ClearEditorWidgetsContent(TreeNode treeNode, PageTemplateInstance pti, bool omitUpdate)
    {
        var documentWebPartsXml = treeNode.GetStringValue("DocumentWebParts", String.Empty);

        if (String.IsNullOrEmpty(documentWebPartsXml))
        {
            return;
        }

        var webPartIds = new List <string>();

        // Get web part IDs from DocumentWebParts column
        webPartIds.AddRange(GetWebPartIDs(documentWebPartsXml));

        // Get web part IDs from page template (widget zones only) and combine them with existing list.
        webPartIds.AddRange(GetWebPartIDs(pti.GetZonesXML(WidgetZoneTypeEnum.Editor)));

        // Remove web part IDs from DocumentContent
        foreach (var wpId in webPartIds.Distinct())
        {
            treeNode.DocumentContent.EditableWebParts.Remove(wpId);
        }

        treeNode.SetValue("DocumentContent", treeNode.DocumentContent.GetContentXml());

        if (!omitUpdate)
        {
            DocumentHelper.UpdateDocument(treeNode, TreeProvider);
        }
    }
    /// <summary>
    /// Gets a unique widget id. Returned widget id is unique among both document widgets (Page tab) and default widgets (Design tab).
    /// </summary>
    /// <param name="baseId">The base id.</param>
    private string GetUniqueWidgetId(string baseId)
    {
        int    counter   = 0;
        string controlId = null;

        if ((CurrentPageInfo != null) &&
            CurrentPageInfo.UsedPageTemplateInfo != null)
        {
            // Get the document widgets template instance
            PageTemplateInstance documentTemplateInstance = mWebPartZoneInstance.ParentTemplateInstance;
            // Get the default widgets template instance
            PageTemplateInstance templateInstance = CurrentPageInfo.UsedPageTemplateInfo.TemplateInstance;

            // Limit the search
            while (counter < 100)
            {
                // Try to find the first available controlId for both templates
                controlId = WebPartZoneInstance.GetUniqueWebPartId(baseId, documentTemplateInstance, counter);

                if (controlId == WebPartZoneInstance.GetUniqueWebPartId(baseId, templateInstance, counter))
                {
                    break;
                }

                counter++;
            }
        }

        return(controlId);
    }
    /// <summary>
    /// Sets the current combination as default
    /// </summary>
    protected void btnUseCombination_Click(object sender, EventArgs e)
    {
        if ((DocumentContext.CurrentPageInfo != null))
        {
            // Keep current page template instance
            PageInfo pi = DocumentContext.CurrentPageInfo;

            // Get combination from cookies
            string combinationName = CookieHelper.GetValue(cookieTestName);

            // Get the page template id
            int templateId = GetPageTemplateId(pi);

            // Get combination info
            MVTCombinationInfo currentCombination = MVTCombinationInfoProvider.GetMVTCombinationInfo(templateId, combinationName);

            // Get default combination info
            MVTCombinationInfo defaultCombination = MVTCombinationInfoProvider.GetDefaultCombinationInfo(templateId);

            // Check whether default and current combination exists
            if ((currentCombination != null) && (defaultCombination != null))
            {
                // Do not save default combination
                if (currentCombination.MVTCombinationID != defaultCombination.MVTCombinationID)
                {
                    // Copy the combination custom name
                    defaultCombination.MVTCombinationCustomName = currentCombination.MVTCombinationCustomName;
                    defaultCombination.Update();

                    // Tree provider instance
                    TreeProvider tp = new TreeProvider(currentUser);

                    // Documents - use the Preview view mode to ensure that only chosen variant will be rendered (Design mode renders all web part/zone variants and does not combine the instance with the variants)
                    PageTemplateInstance instance = MVTestInfoProvider.CombineWithMVT(pi, pi.UsedPageTemplateInfo.TemplateInstance, currentCombination.MVTCombinationID, ViewModeEnum.Preview);
                    CMSPortalManager.SaveTemplateChanges(pi, instance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tp);

                    // Widgets - use the Preview view mode to ensure that only chosen variant will be rendered (Edit mode renders all widget variants and does not combine the instance with the variants)
                    instance = MVTestInfoProvider.CombineWithMVT(pi, pi.DocumentTemplateInstance, currentCombination.MVTCombinationID, ViewModeEnum.Preview);
                    CMSPortalManager.SaveTemplateChanges(pi, instance, WidgetZoneTypeEnum.Editor, ViewModeEnum.Edit, tp);
                }

                // Remove all variants
                var variants = MVTVariantInfoProvider.GetMVTVariants().WhereEquals("MVTVariantPageTemplateID", templateId);

                foreach (MVTVariantInfo info in variants)
                {
                    MVTVariantInfoProvider.DeleteMVTVariantInfo(info);
                }

                // Clear cached template info
                pi.UsedPageTemplateInfo.Update();

                // Redirect to the same page to update the current view
                URLHelper.Redirect(RequestContext.CurrentURL);
            }
        }
    }
Esempio n. 4
0
    /// <summary>
    /// Sets the current combination as default
    /// </summary>
    void btnUseCombination_Click(object sender, EventArgs e)
    {
        if ((CMSContext.CurrentPageInfo != null))
        {
            // Keep current page template insatnce
            PageInfo pi = CMSContext.CurrentPageInfo;

            // Set the selected combination (from cookie by default)
            MVTestInfo mvTestInfo = MVTestInfoProvider.GetRunningTest(CMSContext.CurrentAliasPath, CMSContext.CurrentSiteID, CMSContext.CurrentDocumentCulture.CultureCode);
            // Get combination from cookies
            string combinationName = CookieHelper.GetValue(cookieTestName);
            // Get combination info
            MVTCombinationInfo currentCombination = MVTCombinationInfoProvider.GetMVTCombinationInfo(pi.DocumentPageTemplateID, combinationName);
            // Get default combination info
            MVTCombinationInfo defaultCombination = MVTCombinationInfoProvider.GetDefaultCombinationInfo(pi.DocumentPageTemplateID);

            // Check whether default and current combination exists
            if ((currentCombination != null) && (defaultCombination != null))
            {
                // Do not save default combination
                if (currentCombination.MVTCombinationID != defaultCombination.MVTCombinationID)
                {
                    // Copy the combination custom name
                    defaultCombination.MVTCombinationCustomName = currentCombination.MVTCombinationCustomName;
                    defaultCombination.Update();

                    // Tree provider instance
                    TreeProvider tp = new TreeProvider(currentUser);

                    // Documents - use the Preview view mode to ensure that only chosen variant will be rendered (Design mode renders all web part/zone variants and does not combine the instance with the variants)
                    PageTemplateInstance instance = MVTestInfoProvider.CombineWithMVT(pi, pi.PageTemplateInfo.TemplateInstance, currentCombination.MVTCombinationID, ViewModeEnum.Preview);
                    CMSPortalManager.SaveTemplateChanges(pi, pi.PageTemplateInfo, instance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tp);

                    // Widgets - use the Preview view mode to ensure that only chosen variant will be rendered (Edit mode renders all widget variants and does not combine the instance with the variants)
                    instance = MVTestInfoProvider.CombineWithMVT(pi, pi.DocumentTemplateInstance, currentCombination.MVTCombinationID, ViewModeEnum.Preview);
                    CMSPortalManager.SaveTemplateChanges(pi, pi.PageTemplateInfo, instance, WidgetZoneTypeEnum.Editor, ViewModeEnum.Edit, tp);
                }

                // Remove all variants
                InfoDataSet <MVTVariantInfo> variants = MVTVariantInfoProvider.GetMVTVariants("MVTVariantPageTemplateID = " + pi.DocumentPageTemplateID, null);
                if (!DataHelper.DataSourceIsEmpty(variants))
                {
                    foreach (MVTVariantInfo info in variants)
                    {
                        MVTVariantInfoProvider.DeleteMVTVariantInfo(info);
                    }
                }

                // Clear cached template info
                pi.PageTemplateInfo.Update();

                // Redirect to the same page to update the current view
                URLHelper.Redirect(URLHelper.CurrentURL);
            }
        }
    }
Esempio n. 5
0
    /// <summary>
    /// Handles the OnAfterValidate event of the Control control.
    /// </summary>
    void Control_OnAfterValidate(object sender, EventArgs e)
    {
        PageTemplateInfo pti = Control.EditedObject as PageTemplateInfo;

        if (pti == null)
        {
            return;
        }

        String result             = String.Empty;
        PageTemplateTypeEnum type = EnumStringRepresentationExtensions.ToEnum <PageTemplateTypeEnum>((Control.GetFieldValue("PageTemplateType") as String));

        // Check dashboard prerequisites
        if ((pti.PageTemplateId > 0) && (type == PageTemplateTypeEnum.Dashboard))
        {
            // Check valid zones
            PageTemplateInstance inst = pti.TemplateInstance;
            if (inst != null)
            {
                foreach (WebPartZoneInstance zone in inst.WebPartZones)
                {
                    switch (zone.WidgetZoneType)
                    {
                    case WidgetZoneTypeEnum.Dashboard:
                    case WidgetZoneTypeEnum.None:
                        continue;
                    }

                    result = ResHelper.GetString("template.dashboardinvalidzone");
                    break;
                }
            }
        }

        if (result != String.Empty)
        {
            Control.StopProcessing = true;
            CMSPage pg = Control.Page as CMSPage;
            if (pg != null)
            {
                pg.ShowError(result);
                Control.StopProcessing = true;
            }
        }
    }
Esempio n. 6
0
    /// <summary>
    /// Init event handler.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Setup basic form on live site
        formCustom.AllowMacroEditing = false;
        formCustom.IsLiveSite        = IsLiveSite;

        // Load settings
        if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the widget variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = 0;
                if (VariantMode == VariantModeEnum.MVT)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName);
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName);
                }

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        EnsureDashboard();

        if (!String.IsNullOrEmpty(WidgetId) && !IsInline)
        {
            // Get pageinfo
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                lblInfo.Text        = GetString("Widgets.Properties.aliasnotfound");
                lblInfo.Visible     = true;
                pnlFormArea.Visible = false;
                return;
            }

            // Get template
            pti = pi.PageTemplateInfo;

            // Get template instance
            templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            if (!IsNewWidget)
            {
                // Get the instance of widget
                widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId);
                if (widgetInstance == null)
                {
                    lblInfo.Text        = GetString("Widgets.Properties.WidgetNotFound");
                    lblInfo.Visible     = true;
                    pnlFormArea.Visible = false;
                    return;
                }

                if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null))
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        widgetInstance = pi.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                        widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID));
                        // Set the widget variant mode
                        if (widgetInstance != null)
                        {
                            VariantMode = widgetInstance.VariantMode;
                        }
                    }
                    else
                    {
                        // Not authorised for OnlineMarketing - Manage.
                        RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                    }
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
            }

            CMSPage.EditedObject = wi;
            zoneType             = ZoneType;

            // Get the zone to which it inserts
            WebPartZoneInstance zone = templateInstance.GetZone(ZoneId);
            if ((zoneType == WidgetZoneTypeEnum.None) && (zone != null))
            {
                zoneType = zone.WidgetZoneType;
            }

            // Check security
            CurrentUserInfo currentUser = CMSContext.CurrentUser;

            switch (zoneType)
            {
            // Group zone => Only group widgets and group admin
            case WidgetZoneTypeEnum.Group:
                // Should always be, only group widget are allowed in group zone
                if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupId) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for editor zones
            case WidgetZoneTypeEnum.Editor:
                if (!wi.WidgetForEditor)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for user zones
            case WidgetZoneTypeEnum.User:
                if (!wi.WidgetForUser)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for dasboard zones
            case WidgetZoneTypeEnum.Dashboard:
                if (!wi.WidgetForDashboard)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;
            }

            // Check security
            if ((zoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
            {
                if (OnNotAllowed != null)
                {
                    OnNotAllowed(this, null);
                }
            }

            // Get form schemas
            wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
            FormInfo zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType);
            string   widgetProperties   = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);
            FormInfo fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true);

            if (fi != null)
            {
                // Check if there are some editable properties
                FormFieldInfo[] ffi = fi.GetFields(true, false);
                if ((ffi == null) || (ffi.Length == 0))
                {
                    lblInfo.Visible = true;
                    lblInfo.Text    = GetString("widgets.emptyproperties");
                }

                // Get datarows with required columns
                DataRow dr = CombineWithDefaultValues(fi, wi);

                // Load default values for new widget
                if (IsNewWidget)
                {
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible);

                    // Overide default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName));
                }

                // Load values from existing widget
                LoadDataRowFromWidget(dr);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES;
            }
        }

        if (IsInline)
        {
            //Load text definition from session
            string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty);
            if (String.IsNullOrEmpty(definition))
            {
                definition = Request.Form[hdnWidgetDefinition.UniqueID];
            }
            else
            {
                hdnWidgetDefinition.Value = definition;
            }

            Hashtable parameters = null;

            if (IsNewWidget)
            {
                // new wdiget - load widget info by id
                if (!String.IsNullOrEmpty(WidgetId))
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
                }
                else
                {
                    // Try to get widget from codename
                    mName = QueryHelper.GetString("WidgetName", String.Empty);
                    wi    = WidgetInfoProvider.GetWidgetInfo(mName);
                }
            }
            else
            {
                if (definition == null)
                {
                    ShowError("widget.failedtoload");
                    return;
                }

                //parse defininiton
                parameters = CMSDialogHelper.GetHashTableFromString(definition);

                //trim control name
                if (parameters["name"] != null)
                {
                    mName = parameters["name"].ToString();
                }

                wi = WidgetInfoProvider.GetWidgetInfo(mName);
            }
            if (wi == null)
            {
                ShowError("widget.failedtoload");
                return;
            }

            //If widget cant be used asi inline
            if (!wi.WidgetForInline)
            {
                ShowError("widget.cantbeusedasinline");
                return;
            }


            //Test permission for user
            CurrentUserInfo currentUser = CMSContext.CurrentUser;
            if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
            {
                mIsValidWidget = false;
                OnNotAllowed(this, null);
            }

            //If user is editor, more properties are shown
            WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
            if (currentUser.IsEditor)
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }

            WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
            string      widgetProperties   = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);
            FormInfo    zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType);
            FormInfo    fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true);

            if (fi != null)
            {
                // Check if there are some editable properties
                mFields = fi.GetFields(true, true);
                if ((mFields == null) || (mFields.Length == 0))
                {
                    lblInfo.Visible = true;
                    lblInfo.Text    = GetString("widgets.emptyproperties");
                }

                // Get datarows with required columns
                DataRow dr = CombineWithDefaultValues(fi, wi);

                if (IsNewWidget)
                {
                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible);
                }
                else
                {
                    foreach (string key in parameters.Keys)
                    {
                        string value = parameters[key].ToString();
                        // Test if given property exists
                        if (dr.Table.Columns.Contains(key) && !String.IsNullOrEmpty(value))
                        {
                            try
                            {
                                dr[key] = value;
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                // Overide default value and set title as widget display name
                DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);
                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES;
            }
        }
    }
Esempio n. 7
0
    /// <summary>
    /// Loads the web part form.
    /// </summary>
    protected void LoadForm()
    {
        // Load settings
        if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Indicates whether the new variant should be chosen when closing this dialog
        selectNewVariant = IsNewVariant;

        // Try to find the web part variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = 0;
                if (VariantMode == VariantModeEnum.MVT)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName);
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName);
                }

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        if (!String.IsNullOrEmpty(WebpartId))
        {
            // Get the page info
            pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId, CultureCode);
            if (pi != null)
            {
                // Get template
                pti = pi.UsedPageTemplateInfo;

                // Get template instance
                templateInstance = pti.TemplateInstance;

                if (!IsNewWebPart)
                {
                    // Standard zone
                    webPartInstance = templateInstance.GetWebPart(InstanceGUID, WebpartId);

                    // If the web part not found, try to find it among the MVT/CP variants
                    if (webPartInstance == null)
                    {
                        // MVT/CP variant
                        templateInstance.LoadVariants(false, VariantModeEnum.None);
                        webPartInstance = templateInstance.GetWebPart(InstanceGUID, true);

                        // Set the VariantMode according to the selected web part/zone variant
                        if ((webPartInstance != null) && (webPartInstance.ParentZone != null))
                        {
                            VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode;
                        }
                        else
                        {
                            VariantMode = VariantModeEnum.None;
                        }
                    }
                    else
                    {
                        // Ensure that the ZoneVarianID is not set when the web part was found in a regular zone
                        ZoneVariantID = 0;
                    }

                    if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null))
                    {
                        // Check OnlineMarketing permissions.
                        if (CheckPermissions("Read"))
                        {
                            webPartInstance = webPartInstance.FindVariant(VariantID);
                        }
                        else
                        {
                            // Not authorized for OnlineMarketing - Manage.
                            RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                        }
                    }

                    if (webPartInstance == null)
                    {
                        CMSPage.EditedObject = null;
                        return;
                    }
                }

                // Keep xml version
                if (webPartInstance != null)
                {
                    xmlVersion = webPartInstance.XMLVersion;
                }

                // Get the form info
                FormInfo fi = GetWebPartFormInfo();

                // Get the form definition
                if (fi != null)
                {
                    form.AllowMacroEditing = ((WebPartTypeEnum)wpi.WebPartType != WebPartTypeEnum.Wireframe);

                    // Get data row with required columns
                    DataRow dr = fi.GetDataRow(true, wpi.WebPartDefaultValues);

                    if (IsNewWebPart || (xmlVersion > 0))
                    {
                        fi.LoadDefaultValues(dr);

                        // Load overridden system values
                        fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues);
                    }

                    if (IsNewWebPart)
                    {
                        // Set control ID
                        FormFieldInfo ffi = fi.GetFormField("WebPartControlID");
                        if (ffi != null)
                        {
                            ffi.DefaultValue = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                            fi.UpdateFormField("WebPartControlID", ffi);
                        }
                    }

                    // Load values from existing web part
                    LoadDataRowFromWebPart(dr, webPartInstance, fi);

                    // Set a unique WebPartControlID for the new variant
                    if (IsNewVariant)
                    {
                        // Set control ID
                        dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                    }

                    // Init the form
                    InitForm(form, dr, fi);

                    AddExportLink();
                }
                else
                {
                    CMSPage.EditedObject = null;
                }
            }
        }
    }
    /// <summary>
    /// Loads the web part form.
    /// </summary>
    protected void LoadForm()
    {
        // Load settings
        if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Indicates whether the new variant should be chosen when closing this dialog
        selectNewVariant = IsNewVariant;

        // Try to find the web part variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (varProperties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(varProperties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateID, variantName, true);

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        if (!String.IsNullOrEmpty(WebPartID))
        {
            // Get the page info
            pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode);
            if (pi != null)
            {
                // Get template
                pti = pi.UsedPageTemplateInfo;

                // Get template instance
                templateInstance = pti.TemplateInstance;

                if (!IsNewWebPart)
                {
                    // Standard zone
                    webPartInstance = templateInstance.GetWebPart(InstanceGUID, WebPartID);

                    // If the web part not found, try to find it among the MVT/CP variants
                    if (webPartInstance == null)
                    {
                        // MVT/CP variant
                        templateInstance.LoadVariants(false, VariantModeEnum.None);
                        webPartInstance = templateInstance.GetWebPart(InstanceGUID, -1, 0);

                        // Set the VariantMode according to the selected web part/zone variant
                        if ((webPartInstance != null) && (webPartInstance.ParentZone != null))
                        {
                            VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode;
                        }
                        else
                        {
                            VariantMode = VariantModeEnum.None;
                        }
                    }
                    else
                    {
                        // Ensure that the ZoneVariantID is not set when the web part was found in a regular zone
                        ZoneVariantID = 0;
                    }

                    if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null))
                    {
                        // Check OnlineMarketing permissions.
                        if (CheckPermissions("Read"))
                        {
                            webPartInstance = webPartInstance.FindVariant(VariantID);
                        }
                        else
                        {
                            // Not authorized for OnlineMarketing - Manage.
                            RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                        }
                    }

                    if (webPartInstance == null)
                    {
                        UIContext.EditedObject = null;
                        return;
                    }
                }

                mainWebPartInstance = webPartInstance;

                // Keep xml version
                if (webPartInstance != null)
                {
                    xmlVersion = webPartInstance.XMLVersion;

                    // If data source ID set, edit the data source
                    if (NestedWebPartID > 0)
                    {
                        webPartInstance = webPartInstance.NestedWebParts[NestedWebPartKey] ?? new WebPartInstance() { InstanceGUID = Guid.NewGuid() };
                    }
                }

                // Get the form info
                FormInfo fi = GetWebPartFormInfo();

                // Get the form definition
                if (fi != null)
                {
                    fi.ContextResolver.Settings.RelatedObject = templateInstance;
                    form.AllowMacroEditing = ((WebPartTypeEnum)wpi.WebPartType != WebPartTypeEnum.Wireframe);

                    // Get data row with required columns
                    DataRow dr = fi.GetDataRow();

                    if (IsNewWebPart || (xmlVersion > 0))
                    {
                        fi.LoadDefaultValues(dr);
                    }

                    // Load values from existing web part
                    LoadDataRowFromWebPart(dr, webPartInstance, fi);

                    // Set a unique WebPartControlID for the new variant
                    if (IsNewVariant || IsNewWebPart)
                    {
                        // Set control ID
                        string webPartControlId = ValidationHelper.GetCodeName(wpi.WebPartDisplayName);
                        dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(webPartControlId, templateInstance);
                    }

                    // Init the form
                    InitForm(form, dr, fi);

                    AddExportLink();
                }
                else
                {
                    UIContext.EditedObject = null;
                }
            }
        }
    }
Esempio n. 9
0
    /// <summary>
    /// Loads the web part form.
    /// </summary>
    protected void LoadForm()
    {
        // Load settings
        if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Indicates whether the new variant should be chosen when closing this dialog
        selectNewVariant = IsNewVariant;

        // Try to find the web part variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (varProperties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(varProperties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateID, variantName, true);

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        if (!String.IsNullOrEmpty(WebPartID))
        {
            // Get the page info
            pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode);

            if (pi == null)
            {
                ShowError(GetString("general.pagenotfound"));
                pnlExport.Visible = false;
                return;
            }

            // Get template
            pti = pi.UsedPageTemplateInfo;

            // Get template instance
            templateInstance = pti.TemplateInstance;

            if (!IsNewWebPart)
            {
                // Standard zone
                webPartInstance = templateInstance.GetWebPart(InstanceGUID, WebPartID);

                // If the web part not found, try to find it among the MVT/CP variants
                if (webPartInstance == null)
                {
                    // MVT/CP variant

                    // Clone templateInstance to avoid caching of the temporary template instance loaded with CP/MVT variants
                    var tempTemplateInstance = templateInstance.Clone();
                    tempTemplateInstance.LoadVariants(false, VariantModeEnum.None);

                    webPartInstance = tempTemplateInstance.GetWebPart(InstanceGUID, -1);

                    // Set the VariantMode according to the selected web part/zone variant
                    if (webPartInstance?.ParentZone != null)
                    {
                        VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode;
                    }
                    else
                    {
                        VariantMode = VariantModeEnum.None;
                    }
                }
                else
                {
                    // Ensure that the ZoneVariantID is not set when the web part was found in a regular zone
                    ZoneVariantID = 0;
                }

                if ((VariantID > 0) && webPartInstance?.PartInstanceVariants != null)
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        webPartInstance = webPartInstance.FindVariant(VariantID);
                    }
                    else
                    {
                        // Not authorized for OnlineMarketing - Manage.
                        RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                    }
                }

                if (webPartInstance == null)
                {
                    UIContext.EditedObject = null;
                    return;
                }
            }

            // Keep xml version
            if (webPartInstance != null)
            {
                xmlVersion = webPartInstance.XMLVersion;
            }

            // Get the form info
            FormInfo fi = GetWebPartFormInfo();

            // Get the form definition
            if (fi != null)
            {
                fi.ContextResolver.Settings.RelatedObject = templateInstance;
                form.AllowMacroEditing = true;

                // Get data row with required columns
                DataRow dr = fi.GetDataRow();

                if (IsNewWebPart || (xmlVersion > 0))
                {
                    fi.LoadDefaultValues(dr);
                }

                // Load values from existing web part
                LoadDataRowFromWebPart(dr, webPartInstance, fi);

                // Set a unique WebPartControlID for the new variant
                if (IsNewVariant || IsNewWebPart)
                {
                    dr["WebPartControlID"] = GetUniqueWebPartId();
                }

                // Init the form
                InitForm(form, dr, fi);

                DisplayExportPropertiesButton();
            }
            else
            {
                UIContext.EditedObject = null;
            }
        }
    }
    /// <summary>
    /// Loads the widget form.
    /// </summary>
    private void LoadForm()
    {
        // Setup basic form on live site
        formCustom.AllowMacroEditing = false;
        formCustom.IsLiveSite        = IsLiveSite;

        // Load settings
        if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the widget variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateId, variantName, false);

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        EnsureDashboard();

        if (!String.IsNullOrEmpty(WidgetId) && !IsInline)
        {
            if (CurrentPageInfo == null)
            {
                ShowError(GetString("Widgets.Properties.aliasnotfound"));
                pnlFormArea.Visible = false;
                return;
            }

            // Get template instance
            mTemplateInstance = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo);

            if (!IsNewWidget)
            {
                // Get the instance of widget
                mWidgetInstance = mTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                if (mWidgetInstance == null)
                {
                    ShowError(GetString("Widgets.Properties.WidgetNotFound"));
                    pnlFormArea.Visible = false;
                    return;
                }

                if ((VariantID > 0) && (mWidgetInstance != null) && (mWidgetInstance.PartInstanceVariants != null))
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        mWidgetInstance = CurrentPageInfo.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                        mWidgetInstance = mWidgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID));
                        // Set the widget variant mode
                        if (mWidgetInstance != null)
                        {
                            VariantMode = mWidgetInstance.VariantMode;
                        }
                    }
                    else
                    {
                        // Not authorized for OnlineMarketing - Manage.
                        RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                    }
                }

                // Get widget info by widget name(widget type)
                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(mWidgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
            }

            // Keep xml version
            if (mWidgetInstance != null)
            {
                mXmlVersion = mWidgetInstance.XMLVersion;
            }

            UIContext.EditedObject = mWidgetInfo;

            // Get the zone to which it inserts
            WebPartZoneInstance zone = mTemplateInstance.GetZone(ZoneId);
            if ((ZoneType == WidgetZoneTypeEnum.None) && (zone != null))
            {
                ZoneType = zone.WidgetZoneType;
            }

            // Check security
            var currentUser = MembershipContext.AuthenticatedUser;

            switch (ZoneType)
            {
            // Group zone => Only group widgets and group admin
            case WidgetZoneTypeEnum.Group:
                // Should always be, only group widget are allowed in group zone
                if (!mWidgetInfo.WidgetForGroup || (!currentUser.IsGroupAdministrator(CurrentPageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for editor zones
            case WidgetZoneTypeEnum.Editor:
                if (!mWidgetInfo.WidgetForEditor)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for user zones
            case WidgetZoneTypeEnum.User:
                if (!mWidgetInfo.WidgetForUser)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for dashboard zones
            case WidgetZoneTypeEnum.Dashboard:
                if (!mWidgetInfo.WidgetForDashboard)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;
            }

            // Check security
            if ((ZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                if (OnNotAllowed != null)
                {
                    OnNotAllowed(this, null);
                }
            }

            // Get form schemas
            mWebPartInfo = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID);
            string   widgetProperties = FormHelper.MergeFormDefinitions(mWebPartInfo.WebPartProperties, mWidgetInfo.WidgetProperties);
            FormInfo fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, ZoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues);

            if (fi != null)
            {
                fi.ContextResolver.Settings.RelatedObject = mTemplateInstance;

                // Check if there are some editable properties
                var ffi = fi.GetFields(true, false);
                if ((ffi == null) || (ffi.Count == 0))
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                DataRow dr = fi.GetDataRow();

                // Load overridden values for new widget
                if (IsNewWidget || (mXmlVersion > 0))
                {
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }

                if (IsNewWidget)
                {
                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(mWidgetInfo.WidgetDisplayName));
                }

                // Load values from existing widget
                LoadDataRowFromWidget(dr, fi);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.Base.Web.UI.ControlContext.WIDGET_PROPERTIES;
            }
        }

        if (IsInline)
        {
            // Load text definition from session
            string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), String.Empty);
            if (String.IsNullOrEmpty(definition))
            {
                definition = Request.Form[hdnWidgetDefinition.UniqueID];
            }
            else
            {
                hdnWidgetDefinition.Value = definition;
            }

            Hashtable parameters = null;
            string    widgetName = String.Empty;



            if (IsNewWidget)
            {
                // New widget - load widget info by id
                if (!String.IsNullOrEmpty(WidgetId))
                {
                    mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
                }
                else
                {
                    // Try to get widget from codename
                    widgetName  = QueryHelper.GetString("WidgetName", String.Empty);
                    mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }
            else
            {
                if (definition == null)
                {
                    DisplayError("widget.failedtoload");
                    return;
                }

                // Parse definition
                parameters = CMSDialogHelper.GetHashTableFromString(definition);

                // Trim control name
                if (parameters["name"] != null)
                {
                    widgetName = parameters["name"].ToString();
                }

                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }
            if (mWidgetInfo == null)
            {
                DisplayError("widget.failedtoload");
                return;
            }

            // If widget cant be used as inline
            if (!mWidgetInfo.WidgetForInline)
            {
                DisplayError("widget.cantbeusedasinline");
                return;
            }


            // Test permission for user
            var currentUser = MembershipContext.AuthenticatedUser;
            if (!WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                mIsValidWidget = false;
                OnNotAllowed(this, null);
            }

            // If user is editor, more properties are shown
            WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
            if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName))
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }

            WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID);
            string      widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, mWidgetInfo.WidgetProperties);
            FormInfo    fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, zoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues);
            if (fi != null)
            {
                // Check if there are some editable properties
                mFields = fi.GetFields(true, true);
                if ((mFields == null) || !mFields.Any())
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                // Get datarows with required columns
                DataRow dr = PortalHelper.CombineWithDefaultValues(fi, mWidgetInfo);

                if (IsNewWidget)
                {
                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }
                else
                {
                    foreach (string key in parameters.Keys)
                    {
                        object value = parameters[key];
                        // Test if given property exists
                        if (dr.Table.Columns.Contains(key) && (value != null))
                        {
                            try
                            {
                                dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                // Override default value and set title as widget display name
                DataHelper.SetDataRowValue(dr, "WidgetTitle", mWidgetInfo.WidgetDisplayName);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.Base.Web.UI.ControlContext.WIDGET_PROPERTIES;
            }
        }
    }
    /// <summary>
    /// Loads the widget form.
    /// </summary>
    private void LoadForm()
    {
        // Setup basic form on live site
        formCustom.AllowMacroEditing = false;
        formCustom.IsLiveSite = IsLiveSite;

        // Load settings
        if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the widget variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateId, variantName, false);

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        EnsureDashboard();

        if (!String.IsNullOrEmpty(WidgetId) && !IsInline)
        {
            if (CurrentPageInfo == null)
            {
                ShowError(GetString("Widgets.Properties.aliasnotfound"));
                pnlFormArea.Visible = false;
                return;
            }

            // Get template instance
            templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo);

            if (!IsNewWidget)
            {
                // Get the instance of widget
                widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId);
                if (widgetInstance == null)
                {
                    ShowError(GetString("Widgets.Properties.WidgetNotFound"));
                    pnlFormArea.Visible = false;
                    return;
                }

                if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null))
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        widgetInstance = CurrentPageInfo.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                        widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID));
                        // Set the widget variant mode
                        if (widgetInstance != null)
                        {
                            VariantMode = widgetInstance.VariantMode;
                        }
                    }
                    else
                    {
                        // Not authorized for OnlineMarketing - Manage.
                        RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                    }
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
            }

            // Keep xml version
            if (widgetInstance != null)
            {
                xmlVersion = widgetInstance.XMLVersion;
            }

            UIContext.EditedObject = wi;

            // Get the zone to which it inserts
            WebPartZoneInstance zone = templateInstance.GetZone(ZoneId);
            if ((ZoneType == WidgetZoneTypeEnum.None) && (zone != null))
            {
                ZoneType = zone.WidgetZoneType;
            }

            // Check security
            var currentUser = MembershipContext.AuthenticatedUser;

            switch (ZoneType)
            {
                // Group zone => Only group widgets and group admin
                case WidgetZoneTypeEnum.Group:
                    // Should always be, only group widget are allowed in group zone
                    if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(CurrentPageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                    {
                        if (OnNotAllowed != null)
                        {
                            OnNotAllowed(this, null);
                        }
                    }
                    break;

                // Widget must be allowed for editor zones
                case WidgetZoneTypeEnum.Editor:
                    if (!wi.WidgetForEditor)
                    {
                        if (OnNotAllowed != null)
                        {
                            OnNotAllowed(this, null);
                        }
                    }
                    break;

                // Widget must be allowed for user zones
                case WidgetZoneTypeEnum.User:
                    if (!wi.WidgetForUser)
                    {
                        if (OnNotAllowed != null)
                        {
                            OnNotAllowed(this, null);
                        }
                    }
                    break;

                // Widget must be allowed for dashboard zones
                case WidgetZoneTypeEnum.Dashboard:
                    if (!wi.WidgetForDashboard)
                    {
                        if (OnNotAllowed != null)
                        {
                            OnNotAllowed(this, null);
                        }
                    }
                    break;
            }

            // Check security
            if ((ZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                if (OnNotAllowed != null)
                {
                    OnNotAllowed(this, null);
                }
            }

            // Get form schemas
            wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
            FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(ZoneType);
            string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);
            FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), ZoneType), widgetProperties, zoneTypeDefinition, true, wi.WidgetDefaultValues);

            if (fi != null)
            {

                fi.ContextResolver.Settings.RelatedObject = templateInstance;

                // Check if there are some editable properties
                var ffi = fi.GetFields(true, false).ToList<FormFieldInfo>();
                if ((ffi == null) || (ffi.Count == 0))
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                DataRow dr = fi.GetDataRow();

                // Load overridden values for new widget
                if (IsNewWidget || (xmlVersion > 0))
                {
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }

                if (IsNewWidget)
                {
                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName));
                }

                // Load values from existing widget
                LoadDataRowFromWidget(dr, fi);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.ExtendedControls.ControlContext.WIDGET_PROPERTIES;
            }
        }

        if (IsInline)
        {
            // Load text definition from session
            string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty);
            if (String.IsNullOrEmpty(definition))
            {
                definition = Request.Form[hdnWidgetDefinition.UniqueID];
            }
            else
            {
                hdnWidgetDefinition.Value = definition;
            }

            Hashtable parameters = null;
            string widgetName = string.Empty;

            if (IsNewWidget)
            {
                // New widget - load widget info by id
                if (!String.IsNullOrEmpty(WidgetId))
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
                }
                else
                {
                    // Try to get widget from codename
                    widgetName = QueryHelper.GetString("WidgetName", String.Empty);
                    wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }
            else
            {
                if (definition == null)
                {
                    DisplayError("widget.failedtoload");
                    return;
                }

                // Parse definition
                parameters = CMSDialogHelper.GetHashTableFromString(definition);

                // Trim control name
                if (parameters["name"] != null)
                {
                    widgetName = parameters["name"].ToString();
                }

                wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }
            if (wi == null)
            {
                DisplayError("widget.failedtoload");
                return;
            }

            // If widget cant be used as inline
            if (!wi.WidgetForInline)
            {
                DisplayError("widget.cantbeusedasinline");
                return;
            }

            // Test permission for user
            var currentUser = MembershipContext.AuthenticatedUser;
            if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                isValidWidget = false;
                OnNotAllowed(this, null);
            }

            // If user is editor, more properties are shown
            WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
            if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName))
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }

            WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
            string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);
            FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType);
            FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true, wi.WidgetDefaultValues);
            if (fi != null)
            {
                // Check if there are some editable properties
                mFields = fi.GetFields(true, true);
                if ((mFields == null) || !mFields.Any())
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                // Get datarows with required columns
                DataRow dr = PortalHelper.CombineWithDefaultValues(fi, wi);

                if (IsNewWidget)
                {
                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }
                else
                {
                    foreach (string key in parameters.Keys)
                    {
                        object value = parameters[key];
                        // Test if given property exists
                        if (dr.Table.Columns.Contains(key) && (value != null))
                        {
                            try
                            {
                                dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                // Override default value and set title as widget display name
                DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.ExtendedControls.ControlContext.WIDGET_PROPERTIES;
            }
        }
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Public user is not allowed for widgets
        if (!AuthenticationHelper.IsAuthenticated())
        {
            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
        }

        var viewMode = ViewModeCode.FromString(QueryHelper.GetString("viewmode", String.Empty));
        var hash     = QueryHelper.GetString("hash", String.Empty);

        LiveSiteWidgetsParameters dialogparameters = new LiveSiteWidgetsParameters(aliasPath, viewMode)
        {
            ZoneId         = zoneId,
            ZoneType       = zoneType,
            InstanceGuid   = instanceGuid,
            TemplateId     = templateId,
            IsInlineWidget = inline
        };

        if (!dialogparameters.ValidateHash(hash))
        {
            return;
        }

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        if ((widgetId != string.Empty) && (aliasPath != string.Empty))
        {
            // Get page info
            var      siteName = SiteContext.CurrentSiteName;
            PageInfo pi       = PageInfoProvider.GetPageInfo(siteName, aliasPath, LocalizationContext.PreferredCultureCode, null, SiteInfoProvider.CombineWithDefaultCulture(siteName));

            if (pi == null)
            {
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            // Get widget from instance
            WidgetInfo wi = null;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGuid, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }


            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    var currentUser = MembershipContext.AuthenticatedUser;

                    bool checkSecurity = true;

                    // Check security
                    // It is group zone type but widget is not allowed in group
                    if (zone.WidgetZoneType == WidgetZoneTypeEnum.Group)
                    {
                        // Should always be, only group widget are allowed in group zone
                        if (wi.WidgetForGroup)
                        {
                            if (!currentUser.IsGroupAdministrator(pi.NodeGroupID))
                            {
                                RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                            }

                            // All ok, don't check classic security
                            checkSecurity = false;
                        }
                    }

                    if (checkSecurity && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }
            }
        }
        // If all ok, set up frames
        rowsFrameset.Attributes.Add("rows", string.Format("{0}, *", TitleOnlyHeight));

        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + RequestContext.CurrentQueryString);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + RequestContext.CurrentQueryString);
        }
    }
    /// <summary>
    /// Saves the given DataRow data to the web part properties.
    /// </summary>
    /// <param name="form">Form to save</param>
    /// <param name="pti">Page template instance</param>
    /// <param name="isLayoutWidget">Indicates whether the edited widget is a layout widget</param>
    private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti, bool isLayoutWidget)
    {
        if (form.Visible && (mWidgetInstance != null))
        {
            // Keep the old ID to check the change of the ID
            string oldId = mWidgetInstance.ControlID.ToLowerCSafe();

            DataRow dr = form.DataRow;

            foreach (DataColumn column in dr.Table.Columns)
            {
                mWidgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()];
                mWidgetInstance.SetValue(column.ColumnName, dr[column]);

                // If name changed, move the content
                // (This can happen when a user overrides the WidgetControlID property to be visible in the widget properties dialog)
                if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0)
                {
                    try
                    {
                        string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe();

                        // Name changed
                        if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0))
                        {
                            WidgetIdChanged = true;
                            WidgetId        = newId;

                            // Move the document content if present
                            string currentContent = CurrentPageInfo.EditableWebParts[oldId];
                            if (currentContent != null)
                            {
                                TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider);

                                // Move the content in the page info
                                CurrentPageInfo.EditableWebParts[oldId] = null;
                                CurrentPageInfo.EditableWebParts[newId] = currentContent;

                                // Update the document
                                node.SetValue("DocumentContent", CurrentPageInfo.GetContentXml());
                                DocumentHelper.UpdateDocument(node, mTreeProvider);
                            }

                            // Change the underlying zone names if layout widget
                            if (isLayoutWidget)
                            {
                                string prefix = oldId + "_";

                                foreach (WebPartZoneInstance zone in pti.WebPartZones)
                                {
                                    if (zone.ZoneID.StartsWithCSafe(prefix, true))
                                    {
                                        // Change the zone prefix to the new one
                                        zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("Content", "CHANGEWIDGET", ex);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Init event handler.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Load settings
        if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the web part variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = 0;
                if (VariantMode == VariantModeEnum.MVT)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName);
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName);
                }

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        if (!String.IsNullOrEmpty(WebpartId))
        {
            // Get the page info
            pi = CMSWebPartPropertiesPage.GetPageInfo(this.AliasPath, this.PageTemplateId);
            if (pi != null)
            {
                // Get template
                pti = pi.PageTemplateInfo;

                // Get template instance
                templateInstance = pti.TemplateInstance;

                // Parent webpart
                WebPartInfo parentWpi = null;

                //Before FormInfo
                FormInfo beforeFI = null;

                //After FormInfo
                FormInfo afterFI = null;

                // Webpart form info
                FormInfo fi = null;

                if (!IsNewWebPart)
                {
                    if (ZoneVariantID > 0)
                    {
                        // Zone variant
                        WebPartZoneInstance wpzi = pti.GetZone(ZoneId, ZoneVariantID);
                        webPartInstance = wpzi.GetWebPart(InstanceGUID);
                    }
                    else
                    {
                        // Standard zone
                        webPartInstance = pti.GetWebPart(InstanceGUID, WebpartId);
                    }

                    if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null))
                    {
                        // Check OnlineMarketing permissions.
                        if (CheckPermissions("Read"))
                        {
                            webPartInstance = webPartInstance.FindVariant(VariantID);
                        }
                        else
                        {
                            // Not authorised for OnlineMarketing - Manage.
                            RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                        }
                    }

                    if (webPartInstance == null)
                    {
                        lblInfo.Text = GetString("WebPartProperties.WebPartNotFound");
                        pnlFormArea.Visible = false;
                        return;
                    }

                    wpi = WebPartInfoProvider.GetWebPartInfo(webPartInstance.WebPartType);
                    form.Mode = FormModeEnum.Update;
                }
                // Webpart instance hasn't created yet
                else
                {
                    wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(WebpartId, 0));
                    form.Mode = FormModeEnum.Insert;
                }

                // Load parent
                if (wpi != null)
                {
                    if (wpi.WebPartParentID > 0)
                    {
                        parentWpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    }
                }

                // Get the form definition
                string wpProperties = "<form></form>";
                if (wpi != null)
                {
                    wpProperties = wpi.WebPartProperties;

                    // Use parent webpart if is defined
                    if (parentWpi != null)
                    {
                        wpProperties = parentWpi.WebPartProperties;
                    }

                    // Get before FormInfo
                    if (BeforeFormDefinition == null)
                    {
                        beforeFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before);
                    }
                    else
                    {
                        beforeFI = new FormInfo(BeforeFormDefinition);
                    }

                    // Get after FormInfo
                    if (AfterFormDefinition == null)
                    {
                        afterFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After);
                    }
                    else
                    {
                        afterFI = new FormInfo(AfterFormDefinition);
                    }
                }

                // Add 'General' category at the beginning if no one is specified
                if (!string.IsNullOrEmpty(wpProperties) && (!wpProperties.StartsWith("<form><category", StringComparison.InvariantCultureIgnoreCase)))
                {
                    wpProperties = wpProperties.Insert(6, "<category name=\"" + GetString("general.general") + "\" />");
                }

                // Get merged web part FormInfo
                fi = FormHelper.GetWebPartFormInfo(wpi.WebPartName, wpProperties, beforeFI, afterFI, true);

                // Get datarow with required columns
                DataRow dr = fi.GetDataRow();

                if (IsNewWebPart)
                {
                    // Load default properties values
                    fi.LoadDefaultValues(dr);

                    // Load overriden system values
                    fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues);

                    // Set control ID
                    FormFieldInfo ffi = fi.GetFormField("WebPartControlID");
                    if (ffi != null)
                    {
                        ffi.DefaultValue = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                        fi.UpdateFormField("WebPartControlID", ffi);
                    }
                }

                // Load values from existing webpart
                LoadDataRowFromWebPart(dr, webPartInstance);

                // Set a unique WebPartControlID for athe new variant
                if (IsNewVariant)
                {
                    // Set control ID
                    dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                }

                // Init the form
                InitForm(form, dr, fi);

                AddExportLink();
            }
        }
    }
Esempio n. 15
0
    protected override void OnLoad(EventArgs e)
    {
        plImg  = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/plus.png");
        minImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/minus.png");

        if (WebpartID != String.Empty)
        {
            wpi = WebPartInfoProvider.GetWebPartInfo(WebpartID);
        }


        // Ensure correct view mode
        if (String.IsNullOrEmpty(AliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (!string.IsNullOrEmpty(DashboardName))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName     = DashboardName;
                PortalContext.DashboardSiteName = DashboardSiteName;
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        if (WidgetID != String.Empty)
        {
            PageInfo pi = null;
            try
            {
                // Load page info from alias path and page template
                pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi != null)
            {
                PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

                if (templateInstance != null)
                {
                    // Get the instance of widget
                    WebPartInstance widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetID);

                    // Info for zone type
                    WebPartZoneInstance zone = templateInstance.GetZone(ZoneID);

                    if (zone != null)
                    {
                        zoneType = zone.WidgetZoneType;
                    }

                    if (widgetInstance != null)
                    {
                        // Create widget from webpart instance
                        wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
                    }
                }
            }

            // If inline widget display columns as in editor zone
            if (IsInline)
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }


            // If no zone set (only global admins allowed to continue)
            if (zoneType == WidgetZoneTypeEnum.None)
            {
                if (!CMSContext.CurrentUser.UserSiteManagerAdmin)
                {
                    RedirectToAccessDenied(GetString("attach.actiondenied"));
                }
            }

            // If wi is still null (new item f.e.)
            if (wi == null)
            {
                // Try to get widget info directly by ID
                if (!IsNew)
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(WidgetID);
                }
                else
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetID, 0));
                }
            }
        }

        String itemDescription   = String.Empty;
        String itemType          = String.Empty;
        String itemDisplayName   = String.Empty;
        String itemDocumentation = String.Empty;
        int    itemID            = 0;

        // Check whether webpart was found
        if (wpi != null)
        {
            itemDescription   = wpi.WebPartDescription;
            itemType          = PortalObjectType.WEBPART;
            itemID            = wpi.WebPartID;
            itemDisplayName   = wpi.WebPartDisplayName;
            itemDocumentation = wpi.WebPartDocumentation;
        }
        // Or widget was found
        else if (wi != null)
        {
            itemDescription   = wi.WidgetDescription;
            itemType          = PortalObjectType.WIDGET;
            itemID            = wi.WidgetID;
            itemDisplayName   = wi.WidgetDisplayName;
            itemDocumentation = wi.WidgetDocumentation;
        }

        if ((wpi != null) || (wi != null))
        {
            // Get WebPart (widget) image
            DataSet ds = MetaFileInfoProvider.GetMetaFiles(itemID, itemType);

            // Set image url of exists
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                MetaFileInfo mtfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                if (mtfi != null)
                {
                    if (mtfi.MetaFileImageWidth > 385)
                    {
                        imgTeaser.Width = 385;
                    }

                    imgTeaser.ImageUrl = ResolveUrl("~/CMSPages/GetMetaFile.aspx?fileguid=" + mtfi.MetaFileGUID.ToString());
                }
            }
            else
            {
                // Set default image
                imgTeaser.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/imagenotavailable.png");
            }

            // Additional image information
            imgTeaser.ToolTip       = HTMLHelper.HTMLEncode(itemDisplayName);
            imgTeaser.AlternateText = HTMLHelper.HTMLEncode(itemDisplayName);

            // Set description of webpart
            ltlDescription.Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(itemDescription));

            // Get description from parent weboart if webpart is inherited
            if ((wpi != null) && (string.IsNullOrEmpty(wpi.WebPartDescription) && (wpi.WebPartParentID > 0)))
            {
                WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                if (pwpi != null)
                {
                    ltlDescription.Text = HTMLHelper.HTMLEncode(pwpi.WebPartDescription);
                }
            }

            FormInfo fi = null;

            // Generate properties
            if (wpi != null)
            {
                // Get form info from parent if webpart is inherited
                if (wpi.WebPartParentID != 0)
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null)
                    {
                        fi = GetWebPartProperties(pwpi);
                    }
                }
                else
                {
                    fi = GetWebPartProperties(wpi);
                }
            }
            else if (wi != null)
            {
                fi = GetWidgetProperties(wi);
            }

            // Generate properties
            if (fi != null)
            {
                GenerateProperties(fi);
            }

            // Generate documentation text
            if (itemDocumentation == null || itemDocumentation.Trim() == "")
            {
                if ((wpi != null) && (wpi.WebPartParentID != 0))
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null && pwpi.WebPartDocumentation.Trim() != "")
                    {
                        ltlContent.Text = HTMLHelper.ResolveUrls(pwpi.WebPartDocumentation, null);
                    }
                    else
                    {
                        ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                    }
                }
                else
                {
                    ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                }
            }
            else
            {
                ltlContent.Text = HTMLHelper.ResolveUrls(itemDocumentation, null);
            }
        }
        ScriptHelper.RegisterJQuery(Page);

        string script = @"
$j(document.body).ready(initializeResize);
           
function initializeResize ()  { 
    resizeareainternal();
    $j(window).resize(function() { resizeareainternal(); });
}

function resizeareainternal () {
    var height = document.body.clientHeight ; 
    var panel = document.getElementById ('" + divScrolable.ClientID + @"');
                
    // Get parent footer to count proper height (with padding included)
    var footer = $j('.PageFooterLine');                      
    panel.style.height = (height - footer.outerHeight() - panel.offsetTop) +'px';                  
}";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "mainScript", ScriptHelper.GetScript(script));

        string[,] tabs = new string[4, 4];
        tabs[0, 0]     = GetString("webparts.documentation");
        tabs[1, 0]     = GetString("general.properties");

        tabControlElem.Tabs        = tabs;
        tabControlElem.UsePostback = true;

        // Disable caching
        Response.Cache.SetNoStore();

        base.OnLoad(e);
    }
Esempio n. 16
0
    /// <summary>
    /// Init event handler.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Load settings
        if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the web part variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = 0;
                if (VariantMode == VariantModeEnum.MVT)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName);
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName);
                }

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        if (!String.IsNullOrEmpty(WebpartId))
        {
            // Get the page info
            pi = CMSWebPartPropertiesPage.GetPageInfo(this.AliasPath, this.PageTemplateId);
            if (pi != null)
            {
                // Get template
                pti = pi.PageTemplateInfo;

                // Get template instance
                templateInstance = pti.TemplateInstance;

                // Parent webpart
                WebPartInfo parentWpi = null;

                //Before FormInfo
                FormInfo beforeFI = null;

                //After FormInfo
                FormInfo afterFI = null;

                // Webpart form info
                FormInfo fi = null;

                if (!IsNewWebPart)
                {
                    // Standard zone
                    webPartInstance = pti.GetWebPart(InstanceGUID, WebpartId);

                    // If the web part not found, try to find it among the MVT/CP variants
                    if (webPartInstance == null)
                    {
                        // MVT/CP variant
                        templateInstance.LoadVariants(false, VariantModeEnum.None);
                        webPartInstance = templateInstance.GetWebPart(InstanceGUID, true);

                        // Set the VariantMode according to the selected web part/zone variant
                        if ((webPartInstance != null) && (webPartInstance.ParentZone != null))
                        {
                            VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode;
                        }
                        else
                        {
                            VariantMode = VariantModeEnum.None;
                        }
                    }
                    else
                    {
                        // Ensure that the ZoneVarianID is not set when the web part was found in a regural zone.
                        ZoneVariantID = 0;
                    }

                    if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null))
                    {
                        // Check OnlineMarketing permissions.
                        if (CheckPermissions("Read"))
                        {
                            webPartInstance = webPartInstance.FindVariant(VariantID);
                        }
                        else
                        {
                            // Not authorised for OnlineMarketing - Manage.
                            RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                        }
                    }

                    if (webPartInstance == null)
                    {
                        lblInfo.Text        = GetString("WebPartProperties.WebPartNotFound");
                        pnlFormArea.Visible = false;
                        return;
                    }

                    wpi       = WebPartInfoProvider.GetWebPartInfo(webPartInstance.WebPartType);
                    form.Mode = FormModeEnum.Update;
                }
                // Webpart instance hasn't created yet
                else
                {
                    wpi       = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(WebpartId, 0));
                    form.Mode = FormModeEnum.Insert;
                }

                // Load parent
                if (wpi != null)
                {
                    if (wpi.WebPartParentID > 0)
                    {
                        parentWpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    }
                }

                // Get the form definition
                string wpProperties = "<form></form>";
                if (wpi != null)
                {
                    wpProperties = wpi.WebPartProperties;

                    // Use parent webpart if is defined
                    if (parentWpi != null)
                    {
                        wpProperties = parentWpi.WebPartProperties;
                    }

                    // Get before FormInfo
                    if (BeforeFormDefinition == null)
                    {
                        beforeFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before);
                    }
                    else
                    {
                        beforeFI = new FormInfo(BeforeFormDefinition);
                    }

                    // Get after FormInfo
                    if (AfterFormDefinition == null)
                    {
                        afterFI = PortalHelper.GetPositionFormInfo((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After);
                    }
                    else
                    {
                        afterFI = new FormInfo(AfterFormDefinition);
                    }
                }

                // Add 'General' category at the beginning if no one is specified
                if (!string.IsNullOrEmpty(wpProperties) && (!wpProperties.StartsWith("<form><category", StringComparison.InvariantCultureIgnoreCase)))
                {
                    wpProperties = wpProperties.Insert(6, "<category name=\"" + GetString("general.general") + "\" />");
                }

                // Get merged web part FormInfo
                fi = FormHelper.GetWebPartFormInfo(wpi.WebPartName, wpProperties, beforeFI, afterFI, true);

                // Get datarow with required columns
                DataRow dr = fi.GetDataRow();

                if (IsNewWebPart)
                {
                    // Load default properties values
                    fi.LoadDefaultValues(dr);

                    // Load overriden system values
                    fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues);

                    // Set control ID
                    FormFieldInfo ffi = fi.GetFormField("WebPartControlID");
                    if (ffi != null)
                    {
                        ffi.DefaultValue = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                        fi.UpdateFormField("WebPartControlID", ffi);
                    }
                }

                // Load values from existing webpart
                LoadDataRowFromWebPart(dr, webPartInstance);

                // Set a unique WebPartControlID for athe new variant
                if (IsNewVariant)
                {
                    // Set control ID
                    dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                }

                // Init the form
                InitForm(form, dr, fi);

                AddExportLink();
            }
        }
    }
    /// <summary>
    /// Initializes menu.
    /// </summary>
    protected void InitalizeMenu()
    {
        string             zoneId      = QueryHelper.GetString("zoneid", "");
        bool               isNewWidget = QueryHelper.GetBoolean("isnew", false);
        WidgetZoneTypeEnum zoneType    = WidgetZoneTypeEnum.None;

        if (!String.IsNullOrEmpty(widgetId) || !String.IsNullOrEmpty(widgetName))
        {
            WidgetInfo wi = null;

            // get pageinfo
            PageInfo pi = null;
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

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

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            if (templateInstance != null)
            {
                // Get zone type
                WebPartZoneInstance zoneInstance = templateInstance.GetZone(zoneId);

                if (zoneInstance != null)
                {
                    zoneType = zoneInstance.WidgetZoneType;
                }
                if (!isNewWidget)
                {
                    // Get web part
                    WebPartInstance widget = templateInstance.GetWebPart(instanceGuid, widgetId);

                    if ((widget != null) && widget.IsWidget)
                    {
                        // WebPartType = codename, get widget by codename
                        wi = WidgetInfoProvider.GetWidgetInfo(widget.WebPartType);

                        // Set the variant mode (MVT/Content personalization)
                        variantMode = widget.VariantMode;
                    }
                }
            }
            // New widget
            if (isNewWidget)
            {
                int id = ValidationHelper.GetInteger(widgetId, 0);
                if (id > 0)
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(id);
                }
                else if (!String.IsNullOrEmpty(widgetName))
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }

            // Get widget info from name if not found yet
            if ((wi == null) && (!String.IsNullOrEmpty(widgetName)))
            {
                wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }

            if (wi != null)
            {
                PageTitle.TitleText = GetString("Widgets.Properties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WidgetDisplayName)) + ")";
            }

            // Use live or non live dialogs
            string documentationUrl = String.Empty;

            // If no zonetype defined or not inline dont show documentation
            switch (zoneType)
            {
            case WidgetZoneTypeEnum.Dashboard:
            case WidgetZoneTypeEnum.Editor:
            case WidgetZoneTypeEnum.Group:
            case WidgetZoneTypeEnum.User:
                documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx");
                break;

            // If no zone set dont create documentation link
            default:
                if (isInline)
                {
                    documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx");
                }
                else
                {
                    return;
                }
                break;
            }

            // Generate documentation link
            Literal ltr = new Literal();
            PageTitle.RightPlaceHolder.Controls.Add(ltr);

            // Ensure correct parameters in documentation url
            documentationUrl += URLHelper.GetQuery(URLHelper.CurrentURL);
            if (!String.IsNullOrEmpty(widgetName))
            {
                documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetname", widgetName);
            }
            if (!String.IsNullOrEmpty(widgetId))
            {
                documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetid", widgetId);
            }
            string docScript = "NewWindow('" + documentationUrl + "', 'WebPartPropertiesDocumentation', 800, 800); return false;";

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


            tabsElem.OnTabCreated           += new UITabs.TabCreatedEventHandler(tabElem_OnTabCreated);
            tabsElem.UrlTarget               = "widgetpropertiescontent";
            tabsElem.OpenTabContentAfterLoad = !isInline;
        }
    }
    /// <summary>
    /// Save button action.
    /// </summary>
    protected void ObjectManager_OnSaveData(object sender, SimpleObjectManagerEventArgs e)
    {
        // Template has to exist
        if (PageTemplate == null)
        {
            return;
        }

        // Limit text length
        txtTemplateCodeName.Text    = TextHelper.LimitLength(txtTemplateCodeName.Text.Trim(), 100, "");
        txtTemplateDisplayName.Text = TextHelper.LimitLength(txtTemplateDisplayName.Text.Trim(), 200, "");

        // Finds whether required fields are not empty
        string result = String.Empty;

        result = new Validator().NotEmpty(txtTemplateDisplayName.Text, GetString("Administration-PageTemplate_General.ErrorEmptyTemplateDisplayName")).NotEmpty(txtTemplateCodeName.Text, GetString("Administration-PageTemplate_General.ErrorEmptyTemplateCodeName"))
                 .IsCodeName(txtTemplateCodeName.Text, GetString("general.invalidcodename"))
                 .Result;

        if ((result == String.Empty) && (SelectedPageType == PageTemplateTypeEnum.Aspx || SelectedPageType == PageTemplateTypeEnum.AspxPortal))
        {
            if (!FileSystemSelector.IsValid())
            {
                result = FileSystemSelector.ValidationError;
            }
        }

        // If name changed, check if new name is unique
        if ((result == String.Empty) && (CMSString.Compare(PageTemplate.CodeName, txtTemplateCodeName.Text, true) != 0))
        {
            if (PageTemplateInfoProvider.PageTemplateNameExists(txtTemplateCodeName.Text))
            {
                result = GetString("general.codenameexists");
            }
        }


        // Check dashboard prerequisites
        if ((PageTemplate.PageTemplateId > 0) && (SelectedPageType == PageTemplateTypeEnum.Dashboard))
        {
            // Check live site usage
            TreeProvider            tp         = new TreeProvider(CMSContext.CurrentUser);
            NodeSelectionParameters parameters = new NodeSelectionParameters()
            {
                ClassNames = TreeProvider.ALL_CLASSNAMES,
                SiteName   = TreeProvider.ALL_SITES,
                Columns    = "NodeID",
                Where      = String.Format("DocumentPageTemplateID = {0} OR NodeTemplateID = {0} OR NodeWireframeTemplateID = {0}", PageTemplate.PageTemplateId)
            };

            DataSet ds = tp.SelectNodes(parameters);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                result = GetString("template.dahsboardliveused");
            }

            // Check valid zones
            if (String.IsNullOrEmpty(result))
            {
                PageTemplateInstance inst = PageTemplate.TemplateInstance;
                if (inst != null)
                {
                    foreach (WebPartZoneInstance zone in inst.WebPartZones)
                    {
                        switch (zone.WidgetZoneType)
                        {
                        case WidgetZoneTypeEnum.Dashboard:
                        case WidgetZoneTypeEnum.None:
                            continue;
                        }

                        result = GetString("template.dashboardinvalidzone");
                        break;
                    }
                }
            }
        }

        if (String.IsNullOrEmpty(result))
        {
            // Update page template info
            PageTemplate.DisplayName = txtTemplateDisplayName.Text;
            PageTemplate.CodeName    = txtTemplateCodeName.Text;
            PageTemplate.Description = txtTemplateDescription.Text;
            PageTemplate.CategoryID  = Convert.ToInt32(categorySelector.Value);

            if (SelectedPageType == PageTemplateTypeEnum.MVC)
            {
                // MVC template
                PageTemplate.IsPortal = false;
                PageTemplate.FileName = String.Empty;

                PageTemplate.ShowAsMasterTemplate     = false;
                PageTemplate.PageTemplateCloneAsAdHoc = false;

                PageTemplate.PageTemplateDefaultController = txtController.Text;
                PageTemplate.PageTemplateDefaultAction     = txtAction.Text;
            }
            else if (SelectedPageType == PageTemplateTypeEnum.Portal)
            {
                // Portal template of various types
                PageTemplate.IsPortal = true;
                PageTemplate.FileName = String.Empty;

                // Save inherit levels
                if (!chkShowAsMasterTemplate.Checked)
                {
                    PageTemplate.InheritPageLevels = ValidationHelper.GetString(lvlElem.Value, "");
                }
                else
                {
                    PageTemplate.InheritPageLevels = "/";
                }

                // Show hide inherit levels radio buttons
                PageTemplate.ShowAsMasterTemplate     = chkShowAsMasterTemplate.Checked;
                PageTemplate.PageTemplateCloneAsAdHoc = chkAdHoc.Checked;
            }
            else
            {
                // ASPX page templates
                PageTemplate.IsPortal = false;
                PageTemplate.FileName = FileSystemSelector.Value.ToString();

                PageTemplate.ShowAsMasterTemplate     = false;
                PageTemplate.PageTemplateCloneAsAdHoc = false;

                PageTemplate.InheritPageLevels = "";
            }

            PageTemplate.PageTemplateType = SelectedPageType;

            // Set ad-hoc status
            PageTemplate.IsReusable = pageTemplateIsReusable;
            if (pageTemplateIsReusable)
            {
                PageTemplate.PageTemplateNodeGUID = Guid.Empty;
            }

            PageTemplate.WebParts = pageTemplateWebParts;

            try
            {
                // Save the template and update the header
                PageTemplateInfoProvider.SetPageTemplateInfo(PageTemplate);
                ScriptHelper.RegisterStartupScript(this, typeof(string), "pageTemplateSaveScript", ScriptHelper.GetScript("RefreshContent()"));
                ShowChangesSaved();
            }
            catch (UnauthorizedAccessException ex)
            {
                ShowError(ResHelper.GetStringFormat("general.sourcecontrolerror", ex.Message));
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
        }
        else
        {
            rfvTemplateDisplayName.Visible = false;
            rfvTemplateCodeName.Visible    = false;

            ShowError(result);
        }
    }
Esempio n. 19
0
    /// <summary>
    /// Initializes menu.
    /// </summary>
    protected void InitalizeMenu()
    {
        if (!String.IsNullOrEmpty(widgetId) || !String.IsNullOrEmpty(widgetName))
        {
            WidgetInfo wi = null;

            // Get page info
            PageInfo pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture);

            if (pi == null)
            {
                Visible = false;
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            if (templateInstance != null)
            {
                // Get zone type
                WebPartZoneInstance zoneInstance = templateInstance.GetZone(zoneId);

                if (zoneInstance != null)
                {
                    zoneType = zoneInstance.WidgetZoneType;
                }
                if (!isNewWidget)
                {
                    // Get web part
                    WebPartInstance widget = templateInstance.GetWebPart(instanceGuid, widgetId);

                    if ((widget != null) && widget.IsWidget)
                    {
                        // WebPartType = codename, get widget by codename
                        wi = WidgetInfoProvider.GetWidgetInfo(widget.WebPartType);

                        // Set the variant mode (MVT/Content personalization)
                        variantMode = widget.VariantMode;
                    }
                }
            }
            // New widget
            if (isNewWidget)
            {
                int id = ValidationHelper.GetInteger(widgetId, 0);
                if (id > 0)
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(id);
                }
                else if (!String.IsNullOrEmpty(widgetName))
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }

            // Get widget info from name if not found yet
            if ((wi == null) && (!String.IsNullOrEmpty(widgetName)))
            {
                wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }

            if (wi != null)
            {
                pageTitle.TitleText = GetString("Widgets.Properties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WidgetDisplayName)) + ")";
            }

            // Use live or non live dialogs
            string documentationUrl = String.Empty;

            // If no zone type defined or not inline => do not show documentation
            switch (zoneType)
            {
            case WidgetZoneTypeEnum.Dashboard:
            case WidgetZoneTypeEnum.Editor:
            case WidgetZoneTypeEnum.Group:
            case WidgetZoneTypeEnum.User:
                documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx");
                break;

            // If no zone set => do not create documentation link
            default:
                if (inline)
                {
                    documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx");
                }
                else
                {
                    return;
                }
                break;
            }

            // Generate documentation link
            Literal ltr = new Literal();
            pageTitle.RightPlaceHolder.Controls.Add(ltr);

            // Ensure correct parameters in documentation URL
            documentationUrl += URLHelper.GetQuery(RequestContext.CurrentURL);
            if (wi != null)
            {
                documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetid", wi.WidgetID.ToString());
            }

            string docScript = "NewWindow('" + ScriptHelper.GetString(documentationUrl, encapsulate: false) + "', 'WebPartPropertiesDocumentation', 800, 800); return false;";
            string tooltip   = GetString("help.tooltip");
            ltr.Text += String.Format
                            ("<div class=\"action-button\"><a onclick=\"{0}\" href=\"#\"><span class=\"sr-only\">{1}</span><i class=\"icon-modal-question cms-icon-80\" title=\"{1}\" aria-hidden=\"true\"></i></a></div>",
                            HTMLHelper.EncodeForHtmlAttribute(docScript), tooltip);
        }
    }
Esempio n. 20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Public user is not allowed for widgets
        if (!CMSContext.CurrentUser.IsAuthenticated())
        {
            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
        }

        string widgetId     = QueryHelper.GetString("widgetid", String.Empty);
        string aliasPath    = QueryHelper.GetString("aliasPath", String.Empty);
        string zoneId       = QueryHelper.GetString("zoneid", String.Empty);
        Guid   instanceGUID = QueryHelper.GetGuid("instanceguid", Guid.Empty);
        bool   isNewWidget  = QueryHelper.GetBoolean("isnew", false);
        bool   inline       = QueryHelper.GetBoolean("inline", false);

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        if ((widgetId != string.Empty) && (aliasPath != string.Empty))
        {
            // Get pageinfo
            PageInfo pi = null;
            try
            {
                pi = PageInfoProvider.GetPageInfo(CMSContext.CurrentSiteName, aliasPath, CMSContext.PreferredCultureCode, null, CMSContext.CurrentSite.CombineWithDefaultCulture);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            // Get widget from instance
            WidgetInfo wi = null;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGUID, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }


            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    CurrentUserInfo currentUser = CMSContext.CurrentUser;

                    bool checkSecurity = true;

                    // Check security
                    // It is group zone type but widget is not allowed in group
                    if (zone.WidgetZoneType == WidgetZoneTypeEnum.Group)
                    {
                        // Should always be, only group widget are allowed in group zone
                        if (wi.WidgetForGroup)
                        {
                            if (!currentUser.IsGroupAdministrator(pi.NodeGroupID))
                            {
                                RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                            }

                            // All ok, don't check classic security
                            checkSecurity = false;
                        }
                    }

                    if (checkSecurity && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }
            }
        }
        // If all ok, set up frames
        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query);
        }
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        string widgetId     = QueryHelper.GetString("widgetid", String.Empty);
        string aliasPath    = QueryHelper.GetString("aliasPath", String.Empty);
        int    templateId   = QueryHelper.GetInteger("templateid", 0);
        string zoneId       = QueryHelper.GetString("zoneid", String.Empty);
        Guid   instanceGUID = QueryHelper.GetGuid("instanceguid", Guid.Empty);

        bool   isNewWidget = QueryHelper.GetBoolean("isnew", false);
        bool   inline      = QueryHelper.GetBoolean("inline", false);
        int    variantId   = QueryHelper.GetInteger("variantid", 0);
        string culture     = QueryHelper.GetString("culture", CMSContext.PreferredCultureCode);

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        // Resize the header (enlarge) to make a space for the tabs header when displaying a widget variant
        if (variantId > 0)
        {
            rowsFrameset.Attributes.Add("rows", "67, *");
        }

        // Ensure correct view mode
        if (String.IsNullOrEmpty(aliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (QueryHelper.Contains("dashboard"))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName     = QueryHelper.GetString("dashboard", String.Empty);
                PortalContext.DashboardSiteName = QueryHelper.GetString("sitename", String.Empty);
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        if (widgetId != "")
        {
            // Get pageinfo
            PageInfo pi = null;
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            // Get widget from instance
            WidgetInfo wi = null;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGUID, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }

            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    CurrentUserInfo currentUser = CMSContext.CurrentUser;

                    switch (zone.WidgetZoneType)
                    {
                    // Group zone => Only group widgets and group admin
                    case WidgetZoneTypeEnum.Group:
                        // Should always be, only group widget are allowed in group zone
                        if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupID) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;

                    // Widget must be allowed for editor zones
                    case WidgetZoneTypeEnum.Editor:
                        if (!wi.WidgetForEditor)
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;

                    // Widget must be allowed for user zones
                    case WidgetZoneTypeEnum.User:
                        if (!wi.WidgetForUser)
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;
                    }

                    if ((zone.WidgetZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }

                // If all ok, set up frames
                frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query);
                frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query);
            }
        }

        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query);
        }
    }
    /// <summary>
    /// Generate documentation page.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Get current resolver
        resolver = CMSContext.CurrentResolver.CreateContextChild();

        plImg  = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/plus.png");
        minImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/minus.png");

        webPartId = QueryHelper.GetString("webPartId", String.Empty);
        if (webPartId != String.Empty)
        {
            wpi = WebPartInfoProvider.GetWebPartInfo(webPartId);
        }

        string aliasPath = QueryHelper.GetString("aliaspath", String.Empty);

        // Ensure correct view mode
        if (String.IsNullOrEmpty(aliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (QueryHelper.Contains("dashboard"))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName     = QueryHelper.GetString("dashboard", String.Empty);
                PortalContext.DashboardSiteName = QueryHelper.GetString("sitename", String.Empty);
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        // If widgetId is in query create widget documentation
        widgetID = QueryHelper.GetString("widgetId", String.Empty);
        if (widgetID != String.Empty)
        {
            // Get widget from instance
            string zoneId       = QueryHelper.GetString("zoneid", String.Empty);
            Guid   instanceGuid = QueryHelper.GetGuid("instanceGuid", Guid.Empty);
            int    templateID   = QueryHelper.GetInteger("templateID", 0);
            bool   newItem      = QueryHelper.GetBoolean("isNew", false);
            bool   isInline     = QueryHelper.GetBoolean("Inline", false);

            PageInfo pi = null;
            try
            {
                // Load page info from alias path and page template
                pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateID);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi != null)
            {
                PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

                if (templateInstance != null)
                {
                    // Get the instance of widget
                    WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGuid, widgetID);

                    // Info for zone type
                    WebPartZoneInstance zone = templateInstance.GetZone(zoneId);

                    if (zone != null)
                    {
                        zoneType = zone.WidgetZoneType;
                    }

                    if (widgetInstance != null)
                    {
                        // Create widget from webpart instance
                        wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
                    }
                }
            }

            // If inline widget display columns as in editor zone
            if (isInline)
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }


            // If no zone set (only global admins allowed to continue)
            if (zoneType == WidgetZoneTypeEnum.None)
            {
                if (!CMSContext.CurrentUser.UserSiteManagerAdmin)
                {
                    RedirectToAccessDenied(GetString("attach.actiondenied"));
                }
            }

            // If wi is still null (new item f.e.)
            if (wi == null)
            {
                // Try to get widget info directly by ID
                if (!newItem)
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(widgetID);
                }
                else
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetID, 0));
                }
            }
        }

        String itemDescription   = String.Empty;
        String itemType          = String.Empty;
        String itemDisplayName   = String.Empty;
        String itemDocumentation = String.Empty;
        int    itemID            = 0;

        // Check whether webpart was found
        if (wpi != null)
        {
            itemDescription   = wpi.WebPartDescription;
            itemType          = PortalObjectType.WEBPART;
            itemID            = wpi.WebPartID;
            itemDisplayName   = wpi.WebPartDisplayName;
            itemDocumentation = wpi.WebPartDocumentation;
        }
        // Or widget was found
        else if (wi != null)
        {
            itemDescription   = wi.WidgetDescription;
            itemType          = PortalObjectType.WIDGET;
            itemID            = wi.WidgetID;
            itemDisplayName   = wi.WidgetDisplayName;
            itemDocumentation = wi.WidgetDocumentation;
        }

        if ((wpi != null) || (wi != null))
        {
            // Get WebPart (widget) image
            DataSet ds = MetaFileInfoProvider.GetMetaFiles(itemID, itemType);

            // Set image url of exists
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                MetaFileInfo mtfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                if (mtfi != null)
                {
                    if (mtfi.MetaFileImageWidth > 385)
                    {
                        imgTeaser.Width = 385;
                    }

                    imgTeaser.ImageUrl = ResolveUrl("~/CMSPages/GetMetaFile.aspx?fileguid=" + mtfi.MetaFileGUID.ToString());
                }
            }
            else
            {
                // Set default image
                imgTeaser.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/imagenotavailable.png");
            }

            // Additional image information
            imgTeaser.ToolTip       = HTMLHelper.HTMLEncode(itemDisplayName);
            imgTeaser.AlternateText = HTMLHelper.HTMLEncode(itemDisplayName);

            // Set description of webpart
            ltlDescription.Text = HTMLHelper.HTMLEncode(itemDescription);

            // Get description from parent weboart if webpart is inherited
            if ((wpi != null) && ((wpi.WebPartDescription == null || wpi.WebPartDescription == "") && (wpi.WebPartParentID > 0)))
            {
                WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                if (pwpi != null)
                {
                    ltlDescription.Text = HTMLHelper.HTMLEncode(pwpi.WebPartDescription);
                }
            }

            FormInfo fi = null;

            // Generate properties
            if (wpi != null)
            {
                // Get form info from parent if webpart is inherited
                if (wpi.WebPartParentID != 0)
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null)
                    {
                        fi = GetWebPartProperties(pwpi);
                    }
                }
                else
                {
                    fi = GetWebPartProperties(wpi);
                }
            }
            else if (wi != null)
            {
                fi = GetWidgetProperties(wi);
            }

            // Generate properties
            if (fi != null)
            {
                GenerateProperties(fi);
            }

            // Generate documentation text
            if (itemDocumentation == null || itemDocumentation.Trim() == "")
            {
                if ((wpi != null) && (wpi.WebPartParentID != 0))
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null && pwpi.WebPartDocumentation.Trim() != "")
                    {
                        ltlContent.Text = HTMLHelper.ResolveUrls(pwpi.WebPartDocumentation, null);
                    }
                    else
                    {
                        ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                    }
                }
                else
                {
                    ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                }
            }
            else
            {
                ltlContent.Text = HTMLHelper.ResolveUrls(itemDocumentation, null);
            }
        }
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterModalPageScripts();

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        // Resize the header (enlarge) to make a space for the tabs header when displaying a widget variant
        var headerHeight = TitleOnlyHeight;

        if (variantId > 0)
        {
            headerHeight = TabsFrameHeight;
        }

        rowsFrameset.Attributes.Add("rows", string.Format("{0}, *", headerHeight));

        // Ensure correct view mode
        if (String.IsNullOrEmpty(aliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (QueryHelper.Contains("dashboard"))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName     = QueryHelper.GetString("dashboard", String.Empty);
                PortalContext.DashboardSiteName = QueryHelper.GetString("sitename", String.Empty);
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        if (widgetId != "")
        {
            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(PageInfo);

            // Get widget from instance
            WidgetInfo wi;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGuid, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }

            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    var currentUser = MembershipContext.AuthenticatedUser;

                    switch (zone.WidgetZoneType)
                    {
                    // Group zone => Only group widgets and group admin
                    case WidgetZoneTypeEnum.Group:
                        // Should always be, only group widget are allowed in group zone
                        if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(PageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;

                    // Widget must be allowed for editor zones
                    case WidgetZoneTypeEnum.Editor:
                        if (!wi.WidgetForEditor)
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;

                    // Widget must be allowed for user zones
                    case WidgetZoneTypeEnum.User:
                        if (!wi.WidgetForUser)
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;
                    }

                    if ((zone.WidgetZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }

                // If all ok, set up frames
                frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + RequestContext.CurrentQueryString);
                frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + RequestContext.CurrentQueryString);
            }
        }

        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + RequestContext.CurrentQueryString);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + RequestContext.CurrentQueryString);
        }
    }
    /// <summary>
    /// Removes document content for all editor widgets in a given document.
    /// </summary>
    /// <param name="treeNode">Document to update</param>
    /// <param name="pti">Page template instance</param>
    /// <param name="omitUpdate">Indicates whether update on a given document should be omitted</param>
    private void ClearEditorWidgetsContent(TreeNode treeNode, PageTemplateInstance pti, bool omitUpdate)
    {
        var documentWebPartsXml = treeNode.GetStringValue("DocumentWebParts", String.Empty);

        if (String.IsNullOrEmpty(documentWebPartsXml))
        {
            return;
        }

        var webPartIds = new List<string>();

        // Get web part IDs from DocumentWebParts column
        webPartIds.AddRange(GetWebPartIDs(documentWebPartsXml));

        // Get web part IDs from page template (widget zones only) and combine them with existing list.
        webPartIds.AddRange(GetWebPartIDs(pti.GetZonesXML(WidgetZoneTypeEnum.Editor)));

        // Remove web part IDs from DocumentContent
        foreach (var wpId in webPartIds.Distinct())
        {
            treeNode.DocumentContent.EditableWebParts.Remove(wpId);
        }

        treeNode.SetValue("DocumentContent", treeNode.DocumentContent.GetContentXml());

        if (!omitUpdate)
        {
            DocumentHelper.UpdateDocument(treeNode, TreeProvider);
        }
    }
    /// <summary>
    /// Saves the given DataRow data to the web part properties.
    /// </summary>
    /// <param name="form">Form to save</param>
    /// <param name="pti">Page template instance</param>
    /// <param name="isLayoutWidget">Indicates whether the edited widget is a layout widget</param>
    private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti, bool isLayoutWidget)
    {
        if (form.Visible && (widgetInstance != null))
        {
            // Keep the old ID to check the change of the ID
            string oldId = widgetInstance.ControlID.ToLowerCSafe();

            DataRow dr = form.DataRow;

            foreach (DataColumn column in dr.Table.Columns)
            {
                widgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()];
                widgetInstance.SetValue(column.ColumnName, dr[column]);

                // If name changed, move the content
                // (This can happen when a user overrides the WidgetControlID property to be visible in the widget properties dialog)
                if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0)
                {
                    try
                    {
                        string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe();

                        // Name changed
                        if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0))
                        {
                            WidgetIdChanged = true;
                            WidgetId = newId;

                            // Move the document content if present
                            string currentContent = CurrentPageInfo.EditableWebParts[oldId];
                            if (currentContent != null)
                            {
                                TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, tree);

                                // Move the content in the page info
                                CurrentPageInfo.EditableWebParts[oldId] = null;
                                CurrentPageInfo.EditableWebParts[newId] = currentContent;

                                // Update the document
                                node.SetValue("DocumentContent", CurrentPageInfo.GetContentXml());
                                DocumentHelper.UpdateDocument(node, tree);
                            }

                            // Change the underlying zone names if layout widget
                            if (isLayoutWidget)
                            {
                                string prefix = oldId + "_";

                                foreach (WebPartZoneInstance zone in pti.WebPartZones)
                                {
                                    if (zone.ZoneID.StartsWithCSafe(prefix, true))
                                    {
                                        // Change the zone prefix to the new one
                                        zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("Content", "CHANGEWIDGET", ex);
                    }
                }
            }
        }
    }
Esempio n. 26
0
    /// <summary>
    /// Saves the given DataRow data to the web part properties.
    /// </summary>
    /// <param name="form">Form to save</param>
    /// <param name="pti">Page template instance</param>
    private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti)
    {
        if (form.Visible && (widgetInstance != null))
        {
            // Keep the old ID to check the change of the ID
            string oldId = widgetInstance.ControlID.ToLowerCSafe();

            DataRow dr = form.DataRow;

            // Load default values for new widget
            if (IsNewWidget)
            {
                form.FormInformation.LoadDefaultValues(dr, wi.WidgetDefaultValues);
            }

            foreach (DataColumn column in dr.Table.Columns)
            {
                widgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()];
                widgetInstance.SetValue(column.ColumnName, dr[column]);

                // If name changed, move the content
                if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0)
                {
                    try
                    {
                        string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe();

                        // Name changed
                        if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0))
                        {
                            mWidgetIdChanged = true;
                            WidgetId         = newId;

                            // Move the document content if present
                            string currentContent = pi.EditableWebParts[oldId];
                            if (currentContent != null)
                            {
                                TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree);

                                // Move the content in the page info
                                pi.EditableWebParts[oldId] = null;
                                pi.EditableWebParts[newId] = currentContent;

                                // Update the document
                                node.SetValue("DocumentContent", pi.GetContentXml());
                                DocumentHelper.UpdateDocument(node, tree);
                            }

                            // Change the underlying zone names if layout web part
                            if ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout))
                            {
                                string prefix = oldId + "_";

                                foreach (WebPartZoneInstance zone in pti.WebPartZones)
                                {
                                    if (zone.ZoneID.StartsWithCSafe(prefix, true))
                                    {
                                        // Change the zone prefix to the new one
                                        zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("Content", "CHANGEWIDGET", ex);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Initializes menu.
    /// </summary>
    protected void InitalizeMenu()
    {
        string             zoneId       = QueryHelper.GetString("zoneid", string.Empty);
        string             culture      = QueryHelper.GetString("culture", CMSContext.PreferredCultureCode);
        Guid               instanceGuid = QueryHelper.GetGuid("instanceguid", Guid.Empty);
        bool               isNewWidget  = QueryHelper.GetBoolean("isnew", false);
        WidgetZoneTypeEnum zoneType     = WidgetZoneTypeEnum.None;

        if (!String.IsNullOrEmpty(widgetId) || !String.IsNullOrEmpty(widgetName))
        {
            WidgetInfo wi = null;

            // get pageinfo
            PageInfo pi = null;
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                Visible = false;
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);
            if (templateInstance != null)
            {
                // Get zone type
                WebPartZoneInstance zoneInstance = templateInstance.GetZone(zoneId);

                if (zoneInstance != null)
                {
                    zoneType = zoneInstance.WidgetZoneType;
                }

                // Get web part
                WebPartInstance widget = templateInstance.GetWebPart(instanceGuid, widgetId);

                if ((widget != null) && widget.IsWidget)
                {
                    // WebPartType = codename, get widget by codename
                    wi = WidgetInfoProvider.GetWidgetInfo(widget.WebPartType);
                }
            }

            // New widget
            if (isNewWidget)
            {
                int id = ValidationHelper.GetInteger(widgetId, 0);
                if (id > 0)
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(id);
                }
                else if (!String.IsNullOrEmpty(widgetName))
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }

            // Get widget info from name if not found yet
            if ((wi == null) && (!String.IsNullOrEmpty(widgetName)))
            {
                wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }

            if (wi != null)
            {
                PageTitle.TitleText = GetString("Widgets.Properties.Title") + " (" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wi.WidgetDisplayName)) + ")";
            }

            // If no zonetype defined or not inline dont show documentation
            string documentationUrl = String.Empty;
            switch (zoneType)
            {
            case WidgetZoneTypeEnum.Dashboard:
            case WidgetZoneTypeEnum.Editor:
            case WidgetZoneTypeEnum.Group:
            case WidgetZoneTypeEnum.User:
                documentationUrl = ResolveUrl("~/CMSModules/Widgets/LiveDialogs/WidgetDocumentation.aspx");
                break;

            // If no zone set dont create documentation link
            default:
                if (isInline)
                {
                    documentationUrl = ResolveUrl("~/CMSModules/Widgets/Dialogs/WidgetDocumentation.aspx");
                }
                else
                {
                    return;
                }
                break;
            }

            // Generate documentation link
            Literal ltr = new Literal();
            PageTitle.RightPlaceHolder.Controls.Add(ltr);

            // Ensure correct parameters in documentation url
            documentationUrl += URLHelper.GetQuery(URLHelper.CurrentURL);
            if (!String.IsNullOrEmpty(widgetName))
            {
                documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetname", widgetName);
            }
            if (!String.IsNullOrEmpty(widgetId))
            {
                documentationUrl = URLHelper.UpdateParameterInUrl(documentationUrl, "widgetid", widgetId);
            }
            string docScript = "NewWindow('" + documentationUrl + "', 'WebPartPropertiesDocumentation', 800, 800); return false;";

            ltr.Text += "<a onclick=\"" + docScript + "\" href=\"#\"><img src=\"" + ResolveUrl(GetImageUrl("General/HelpLargeDark.png")) + "\" style=\"border-width: 0px;\"></a>";
        }
    }
Esempio n. 28
0
    protected override void OnLoad(EventArgs e)
    {
        plImg  = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/plus.png");
        minImg = GetImageUrl("CMSModules/CMS_PortalEngine/WebpartProperties/minus.png");

        if (WebpartID != String.Empty)
        {
            wpi = WebPartInfoProvider.GetWebPartInfo(WebpartID);
        }


        // Ensure correct view mode
        if (String.IsNullOrEmpty(AliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (!string.IsNullOrEmpty(DashboardName))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName     = DashboardName;
                PortalContext.DashboardSiteName = DashboardSiteName;
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        if (WidgetID != 0)
        {
            PageInfo pi = null;
            try
            {
                // Load page info from alias path and page template
                pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi != null)
            {
                PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

                if (templateInstance != null)
                {
                    // Get the instance of widget
                    WebPartInstance widgetInstance = templateInstance.GetWebPart(InstanceGUID);

                    // Info for zone type
                    WebPartZoneInstance zone = templateInstance.GetZone(ZoneID);

                    if (zone != null)
                    {
                        zoneType = zone.WidgetZoneType;
                    }

                    if (widgetInstance != null)
                    {
                        // Create widget from webpart instance
                        wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
                    }
                }
            }

            // If inline widget display columns as in editor zone
            if (IsInline)
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }


            // If no zone set (only global admins allowed to continue)
            if (zoneType == WidgetZoneTypeEnum.None)
            {
                if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                {
                    RedirectToAccessDenied(GetString("attach.actiondenied"));
                }
            }

            // If wi is still null (new item f.e.)
            if (wi == null)
            {
                // Try to get widget info directly by ID
                wi = WidgetInfoProvider.GetWidgetInfo(WidgetID);
            }
        }

        String itemDescription   = String.Empty;
        String itemType          = String.Empty;
        String itemDisplayName   = String.Empty;
        String itemDocumentation = String.Empty;
        String itemIcon          = String.Empty;
        int    itemID            = 0;

        // Check whether webpart was found
        if (wpi != null)
        {
            itemDescription   = wpi.WebPartDescription;
            itemType          = WebPartInfo.OBJECT_TYPE;
            itemID            = wpi.WebPartID;
            itemDisplayName   = wpi.WebPartDisplayName;
            itemDocumentation = wpi.WebPartDocumentation;

            itemIcon = PortalHelper.GetIconHtml(wpi.WebPartThumbnailGUID, wpi.WebPartIconClass ?? PortalHelper.DefaultWebPartIconClass);
        }
        // Or widget was found
        else if (wi != null)
        {
            itemDescription   = wi.WidgetDescription;
            itemType          = WidgetInfo.OBJECT_TYPE;
            itemID            = wi.WidgetID;
            itemDisplayName   = wi.WidgetDisplayName;
            itemDocumentation = wi.WidgetDocumentation;
            itemIcon          = PortalHelper.GetIconHtml(wi.WidgetThumbnailGUID, wi.WidgetIconClass ?? PortalHelper.DefaultWidgetIconClass);
        }

        if ((wpi != null) || (wi != null))
        {
            // Get WebPart (widget) icon
            ltrImage.Text = itemIcon;

            // Set description of webpart
            ltlDescription.Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(itemDescription));

            // Get description from parent weboart if webpart is inherited
            if ((wpi != null) && (string.IsNullOrEmpty(wpi.WebPartDescription) && (wpi.WebPartParentID > 0)))
            {
                WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                if (pwpi != null)
                {
                    ltlDescription.Text = HTMLHelper.HTMLEncode(pwpi.WebPartDescription);
                }
            }

            FormInfo fi = null;

            // Generate properties
            if (wpi != null)
            {
                // Get form info from parent if webpart is inherited
                if (wpi.WebPartParentID != 0)
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null)
                    {
                        fi = GetWebPartProperties(pwpi);
                    }
                }
                else
                {
                    fi = GetWebPartProperties(wpi);
                }
            }
            else if (wi != null)
            {
                fi = GetWidgetProperties(wi);
            }

            // Generate properties
            if (fi != null)
            {
                GenerateProperties(fi);
            }

            // Generate documentation text
            if (itemDocumentation == null || itemDocumentation.Trim() == "")
            {
                if ((wpi != null) && (wpi.WebPartParentID != 0))
                {
                    WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                    if (pwpi != null && pwpi.WebPartDocumentation.Trim() != "")
                    {
                        ltlContent.Text = HTMLHelper.ResolveUrls(pwpi.WebPartDocumentation, null);
                    }
                    else
                    {
                        ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                    }
                }
                else
                {
                    ltlContent.Text = "<br /><div style=\"padding-left:5px; font-weight: bold;\">" + GetString("WebPartDocumentation.DocumentationText") + "</div><br />";
                }
            }
            else
            {
                ltlContent.Text = HTMLHelper.ResolveUrls(itemDocumentation, null);
            }
        }
        ScriptHelper.RegisterJQuery(Page);

        string script = @"
$cmsj(document.body).ready(initializeResize);
           
function initializeResize ()  { 
    resizeareainternal();
    $cmsj(window).resize(function() { resizeareainternal(); });
}

function resizeareainternal () {
    var height = document.body.clientHeight ; 
    var panel = document.getElementById ('" + divScrolable.ClientID + @"');
                
    // Get parent footer to count proper height (with padding included)
    var footer = $cmsj('#divFooter');                      
    panel.style.height = (height - footer.outerHeight() - panel.offsetTop) +'px';                  
}";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(Page), "mainScript", ScriptHelper.GetScript(script));

        // Init tabs
        tabControlElem.UsePostback = true;

        tabControlElem.AddTab(new UITabItem()
        {
            Text = GetString("webparts.documentation"),
        });

        tabControlElem.AddTab(new UITabItem()
        {
            Text = GetString("general.properties"),
        });

        // Disable caching
        Response.Cache.SetNoStore();

        base.OnLoad(e);
    }
    /// <summary>
    /// Handles the OnAfterValidate event of the Control control.
    /// </summary>
    void Control_OnAfterValidate(object sender, EventArgs e)
    {
        PageTemplateInfo pti = Control.EditedObject as PageTemplateInfo;

        if (pti == null)
        {
            return;
        }

        String result             = String.Empty;
        PageTemplateTypeEnum type = (Control.GetFieldValue("PageTemplateType") as String).ToEnum <PageTemplateTypeEnum>();
        String fileName           = Control.GetFieldValue("PageTemplateFile") as String;

        // Check dashboard prerequisites
        if ((pti.PageTemplateId > 0) && (type == PageTemplateTypeEnum.Dashboard))
        {
            // Check live site usage
            TreeProvider            tp         = new TreeProvider(MembershipContext.AuthenticatedUser);
            NodeSelectionParameters parameters = new NodeSelectionParameters
            {
                ClassNames  = TreeProvider.ALL_CLASSNAMES,
                SiteName    = TreeProvider.ALL_SITES,
                Columns     = "NodeID, DocumentCulture",
                Where       = String.Format("DocumentPageTemplateID = {0} OR NodeTemplateID = {0}", pti.PageTemplateId),
                CultureCode = TreeProvider.ALL_CULTURES,
                CombineWithDefaultCulture = true,
            };

            DataSet ds = tp.SelectNodes(parameters);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                result = ResHelper.GetString("template.dahsboardliveused");
            }

            // Check valid zones
            if (String.IsNullOrEmpty(result))
            {
                PageTemplateInstance inst = pti.TemplateInstance;
                if (inst != null)
                {
                    foreach (WebPartZoneInstance zone in inst.WebPartZones)
                    {
                        switch (zone.WidgetZoneType)
                        {
                        case WidgetZoneTypeEnum.Dashboard:
                        case WidgetZoneTypeEnum.None:
                            continue;
                        }

                        result = ResHelper.GetString("template.dashboardinvalidzone");
                        break;
                    }
                }
            }
        }

        // Validate file
        if (((type == PageTemplateTypeEnum.Aspx) || (type == PageTemplateTypeEnum.AspxPortal)) &&
            String.IsNullOrEmpty(fileName))
        {
            result = ResHelper.GetString("development-webpart_edit.emptywebpartfilename");
        }

        if (result != String.Empty)
        {
            Control.StopProcessing = true;
            CMSPage pg = Control.Page as CMSPage;
            if (pg != null)
            {
                pg.ShowError(result);
                Control.StopProcessing = true;
            }
        }
    }
 /// <summary>
 /// Generates basic web parts markup
 /// </summary>
 /// <param name="sb">String builder</param>
 /// <param name="xml">Web part xml</param>
 private void GenerateWebPartsMarkup(ref StringBuilder sb, string xml, bool isLeft)
 {
     if (!String.IsNullOrEmpty(xml))
     {
         PageTemplateInstance inst = new PageTemplateInstance(xml);
         if (inst.WebPartZones.Count > 0)
         {
             sb.Append(@"<a href=""#"" onclick=""versionExpandWebParts()"" id=""", isLeft ? "vWpLeftLink" : "vWpRightLink" , "\">"+ GetString("General.Expand") +"</a>");
             sb.Append("<div style=\"display:none\" id=\"", isLeft ? "vWpLeft" : "vWpRight" , "\">");
             foreach (WebPartZoneInstance zone in inst.WebPartZones)
             {
                 sb.Append("<b>Zone</b>: ", HTMLHelper.HTMLEncode(zone.ZoneID));
                 sb.Append(@"<div class=""VZoneEnvelope"">");
                 foreach (WebPartInstance webPart in zone.WebParts)
                 {
                     sb.Append(HTMLHelper.HTMLEncode(webPart.ControlID), " (", HTMLHelper.HTMLEncode(webPart.WebPartType), ")");
                     sb.Append(@"<div class=""VWebPartEnvelope"">");
                     foreach (DictionaryEntry item in webPart.Properties)
                     {
                         string itemValue = Convert.ToString(item.Value);
                         string itemKey = Convert.ToString(item.Key);
                         if (!String.IsNullOrEmpty(itemValue))
                         {
                             sb.Append(HTMLHelper.HTMLEncode(itemKey), " : ", HTMLHelper.HTMLEncode(itemValue), "<br />");
                         }
                     }
                     sb.Append("</div>");
                 }
                 sb.Append("</div>");
             }
             sb.Append("</div>");
         }
     }
 }
Esempio n. 31
0
    /// <summary>
    /// Page load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        treeElem.OnItemSelected += treeElem_OnItemSelected;

        if (!RequestHelper.IsPostBack())
        {
            // Select root by default
            ResetToDefault();
        }

        // Different behavior of flat selector for different group zones
        if (IsInline)
        {
            // Inline widget
            flatElem.SelectInlineWidgets = true;
            treeElem.SelectInlineWidgets = true;
        }
        else if (IsDashboard)
        {
            // Dashboard zone
            flatElem.SelectDashboardWidgets = true;
            treeElem.SelectDashboardWidgets = true;
        }
        else if (!String.IsNullOrEmpty(ZoneId))
        {
            // Get pageinfo
            PageInfo pi = null;
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId, CultureCode);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);
            if (templateInstance != null)
            {
                WidgetZoneTypeEnum zoneType = ZoneType;

                // Get settings of the zone if present in the template
                WebPartZoneInstance zone = templateInstance.GetZone(ZoneId);
                if ((zoneType == WidgetZoneTypeEnum.None) && (zone != null))
                {
                    zoneType = zone.WidgetZoneType;
                }

                // Set flags to flat element by type of widget zone
                if (zoneType == WidgetZoneTypeEnum.Group)
                {
                    flatElem.SelectGroupWidgets = true;
                    treeElem.SelectGroupWidgets = true;
                    flatElem.GroupID            = pi.NodeGroupID;
                }
                else if (zoneType == WidgetZoneTypeEnum.User)
                {
                    flatElem.SelectUserWidgets = true;
                    treeElem.SelectUserWidgets = true;
                }
                else if (zoneType == WidgetZoneTypeEnum.Editor)
                {
                    flatElem.SelectEditorWidgets = true;
                    treeElem.SelectEditorWidgets = true;
                }
            }
        }
    }
    /// <summary>
    /// Saves the given DataRow data to the web part properties.
    /// </summary>
    /// <param name="form">Form to save</param>
    /// <param name="pti">Page template instance</param>
    private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti)
    {
        if (form.Visible && (widgetInstance != null))
        {
            // Keep the old ID to check the change of the ID
            string oldId = widgetInstance.ControlID.ToLowerCSafe();

            DataRow dr = form.DataRow;

            // Load default values for new widget
            if (IsNewWidget)
            {
                form.FormInformation.LoadDefaultValues(dr, wi.WidgetDefaultValues);
            }

            foreach (DataColumn column in dr.Table.Columns)
            {
                widgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()];
                widgetInstance.SetValue(column.ColumnName, dr[column]);

                // If name changed, move the content
                if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0)
                {
                    try
                    {
                        string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe();

                        // Name changed
                        if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0))
                        {
                            mWidgetIdChanged = true;
                            WidgetId = newId;

                            // Move the document content if present
                            string currentContent = pi.EditableWebParts[oldId];
                            if (currentContent != null)
                            {
                                TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree);

                                // Move the content in the page info
                                pi.EditableWebParts[oldId] = null;
                                pi.EditableWebParts[newId] = currentContent;

                                // Update the document
                                node.SetValue("DocumentContent", pi.GetContentXml());
                                DocumentHelper.UpdateDocument(node, tree);
                            }

                            // Change the underlying zone names if layout web part
                            if ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout))
                            {
                                string prefix = oldId + "_";

                                foreach (WebPartZoneInstance zone in pti.WebPartZones)
                                {
                                    if (zone.ZoneID.StartsWithCSafe(prefix, true))
                                    {
                                        // Change the zone prefix to the new one
                                        zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("Content", "CHANGEWIDGET", ex);
                    }
                }
            }
        }
    }