Beispiel #1
0
        /// <summary>
        /// Provisions the web parts.
        /// </summary>
        /// <param name="manager">The manager.</param>
        protected virtual void ProvisionWebParts(SPLimitedWebPartManager manager)
        {
            // Guard
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            ImageWebPart webPart = new ImageWebPart {
                ImageLink = "/_layouts/images/docset_welcomepage_big.png"
            };

            manager.AddWebPart(webPart, "WebPartZone_TopLeft", 1);
            this.AddWebPart(manager, this.Web.Url + "/_catalogs/wp/documentsetproperties.dwp", "WebPartZone_Top", 2);
            this.AddWebPart(
                manager, this.Web.Url + "/_catalogs/wp/documentsetcontents.dwp", "WebPartZone_CenterMain", 2);
        }
Beispiel #2
0
        private static void AddListViewWebPartToPage(SPList sitesList, PublishingPage partnerSitesPage, SPFile partnerSitesPageFile)
        {
            ListViewWebPart listViewWebPart = new ListViewWebPart();

            listViewWebPart.ViewType   = ViewType.None;
            listViewWebPart.ListName   = sitesList.ID.ToString("B").ToUpper(CultureInfo.CurrentCulture);
            listViewWebPart.ViewGuid   = sitesList.Views[Constants.PartnerSitesView].ID.ToString("B").ToUpper(CultureInfo.CurrentCulture);
            listViewWebPart.Title      = Constants.PartnerSitesTile;
            listViewWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;

            SPLimitedWebPartManager webPartManager =
                partnerSitesPageFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

            webPartManager.AddWebPart(listViewWebPart, Constants.LeftColumnZone, 1);
            webPartManager.Web.Dispose();
            partnerSitesPage.CheckIn(Constants.CheckInComment);
        }
Beispiel #3
0
        public static string AddWebPartToPage(this SPWeb web, string webPartName, string pageUrl, string zoneId, int zoneIndex, Action <WebPart> action, out string errorMsg)
        {
            using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
            {
                using (WebPart webPart = CreateWebPart(web, webPartName, webPartManager, out errorMsg))
                {
                    webPartManager.AddWebPart(webPart, zoneId, zoneIndex);

                    if (action != null)
                    {
                        action(webPart);
                        webPartManager.SaveChanges(webPart);
                    }

                    return(webPart.ID);
                }
            }
        }
Beispiel #4
0
        private void AddWebPartToHome()
        {
            SPWeb  web  = SPContext.Current.Web;
            SPFile file = web.GetFile("SitePages/Home.aspx");

            using (SPLimitedWebPartManager webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                string zoneId = ClearWebParts(webPartManager);

                using (System.Web.UI.WebControls.WebParts.WebPart calculatorWebPart = GetWebPart(web, "AwesomeCalculator_CalculatorWebPart.webpart"))
                {
                    calculatorWebPart.ChromeType = PartChromeType.TitleOnly;
                    calculatorWebPart.Title      = "Calculator";
                    webPartManager.AddWebPart(calculatorWebPart, "Left", 1);
                    webPartManager.SaveChanges(calculatorWebPart);
                }
            }
        }
Beispiel #5
0
 private void AddGroupUsers(string pageUrl, string zoneId, string Title, string Description)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             using (SPSite sharepointSite = new SPSite(pageUrl))
             {
                 using (SPWeb sharepointWeb = sharepointSite.OpenWeb())
                 {
                     sharepointWeb.AllowUnsafeUpdates = true;
                     SPFile file = sharepointWeb.GetFile(pageUrl);
                     if (null != file)
                     {
                         using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                         {
                             if (null != mgr)
                             {
                                 SPQuery query         = new SPQuery();
                                 query.Query           = String.Format(CultureInfo.CurrentCulture, "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>wp_AddGroupUsers</Value></Eq></Where>");
                                 SPList webPartGallery = sharepointWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                                 SPListItemCollection webPartGalCol = webPartGallery.GetItems(query);
                                 XmlReader xmlReader = new XmlTextReader(webPartGalCol[0].File.OpenBinaryStream());
                                 string errorMessage;
                                 System.Web.UI.WebControls.WebParts.WebPart SiteProcertForm = mgr.ImportWebPart(xmlReader, out errorMessage);
                                 SiteProcertForm.Title       = Title;
                                 SiteProcertForm.Description = Description;
                                 SiteProcertForm.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                                 SiteProcertForm.ChromeType  = System.Web.UI.WebControls.WebParts.PartChromeType.None;
                                 mgr.AddWebPart(SiteProcertForm, "", SiteProcertForm.ZoneIndex);
                                 sharepointWeb.Update();
                             }
                         }
                     }
                 }
             }
         });
     }
     catch (Exception ex)
     {
         ex.ToString();
     }
 }
Beispiel #6
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="web"></param>
    /// <param name="page"></param>
    /// <param name="webPartZone"></param>
    /// <param name="order"></param>
    /// <param name="webpart"></param>
    public static void AddWebPartToPage(this SPWeb web, string page, string webPartZone, int order, System.Web.UI.WebControls.WebParts.WebPart webpart)
    {
        try
        {
            SPFile file = web.GetFile(page);

            if (!file.Exists)
            {
                throw new SPException(string.Format("File '{0}' does not exist", file.ServerRelativeUrl));
            }

            SPLimitedWebPartManager partManager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

            partManager.AddWebPart(webpart, webPartZone, order);
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CORE:HELPERS", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, String.Format("Exception happened in Helpers:AddWebPartToPage. MESSAGE: {0}. EXCEPTION TRACE: {1} ", ex.Message, ex.StackTrace), ex.StackTrace);
        }
    }
Beispiel #7
0
 private void btn_Import_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);
             string[]  webParts = Directory.GetFiles(tb_ImportPath.Text);
             XmlReader xReader  = null;
             System.Web.UI.WebControls.WebParts.WebPart wp = null;
             for (int i = 0; i < webParts.Length; i++)
             {
                 string customError = string.Empty;
                 xReader = new XmlTextReader(webParts[i]);
                 wp      = theWebPartManager.ImportWebPart(xReader, out customError);
                 theWebPartManager.AddWebPart(wp, "Rich Content", 1);
                 tb_Message.Text += wp.Title + "Import Success...";
             }
         }
     }
 }
        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);
            }
        }
Beispiel #9
0
        private void InstallListsViewsWebPartsInstall(string viewTitle, bool bInstallGrid, int parentMessageId, SPLimitedWebPartManager viewWebManager)
        {
            if (viewWebManager == null)
            {
                throw new ArgumentNullException(nameof(viewWebManager));
            }
            var hasGrid = false;

            try
            {
                if (bInstallGrid)
                {
                    foreach (var webPart in viewWebManager.WebParts)
                    {
                        if (webPart.GetType().ToString() == "EPMLiveWebParts.GridListView")
                        {
                            hasGrid = true;
                            break;
                        }
                    }

                    if (!hasGrid)
                    {
                        var webPart = WebPartsReflector.CreateGridListViewWebPart();
                        viewWebManager.AddWebPart(webPart, "Main", 0);
                    }
                }
                addMessage(0, viewTitle, string.Empty, parentMessageId);
            }
            catch (Exception ex)
            {
                addMessage(ErrorLevels.Error, viewTitle, "Error: " + ex.Message, parentMessageId);
                Trace.WriteLine(ex.ToString());
            }
            finally
            {
                viewWebManager.Web.Dispose();
            }
        }
        public XsltListViewWebPart AddListToPage(SPList list, string title, string zone, SPLimitedWebPartManager webPartManager, int index)
        {
            // validation
            list.RequireNotNull("list");
            title.RequireNotNullOrEmpty("title");
            zone.RequireNotNullOrEmpty("zone");
            webPartManager.RequireNotNull("webPartManager");
            index.Require(index >= 0, "index");

            XsltListViewWebPart wp = new XsltListViewWebPart();
            wp.ListName = list.ID.ToString("B").ToUpper();
            wp.Title = title;
            wp.ZoneID = zone;
            ModifyViewClass viewOperations = new ModifyViewClass();
            SPView defaultView = viewOperations.GetDefaultView(list);
            SPView modifiedView = viewOperations.CopyView(defaultView, list);
            viewOperations.SetToolbarType(modifiedView, "Standard");
            modifiedView.Update();
            wp.ViewGuid = modifiedView.ID.ToString("B").ToUpper();
            webPartManager.AddWebPart(wp, zone, index);
            list.Update();
            webPartManager.SaveChanges(wp);
            return wp;
        }
Beispiel #11
0
 private void btn_AddToPage_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);
             string  webPartName = cBox_WebPart.SelectedItem.ToString();
             SPQuery qry         = new SPQuery();
             qry.Query = String.Format(CultureInfo.CurrentCulture, "<Where><Eq><FieldRef Name=\"FileLeafRef\" /><Value Type=\"Text\">{0}</Value></Eq></Where>", webPartName);
             SPList webPartGallery = null;
             if (null == web.ParentWeb)
             {
                 webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
             }
             else
             {
                 webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
             }
             SPListItemCollection webParts = webPartGallery.GetItems(qry);
             if (webParts.Count == 0)
             {
                 tb_Message.Text += "Can't find " + webPartName + "...";
             }
             else
             {
                 XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                 string    errorMsg;
                 System.Web.UI.WebControls.WebParts.WebPart webPart = theWebPartManager.ImportWebPart(xmlReader, out errorMsg);
                 theWebPartManager.AddWebPart(webPart, "Rich Content", 1);
                 tb_Message.Text += "Add " + webPartName + " Success...";
             }
         }
     }
 }
        private static void CopyAllWebParts(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 (webParts.Count > 0)
                {
                    foreach (System.Web.UI.WebControls.WebParts.WebPart part in webParts)
                    {
                        if (!part.IsClosed)
                        {
                            System.Web.UI.WebControls.WebParts.WebPart webPart = parts2[part.ID];
                            if (webPart == null)
                            {
                                try
                                {
                                    string zoneID = manager2.GetZoneID(part);
                                    limitedWebPartManager.AddWebPart(part, zoneID, part.ZoneIndex);
                                }
                                catch (ArgumentException e)
                                {
                                }
                            }
                            else
                            {
                                if (webPart.IsClosed)
                                {
                                    limitedWebPartManager.OpenWebPart(webPart);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (HttpContext.Current != null)
                {
                    throw;
                }
            }
            finally
            {
                if ((web != sourcePageWeb) && (web != null))
                {
                    web.Close();
                }
                if ((web2 != destinationPageWeb) && (web2 != null))
                {
                    web2.Close();
                }
            }
        }
        public static void CreateContentEditorWebPart(SPLimitedWebPartManager webPartManager, string Content, string zone, int zoneIndex, PartChromeType chromeType, string webPartTitle)
        {
            // validation
            webPartManager.RequireNotNull("webPartManager");
            Content.RequireNotNullOrEmpty("Content");
            zone.RequireNotNullOrEmpty("zone");
            webPartTitle.RequireNotNullOrEmpty("webPartTitle");

            Guid storageKey = Guid.NewGuid();
            string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));
            XmlDocument doc = new XmlDocument();
            XmlElement div = doc.CreateElement("div");
            div.InnerText = Content;
            ContentEditorWebPart cewp = new ContentEditorWebPart { Content = div, ID = wpId, Title = webPartTitle };
            cewp.ChromeType = chromeType;
            webPartManager.AddWebPart(cewp, zone, zoneIndex);
            webPartManager.SaveChanges(cewp);
        }
Beispiel #14
0
        public static WebPart AddWebPartToWikiPage(SPListItem item, string webPartXml, string title, int row, int col, bool addSpace, Hashtable customReplaceText, PartChromeType chromeType, bool publish)
        {
            string      wikiField = (string)item["WikiField"];
            XmlDocument xd        = new XmlDocument();

            xd.PreserveWhitespace = true;
            xd.LoadXml(wikiField);

            // Sometimes the wikifield content seems to be surrounded by an additional div?
            XmlElement layoutsTable = xd.SelectSingleNode("div/div/table") as XmlElement;

            if (layoutsTable == null)
            {
                layoutsTable = xd.SelectSingleNode("div/table") as XmlElement;
            }

            XmlElement layoutsZoneInner = layoutsTable.SelectSingleNode(string.Format("tbody/tr[{0}]/td[{1}]/div/div", row, col)) as XmlElement;

            if (layoutsZoneInner == null)
            {
                throw new ArgumentException("Unable to locate row and/or column to insert HTML into.");
            }

            bool checkBackIn = false;

            if (item.File.InDocumentLibrary)
            {
                bool ignoreCheckOut = item.File.CheckOutType == SPFile.SPCheckOutType.None && !item.ParentList.ForceCheckout;
                if (!ignoreCheckOut)
                {
                    if (!Utilities.IsCheckedOut(item) || !Utilities.IsCheckedOutByCurrentUser(item))
                    {
                        checkBackIn = true;
                        item.File.CheckOut();
                    }
                }
                // If it's checked out by another user then this will throw an informative exception so let it do so.
            }

            SPLimitedWebPartManager limitedWebPartManager = null;
            WebPart wpdNew = null;

            try
            {
                limitedWebPartManager = item.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                wpdNew            = SPCmdletImportWebPart.AddWebPart(limitedWebPartManager, item.File, webPartXml, customReplaceText);
                wpdNew.ChromeType = chromeType;
                limitedWebPartManager.AddWebPart(wpdNew, "wpz", 0);
                Guid storageKey = limitedWebPartManager.GetStorageKey(wpdNew);


                // - space element
                XmlElement space = xd.CreateElement("p");
                XmlText    text  = xd.CreateTextNode(" ");
                space.AppendChild(text);

                // - wpBoxDiv
                XmlElement wpBoxDiv = xd.CreateElement("div");
                layoutsZoneInner.AppendChild(wpBoxDiv);

                if (addSpace)
                {
                    layoutsZoneInner.AppendChild(space);
                }

                XmlAttribute attribute = xd.CreateAttribute("class");
                wpBoxDiv.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-read ms-rte-wpbox";
                attribute       = xd.CreateAttribute("contentEditable");
                wpBoxDiv.Attributes.Append(attribute);
                attribute.Value = "false";
                // - div1
                XmlElement div1 = xd.CreateElement("div");
                wpBoxDiv.AppendChild(div1);
                div1.IsEmpty = false;
                attribute    = xd.CreateAttribute("class");
                div1.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-read " + storageKey.ToString("D");
                attribute       = xd.CreateAttribute("id");
                div1.Attributes.Append(attribute);
                attribute.Value = "div_" + storageKey.ToString("D");
                // - div2
                XmlElement div2 = xd.CreateElement("div");
                wpBoxDiv.AppendChild(div2);
                div2.IsEmpty = false;
                attribute    = xd.CreateAttribute("style");
                div2.Attributes.Append(attribute);
                attribute.Value = "display:none";
                attribute       = xd.CreateAttribute("id");
                div2.Attributes.Append(attribute);
                attribute.Value = "vid_" + storageKey.ToString("D");

                item["WikiField"] = xd.OuterXml;
                item.Update();

                if (wpdNew.Title != title)
                {
                    wpdNew.Title = title;
                    limitedWebPartManager.SaveChanges(wpdNew);
                }
            }
            finally
            {
                if (limitedWebPartManager != null)
                {
                    limitedWebPartManager.Dispose();
                }

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

                if (publish && file.InDocumentLibrary)
                {
                    file.Publish("Publishing changes to page due to new web part being added: " + title);
                    if (file.Item.ModerationInformation != null)
                    {
                        file.Approve("Approving changes to page due to new web part being added: " + title);
                    }
                }
            }
            return(wpdNew);
        }
Beispiel #15
0
        public static void EnableFancyForms(SPList list)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPWeb web = list.ParentWeb;  //No dispose required
                web.AllowUnsafeUpdates = true;

                bool isFancyFormWpExist = false;
                var rootFolder          = list.RootFolder;

                var dispFormUrl = string.Format("{0}/{1}/DispForm.aspx", web.ServerRelativeUrl, rootFolder.Url);
                var dispForm    = web.GetFile(dispFormUrl);



                if (dispForm != null)
                {
                    //Delete webparts from existing list
                    using (SPLimitedWebPartManager wpm = dispForm.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        try
                        {
                            if (wpm.WebParts != null)
                            {
                                for (int i = 0; i < wpm.WebParts.Count; i++)
                                {
                                    try
                                    {
                                        if ((!string.IsNullOrEmpty(wpm.WebParts[i].Title)) && (wpm.WebParts[i].Title.Equals("Fancy Display Form", StringComparison.InvariantCultureIgnoreCase)) && !isFancyFormWpExist)
                                        {
                                            isFancyFormWpExist        = true;
                                            wpm.WebParts[i].AllowHide = false;
                                            wpm.WebParts[i].Hidden    = false;
                                            wpm.SaveChanges(wpm.WebParts[i]);
                                        }
                                        else if (wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.XsltListViewWebPart" ||
                                                 wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.ListFormWebPart" ||
                                                 wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.ListViewWebPart" ||
                                                 wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.DataFormWebPart")
                                        {
                                            wpm.WebParts[i].AllowHide = true;
                                            wpm.WebParts[i].Hidden    = true;
                                            wpm.SaveChanges(wpm.WebParts[i]);
                                        }
                                    }
                                    catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Event, TraceSeverity.Medium, ex.ToString()); }
                                }
                            }
                        }
                        catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Event, TraceSeverity.Medium, ex.ToString()); }
                        finally { if (wpm != null)
                                  {
                                      wpm.Web.Dispose();
                                  }
                        }
                    }
                }
                else
                {
                    dispForm = rootFolder.Files.Add(dispFormUrl, SPTemplateFileType.FormPage);
                }

                if (isFancyFormWpExist)
                {
                    return;
                }

                using (SPLimitedWebPartManager wpm = dispForm.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                {
                    try
                    {
                        //var fancyDispFormWebPart = new EPMLiveWebParts.FancyDisplayForm();
                        var fancyDispFormWebPart         = WebPartsHelper.WebPartsReflector.CreateFancyDisplayFormWebPart();
                        fancyDispFormWebPart.Title       = "Fancy Display Form";
                        fancyDispFormWebPart.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                        fancyDispFormWebPart.ChromeType  = System.Web.UI.WebControls.WebParts.PartChromeType.None;
                        fancyDispFormWebPart.AllowHide   = false;
                        fancyDispFormWebPart.Hidden      = false;
                        fancyDispFormWebPart.Visible     = true;

                        wpm.AddWebPart(fancyDispFormWebPart, "Main", 0);
                    }
                    catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Event, TraceSeverity.Medium, ex.ToString()); }
                    finally { if (wpm != null)
                              {
                                  wpm.Web.Dispose();
                              }
                    }
                }
            });
        }
        public static void AddWebPart(SPLimitedWebPartManager webPartManager, System.Web.UI.WebControls.WebParts.WebPart webPart, string zone, int zoneIndex, PartChromeType chromeType, string accesskey)
        {
            webPartManager.RequireNotNull("webPartManager");
            webPart.RequireNotNull("webPart");
            zone.RequireNotNullOrEmpty("zone");
            zoneIndex.Require(zoneIndex >= 0, "zoneIndex");

            webPart.AccessKey = accesskey;
            webPart.ChromeType = chromeType;
            webPartManager.AddWebPart(webPart, zone, zoneIndex);
            webPartManager.SaveChanges(webPart);
        }
        /// <summary>
        /// Adds the web part to the page from a definition.
        /// </summary>
        /// <param name="manager">The web part manager.</param>
        /// <param name="definition">The web part definition.</param>
        /// <param name="zone">The web part zone.</param>
        /// <param name="index">The zone index.</param>
        protected void AddWebPart(SPLimitedWebPartManager manager, string definition, string zone, int index)
        {
            // Guard
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            if (this.Web == null)
            {
                throw new InvalidOperationException("You must call EnsureContext method before calling this method.");
            }

            string data = this.Web.GetFileAsString(definition);
            if (data != null)
            {
                WebPart webPart;
                using (StringReader reader = new StringReader(data))
                {
                    string errorMessage;
                    XmlTextReader xmlTextReader = new XmlTextReader(reader);
                    webPart = manager.ImportWebPart(xmlTextReader, out errorMessage);
                    if (webPart == null)
                    {
                        throw new WebPartPageUserException(errorMessage);
                    }
                }

                manager.AddWebPart(webPart, zone, index);
            }
        }
Beispiel #18
0
        public static void DeployWebPartsToPage(SPLimitedWebPartManager webPartManager,
                                                IEnumerable <WebPartDefinition> webpartDefinitions,
                                                Action <WebPart> onUpdating,
                                                Action <WebPart> onUpdated)
        {
            foreach (var webpartModel in webpartDefinitions)
            {
                var site            = webPartManager.Web.Site;
                var webPartInstance = ResolveWebPartInstance(site, webPartManager, webpartModel);

                if (onUpdating != null)
                {
                    onUpdating(webPartInstance);
                }

                // webpartModel.InvokeOnModelUpdatingEvents<WebPartDefinition, AspWebPart.WebPart>(webPartInstance);

                var needUpdate        = false;
                var targetWebpartType = webPartInstance.GetType();

                foreach (System.Web.UI.WebControls.WebParts.WebPart existingWebpart in webPartManager.WebParts)
                {
                    if (existingWebpart.ID == webpartModel.Id && existingWebpart.GetType() == targetWebpartType)
                    {
                        webPartInstance = existingWebpart;
                        needUpdate      = true;
                        break;
                    }
                }

                // process common properties
                webPartInstance.Title = webpartModel.Title;
                webPartInstance.ID    = webpartModel.Id;

                // faking context for CQWP deployment
                var webDeploymentAction = new Action(delegate()
                {
                    // webpartModel.InvokeOnModelUpdatedEvents<WebPartDefinition, AspWebPart.WebPart>(webPartInstance);

                    if (!needUpdate)
                    {
                        if (onUpdating != null)
                        {
                            onUpdating(webPartInstance);
                        }

                        if (onUpdated != null)
                        {
                            onUpdated(webPartInstance);
                        }

                        webPartManager.AddWebPart(webPartInstance, webpartModel.ZoneId, webpartModel.ZoneIndex);
                    }
                    else
                    {
                        if (webPartInstance.ZoneIndex != webpartModel.ZoneIndex)
                        {
                            webPartManager.MoveWebPart(webPartInstance, webpartModel.ZoneId, webpartModel.ZoneIndex);
                        }

                        if (onUpdating != null)
                        {
                            onUpdating(webPartInstance);
                        }

                        if (onUpdated != null)
                        {
                            onUpdated(webPartInstance);
                        }

                        webPartManager.SaveChanges(webPartInstance);
                    }
                });

                if (SPContext.Current == null)
                {
                    SPContextExtensions.WithFakeSPContextScope(webPartManager.Web, webDeploymentAction);
                }
                else
                {
                    webDeploymentAction();
                }
            }
        }
        /// <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);
                        }
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="web"></param>
        /// <param name="fileNameWithOutExtension"></param>
        /// <param name="fileName"></param>
        /// <param name="DocLib"></param>
        public void CreateWebPartPage(string fileNameWithOutExtension, string fileName, string DocLib)
        {
            SPWeb            web           = SPContext.Current.Web;
            SPFolder         libraryFolder = web.GetFolder(DocLib);
            SPFileCollection files         = libraryFolder.Files;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //string templateFilename = "spstd2.aspx";
                //string cityName = txtCityPageName.Text.Trim();
                string cityName         = fileNameWithOutExtension;
                string templateFilename = "NewCityPageLayout.aspx";
                //string hive = SPUtility.GetGenericSetupPath("15\\TEMPLATE\\" + SPContext.Current.Web.Language + "\\STS\\DOCTEMP\\SMARTPGS\\");
                string hive = "C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\15\\TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\";

                using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open))
                {
                    // SPFolder libraryFolder = web.GetFolder(DocLib);
                    //SPFileCollection files = libraryFolder.Files;
                    if (!isFileExists(files, fileName))
                    {
                        SPFile newFile = files.Add(fileName, stream);

                        SPLimitedWebPartManager wpmngr = newFile.Web.GetLimitedWebPartManager(newFile.ServerRelativeUrl, PersonalizationScope.Shared);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityDivisionHeader.dwp"), "Header", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "CitiesLeftNavigation.webpart"), "LeftColumn", 0);
                        //  wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "CityPageSummaryLinks.webpart"), "RightColumn", 0);
                        //wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityLOBs.dwp"), "MiddleColumn", 0);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Residential CEWP.dwp"), "Middle1Column", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Residential"), "Middle1Column", 1);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Commercial CEWP.dwp"), "Middle1Column", 2);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Commercial"), "Middle1Column", 3);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Industrial CEWP.dwp"), "Middle2Column", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Industrial"), "Middle2Column", 1);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Operational CEWP.dwp"), "Middle2Column", 2);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Operational"), "Middle2Column", 3);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityDummyDescription.dwp"), "MiddleColumn", 2);

                        AddToCitiesList(fileNameWithOutExtension);

                        lblMsg.Text += string.Format("{0} Webpage successfully created...!<br>", fileName);
                    }
                    else
                    {
                        lblMsg.Text = "page already exists...!";
                    }
                }
            });

            // updatedatainCEWP(fileName, DocLib, txtbxDivision.Text.Trim(), txtbxStateCode.Text.Trim(), fileNameWithOutExtension);
        }
Beispiel #21
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;
                        }
                    }
                }
        }
Beispiel #22
0
        /// <summary>
        /// Adds a List View Web Part to the specified page.
        /// </summary>
        /// <param name="pageUrl">The page URL.</param>
        /// <param name="listUrl">The list URL.</param>
        /// <param name="title">The title.</param>
        /// <param name="viewTitle">Title of the view.</param>
        /// <param name="zoneId">The zone ID.</param>
        /// <param name="zoneIndex">Index within the zone.</param>
        /// <param name="linkTitle">if set to <c>true</c> [link title].</param>
        /// <param name="chromeType">Type of the chrome.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <returns></returns>
        public static Microsoft.SharePoint.WebPartPages.WebPart Add(string pageUrl, string listUrl, string title, string viewTitle, string zoneId, int zoneIndex, bool linkTitle, string jsLink, PartChromeType chromeType, bool publish)
        {
            using (SPSite site = new SPSite(pageUrl))
                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
                {
                    SPFile file = web.GetFile(pageUrl);

                    // 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.

                    SPList list = Utilities.GetListFromViewUrl(listUrl);
                    if (list == null)
                    {
                        throw new ArgumentException("List not found.");
                    }

                    SPView view = null;
                    if (!string.IsNullOrEmpty(viewTitle))
                    {
                        view = list.Views.Cast <SPView>().FirstOrDefault(v => v.Title == viewTitle);
                        if (view == null)
                        {
                            throw new ArgumentException("The specified view was not found.");
                        }
                    }

                    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.
                    }
                    string displayTitle = string.Empty;
                    Microsoft.SharePoint.WebPartPages.WebPart lvw = null;

                    SPLimitedWebPartManager manager = null;
                    try
                    {
                        manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared);
                        lvw     = new XsltListViewWebPart();
                        if (list.BaseTemplate == SPListTemplateType.Events)
                        {
                            lvw = new ListViewWebPart();
                        }

                        if (lvw is ListViewWebPart)
                        {
                            ((ListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant();
                            ((ListViewWebPart)lvw).WebId    = list.ParentWeb.ID;
                            if (view != null)
                            {
                                ((ListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant();
                            }
                        }
                        else
                        {
                            ((XsltListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant();
#if !SP2010
                            if (!string.IsNullOrEmpty(jsLink))
                            {
                                ((XsltListViewWebPart)lvw).JSLink = jsLink;
                            }
#endif
                            ((XsltListViewWebPart)lvw).WebId = list.ParentWeb.ID;
                            if (view != null)
                            {
                                ((XsltListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant();
                            }
                        }

                        if (linkTitle)
                        {
                            if (view != null)
                            {
                                lvw.TitleUrl = view.Url;
                            }
                            else
                            {
                                lvw.TitleUrl = list.DefaultViewUrl;
                            }
                        }

                        if (!string.IsNullOrEmpty(title))
                        {
                            lvw.Title = title;
                        }

                        lvw.ChromeType = chromeType;

                        displayTitle = lvw.DisplayTitle;

                        manager.AddWebPart(lvw, zoneId, zoneIndex);
                    }
                    finally
                    {
                        if (manager != null)
                        {
                            manager.Web.Dispose();
                            manager.Dispose();
                        }
                        if (lvw != null)
                        {
                            lvw.Dispose();
                        }

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

                        if (publish && file.InDocumentLibrary)
                        {
                            file.Publish("Publishing changes to page due to new web part being added: " + displayTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page due to new web part being added: " + displayTitle);
                            }
                        }
                    }
                    return(lvw);
                }
        }
        private static void RestoreDataViewOutZone(SPWeb web, string filePath)
        {
            if (!File.Exists(filePath) || web == null)
            {
                return;
            }

            XmlDocument doc = new XmlDocument();

            try
            {
                doc.Load(filePath);
            }
            catch (XmlException)
            {
                return;
            }

            XmlNodeList xFixupFiles = doc.DocumentElement.SelectNodes("FixupFiles/FixupFile[@DataViewOutZone=\"TRUE\"]");

            foreach (XmlNode xFixupFile in xFixupFiles)
            {
                XmlAttribute xRelativePath = xFixupFile.Attributes["RelativePath"];
                if (xRelativePath == null)
                {
                    continue;
                }
                string relativePath = xRelativePath.Value;

                SPFile file = web.GetFile(relativePath);
                if (file == null)
                {
                    continue;
                }

                string fileName = file.Name;

                string content = String.Empty;
                using (StreamReader reader = new StreamReader(file.OpenBinaryStream()))
                {
                    content = reader.ReadToEnd();
                    content = SubstituteGuid(web, filePath, content);
                }

                UTF8Encoding encoder        = new UTF8Encoding();
                byte[]       contentAsBytes = encoder.GetBytes(content);

                // store to temporary file
                SPFile temp = web.Files.Add("temp.aspx", contentAsBytes);

                SPLimitedWebPartManager    sourceManager  = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                SPLimitedWebPartCollection sourceWebParts = sourceManager.WebParts;

                SPLimitedWebPartManager targetManager = temp.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in sourceWebParts)
                {
                    string zoneId = sourceManager.GetZoneID(webPart);
                    targetManager.AddWebPart(webPart, zoneId, webPart.ZoneIndex);
                }

                foreach (SPWebPartConnection connection in sourceManager.SPWebPartConnections)
                {
                    targetManager.SPConnectWebParts(connection.Provider, connection.ProviderConnectionPoint, connection.Consumer, connection.ConsumerConnectionPoint, connection.Transformer);
                }

                file.Delete();

                temp.CopyTo(fileName);
                temp.Delete();

                web.Update();
            }
        }
Beispiel #24
0
        public static void ProvisionWebpart(SPWeb web, WebpartPageDefinitionCollection collection)
        {
            foreach (var item in collection)
            {
                try
                {
                    string pageUrl = item.PageUrl;
                    if (!string.IsNullOrEmpty(item.RootPath) && !string.IsNullOrEmpty(item.FileName))
                    {
                        if (item.RootPath.EndsWith(".aspx"))
                        {
                            item.PageUrl = item.RootPath;
                            pageUrl      = item.RootPath;
                        }

                        else
                        {
                            pageUrl      = string.Format("{0}/{1}", item.RootPath.TrimEnd('/'), SPEncode.UrlEncode(item.FileName.TrimStart('/')));
                            item.PageUrl = pageUrl;
                        }
                    }

                    if (!IsAbsoluteUrl(pageUrl))
                    {
                        pageUrl = string.Format("{0}/{1}", web.Url.TrimEnd('/'), pageUrl.TrimStart('/'));
                    }

                    web.EnsureWebpartPage(item.PageUrl, item.Title, item.Overwrite, item.UseFormFolder);

                    using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
                               pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        foreach (var wp in item.Webparts)
                        {
                            try
                            {
                                using (var concerateWP = wp.CreateWebPart(web, webPartManager))
                                {
                                    if (concerateWP == null)
                                    {
                                        continue;
                                    }
                                    try
                                    {
                                        if (!wp.AllowDuplicate && webPartManager.WebParts.Cast <System.Web.UI.WebControls.WebParts.WebPart>().Any(p => p.Title == concerateWP.Title))
                                        {
                                            continue;
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        //throw;
                                    }


                                    webPartManager.AddWebPart(concerateWP, wp.ZoneId, wp.Index == 0 ?webPartManager.WebParts.Count + 1:  wp.Index);

                                    CreateDefaultWebPart(web, webPartManager, wp, concerateWP);
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
        public static ListViewWebPart AddListToPage(SPList list, string title, string zone, SPLimitedWebPartManager webPartManager, int index)
        {
            // validation
            if (null == list)
            {
                throw new ArgumentNullException("list");
            }

            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException("title is null or empty!");
            }

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

            ListViewWebPart wp = new ListViewWebPart();
            wp.ListName = list.ID.ToString("B").ToUpper();
            wp.Title = title;
            wp.ZoneID = zone;
            webPartManager.AddWebPart(wp, zone, index);
            list.Update();
            webPartManager.SaveChanges(wp);
            return wp;
        }
        /// <summary>
        /// Provisions the web parts.
        /// </summary>
        /// <param name="manager">The manager.</param>
        protected virtual void ProvisionWebParts(SPLimitedWebPartManager manager)
        {
            // Guard
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            ImageWebPart webPart = new ImageWebPart { ImageLink = "/_layouts/images/docset_welcomepage_big.png" };
            manager.AddWebPart(webPart, "WebPartZone_TopLeft", 1);
            this.AddWebPart(manager, this.Web.Url + "/_catalogs/wp/documentsetproperties.dwp", "WebPartZone_Top", 2);
            this.AddWebPart(
                manager, this.Web.Url + "/_catalogs/wp/documentsetcontents.dwp", "WebPartZone_CenterMain", 2);
        }
        public static void AddListToPage(SPList list, string title, string zone, SPLimitedWebPartManager webPartManager, int index, string viewName)
        {
            // validation
            list.RequireNotNull("list");
            title.RequireNotNullOrEmpty("title");
            webPartManager.RequireNotNull("webPartManager");
            viewName.RequireNotNullOrEmpty("viewName");

            ListViewWebPart wp = new ListViewWebPart();
            wp.ListName = list.ID.ToString("B").ToUpper();
            wp.ViewGuid = list.Views[viewName].ID.ToString("B").ToUpper();
            wp.Title = title;
            wp.ZoneID = zone;
            webPartManager.AddWebPart(wp, zone, index);
            list.Update();
            webPartManager.SaveChanges(wp);
        }
Beispiel #28
0
        public static void DeployWebPartToPage(SPLimitedWebPartManager webPartManager,
            WebPartDefinition webpartModel,
            Action<WebPart> onUpdating,
            Action<WebPart> onUpdated,
            Action<WebPart, WebPartDefinition> onProcessCommonProperties)
        {
            var site = webPartManager.Web.Site;
            var webPartInstance = ResolveWebPartInstance(site, webPartManager, webpartModel);

            if (onUpdating != null)
                onUpdating(webPartInstance);

            // webpartModel.InvokeOnModelUpdatingEvents<WebPartDefinition, AspWebPart.WebPart>(webPartInstance);

            var needUpdate = false;
            var targetWebpartType = webPartInstance.GetType();

            foreach (System.Web.UI.WebControls.WebParts.WebPart existingWebpart in webPartManager.WebParts)
            {
                if (existingWebpart.ID == webpartModel.Id && existingWebpart.GetType() == targetWebpartType)
                {
                    webPartInstance = existingWebpart;
                    needUpdate = true;
                    break;
                }
            }

            // process common properties
            webPartInstance.Title = webpartModel.Title;
            webPartInstance.ID = webpartModel.Id;

            if (onProcessCommonProperties != null)
                onProcessCommonProperties(webPartInstance, webpartModel);

            // faking context for CQWP deployment
            var webDeploymentAction = new Action(delegate()
            {
                // webpartModel.InvokeOnModelUpdatedEvents<WebPartDefinition, AspWebPart.WebPart>(webPartInstance);

                if (!needUpdate)
                {
                    if (onUpdating != null)
                        onUpdating(webPartInstance);

                    if (onUpdated != null)
                        onUpdated(webPartInstance);

                    webPartManager.AddWebPart(webPartInstance, webpartModel.ZoneId, webpartModel.ZoneIndex);
                }
                else
                {
                    if (webPartInstance.ZoneIndex != webpartModel.ZoneIndex)
                        webPartManager.MoveWebPart(webPartInstance, webpartModel.ZoneId, webpartModel.ZoneIndex);

                    if (onUpdating != null)
                        onUpdating(webPartInstance);

                    if (onUpdated != null)
                        onUpdated(webPartInstance);

                    webPartManager.SaveChanges(webPartInstance);
                }
            });

            if (SPContext.Current == null)
                SPContextExtensions.WithFakeSPContextScope(webPartManager.Web, webDeploymentAction);
            else
                webDeploymentAction();
        }
Beispiel #29
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;
                        }
                    }
                }
        }