Example #1
0
        public WebPartTracker(WebPart webPart, ProviderConnectionPoint providerConnectionPoint)
        {
            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            if (providerConnectionPoint == null)
            {
                throw new ArgumentNullException("providerConnectionPoint");
            }

            if (providerConnectionPoint.ControlType != webPart.GetType())
            {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_InvalidConnectionPoint), "providerConnectionPoint");
            }

            _webPart = webPart;
            _providerConnectionPoint = providerConnectionPoint;

            if (++Count > 1)
            {
                webPart.SetConnectErrorMessage(SR.GetString(SR.WebPartTracker_CircularConnection, _providerConnectionPoint.DisplayName));
            }
        }
        internal static bool IsPartSupported(IDictionary action, SystemWebPart wp, bool isPeop, SPList list, out bool origPage)
        {
            string flag;
            Type   wpType = null;

            try {
                wpType = wp.GetType();
            } catch {
            }
            if ((wpType != null) && ("Microsoft.SharePoint.WebPartPages.XsltListFormWebPart".Equals(wpType.FullName) || (wp is ListFormWebPart)))
            {
                origPage = "o".Equals(flag = action ["mlf"] + string.Empty);
                return(!"n".Equals(flag));
            }
            if (list != null)
            {
                origPage = "o".Equals(flag = action [(list.BaseTemplate == SPListTemplateType.Events) ? "mcv" : "mlv"] + string.Empty);
                return(!"n".Equals(flag));
            }
            if (isPeop)
            {
                origPage = "o".Equals(flag = action ["mpz"] + string.Empty);
                return(!"n".Equals(flag));
            }
            origPage = "o".Equals(flag = action ["mwp"] + string.Empty);
            return((!(wp is TitleBarWebPart)) && !"n".Equals(flag));
        }
        protected ProxyWebPart(WebPart webPart)
        {
            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }

            GenericWebPart genericWebPart = webPart as GenericWebPart;

            if (genericWebPart != null)
            {
                Control childControl = genericWebPart.ChildControl;
                if (childControl == null)
                {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "ChildControl"), "webPart");
                }

                _originalID = childControl.ID;
                if (String.IsNullOrEmpty(_originalID))
                {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNullOrEmptyString, "ChildControl.ID"), "webPart");
                }

                Type        originalType;
                UserControl childUserControl = childControl as UserControl;
                if (childUserControl != null)
                {
                    originalType  = typeof(UserControl);
                    _originalPath = childUserControl.AppRelativeVirtualPath;
                }
                else
                {
                    originalType = childControl.GetType();
                }
                _originalTypeName = WebPartUtil.SerializeType(originalType);
                _genericWebPartID = genericWebPart.ID;
                if (String.IsNullOrEmpty(_genericWebPartID))
                {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNullOrEmptyString, "ID"), "webPart");
                }
                ID = _genericWebPartID;
            }
            else
            {
                _originalID = webPart.ID;
                if (String.IsNullOrEmpty(_originalID))
                {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNullOrEmptyString, "ID"), "webPart");
                }
                _originalTypeName = WebPartUtil.SerializeType(webPart.GetType());
                ID = _originalID;
            }
        }
        internal static string GetPartDesc(SystemWebPart part, Reflector refl)
        {
            SPView view;

            if (!string.IsNullOrEmpty(part.Description))
            {
                return(part.Description);
            }
            if ((view = refl.Get(part, (part is ListViewWebPart) ? "View" : "ContextView") as SPView) != null)
            {
                return((view.ParentList.Title.Equals(part.DisplayTitle) ? string.Empty : (view.ParentList.Title + HttpUtility.HtmlDecode(" — "))) + (string.IsNullOrEmpty(view.Title) ? ProductPage.GetProductResource("CustomView") : view.Title));
            }
            return(part.GetType().Name);
        }
Example #5
0
        protected ProxyWebPart(WebPart webPart)
        {
            if (webPart == null)
            {
                throw new ArgumentNullException("webPart");
            }
            GenericWebPart part = webPart as GenericWebPart;

            if (part != null)
            {
                Type    type;
                Control childControl = part.ChildControl;
                if (childControl == null)
                {
                    throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNull", new object[] { "ChildControl" }), "webPart");
                }
                this._originalID = childControl.ID;
                if (string.IsNullOrEmpty(this._originalID))
                {
                    throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNullOrEmptyString", new object[] { "ChildControl.ID" }), "webPart");
                }
                UserControl control2 = childControl as UserControl;
                if (control2 != null)
                {
                    type = typeof(UserControl);
                    this._originalPath = control2.AppRelativeVirtualPath;
                }
                else
                {
                    type = childControl.GetType();
                }
                this._originalTypeName = WebPartUtil.SerializeType(type);
                this._genericWebPartID = part.ID;
                if (string.IsNullOrEmpty(this._genericWebPartID))
                {
                    throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNullOrEmptyString", new object[] { "ID" }), "webPart");
                }
                this.ID = this._genericWebPartID;
            }
            else
            {
                this._originalID = webPart.ID;
                if (string.IsNullOrEmpty(this._originalID))
                {
                    throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNullOrEmptyString", new object[] { "ID" }), "webPart");
                }
                this._originalTypeName = WebPartUtil.SerializeType(webPart.GetType());
                this.ID = this._originalID;
            }
        }
 protected ProxyWebPart(WebPart webPart)
 {
     if (webPart == null)
     {
         throw new ArgumentNullException("webPart");
     }
     GenericWebPart part = webPart as GenericWebPart;
     if (part != null)
     {
         Type type;
         Control childControl = part.ChildControl;
         if (childControl == null)
         {
             throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNull", new object[] { "ChildControl" }), "webPart");
         }
         this._originalID = childControl.ID;
         if (string.IsNullOrEmpty(this._originalID))
         {
             throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNullOrEmptyString", new object[] { "ChildControl.ID" }), "webPart");
         }
         UserControl control2 = childControl as UserControl;
         if (control2 != null)
         {
             type = typeof(UserControl);
             this._originalPath = control2.AppRelativeVirtualPath;
         }
         else
         {
             type = childControl.GetType();
         }
         this._originalTypeName = WebPartUtil.SerializeType(type);
         this._genericWebPartID = part.ID;
         if (string.IsNullOrEmpty(this._genericWebPartID))
         {
             throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNullOrEmptyString", new object[] { "ID" }), "webPart");
         }
         this.ID = this._genericWebPartID;
     }
     else
     {
         this._originalID = webPart.ID;
         if (string.IsNullOrEmpty(this._originalID))
         {
             throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNullOrEmptyString", new object[] { "ID" }), "webPart");
         }
         this._originalTypeName = WebPartUtil.SerializeType(webPart.GetType());
         this.ID = this._originalID;
     }
 }
        // Extracts the personalization state from webPartA, and applies it to webPartB.
        // Assumes that webPartA and webPartB are the same type.  If the WebParts are GenericWebParts,
        // then copies the personalization state from the ChildControl of webPartA to the
        // ChildControl of webPartB.
        protected internal virtual void CopyPersonalizationState(WebPart webPartA, WebPart webPartB)
        {
            if (webPartA == null)
            {
                throw new ArgumentNullException("webPartA");
            }
            if (webPartB == null)
            {
                throw new ArgumentNullException("webPartB");
            }
            if (webPartA.GetType() != webPartB.GetType())
            {
                throw new ArgumentException(SR.GetString(SR.WebPartPersonalization_SameType, "webPartA", "webPartB"));
            }

            CopyPersonalizationState((Control)webPartA, (Control)webPartB);

            GenericWebPart genericWebPartA = webPartA as GenericWebPart;
            GenericWebPart genericWebPartB = webPartB as GenericWebPart;

            // Assert that the GenericWebParts are either both null or both non-null
            Debug.Assert((genericWebPartA == null) == (genericWebPartB == null));
            if (genericWebPartA != null && genericWebPartB != null)
            {
                Control childControlA = genericWebPartA.ChildControl;
                Control childControlB = genericWebPartB.ChildControl;

                if (childControlA == null)
                {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "ChildControl"), "webPartA");
                }
                if (childControlB == null)
                {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "ChildControl"), "webPartB");
                }
                if (childControlA.GetType() != childControlB.GetType())
                {
                    throw new ArgumentException(SR.GetString(SR.WebPartPersonalization_SameType, "webPartA.ChildControl", "webPartB.ChildControl"));
                }

                CopyPersonalizationState(childControlA, childControlB);
            }

            // IPersonalizable.IsDirty should always be false on the new WebPart, since the only data
            // on the new WebPart was loaded via personalization, which should not cause the control
            // to be dirty.  However, we want to save the IPersonalizable data on this request, so
            // we call SetDirty() to force the IPersonalizable data to be saved.
            SetDirty(webPartB);
        }
Example #8
0
        private void FindWebSiteParts(HtmlTextWriter writer, Microsoft.SharePoint.WebPartPages.WebPartZone zone)
        {
            for (int i = 0; i < zone.WebParts.Count; i++)
            {
                System.Web.UI.WebControls.WebParts.WebPart webpart = zone.WebParts[i];

                if (webpart.GetType() == typeof(WebSitePart))
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "WebSitePart");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    zone.WebParts[i].RenderControl(writer);
                    writer.RenderEndTag();
                }
            }
        }
 public void SetWebPartProperty(
     SPWeb web,
     string pageUrl,
     string webPartID,
     string propertyName,
     string propertyValue)
 {
     using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared)) {
         WebPart      part        = manager.WebParts [webPartID];
         Type         runtimeType = part.GetType();
         PropertyInfo property    = runtimeType.GetProperty(propertyName);
         object       value       = ConvertValue(propertyValue, property.PropertyType);
         property.SetValue(part, value, null);
         manager.SaveChanges(part);
     }
 }
        protected ProxyWebPart(WebPart webPart) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }

            GenericWebPart genericWebPart = webPart as GenericWebPart;
            if (genericWebPart != null) {
                Control childControl = genericWebPart.ChildControl;
                if (childControl == null) {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "ChildControl"), "webPart");
                }

                _originalID = childControl.ID;
                if (String.IsNullOrEmpty(_originalID)) {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNullOrEmptyString, "ChildControl.ID"), "webPart");
                }

                Type originalType;
                UserControl childUserControl = childControl as UserControl;
                if (childUserControl != null) {
                    originalType = typeof(UserControl);
                    _originalPath = childUserControl.AppRelativeVirtualPath;
                }
                else {
                    originalType = childControl.GetType();
                }
                _originalTypeName = WebPartUtil.SerializeType(originalType);
                _genericWebPartID = genericWebPart.ID;
                if (String.IsNullOrEmpty(_genericWebPartID)) {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNullOrEmptyString, "ID"), "webPart");
                }
                ID = _genericWebPartID;
            }
            else {
                _originalID = webPart.ID;
                if (String.IsNullOrEmpty(_originalID)) {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNullOrEmptyString, "ID"), "webPart");
                }
                _originalTypeName = WebPartUtil.SerializeType(webPart.GetType());
                ID = _originalID;
            }
        }
        public WebPartTracker(WebPart webPart, ProviderConnectionPoint providerConnectionPoint) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }

            if (providerConnectionPoint == null) {
                throw new ArgumentNullException("providerConnectionPoint");
            }

            if (providerConnectionPoint.ControlType != webPart.GetType()) {
                throw new ArgumentException(SR.GetString(SR.WebPartManager_InvalidConnectionPoint), "providerConnectionPoint");
            }

            _webPart = webPart;
            _providerConnectionPoint = providerConnectionPoint;

            if (++Count > 1) {
                webPart.SetConnectErrorMessage(SR.GetString(SR.WebPartTracker_CircularConnection, _providerConnectionPoint.DisplayName));
            }
        }
 public WebPartTracker(WebPart webPart, ProviderConnectionPoint providerConnectionPoint)
 {
     if (webPart == null)
     {
         throw new ArgumentNullException("webPart");
     }
     if (providerConnectionPoint == null)
     {
         throw new ArgumentNullException("providerConnectionPoint");
     }
     if (providerConnectionPoint.ControlType != webPart.GetType())
     {
         throw new ArgumentException(System.Web.SR.GetString("WebPartManager_InvalidConnectionPoint"), "providerConnectionPoint");
     }
     this._webPart = webPart;
     this._providerConnectionPoint = providerConnectionPoint;
     if (++this.Count > 1)
     {
         webPart.SetConnectErrorMessage(System.Web.SR.GetString("WebPartTracker_CircularConnection", new object[] { this._providerConnectionPoint.DisplayName }));
     }
 }
Example #13
0
 public WebPartTracker(WebPart webPart, ProviderConnectionPoint providerConnectionPoint)
 {
     if (webPart == null)
     {
         throw new ArgumentNullException("webPart");
     }
     if (providerConnectionPoint == null)
     {
         throw new ArgumentNullException("providerConnectionPoint");
     }
     if (providerConnectionPoint.ControlType != webPart.GetType())
     {
         throw new ArgumentException(System.Web.SR.GetString("WebPartManager_InvalidConnectionPoint"), "providerConnectionPoint");
     }
     this._webPart = webPart;
     this._providerConnectionPoint = providerConnectionPoint;
     if (++this.Count > 1)
     {
         webPart.SetConnectErrorMessage(System.Web.SR.GetString("WebPartTracker_CircularConnection", new object[] { this._providerConnectionPoint.DisplayName }));
     }
 }
Example #14
0
        internal void AddPeopleWebPart(IDictionary action, string pageUrl, ArrayList filters, Hashtable fht)
        {
            string        wpID = Request.QueryString ["l"], jop = Request.QueryString ["o"];
            Hashtable     opt;
            Guid          wpGuid = ProductPage.GetGuid(wpID.Replace('_', '-').Substring(2));
            SystemWebPart wp     = null;

            wpMan2 = web.GetLimitedWebPartManager(pageUrl.StartsWith("/", StringComparison.InvariantCultureIgnoreCase) ? pageUrl : (web.Url.TrimEnd('/') + '/' + pageUrl.TrimStart('/')), PersonalizationScope.Shared);
            try {
                wp = wpMan2.WebParts [wpID];
            } catch (Exception ex) {
                if (Guid.Empty.Equals(wpGuid))
                {
                    Errors.Add(ex);
                }
                else
                {
                    try {
                        wp = wpMan2.WebParts [wpGuid];
                    } catch (Exception ex2) {
                        Errors.Add(ex2);
                    }
                }
            }
            if ((wp != null) && (bool)(new Reflector(wp.GetType().Assembly).Get(wp, "IsB")))
            {
                if (string.IsNullOrEmpty(Title))
                {
                    Title = wp.Title;
                }
                if (!string.IsNullOrEmpty(jop))
                {
                    opt = JSON.JsonDecode(jop) as Hashtable;
                }
                InitWebPart(wp);
                MainWebPart.Controls.Add(wp);
                PhVals ["Context_Title"] = PhVals ["WebPart_Title"] = wp.DisplayTitle;
            }
        }
Example #15
0
        protected virtual void ProcessWebpartCustomProperties(WebPart instance, WebPartDefinition definition)
        {
            if (definition.Properties != null && definition.Properties.Count > 0)
            {
                var wpType = instance.GetType();

                foreach (var prop in definition.Properties)
                {
                    var isCdata = prop.IsCData.HasValue && prop.IsCData.Value;

                    if (ReflectionUtils.HasProperty(instance, prop.Name))
                    {
                        var wpProp     = wpType.GetProperty(prop.Name);
                        var wpPropType = wpProp.PropertyType;

                        var targetValue = Convert.ChangeType(prop.Value, wpPropType);

                        wpProp.SetValue(instance, targetValue, null);
                    }
                }
            }
        }
Example #16
0
        protected internal virtual void CopyPersonalizationState(WebPart webPartA, WebPart webPartB)
        {
            if (webPartA == null)
            {
                throw new ArgumentNullException("webPartA");
            }
            if (webPartB == null)
            {
                throw new ArgumentNullException("webPartB");
            }
            if (webPartA.GetType() != webPartB.GetType())
            {
                throw new ArgumentException(System.Web.SR.GetString("WebPartPersonalization_SameType", new object[] { "webPartA", "webPartB" }));
            }
            this.CopyPersonalizationState((Control)webPartA, (Control)webPartB);
            GenericWebPart part  = webPartA as GenericWebPart;
            GenericWebPart part2 = webPartB as GenericWebPart;

            if ((part != null) && (part2 != null))
            {
                Control childControl = part.ChildControl;
                Control controlB     = part2.ChildControl;
                if (childControl == null)
                {
                    throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNull", new object[] { "ChildControl" }), "webPartA");
                }
                if (controlB == null)
                {
                    throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNull", new object[] { "ChildControl" }), "webPartB");
                }
                if (childControl.GetType() != controlB.GetType())
                {
                    throw new ArgumentException(System.Web.SR.GetString("WebPartPersonalization_SameType", new object[] { "webPartA.ChildControl", "webPartB.ChildControl" }));
                }
                this.CopyPersonalizationState(childControl, controlB);
            }
            this.SetDirty(webPartB);
        }
        internal static void SetWebPart(WebPart sourceWebPart, string targetUrl, string zone, int? zoneIndex, bool publish, bool test)
        {
            if (sourceWebPart.IsClosed)
            {
                sourceWebPart.Dispose();
                throw new Exception("The source web part is closed and cannot be copied.");
            }

            int zoneIndex1 = sourceWebPart.ZoneIndex;
            if (zoneIndex.HasValue)
                zoneIndex1 = zoneIndex.Value;
            Guid storageKey = Guid.NewGuid();
            string id = StorageKeyToID(storageKey);

            using (SPSite site = new SPSite(targetUrl))
            using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
            {
                bool cleanupContext = false;
                try
                {
                    if (HttpContext.Current == null)
                    {
                        cleanupContext = true;
                        HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                        HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                        SPControl.SetContextWeb(HttpContext.Current, web);
                    }

                    SPFile file = web.GetFile(targetUrl);

                    // file.Item will throw "The object specified does not belong to a list." if the url passed
                    // does not correspond to a file in a list.

                    bool checkIn = false;
                    if (file.InDocumentLibrary && !test)
                    {
                        if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                        {
                            file.CheckOut();
                            checkIn = true;
                            // If it's checked out by another user then this will throw an informative exception so let it do so.
                        }
                    }

                    SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                    try
                    {
                        string wpTitle = sourceWebPart.Title;
                        if (string.IsNullOrEmpty(wpTitle)) wpTitle = sourceWebPart.DisplayTitle;

                        Logger.Write("Copying web part \"{0}\"...", wpTitle);
                        WebPart newWebPart = (WebPart)Activator.CreateInstance(sourceWebPart.GetType());
                        if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                        {
                            Logger.WriteWarning("An error was encountered setting web part properties so try one more time in case the error is the result of a sequencing issue.");
                            if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                            {
                                Logger.WriteWarning("Unable to set all properties for web part.");
                            }
                        }

                        try
                        {
                            if (!test)
                            {
                                newWebPart.ID = id;

                                manager.AddWebPart(newWebPart, zone, zoneIndex1);
                            }
                        }
                        catch (Exception)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

                            // We've not already added the web part so use the web service to do this.
                            using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                            {
                                // We failed adding via the OM so try the web service as a fall back.
                                svc.Url = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                                svc.Credentials = CredentialCache.DefaultCredentials;

                                try
                                {
                                    // Add the web part to the web service.  We use a web service because many
                                    // web parts require the SPContext.Current variables to be set which are
                                    // not set when run from a command line.
                                    StringBuilder sb = new StringBuilder();
                                    XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                    xmlWriter.Formatting = Formatting.Indented;
                                    manager.ExportWebPart(newWebPart, xmlWriter);
                                    xmlWriter.Flush();

                                    svc.AddWebPartToZone(targetUrl, sb.ToString(), Storage.Shared, zone, zoneIndex1);

                                }
                                catch (SoapException ex)
                                {
                                    throw new Exception(ex.Detail.OuterXml);
                                }
                            }
                        }
                        finally
                        {
                            sourceWebPart.Dispose();
                            newWebPart.Dispose();
                        }
                        if (zone == "wpz" && file.InDocumentLibrary)
                        {
                            foreach (SPField field in file.Item.Fields)
                            {
                                if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking)
                                {
                                    string content = null;
                                    if (file.Item[field.Id] != null)
                                        content = file.Item[field.Id].ToString();

                                    string div = string.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"/></div>", new object[] { storageKey.ToString("D") });
                                    content += div;
                                    Logger.Write("Adding web part to text field \"{0}\"...", field.InternalName);
                                    if (!test)
                                    {
                                        file.Item[field.Id] = content;
                                        file.Item.SystemUpdate();
                                    }
                                }
                            }
                        }

                    }
                    finally
                    {
                        if (manager != null)
                        {
                            manager.Web.Dispose();
                            manager.Dispose();
                        }

                        if (!test)
                        {
                            if (checkIn)
                                file.CheckIn("Checking in changes to page due to web part being replaced with a different type.");
                            if (publish && file.InDocumentLibrary)
                            {
                                PublishItems pi = new PublishItems();
                                pi.PublishListItem(file.Item, file.Item.ParentList, false, "Copy-SPWebPart", "Checking in changes to page due to web part being copied from another page.", null);
                            }
                        }
                    }
                }
                finally
                {
                    if (HttpContext.Current != null && cleanupContext)
                    {
                        HttpContext.Current = null;
                    }
                }

            }
        }
Example #18
0
        internal static void SetWebPart(WebPart sourceWebPart, string targetUrl, string zone, int?zoneIndex, bool publish, bool test)
        {
            if (sourceWebPart.IsClosed)
            {
                sourceWebPart.Dispose();
                throw new Exception("The source web part is closed and cannot be copied.");
            }

            int zoneIndex1 = sourceWebPart.ZoneIndex;

            if (zoneIndex.HasValue)
            {
                zoneIndex1 = zoneIndex.Value;
            }
            Guid   storageKey = Guid.NewGuid();
            string id         = StorageKeyToID(storageKey);

            using (SPSite site = new SPSite(targetUrl))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }


                        SPFile file = web.GetFile(targetUrl);

                        // file.Item will throw "The object specified does not belong to a list." if the url passed
                        // does not correspond to a file in a list.

                        bool checkIn = false;
                        if (file.InDocumentLibrary && !test)
                        {
                            if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                            {
                                file.CheckOut();
                                checkIn = true;
                                // If it's checked out by another user then this will throw an informative exception so let it do so.
                            }
                        }

                        SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                        try
                        {
                            string wpTitle = sourceWebPart.Title;
                            if (string.IsNullOrEmpty(wpTitle))
                            {
                                wpTitle = sourceWebPart.DisplayTitle;
                            }

                            Logger.Write("Copying web part \"{0}\"...", wpTitle);
                            WebPart newWebPart = (WebPart)Activator.CreateInstance(sourceWebPart.GetType());
                            if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                            {
                                Logger.WriteWarning("An error was encountered setting web part properties so try one more time in case the error is the result of a sequencing issue.");
                                if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                                {
                                    Logger.WriteWarning("Unable to set all properties for web part.");
                                }
                            }

                            try
                            {
                                if (!test)
                                {
                                    newWebPart.ID = id;

                                    manager.AddWebPart(newWebPart, zone, zoneIndex1);
                                }
                            }
                            catch (Exception)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                                // We've not already added the web part so use the web service to do this.
                                using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                                {
                                    // We failed adding via the OM so try the web service as a fall back.
                                    svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                                    svc.Credentials = CredentialCache.DefaultCredentials;

                                    try
                                    {
                                        // Add the web part to the web service.  We use a web service because many
                                        // web parts require the SPContext.Current variables to be set which are
                                        // not set when run from a command line.
                                        StringBuilder sb        = new StringBuilder();
                                        XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                        xmlWriter.Formatting = Formatting.Indented;
                                        manager.ExportWebPart(newWebPart, xmlWriter);
                                        xmlWriter.Flush();

                                        svc.AddWebPartToZone(targetUrl, sb.ToString(), Storage.Shared, zone, zoneIndex1);
                                    }
                                    catch (SoapException ex)
                                    {
                                        throw new Exception(ex.Detail.OuterXml);
                                    }
                                }
                            }
                            finally
                            {
                                sourceWebPart.Dispose();
                                newWebPart.Dispose();
                            }
                            if (zone == "wpz" && file.InDocumentLibrary)
                            {
                                foreach (SPField field in file.Item.Fields)
                                {
                                    if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking)
                                    {
                                        string content = null;
                                        if (file.Item[field.Id] != null)
                                        {
                                            content = file.Item[field.Id].ToString();
                                        }

                                        string div = string.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"/></div>", new object[] { storageKey.ToString("D") });
                                        content += div;
                                        Logger.Write("Adding web part to text field \"{0}\"...", field.InternalName);
                                        if (!test)
                                        {
                                            file.Item[field.Id] = content;
                                            file.Item.SystemUpdate();
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }

                            if (!test)
                            {
                                if (checkIn)
                                {
                                    file.CheckIn("Checking in changes to page due to web part being replaced with a different type.");
                                }
                                if (publish && file.InDocumentLibrary)
                                {
                                    PublishItems pi = new PublishItems();
                                    pi.PublishListItem(file.Item, file.Item.ParentList, false, "Copy-SPWebPart", "Checking in changes to page due to web part being copied from another page.", null);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
 protected internal virtual void CopyPersonalizationState(WebPart webPartA, WebPart webPartB)
 {
     if (webPartA == null)
     {
         throw new ArgumentNullException("webPartA");
     }
     if (webPartB == null)
     {
         throw new ArgumentNullException("webPartB");
     }
     if (webPartA.GetType() != webPartB.GetType())
     {
         throw new ArgumentException(System.Web.SR.GetString("WebPartPersonalization_SameType", new object[] { "webPartA", "webPartB" }));
     }
     this.CopyPersonalizationState((Control) webPartA, (Control) webPartB);
     GenericWebPart part = webPartA as GenericWebPart;
     GenericWebPart part2 = webPartB as GenericWebPart;
     if ((part != null) && (part2 != null))
     {
         Control childControl = part.ChildControl;
         Control controlB = part2.ChildControl;
         if (childControl == null)
         {
             throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNull", new object[] { "ChildControl" }), "webPartA");
         }
         if (controlB == null)
         {
             throw new ArgumentException(System.Web.SR.GetString("PropertyCannotBeNull", new object[] { "ChildControl" }), "webPartB");
         }
         if (childControl.GetType() != controlB.GetType())
         {
             throw new ArgumentException(System.Web.SR.GetString("WebPartPersonalization_SameType", new object[] { "webPartA.ChildControl", "webPartB.ChildControl" }));
         }
         this.CopyPersonalizationState(childControl, controlB);
     }
     this.SetDirty(webPartB);
 }
Example #20
0
        /// <summary>
        /// Sets the web part properties.
        /// </summary>
        /// <param name="xWp">The x wp.</param>
        /// <param name="properties">The properties.</param>
        private static void SetWebPartProperties(WebPart xWp, Hashtable properties)
        {
            if (properties == null)
            {
                return;
            }

            foreach (string prop in properties.Keys)
            {
                try
                {
                    object val = properties[prop];
                    if (xWp is Microsoft.SharePoint.WebPartPages.WebPart)
                    {
                        if (prop == "Width")
                        {
                            ((Microsoft.SharePoint.WebPartPages.WebPart)xWp).Width = val.ToString();
                            return;
                        }
                        if (prop == "Height")
                        {
                            ((Microsoft.SharePoint.WebPartPages.WebPart)xWp).Height = val.ToString();
                            return;
                        }
                    }
                    PropertyInfo propInfo = xWp.GetType().GetProperty(prop);
                    if (propInfo == null)
                    {
                        throw new SPException(string.Format("Unable to set property '{0}'.  The property could not be found.", prop));
                    }

                    val = Convert.ChangeType(val, propInfo.PropertyType);
                    if (val == null)
                    {
                        throw new SPException(string.Format("Unable to convert '{0}' to type '{1}'", properties[prop], propInfo.PropertyType));
                    }

#if MOSS
                    if (xWp is KPIListWebPart && prop == "TitleUrl")
                    {
                        if (val.ToString().Contains("://"))
                        {
                            val = Utilities.GetServerRelUrlFromFullUrl((string)val);
                        }
                    }
                    if (xWp is KPIListWebPart && prop == "ListURL")
                    {
                        if (val.ToString().Contains("://"))
                        {
                            val = Utilities.GetServerRelUrlFromFullUrl((string)val);
                        }

                        Utilities.SetFieldValue(xWp, typeof(KPIListWebPart), "listUrl", val);
                        Utilities.SetFieldValue(xWp, typeof(KPIListWebPart), "spList", null);
                        continue;
                    }
#endif

                    propInfo.SetValue(xWp, val, null);
                }
                catch (Exception ex)
                {
                    throw new SPException(string.Format("Error setting property value {0} to {1}:\r\n{2}", prop, properties[prop], Utilities.FormatException(ex)));
                }
            }
        }
        /// <summary>
        /// Sets the web part properties.
        /// </summary>
        /// <param name="xWp">The x wp.</param>
        /// <param name="properties">The properties.</param>
        private static void SetWebPartProperties(WebPart xWp, Hashtable properties)
        {
            if (properties == null)
                return;

            foreach (string prop in properties.Keys)
            {
                try
                {
                    object val = properties[prop];
                    if (xWp is Microsoft.SharePoint.WebPartPages.WebPart)
                    {
                        if (prop == "Width")
                        {
                            ((Microsoft.SharePoint.WebPartPages.WebPart)xWp).Width = val.ToString();
                            return;
                        }
                        if (prop == "Height")
                        {
                            ((Microsoft.SharePoint.WebPartPages.WebPart)xWp).Height = val.ToString();
                            return;
                        }
                    }
                    PropertyInfo propInfo = xWp.GetType().GetProperty(prop);
                    if (propInfo == null)
                        throw new SPException(string.Format("Unable to set property '{0}'.  The property could not be found.", prop));

                    val = Convert.ChangeType(val, propInfo.PropertyType);
                    if (val == null)
                        throw new SPException(string.Format("Unable to convert '{0}' to type '{1}'", properties[prop], propInfo.PropertyType));

            #if MOSS
                    if (xWp is KPIListWebPart && prop == "TitleUrl")
                    {
                        if (val.ToString().Contains("://"))
                            val = Utilities.GetServerRelUrlFromFullUrl((string)val);
                    }
                    if (xWp is KPIListWebPart && prop == "ListURL")
                    {
                        if (val.ToString().Contains("://"))
                            val = Utilities.GetServerRelUrlFromFullUrl((string)val);

                        Utilities.SetFieldValue(xWp, typeof(KPIListWebPart), "listUrl", val);
                        Utilities.SetFieldValue(xWp, typeof(KPIListWebPart), "spList", null);
                        continue;
                    }
            #endif

                    propInfo.SetValue(xWp, val, null);
                }
                catch (Exception ex)
                {
                    throw new SPException(string.Format("Error setting property value {0} to {1}:\r\n{2}", prop, properties[prop], Utilities.FormatException(ex)));
                }
            }
        }
Example #22
0
 public override void ExportWebPart(WebPart webPart, XmlWriter writer)
 {
     if (webPart is IConfigurableWebPart)
     {
         writer.WriteStartElement("webPart");
         writer.WriteAttributeString("type", SerializationServices.ShortAssemblyQualifiedName(webPart.GetType().AssemblyQualifiedName));
         IConfiguration config = (webPart as IConfigurableWebPart).Configuration;
         SerializationServices.Serialize(config, writer);
         writer.WriteEndElement();
     }
     else
     {
         base.ExportWebPart(webPart, writer);
     }
 }
Example #23
0
        protected virtual void ProcessWebpartCustomProperties(WebPart instance, WebPartDefinition definition)
        {
            if (definition.Properties != null && definition.Properties.Count > 0)
            {
                var wpType = instance.GetType();

                foreach (var prop in definition.Properties)
                {
                    var isCdata = prop.IsCData.HasValue && prop.IsCData.Value;

                    if (ReflectionUtils.HasProperty(instance, prop.Name))
                    {
                        var wpProp = wpType.GetProperty(prop.Name);
                        var wpPropType = wpProp.PropertyType;

                        var targetValue = Convert.ChangeType(prop.Value, wpPropType);

                        wpProp.SetValue(instance, targetValue, null);
                    }
                }
            }
        }
        public static void GetFilterInfo(IDictionary inst, string schemaName, ref string clickScript, System.Web.UI.WebControls.WebParts.WebPart webPart, Page page, ref bool includeFilters, ref string fj, ref List <KeyValuePair <string, KeyValuePair <List <KeyValuePair <string, CamlOperator> >, bool> > > effectiveFilters)
        {
            SPWebPartManager currentWebPartManager = null;

            System.Web.UI.WebControls.WebParts.WebPart part = null;
            IList           list  = null;
            List <string>   list2 = new List <string>();
            List <object[]> list3 = new List <object[]>();

            includeFilters = false;
            string filterCaml = "";

            if (inst["filter"] != null)
            {
                try
                {
                    includeFilters = (bool)inst["filter"];
                }
                catch
                {
                    includeFilters = false;
                }
            }
            if (includeFilters && !IsLic(2))
            {
                includeFilters = false;
                clickScript    = "alert('" + SPEncode.ScriptEncode(ProductPage.GetResource("NopeEd", new object[] { ProductPage.GetProductResource("PC_" + schemaName + "_filter", new object[0]), "Basic" })) + "');";
            }
            if (includeFilters && (effectiveFilters == null))
            {
                effectiveFilters = new List <KeyValuePair <string, KeyValuePair <List <KeyValuePair <string, CamlOperator> >, bool> > >();
                try
                {
                    currentWebPartManager = WebPartManager.GetCurrentWebPartManager(page) as SPWebPartManager;
                }
                catch
                {
                }
                if ((webPart != null) && (currentWebPartManager != null))
                {
                    foreach (System.Web.UI.WebControls.WebParts.WebPart part2 in ProductPage.TryEach <System.Web.UI.WebControls.WebParts.WebPart>(currentWebPartManager.WebParts))
                    {
                        if (part2.GetType().AssemblyQualifiedName == "roxority_FilterZen.roxority_FilterWebPart, roxority_FilterZen, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a2103dd0c3e898e1")
                        {
                            foreach (System.Web.UI.WebControls.WebParts.WebPart part3 in ((getConnPartMethod == null) ? (getConnPartMethod = part2.GetType().GetMethod("GetConnectedParts", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, System.Type.EmptyTypes, null)) : getConnPartMethod).Invoke(part2, null) as IEnumerable <System.Web.UI.WebControls.WebParts.WebPart> )
                            {
                                if (part3.ID.Equals(webPart.ID))
                                {
                                    part = part2;
                                    break;
                                }
                            }
                        }
                        if (part != null)
                        {
                            break;
                        }
                    }
                }
                if (part != null)
                {
                    try
                    {
                        if (!((bool)part.GetType().GetMethod("LicEd", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(part, new object[] { 2 })))
                        {
                            clickScript = "alert('" + SPEncode.ScriptEncode(ProductPage.GetProductResource("Old_NoFilterZenEnt", new object[0])) + "');";
                            part        = null;
                        }
                    }
                    catch
                    {
                        clickScript = "alert('" + SPEncode.ScriptEncode(ProductPage.GetProductResource("Old_NoFilterZenEnt", new object[0])) + "');";
                        part        = null;
                    }
                }
                fj = string.Empty;
                if (part != null)
                {
                    try
                    {
                        filterCaml = ((roxority_FilterZen.roxority_FilterWebPart)(part)).GeneratedQuery;
                        list       = ((partFiltersProp == null) ? (partFiltersProp = part.GetType().GetProperty("PartFilters", BindingFlags.Public | BindingFlags.Instance)) : partFiltersProp).GetValue(part, null) as IList;
                        fj         = ((partJsonProp == null) ? (partJsonProp = part.GetType().GetProperty("JsonFilters", BindingFlags.Public | BindingFlags.Instance)) : partJsonProp).GetValue(part, null) as string;
                        list2.AddRange(((string)((camlAndProp == null) ? (camlAndProp = part.GetType().GetProperty("CamlFiltersAndCombined", BindingFlags.Public | BindingFlags.Instance)) : camlAndProp).GetValue(part, null)).Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
                    }
                    catch
                    {
                    }
                    if (list != null)
                    {
                        foreach (object obj3 in list)
                        {
                            if (kvpValProp == null)
                            {
                                kvpValProp = obj3.GetType().GetProperty("Value", BindingFlags.Public | BindingFlags.Instance);
                            }
                            object obj2 = kvpValProp.GetValue(obj3, null);
                            if (obj2 != null)
                            {
                                if (fpKeyProp == null)
                                {
                                    fpKeyProp = obj2.GetType().GetProperty("Key", BindingFlags.Public | BindingFlags.Instance);
                                }
                                if (fpValProp == null)
                                {
                                    fpValProp = obj2.GetType().GetProperty("Value", BindingFlags.Public | BindingFlags.Instance);
                                }
                                if (fpOpProp == null)
                                {
                                    fpOpProp = obj2.GetType().GetProperty("CamlOperator", BindingFlags.Public | BindingFlags.Instance);
                                }
                                list3.Add(new object[] { fpKeyProp.GetValue(obj2, null), fpValProp.GetValue(obj2, null), (CamlOperator)Enum.Parse(typeof(CamlOperator), fpOpProp.GetValue(obj2, null).ToString(), true) });
                            }
                        }
                    }
                    foreach (object[] objArray in list3)
                    {
                        int num2;
                        KeyValuePair <string, KeyValuePair <List <KeyValuePair <string, CamlOperator> >, bool> > item = new KeyValuePair <string, KeyValuePair <List <KeyValuePair <string, CamlOperator> >, bool> >(objArray[0] as string, new KeyValuePair <List <KeyValuePair <string, CamlOperator> >, bool>(new List <KeyValuePair <string, CamlOperator> >(), list2.Contains(objArray[0] as string)));
                        int num = num2 = -1;
                        foreach (KeyValuePair <string, KeyValuePair <List <KeyValuePair <string, CamlOperator> >, bool> > pair2 in effectiveFilters)
                        {
                            num2++;
                            if (pair2.Key == item.Key)
                            {
                                num  = num2;
                                item = pair2;
                                break;
                            }
                        }
                        item.Value.Key.Add(new KeyValuePair <string, CamlOperator>(objArray[1] as string, (CamlOperator)objArray[2]));
                        if (num >= 0)
                        {
                            effectiveFilters[num] = item;
                        }
                        else
                        {
                            effectiveFilters.Add(item);
                        }
                    }
                }
            }
            fj += "((((((" + filterCaml + "))))))";
        }
        // Extracts the personalization state from webPartA, and applies it to webPartB.
        // Assumes that webPartA and webPartB are the same type.  If the WebParts are GenericWebParts,
        // then copies the personalization state from the ChildControl of webPartA to the
        // ChildControl of webPartB.
        protected internal virtual void CopyPersonalizationState(WebPart webPartA, WebPart webPartB) {
            if (webPartA == null) {
                throw new ArgumentNullException("webPartA");
            }
            if (webPartB == null) {
                throw new ArgumentNullException("webPartB");
            }
            if (webPartA.GetType() != webPartB.GetType()) {
                throw new ArgumentException(SR.GetString(SR.WebPartPersonalization_SameType, "webPartA", "webPartB"));
            }

            CopyPersonalizationState((Control)webPartA, (Control)webPartB);

            GenericWebPart genericWebPartA = webPartA as GenericWebPart;
            GenericWebPart genericWebPartB = webPartB as GenericWebPart;
            // Assert that the GenericWebParts are either both null or both non-null
            Debug.Assert((genericWebPartA == null) == (genericWebPartB == null));
            if (genericWebPartA != null && genericWebPartB != null) {
                Control childControlA = genericWebPartA.ChildControl;
                Control childControlB = genericWebPartB.ChildControl;

                if (childControlA == null) {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "ChildControl"), "webPartA");
                }
                if (childControlB == null) {
                    throw new ArgumentException(SR.GetString(SR.PropertyCannotBeNull, "ChildControl"), "webPartB");
                }
                if (childControlA.GetType() != childControlB.GetType()) {
                    throw new ArgumentException(SR.GetString(SR.WebPartPersonalization_SameType, "webPartA.ChildControl", "webPartB.ChildControl"));
                }

                CopyPersonalizationState(childControlA, childControlB);
            }

            // IPersonalizable.IsDirty should always be false on the new WebPart, since the only data
            // on the new WebPart was loaded via personalization, which should not cause the control
            // to be dirty.  However, we want to save the IPersonalizable data on this request, so
            // we call SetDirty() to force the IPersonalizable data to be saved.
            SetDirty(webPartB);
        }
 protected virtual WebPart CopyWebPart(WebPart webPart)
 {
     WebPart part;
     GenericWebPart part2 = webPart as GenericWebPart;
     if (part2 != null)
     {
         Control childControl = part2.ChildControl;
         this.VerifyType(childControl);
         Type type = childControl.GetType();
         Control control = (Control) this.Internals.CreateObjectFromType(type);
         control.ID = this.CreateDynamicWebPartID(type);
         part = this.CreateWebPart(control);
     }
     else
     {
         this.VerifyType(webPart);
         part = (WebPart) this.Internals.CreateObjectFromType(webPart.GetType());
     }
     part.ID = this.CreateDynamicWebPartID(webPart.GetType());
     return part;
 }
        // Returns a copy of the WebPart, with all the properties reset to their default value.
        // If the WebPart is a GenericWebPart, returns a copy of the GenericWebPart and a copy of the
        // ChildControl inside the GenericWebPart.  The ID of the new WebPart and ChildControl should
        // be set to a value obtained from CreateDynamicWebPartID.
        // Virtual because a derived WebPartManager will deserialize a WebPart from XML in this method.
        protected virtual WebPart CopyWebPart(WebPart webPart) {
            WebPart newWebPart;

            GenericWebPart genericWebPart = webPart as GenericWebPart;
            if (genericWebPart != null) {
                Control childControl = genericWebPart.ChildControl;
                VerifyType(childControl);
                Type childControlType = childControl.GetType();
                Control newChildControl = (Control)Internals.CreateObjectFromType(childControlType);
                newChildControl.ID = CreateDynamicWebPartID(childControlType);

                newWebPart = CreateWebPart(newChildControl);
            }
            else {
                VerifyType(webPart);
                newWebPart = (WebPart)Internals.CreateObjectFromType(webPart.GetType());
            }

            newWebPart.ID = CreateDynamicWebPartID(webPart.GetType());

            return newWebPart;
        }
        public bool IsAuthorized(WebPart webPart) {
            if (webPart == null) {
                throw new ArgumentNullException("webPart");
            }

            // Do not check that Controls.Contains(webPart), since this will be called on a WebPart
            // before it is added to the Controls collection.

            // Calculate authorizationFilter from property value and personalization data
            string authorizationFilter = webPart.AuthorizationFilter;

            // webPart.ID will be null for imported WebParts.  Also, a user may want to call
            // this method on a WebPart before it has an ID.
            string webPartID = webPart.ID;
            if (!String.IsNullOrEmpty(webPartID) && Personalization.IsEnabled) {
                string personalizedAuthorizationFilter = Personalization.GetAuthorizationFilter(webPart.ID);
                if (personalizedAuthorizationFilter != null) {
                    authorizationFilter = personalizedAuthorizationFilter;
                }
            }

            GenericWebPart genericWebPart = webPart as GenericWebPart;
            if (genericWebPart != null) {
                Type childType = null;
                string childPath = null;

                Control childControl = genericWebPart.ChildControl;
                UserControl childUserControl = childControl as UserControl;
                if (childUserControl != null) {
                    childType = typeof(UserControl);
                    childPath = childUserControl.AppRelativeVirtualPath;
                }
                else {
                    childType = childControl.GetType();
                }

                // Only authorize the type/path of the child control
                // Don't need to authorize the GenericWebPart as well
                return IsAuthorized(childType, childPath, authorizationFilter, webPart.IsShared);
            }
            else {
                return IsAuthorized(webPart.GetType(), null, authorizationFilter, webPart.IsShared);
            }
        }
 public bool IsAuthorized(WebPart webPart)
 {
     if (webPart == null)
     {
         throw new ArgumentNullException("webPart");
     }
     string authorizationFilter = webPart.AuthorizationFilter;
     if (!string.IsNullOrEmpty(webPart.ID) && this.Personalization.IsEnabled)
     {
         string str3 = this.Personalization.GetAuthorizationFilter(webPart.ID);
         if (str3 != null)
         {
             authorizationFilter = str3;
         }
     }
     GenericWebPart part = webPart as GenericWebPart;
     if (part == null)
     {
         return this.IsAuthorized(webPart.GetType(), null, authorizationFilter, webPart.IsShared);
     }
     Type type = null;
     string path = null;
     Control childControl = part.ChildControl;
     UserControl control2 = childControl as UserControl;
     if (control2 != null)
     {
         type = typeof(UserControl);
         path = control2.AppRelativeVirtualPath;
     }
     else
     {
         type = childControl.GetType();
     }
     return this.IsAuthorized(type, path, authorizationFilter, webPart.IsShared);
 }
Example #30
0
        public List <WebPartToDisplay> GetAllWebPartsOnPage(SPWeb web, string pageUrl, bool includeSharePointWebParts, bool includeCustomWebParts)
        {
            if (web == null)
            {
                return(new List <WebPartToDisplay>());
            }
            if (string.IsNullOrEmpty(pageUrl))
            {
                return(new List <WebPartToDisplay>());
            }

            bool isContextNull = false;

            if (HttpContext.Current == null)
            {
                isContextNull = true;
                HttpRequest request = new HttpRequest(string.Empty, web.Url, string.Empty);
                HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
                HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
            }

            List <WebPartToDisplay> allWebParts = new List <WebPartToDisplay>();

            using (SPLimitedWebPartManager webpartManager = web.GetFile(pageUrl).GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                foreach (object webpartObject in webpartManager.WebParts)
                {
                    try
                    {
                        WebPartToDisplay webpartToDisplay = new WebPartToDisplay();
                        if (webpartObject is Microsoft.SharePoint.WebPartPages.WebPart)
                        {
                            // This is a SharePoint web part
                            Microsoft.SharePoint.WebPartPages.WebPart sharepointWebPart = webpartObject as Microsoft.SharePoint.WebPartPages.WebPart;
                            webpartToDisplay.Title       = sharepointWebPart.Title;
                            webpartToDisplay.Description = sharepointWebPart.Description;
                            webpartToDisplay.Type        = sharepointWebPart.GetType().ToString();
                            webpartToDisplay.Zone        = sharepointWebPart.ZoneID;
                            webpartToDisplay.PageUrl     = web.Url + "/" + pageUrl;
                            webpartToDisplay.Visible     = sharepointWebPart.Visible;
                            webpartToDisplay.Category    = GetWebPartCategory(webpartToDisplay.Type);
                        }
                        else if (webpartObject is System.Web.UI.WebControls.WebParts.WebPart)
                        {
                            // This is a ASP.NET web part
                            System.Web.UI.WebControls.WebParts.WebPart aspnetWebPart = webpartObject as System.Web.UI.WebControls.WebParts.WebPart;
                            webpartToDisplay.Title       = aspnetWebPart.Title;
                            webpartToDisplay.Description = aspnetWebPart.Description;
                            webpartToDisplay.Type        = aspnetWebPart.GetType().ToString();
                            webpartToDisplay.Zone        = webpartManager.GetZoneID(aspnetWebPart);
                            webpartToDisplay.PageUrl     = web.Url + "/" + pageUrl;
                            webpartToDisplay.Visible     = aspnetWebPart.Visible;
                            webpartToDisplay.Category    = GetWebPartCategory(webpartToDisplay.Type);
                        }

                        if (webpartToDisplay.Category == WebPartCategory.SharePoint && !includeSharePointWebParts)
                        {
                            continue;
                        }
                        if (webpartToDisplay.Category == WebPartCategory.Custom && !includeCustomWebParts)
                        {
                            continue;
                        }

                        allWebParts.Add(webpartToDisplay);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        if (isContextNull)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
                webpartManager.Dispose();
            }

            if (isContextNull)
            {
                HttpContext.Current = null;
            }

            return(allWebParts);
        }