예제 #1
0
        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (var site = (SPSite)properties.Feature.Parent)
            {
                using (var web = site.RootWeb)
                {
                    try
                    {
                        //web.AllowUnsafeUpdates = true;
                        SPLimitedWebPartManager webPartManager =
                            web.GetLimitedWebPartManager("LPWebPages/CompanyCalendar.aspx", PersonalizationScope.Shared);

                        //Retrive the webpart and remove
                        IList <WebPart> listFormWebParts = (from wp in webPartManager.WebParts.Cast <WebPart>()
                                                            where string.Compare(wp.Title, "Company Calendar", true) == 0
                                                            select wp).ToList();

                        //Check if there are any web parts found
                        if (listFormWebParts != null && listFormWebParts.Count > 0)
                        {
                            foreach (WebPart listFormWebPart in listFormWebParts)
                            {
                                webPartManager.DeleteWebPart(listFormWebPart);
                                web.Update();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("LPWeb", TraceSeverity.Unexpected, EventSeverity.Error),
                                                              TraceSeverity.Unexpected, string.Format("LPWebPages.LPWebPagesEventReceiver.FeatureDeactivating error: {0}", ex.Message), ex.StackTrace);
                    }
                }
            }
        }
예제 #2
0
        private void btn_DeleteWPinPage_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb(webUrl))
                {
                    SPFile thePage = web.GetFile(pageUrl);
                    SPLimitedWebPartManager    theWebPartManager = thePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    SPLimitedWebPartCollection webParts          = theWebPartManager.WebParts;
                    int Num = webParts.Count;
                    //foreach( System.Web.UI.WebControls.WebParts.WebPart wp inwebParts
                    for (int i = Num - 1; i >= 0; i--)
                    {
                        System.Web.UI.WebControls.WebParts.WebPart wp = webParts[i];
                        for (int j = 0; j < clBox_WebParts.Items.Count; j++)
                        {
                            if ((clBox_WebParts.GetItemChecked(j)) && (clBox_WebParts.Items[j].ToString() == wp.DisplayTitle))
                            {
                                theWebPartManager.DeleteWebPart(wp);
                                tb_Message.Text += clBox_WebParts.Items[j].ToString() + "Delete in Page Success...";
                            }
                        }
                    }

                    clBox_WebParts.Items.Clear();
                    for (int i = 0; i < webParts.Count; i++)
                    {
                        clBox_WebParts.Items.Add(webParts[i].DisplayTitle);
                    }
                }
            }
        }
        private static void AddWebParts(SPFeatureReceiverProperties properties, string url, System.Web.UI.WebControls.WebParts.WebPart[] webPart, string[] zones)
        {
            SPWeb  web  = (SPWeb)properties.Feature.Parent;
            SPFile file = web.GetFile(url);
            SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
            int index = 2;

            while (manager.WebParts.Count > 0)
            {
                manager.DeleteWebPart(manager.WebParts[0]);
            }

            for (int i = 0; i < webPart.Length; i++)
            {
                manager.AddWebPart(webPart[i], zones[i], index);
                index += 2;
            }

            file.Update();

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

            manager.Dispose();
        }
        public static void DeleteAllThenAddWebPartToPage(SPFile page, string wpXml, string wpZone)
        {
            using (SPLimitedWebPartManager wpMgr = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
            {
                // Delete all web parts
                // Play the shell game because you can't delete from a collection in an enumerator
                List <WebPart> wpList = new List <WebPart>();
                foreach (WebPart wp in wpMgr.WebParts)
                {
                    wpList.Add(wp);
                }
                foreach (WebPart wp in wpList)
                {
                    wpMgr.DeleteWebPart(wp);
                }

                // Add our new web part
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(wpXml);
                using (XmlNodeReader reader = new XmlNodeReader(doc))
                {
                    string errorMessage = null;
                    System.Web.UI.WebControls.WebParts.WebPart wp = wpMgr.ImportWebPart(reader, out errorMessage);
                    wpMgr.AddWebPart(wp, wpZone, wp.ZoneIndex);
                }
            }
        }
        public void DeleteWebPart(SPWebPartInstance webPart)
        {
            if (webPart == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A web part must be supplied as the first argument.");
            }

            m_limitedWebPartManager.DeleteWebPart(webPart.WebPart);
        }
        private static void DeleteAllWebParts(string destinationPageUrlServerRelative, SPWeb destinationPageWeb, string sourcePageUrlServerRelative, SPWeb sourcePageWeb, bool shouldOverwriteDestinationWebParts)
        {
            SPWeb web  = null;
            SPWeb web2 = null;

            try
            {
                SPLimitedWebPartManager limitedWebPartManager = destinationPageWeb.GetLimitedWebPartManager(destinationPageUrlServerRelative, PersonalizationScope.Shared);
                SPLimitedWebPartManager manager2 = sourcePageWeb.GetLimitedWebPartManager(sourcePageUrlServerRelative, PersonalizationScope.Shared);
                web2 = limitedWebPartManager.Web;
                web  = manager2.Web;
                SPLimitedWebPartCollection webParts = manager2.WebParts;
                SPLimitedWebPartCollection parts2   = limitedWebPartManager.WebParts;
                if (shouldOverwriteDestinationWebParts && (parts2 != null))
                {
                    while (parts2.Count > 0)
                    {
                        try
                        {
                            limitedWebPartManager.DeleteWebPart(parts2[0]);
                            continue;
                        }
                        catch (WebPartPageUserException)
                        {
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (HttpContext.Current != null)
                {
                    throw;
                }
            }
            finally
            {
                if ((web != sourcePageWeb) && (web != null))
                {
                    web.Close();
                }
                if ((web2 != destinationPageWeb) && (web2 != null))
                {
                    web2.Close();
                }
            }
        }
        private static void CheckifExists(SPLimitedWebPartManager webpartMgr, string webPartTitle)
        {
            List<System.Web.UI.WebControls.WebParts.WebPart> toRemove = new List<System.Web.UI.WebControls.WebParts.WebPart>();
            foreach (System.Web.UI.WebControls.WebParts.WebPart part in webpartMgr.WebParts)
            {

                if (part.Title == webPartTitle)
                {
                    toRemove.Add(part);
                }

            }

            foreach (var item in toRemove)
            {
                webpartMgr.DeleteWebPart(item);
            }
        }
예제 #8
0
    /// <summary> 
    /// Provisions the document set. 
    /// </summary> 
    /// <param name="contentType">Type of the content.</param> 
    private void ProvisionDocumentSet(SPContentType contentType)
    {
            ProvisionEventHandler(contentType);
      SPFile file = ProvisionWelcomePage(contentType);
            using (SPLimitedWebPartManager manager = GetWelcomePageWebPartmanager(file))
      {
                if (EnsureWebParts)
        {
          if (manager.WebParts != null)
          {
            List<WebPart> webParts = new List<WebPart>(manager.WebParts.Cast<WebPart>());
            foreach (WebPart webPart in webParts)
            {
              manager.DeleteWebPart(webPart);
            }
          }
        }

                ProvisionWebParts(manager);
      }
    }
        protected void setUpList(int baseId)
        {
            string siteUrl         = SPContext.Current.Web.Url;
            SPSite oSiteCollection = SPContext.Current.Site;

            oList = SPContext.Current.Web.Lists["Alerts Noticeboard"];
            SPWeb web = SPContext.Current.Web;


            web.AllowUnsafeUpdates = true;
            string pageUrl = "SitePages/managealerts.aspx";
            SPFile page    = web.GetFile(pageUrl);
            SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
            Guid   storageKey             = Guid.NewGuid();
            string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));



            SPLimitedWebPartCollection WebParts = wpmgr.WebParts;



            XsltListViewWebPart xwp = new XsltListViewWebPart();



            //SPViewCollection viewsCol = oList.Views;

            xwp.ID       = wpId;
            xwp.ListName = oList.ID.ToString("B").ToUpper();



            wpmgr.AddWebPart(xwp, "WebPartZone1", 0);
            if (WebParts.Count > 1)
            {
                wpmgr.DeleteWebPart(xwp);
            }
        }
예제 #10
0
        private string ClearWebParts(SPLimitedWebPartManager webPartManager)
        {
            string zoneId      = "Bottom";
            var    webPartList = new List <System.Web.UI.WebControls.WebParts.WebPart>();

            foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in webPartManager.WebParts)
            {
                webPartList.Add(webpart);
            }

            if (webPartList.Any())
            {
                // take any of the webpart zones Id
                zoneId = webPartManager.GetZoneID(webPartList[0]);

                foreach (var webpart in webPartList)
                {
                    webPartManager.DeleteWebPart(webpart);
                }
            }
            return(zoneId);
        }
        private static void ConnectWebParts(SPFeatureReceiverProperties properties, string url, System.Web.UI.WebControls.WebParts.WebPart provider,
                                            System.Web.UI.WebControls.WebParts.WebPart[] consumer)
        {
            SPWeb  web  = (SPWeb)properties.Feature.Parent;
            SPFile file = web.GetFile(url);
            SPLimitedWebPartManager manager       = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ProviderConnectionPoint providerPoint = null;
            ConsumerConnectionPoint consumerPoint = null;
            int index = 6;

            while (manager.WebParts.Count > 0)
            {
                manager.DeleteWebPart(manager.WebParts[0]);
            }

            manager.AddWebPart(consumer[0], "MiddleColumn", 2);
            manager.AddWebPart(provider, "MiddleColumn", 4);

            for (int i = 1; i < consumer.Length; i++)
            {
                System.Web.UI.WebControls.WebParts.WebPart webpart = consumer[i];

                manager.AddWebPart(webpart, "MiddleColumn", index);
                index += 2;
            }

            providerPoint = manager.GetProviderConnectionPoints(provider)[0];
            consumerPoint = manager.GetConsumerConnectionPoints(consumer[0])[0];
            manager.SPConnectWebParts(provider, providerPoint, consumer[0], consumerPoint);
            file.Update();

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

            manager.Dispose();
        }
 public static void DeleteAllWebPartOfType <T>(SPWeb web) where T : WebPart
 {
     foreach (var list in web.Lists.Cast <SPList>().Where(list => !list.Hidden))
     {
         foreach (var view in list.Views.Cast <SPView>().Where(v => !v.PersonalView))
         {
             try
             {
                 using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(view.Url, PersonalizationScope.Shared))
                 {
                     var webpartsToDelete = manager.WebParts.OfType <T>().ToArray();
                     for (int i = webpartsToDelete.Length; i != 0; i--)
                     {
                         manager.DeleteWebPart(webpartsToDelete[i - 1]);
                     }
                 }
             }
             catch (Exception ex)
             {
                 Logger.WriteError(string.Format("Ошибка при попытке удалить вебчать из списка: '{0}', из представления: '{1}'", list.RootFolder.Url, view.Url), ex);
             }
         }
     }
 }
        /// <summary>
        /// Adds the web part.
        /// </summary>
        /// <param name="file">The page.</param>
        /// <param name="webPartXml">The web part XML file.</param>
        /// <param name="webPartTitle">The web part title.</param>
        /// <param name="zone">The zone.</param>
        /// <param name="zoneId">The zone id.</param>
        /// <param name="deleteWebPart">if set to <c>true</c> [delete web part].</param>
        /// <param name="customReplaceText">The custom replace text.</param>
        /// <param name="chromeType">Type of the chrome.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <returns></returns>
        public WebPart AddWebPart(SPFile file, string webPartXml, string assembly, string typeName, string webPartTitle, string zone, int zoneId, bool deleteWebPart, Hashtable customReplaceText, PartChromeType chromeType, bool publish)
        {
            bool cleanupContext = false;
            bool checkBackIn    = false;

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

            if (HttpContext.Current == null)
            {
                cleanupContext = true;
                HttpRequest httpRequest = new HttpRequest("", file.Item.ParentList.ParentWeb.Url, "");
                HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                SPControl.SetContextWeb(HttpContext.Current, file.Item.ParentList.ParentWeb);
            }

            string url = file.Item.ParentList.ParentWeb.Site.MakeFullUrl(file.ServerRelativeUrl);

            using (SPLimitedWebPartManager manager = file.Item.ParentList.ParentWeb.GetLimitedWebPartManager(url, PersonalizationScope.Shared))
            {
                try
                {
                    WebPart wp;
                    if (!string.IsNullOrEmpty(webPartXml))
                    {
                        wp = AddWebPart(manager, file, webPartXml, customReplaceText);
                    }
                    else
                    {
                        wp = AddWebPart(assembly, typeName);
                    }

                    if (!string.IsNullOrEmpty(webPartTitle))
                    {
                        wp.Title = webPartTitle;
                    }
                    webPartTitle  = wp.Title;
                    wp.ChromeType = chromeType;

                    // Delete existing web part with same title so that we only have the latest version on the page
                    foreach (WebPart wpTemp in manager.WebParts)
                    {
                        try
                        {
                            if (wpTemp.Title == wp.Title)
                            {
                                if (deleteWebPart)
                                {
                                    manager.DeleteWebPart(wpTemp);
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                        finally
                        {
                            wpTemp.Dispose();
                        }
                    }

                    try
                    {
                        manager.AddWebPart(wp, zone, zoneId);
                    }
                    catch (Exception)
                    {
                        System.Net.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 = System.Net.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(wp, xmlWriter);
                                xmlWriter.Flush();

                                svc.AddWebPartToZone(url, sb.ToString(), WebPartPagesWebService.Storage.Shared, zone, zoneId);
                            }
                            catch (System.Web.Services.Protocols.SoapException ex)
                            {
                                throw new Exception(ex.Detail.OuterXml);
                            }
                        }
                    }
                    return(wp);
                }
                finally
                {
                    if (cleanupContext)
                    {
                        HttpContext.Current = null;
                    }
                    if (manager != null)
                    {
                        manager.Web.Dispose();
                        manager.Dispose();
                    }

                    if (file.InDocumentLibrary && Utilities.IsCheckedOut(file.Item) && (checkBackIn || publish))
                    {
                        file.CheckIn("Checking in changes to page due to new web part being added: " + webPartTitle);
                    }

                    if (publish && file.InDocumentLibrary && file.Item.ParentList.EnableMinorVersions)
                    {
                        try
                        {
                            file.Publish("Publishing changes to page due to new web part being added: " + webPartTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page due to new web part being added: " + webPartTitle);
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteWarning("Unable to publish or approve file: " + ex.Message);
                        }
                    }
                }
            }
        }
예제 #14
0
        internal static void SetWebPart(string url, SetWebPartStateAction action, string webPartId, string webPartTitle, string webPartZone, string webPartZoneIndex, Hashtable props, bool publish)
        {
            using (SPSite site = new SPSite(url))
                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(url);

                        // 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)
                        {
                            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.
                            }
                        }

                        string  displayTitle            = string.Empty;
                        WebPart wp                      = null;
                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            if (!string.IsNullOrEmpty(webPartId))
                            {
                                wp = Utilities.GetWebPartById(web, url, webPartId, out manager);
                            }
                            else
                            {
                                wp = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                                if (wp == null)
                                {
                                    throw new SPException(
                                              "Unable to find specified web part using title \"" + webPartTitle + "\". Try specifying the -id parameter instead (use Get-SPWebPartList to get the ID)");
                                }
                            }

                            if (wp == null)
                            {
                                throw new SPException("Unable to find specified web part.");
                            }

                            // Set this so that we can add it to the check-in comment.
                            displayTitle = wp.DisplayTitle;

                            if (action == SetWebPartStateAction.Delete)
                            {
                                manager.DeleteWebPart(wp);
                            }
                            else if (action == SetWebPartStateAction.Close)
                            {
                                manager.CloseWebPart(wp);
                            }
                            else if (action == SetWebPartStateAction.Open)
                            {
                                manager.OpenWebPart(wp);
                            }


                            if (action != SetWebPartStateAction.Delete)
                            {
                                string zoneID    = manager.GetZoneID(wp);
                                int    zoneIndex = wp.ZoneIndex;

                                if (!string.IsNullOrEmpty(webPartZone))
                                {
                                    zoneID = webPartZone;
                                }
                                if (!string.IsNullOrEmpty(webPartZoneIndex))
                                {
                                    zoneIndex = int.Parse(webPartZoneIndex);
                                }

                                manager.MoveWebPart(wp, zoneID, zoneIndex);

                                if (props != null && props.Count > 0)
                                {
                                    SetWebPartProperties(wp, props);
                                }
                                manager.SaveChanges(wp);
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }
                            if (wp != null)
                            {
                                wp.Dispose();
                            }

                            if (checkIn)
                            {
                                file.CheckIn("Checking in changes to page due to state change of web part " + displayTitle);
                            }
                            if (publish && file.InDocumentLibrary)
                            {
                                PublishItems pi = new PublishItems();
                                pi.PublishListItem(file.Item, file.Item.ParentList, false, "Set-SPWebPart", "Checking in changes to page due to state change of web part " + displayTitle, null);
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
        internal static void RemoveFilterZen(bool flagsOnly, params string [] flags)
        {
            List <SPPersistedObject> objs             = new List <SPPersistedObject> (new SPPersistedObject [] { SPWebService.AdministrationService, SPWebService.ContentService, SPWebService.AdministrationService, SPWebService.ContentService.Farm });
            string centralAdminUrl                    = "http://your_central_administration";
            Action <SPPersistedObject> removeFlags    = null;
            Action <SPFolder>          removeWebParts = null;
            Action <SPWeb>             webAction      = delegate(SPWeb web) {
                Console.Title          = "... " + web.Title + " @ " + web.Url;
                web.AllowUnsafeUpdates = true;
                removeWebParts(web.RootFolder);
            };
            Action <SPSite> sitePreAction = delegate(SPSite site) {
                site.AllowUnsafeUpdates = true;
                Console.WriteLine("Detecting Filter Web Parts throughout " + site.Url);
            }, sitePostAction = delegate(SPSite site) {
                Console.Title = "... " + site.RootWeb.Title + " @ " + site.Url;
                if (config.DeactivateFeature)
                {
                    foreach (SPFeature feature in ProductPage.TryEach <SPFeature> (site.Features))
                    {
                        if (feature.Definition.DisplayName == "roxority_FilterWebPart")
                        {
                            try {
                                site.Features.Remove(feature.DefinitionId, true);
                                Console.WriteLine("Deactivated " + feature.Definition.DisplayName + " at " + site.Url);
                            } catch {
                                Console.WriteLine("Site Collection Feature " + feature.Definition.DisplayName + " could not be deactivated at " + site.Url + ". Manually deactivate this feature before proceeding.");
                            }
                        }
                    }
                }
            };

            removeWebParts = delegate(SPFolder folder) {
                SPLimitedWebPartManager webParts = null;
                SystemWebPart           wp;
                int wpCount;
                foreach (SPFile file in folder.Files)
                {
                    if (file.Url.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase))
                    {
                        wpCount = 0;
                        try {
                            webParts = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                        } catch {
                            webParts = null;
                        }
                        if (webParts != null)
                        {
                            for (int i = 0; i < webParts.WebParts.Count; i++)
                            {
                                try {
                                    wp = webParts.WebParts [i];
                                } catch {
                                    wp = null;
                                }
                                if ((wp != null) && wp.GetType().FullName.ToLowerInvariant().Contains("roxority_filterwebpart"))
                                {
                                    try {
                                        webParts.DeleteWebPart(wp);
                                        wpCount++;
                                        i--;
                                    } catch {
                                        Console.WriteLine("Filter Web Part(s) on " + ProductPage.MergeUrlPaths(folder.ParentWeb.Site.Url, file.Url) + " could not be deleted. Delete them manually before proceeding.");
                                    }
                                }
                            }
                        }
                        if (wpCount > 0)
                        {
                            try {
                                file.Update();
                                Console.WriteLine("...deleted " + wpCount + " Filter Web Part(s) from " + file.Name);
                            } catch {
                                Console.WriteLine("Filter Web Part(s) on " + ProductPage.MergeUrlPaths(folder.ParentWeb.Site.Url, file.Url) + " were deleted, but file could not be saved. Delete them manually before proceeding.");
                            }
                        }
                    }
                }
                foreach (SPFolder subFolder in folder.SubFolders)
                {
                    removeWebParts(subFolder);
                }
            };
#if DEBUG
            removeFlags = delegate(SPPersistedObject obj) {
                SPWebService     service = obj as SPWebService;
                SPWebApplication app     = obj as SPWebApplication;
                foreach (string f in flags)
                {
                    obj.Properties [obj.GetType().Name.Substring(2) + f] = null;
                    obj.Properties.Remove(obj.GetType().Name.Substring(2) + f);
                }
                obj.Update(true);
                if (service != null)
                {
                    foreach (SPWebApplication a in ProductPage.TryEach <SPWebApplication> (service.WebApplications))
                    {
                        removeFlags(a);
                    }
                }
            };
#endif
            Console.WriteLine("Initialization...");
            if (!flagsOnly)
            {
                foreach (SPPersistedObject obj in objs.ConvertAll <SPPersistedObject> (delegate(SPPersistedObject po) {
                    return(po);
                }))
                {
                    if (obj is SPWebService)
                    {
                        foreach (SPWebApplication app in ProductPage.TryEach <SPWebApplication> (((SPWebService)obj).WebApplications))
                        {
                            objs.Add(app);
                            if (app.IsAdministrationWebApplication)
                            {
                                centralAdminUrl = app.Sites [0].Url;
                            }
                        }
                    }
                }
            }
#if DEBUG
            Console.WriteLine("Removing product configuration flags from content database...");
            SPSecurity.RunWithElevatedPrivileges(delegate() {
                foreach (SPPersistedObject obj in objs)
                {
                    removeFlags(obj);
                }
            });
#endif
            if (!flagsOnly)
            {
                Iterate(config.WebUrls, objs, sitePreAction, webAction, sitePostAction);
            }
            Console.Title = "Done.";
            Console.WriteLine("\r\n\r\nThis tool has finished its jobs. Now scan the above messages for any instructions on manual actions required on your part. If any, perform them, THEN go to " + ProductPage.MergeUrlPaths(centralAdminUrl, "/_admin/Solutions.aspx") + " and manually first retract, THEN remove the FilterZen solution from the solution store, THEN press ENTER to exit.");
        }
예제 #16
0
        internal static void SetWebPart(string url, Type oldType, Type newType, string title, Hashtable properties, bool publish, bool test)
        {
            using (SPSite site = new SPSite(url))
                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(url);

                        // 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 = null;
                        try
                        {
                            List <WebPart> webParts = Utilities.GetWebPartsByType(web, url, oldType, out manager);
                            foreach (var oldWebPart in webParts)
                            {
                                if (oldWebPart.IsClosed)
                                {
                                    continue;
                                }

                                string wpTitle = oldWebPart.Title;
                                if (string.IsNullOrEmpty(wpTitle))
                                {
                                    wpTitle = oldWebPart.DisplayTitle;
                                }

                                if (!string.IsNullOrEmpty(title) &&
                                    (oldWebPart.DisplayTitle.ToLowerInvariant() != title.ToLowerInvariant() &&
                                     oldWebPart.Title.ToLowerInvariant() != title.ToLowerInvariant()))
                                {
                                    continue;
                                }
                                Logger.Write("Replacing web part \"{0}\"...", wpTitle);
                                string  zone       = manager.GetZoneID(oldWebPart);
                                WebPart newWebPart = (WebPart)Activator.CreateInstance(newType);
                                if (SetProperties(oldWebPart, newWebPart, properties))
                                {
                                    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 (SetProperties(oldWebPart, newWebPart, properties))
                                    {
                                        Logger.WriteWarning("Unable to set all properties for web part.");
                                    }
                                }
                                if (!test)
                                {
                                    manager.DeleteWebPart(oldWebPart);
                                }

                                try
                                {
                                    if (!test)
                                    {
                                        manager.AddWebPart(newWebPart, zone, oldWebPart.ZoneIndex);
                                    }
                                }
                                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(url, sb.ToString(), Storage.Shared, zone, oldWebPart.ZoneIndex);
                                        }
                                        catch (SoapException ex)
                                        {
                                            throw new Exception(ex.Detail.OuterXml);
                                        }
                                    }
                                }
                                finally
                                {
                                    oldWebPart.Dispose();
                                    newWebPart.Dispose();
                                }
                                if (zone == "wpz" && file.InDocumentLibrary)
                                {
                                    foreach (SPField field in file.Item.Fields)
                                    {
                                        if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking && file.Item[field.Id] != null)
                                        {
                                            string content = file.Item[field.Id].ToString();
                                            if (content.Contains(oldWebPart.ID.Replace("_", "-").Substring(2)))
                                            {
                                                Logger.Write("Replacing web part identifier in text field \"{0}\"...", field.InternalName);
                                                if (!test)
                                                {
                                                    file.Item[field.Id] = content.Replace(oldWebPart.ID.Replace("_", "-").Substring(2), newWebPart.ID.Replace("_", "-").Substring(2));
                                                    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, "Replace-SPWebPartType", "Checking in changes to page due to web part being replaced with a different type.", null);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }