Example #1
0
 public static void DeployWebPartToPage(SPLimitedWebPartManager webPartManager,
                                        WebPartDefinition webpartDefinitions,
                                        Action <WebPart> onUpdating,
                                        Action <WebPart> onUpdated)
 {
     DeployWebPartToPage(webPartManager, webpartDefinitions, onUpdating, onUpdated, null);
 }
        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);
                }
            }
        }
        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 override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = properties.Feature.Parent as SPWeb;

                foreach (SPList list in web.Lists.OfType <SPList>().Where(l => !l.Hidden))
                {
                    list.NavigateForFormsPages = false;
                    list.Update();

                    using (SPLimitedWebPartManager wpm = web.GetLimitedWebPartManager(list.DefaultNewFormUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        foreach (WebPart wp in wpm.WebParts)
                        {
                            if (wp is ListFormWebPart)
                            {
                                ListFormWebPart lfwp = (ListFormWebPart)wp;
                                lfwp.CSRRenderMode = CSRRenderMode.ServerRender;
                                wpm.SaveChanges(lfwp);
                            }
                        }
                    }
                }
                web.Update();
            }
            catch (Exception ex)
            {
            }
        }
Example #5
0
 public static void AddXsltViewWebPart(SPWeb web, SPList list, string pageUrl, string webPartName, string zoneID,
                                       int zoneIndex, bool isHidden, string viewTitle)
 {
     using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
                pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
     {
         bool isExists = false;
         foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts)
         {
             if (wp.Title.Equals(webPartName))
             {
                 isExists = true;
                 break;
             }
             else
             {
                 isExists = false;
             }
         }
         if (!isExists)
         {
             XsltListViewWebPart webPart = new XsltListViewWebPart();
             webPart.ListId     = list.ID;
             webPart.Title      = webPartName;
             webPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.TitleAndBorder;
             SPView view = list.Views[viewTitle];
             webPart.ViewGuid      = view.ID.ToString();
             webPart.XmlDefinition = view.GetViewXml();
             webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
         }
     }
 }
Example #6
0
        public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
        {
            try
            {
                web.AllowUnsafeUpdates = false;
                using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                {
                    using (var webPart = CreateWebPart(web, webPartName, webPartManager))
                    {
                        if (webPart != null)
                        {
                            webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
                            return(webPart.ID);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // throw;
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }

            return(string.Empty);
        }
Example #7
0
        /// <summary>
        /// Add the web part to page.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="pageUrl">The page URL.</param>
        /// <param name="webPartName">Name of the web part.</param>
        /// <param name="zoneID">The zone ID.</param>
        /// <param name="zoneIndex">Index of the zone.</param>
        /// <returns></returns>
        public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex, bool isHidden)
        {
            using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
                       pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
            {
                using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, webPartManager, isHidden))
                {
                    bool isExists = false;
                    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts)
                    {
                        if (wp.Title.Equals(webPartName.Replace(".webpart", "")))
                        {
                            isExists = true;
                            break;
                        }
                        else
                        {
                            isExists = false;
                        }
                    }
                    if (!isExists)
                    {
                        webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
                    }

                    return(webPart.ID);
                }
            }
        }
Example #8
0
 public static void DeployWebPartToPage(SPLimitedWebPartManager webPartManager,
     WebPartDefinition webpartDefinitions,
     Action<WebPart> onUpdating,
     Action<WebPart> onUpdated)
 {
     DeployWebPartToPage(webPartManager, webpartDefinitions, onUpdating, onUpdated, null);
 }
Example #9
0
    /// <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 (Web == null)
      {
        throw new InvalidOperationException("You must call EnsureContext method before calling this method.");
      }

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

        manager.AddWebPart(webPart, zone, index);
      }
    }
Example #10
0
        public override TabPage[] GetTabPages()
        {
            ArrayList alPages = new ArrayList();

            alPages.AddRange(base.GetTabPages());


            if (this.Parent.Tag != null)
            {
                string xml = string.Empty;

                SPLimitedWebPartManager manager = (SPLimitedWebPartManager)this.Parent.Tag;
                using (StringWriter writer = new StringWriter())
                {
                    XmlTextWriter xtw = new XmlTextWriter(writer);
                    //this.ASPWebPart.ExportMode == WebPartExportMode.All;
                    manager.ExportWebPart(this.ASPWebPart, xtw);
                    xml = writer.ToString();
                }
                TabXmlPage xmlPage = TabPages.GetXmlPage("Xml", xml);
                alPages.Add(xmlPage);
            }

            return((TabPage[])alPages.ToArray(typeof(TabPage)));
        }
Example #11
0
        /// <summary>
        /// Save the auto located location in the webpart settings
        /// </summary>
        private void SaveAutoLoc()
        {
            String[] Location = new String[4];

            Location = GetLocation();

            using (SPSite objSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb objWeb = objSite.OpenWeb())
                {
                    SPFile objPage = objWeb.GetFile(HttpContext.Current.Request.Url.ToString());
                    SPLimitedWebPartManager mgr = objPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
                    System.Web.UI.WebControls.WebParts.WebPart objWebPart = mgr.WebParts[this.ID];

                    if (objWebPart != null)
                    {
                        if (Location[1] == null && Location[2] == null)
                        {
                            ((Sumit.Webpart.Weather.Weather.Weather)(objWebPart.WebBrowsableObject)).CityName = null;
                        }
                        else
                        {
                            ((Sumit.Webpart.Weather.Weather.Weather)(objWebPart.WebBrowsableObject)).CityName = Location[1] + " , " + Location[2];
                        }

                        mgr.SaveChanges(objWebPart);
                    }
                }
            }
        }
        public static string AddWebPartToPage(
            SPWeb web,
            string pageUrl,
            string webPartName,
            string zoneID,
            int zoneIndex)
        {
            using (WebPart webPart = CreateWebPart(web, webPartName)) {
                using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared)) {
                    manager.AddWebPart(webPart, zoneID, zoneIndex);
                    //TODO: Will the list always be index = 0?
                    foreach (WebPart listWebPart in manager.WebParts)
                    {
                        if (listWebPart is ListViewWebPart)
                        {
                            //AddWebPartConnectionAspNet (web, pageUrl, webPart.ID, listWebPart.ID, "Send values as filters to", "Get Sort/Filter From");
                            AddWebPartConnectionWss(web, pageUrl, webPart.ID, listWebPart.ID);
                            break;
                        }
                    }

                    return(webPart.ID);
                }
            }
        }
        internal static void TestWebParts()
        {
            string url  = "http://roxserver/sites/filterzen/default.aspx";
            SPSite site = new SPSite(url);
            SPWeb  web  = site.OpenWeb();

            roxority_FilterWebPart.OffSite = site;
            roxority_FilterWebPart webPart           = new roxority_FilterWebPart();
            FilterBase             pageRequestFilter = FilterBase.Create("roxority_FilterZen.FilterBase+RequestParameter");

            webPart.GetFilters().Add(pageRequestFilter);
            pageRequestFilter.Name    = "Project";
            pageRequestFilter.Enabled = true;
            pageRequestFilter.Set("ParameterName", "projects");
            pageRequestFilter.Set("RequestMode", 3);
            webPart.SerializedFilters         = FilterBase.Serialize(webPart.GetFilters());
            webPart.DebugMode                 = true;
            webPart.ApplyToolbarStylings      = false;
            webPart.AutoRepost                = false;
            webPart.DynamicInteractiveFilters = 1;
            webPart.HtmlMode             = 0;
            webPart.RememberFilterValues = false;
            webPart.Title = "foo";
            SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(url, PersonalizationScope.Shared);

            webPartManager.AddWebPart(webPart, "LeftZone", 0);
            webPartManager.CacheInvalidate(webPart, Storage.Shared);
            webPartManager.SaveChanges(webPart);
        }
Example #14
0
 private void btn_Export_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;
             XmlWriter writer = null;
             for (int i = 0; i < webParts.Count; i++)
             {
                 try
                 {
                     writer = new XmlTextWriter(tb_ExportPath.Text + webParts[i].Title + ".xml", Encoding.UTF8);
                     theWebPartManager.ExportWebPart(webParts[i], writer);
                     writer.Flush();
                     writer.Close();
                     tb_Message.Text += webParts[i].Title + "Export Success...";
                 }
                 catch
                 {
                     tb_Message.Text += webParts[i].Title + "Export Failed...";
                 }
             }
         }
     }
 }
Example #15
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);
                    }
                }
            }
        }
        internal static WebPart AddWebPart(SPLimitedWebPartManager manager, SPFile file, string webPartXml, Hashtable customReplaceText)
        {
            WebPart       wp;
            XmlTextReader reader = null;

            try
            {
                webPartXml = webPartXml.Replace("${siteCollection}", file.Item.ParentList.ParentWeb.Site.Url);
                webPartXml = webPartXml.Replace("${site}", file.Item.ParentList.ParentWeb.Url);
                webPartXml = webPartXml.Replace("${webTitle}", HttpUtility.HtmlEncode(file.Item.ParentList.ParentWeb.Title));
                if (customReplaceText != null)
                {
                    foreach (string key in customReplaceText.Keys)
                    {
                        webPartXml = webPartXml.Replace(key, HttpUtility.HtmlEncode(customReplaceText[key].ToString()));
                    }
                }
                reader = new XmlTextReader(new StringReader(webPartXml));

                string err;
                wp = manager.ImportWebPart(reader, out err);
                if (!string.IsNullOrEmpty(err))
                {
                    throw new Exception(err);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return(wp);
        }
Example #17
0
        /// <summary>
        /// Get the ListGuid from a ListViewWebPart that contains a specified ViewGuid
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="viewGuid">View Guid</param>
        /// <returns>The Guid of the List, null if not found</returns>
        internal static string GetListGuidFromListViewGuid(HttpContext context, string viewGuid)
        {
            SPWeb curWeb = SPContext.Current.Web;

            using (SPLimitedWebPartManager webpartManager =
                       curWeb.GetLimitedWebPartManager(context.Request.Url.ToString(),
                                                       PersonalizationScope.Shared))
            {
                foreach (WebPart webpart in webpartManager.WebParts)
                {
                    ListViewWebPart listViewWebPart = webpart as ListViewWebPart;

                    // if the list is a ListView WebPart
                    if (listViewWebPart != null)
                    {
                        // and is the view
                        if (listViewWebPart.ViewGuid == viewGuid)
                        {
                            return(listViewWebPart.ListName);
                        }
                    }
                    webpart.Dispose();
                }
                webpartManager.Web.Dispose();
            }

            return(null);
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            //Create the textbox for specifying the Silverlight application
            textboxSilverlightApplication       = new TextBox();
            textboxSilverlightApplication.Width = 300;
            this.Controls.Add(textboxSilverlightApplication);
            //Create the drop down list for choosing the web part to connect to
            ddlSendMessageToThisWebPart = new DropDownList();
            //Add an item to the drop down list for every Connectable Silverlight Web Part on the page
            ListItem currentItem;
            SPFile   currentPage           = SPContext.Current.File;
            SPLimitedWebPartManager    WPM = currentPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            SPLimitedWebPartCollection WebPartCollection = WPM.WebParts;

            foreach (System.Web.UI.WebControls.WebParts.WebPart currentWebPart in WebPartCollection)
            {
                //Make sure this is a Connectable Silverlight Web Part
                if (currentWebPart.GetType().ToString() == "DemoWebParts.SilverlightToSilverlight.ConnectableSilverlightWebPart")
                {
                    //Add the item
                    currentItem       = new ListItem();
                    currentItem.Text  = currentWebPart.Title;
                    currentItem.Value = "SLReceiver_ctl00_m_" + currentWebPart.ClientID;
                    ddlSendMessageToThisWebPart.Items.Add(currentItem);
                }
            }
            this.Controls.Add(ddlSendMessageToThisWebPart);
        }
        private static void AddWebPartConnectionWss(
            SPWeb web,
            string pageUrl,
            string providerWebPartID,
            string consumerWebPartID)
        {
            SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared);

            Microsoft.SharePoint.WebPartPages.WebPart filterWp = (Microsoft.SharePoint.WebPartPages.WebPart)manager.WebParts [providerWebPartID];
            Microsoft.SharePoint.WebPartPages.WebPart listWp   = (Microsoft.SharePoint.WebPartPages.WebPart)manager.WebParts [consumerWebPartID];

            if (filterWp.ConnectionID == Guid.Empty)
            {
                filterWp.ConnectionID = Guid.NewGuid();
            }
            if (listWp.ConnectionID == Guid.Empty)
            {
                listWp.ConnectionID = Guid.NewGuid();
            }

            //listWp.Connections = listWp.ConnectionID + "," +
            //     filterWp.ConnectionID + "," +
            //    "ListViewFilterConsumer_WPQ_" + "," +
            //    "" + "," +
            //    "ListViewFilterConsumer_WPQ_" + "," +
            //    "";
            listWp.Connections = listWp.ConnectionID + "," + filterWp.ConnectionID + ",ListViewFilterConsumer_WPQ_,roxorityFilterProviderInterface,ListViewFilterConsumer_WPQ_,roxorityFilterProviderInterface";
            manager.SaveChanges(filterWp);
            manager.SaveChanges(listWp);
        }
Example #20
0
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsMinimal(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");

            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");

            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
            {
                prop.InnerText = wp.Zone.ToString();
            }
            else
            {
                prop.InnerText = manager.GetZoneID(wp);
            }
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return(Utilities.GetFormattedXml(xmlDoc));
        }
Example #21
0
        public static int GetLatestWebPartIndex(SPWeb web, string pageUrl, string zoneId)
        {
            int idx = 0;

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

                SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager(
                    fullPageUrl,
                    System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
                {
                    if (string.IsNullOrEmpty(zoneId) || (!string.IsNullOrEmpty(zoneId) && mgr.GetZoneID(wp) == zoneId))
                    {
                        if (idx < wp.ZoneIndex)
                        {
                            idx = wp.ZoneIndex;
                        }
                    }
                }
            }
            catch (Exception) { }

            return(idx);
        }
        internal static void SetupConnections(EntitiesDataContext _edc, SPWeb _root)
        {
            SPFile file = _root.GetFile(URLVendorDashboard);

            System.Collections.Generic.Dictionary <string, WebPart> _dict = new System.Collections.Generic.Dictionary <string, WebPart>();
            Anons.WriteEntry(_edc, m_SourceClass + m_SourceSetupConnections, "Setup connections starting");
            string _phase = "starting";

            using (SPLimitedWebPartManager _pageMgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                try
                {
                    _dict  = _pageMgr.WebParts.Cast <WebPart>().ToDictionary(key => key.ID); //.ForEach(wp => wpMgr.DeleteWebPart(wp));
                    _phase = "After wpMgr.WebParts.Cast";
                    ConnectWebParts
                    (
                        _pageMgr,
                        _dict[IDCurrentUser],
                        _dict[IDCarrierDashboardWebPart],
                        CurrentUserWebPart.CurrentUserWebPart.CurrentUserProviderPoint,
                        CarrierDashboard.CarrierDashboardWebPart.CarrierDashboardWebPart.ConsumertIDPartnerInterconnection
                    );
                }
                catch (Exception ex)
                {
                    StringBuilder _names = new StringBuilder();
                    _dict.Keys.ToList <string>().ForEach(name => _names.Append(name + ", "));
                    string _msg = String.Format("Setup connections failed in Phase={0}, Count={1}, First={2}, Ex={3}", _phase, _dict.Count, _names.ToString(), ex.Message);
                    Anons.WriteEntry(_edc, m_SourceClass + m_SourceSetupConnections, _msg);
                    //throw new ApplicationException(_msg);
                }
            Anons.WriteEntry(_edc, m_SourceClass + m_SourceSetupConnections, "Setup connections finished");
        }
Example #23
0
        /// <summary>
        /// Used by EditorParts to fill a ListBox or a DropDownList whith the names of
        /// ListViewWebParts currently loaded in the same page
        /// </summary>
        /// <param name="context">HttpContext, we need the request url</param>
        /// <param name="listControl">Control to fill</param>
        public static void FillWebParts(HttpContext context, ListControl listControl)
        {
            try
            {
                SPWeb curWeb = SPContext.Current.Web;

                using (SPLimitedWebPartManager webpartManager =
                           curWeb.GetLimitedWebPartManager(context.Request.Url.ToString(),
                                                           PersonalizationScope.Shared))
                {
                    foreach (WebPart webpart in webpartManager.WebParts)
                    {
                        ListViewWebPart listViewWebPart = webpart as ListViewWebPart;

                        // if the list is a ListView WebPart
                        if (listViewWebPart != null)
                        {
                            listControl.Items.Add(new ListItem(webpart.Title, listViewWebPart.ViewGuid));
                        }
                        webpart.Dispose();
                    }
                    webpartManager.Web.Dispose();
                }
            }
            catch (Exception)
            {
                listControl.Items.Add(new ListItem(SPSLocalization.GetResourceString("SPSFW_UnavailableListItem"), string.Empty));
            }
        }
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        /// <returns></returns>
        internal static string GetWebPartDetails(WebPart wp, SPLimitedWebPartManager manager)
        {
            if (wp.ExportMode == WebPartExportMode.None)
            {
                Logger.WriteWarning("Unable to export {0}", wp.Title);
                return "";
            }
            StringBuilder sb = new StringBuilder();

            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
            xmlWriter.Formatting = Formatting.Indented;
            manager.ExportWebPart(wp, xmlWriter);
            xmlWriter.Flush();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(sb.ToString());

            XmlElement elem = xmlDoc.DocumentElement;
            if (xmlDoc.DocumentElement.Name == "webParts")
            {
                elem = (XmlElement)xmlDoc.DocumentElement.ChildNodes[0];

                // We've found a v3 web part but the export method does not export what the zone ID is so we
                // have to manually add that in.  Unfortunately the Zone property is always null because we are
                // using a SPLimitedWebPartManager so we have to use the helper method GetZoneID to set the zone ID.
                XmlElement property = xmlDoc.CreateElement("property");
                property.SetAttribute("name", "ZoneID");
                property.SetAttribute("type", "string");
                property.InnerText = manager.GetZoneID(wp);
                elem.ChildNodes[1].ChildNodes[0].AppendChild(property);
            }

            return elem.OuterXml.Replace(" xmlns=\"\"", ""); // Just some minor cleanup to deal with erroneous namespace tags added due to the zoneID being added manually.
        }
Example #25
0
        //public virtual void ExportWebPart(WebPart webPart, XmlWriter writer)
        //{
        //    if (webPart == null)
        //    {
        //        throw new ArgumentNullException("webPart");
        //    }
        //    if (!this.Controls.Contains(webPart))
        //    {
        //        throw new ArgumentException(SR.GetString("UnknownWebPart"), "webPart");
        //    }
        //    if (writer == null)
        //    {
        //        throw new ArgumentNullException("writer");
        //    }
        //    if (webPart.ExportMode == WebPartExportMode.None)
        //    {
        //        throw new ArgumentException(SR.GetString("WebPartManager_PartNotExportable"), "webPart");
        //    }
        //    bool arg_79_0 = (webPart.ExportMode != WebPartExportMode.NonSensitiveData) ? false : (this.Personalization.Scope != PersonalizationScope.Shared);
        //    bool flag = arg_79_0;
        //    writer.WriteStartElement("webParts");
        //    writer.WriteStartElement("webPart");
        //    writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/WebPart/v3");
        //    writer.WriteStartElement("metaData");
        //    writer.WriteStartElement("type");
        //    Control control = webPart.ToControl();
        //    UserControl userControl = control as UserControl;
        //    if (userControl == null)
        //    {
        //        writer.WriteAttributeString("name", WebPartUtil.SerializeType(control.GetType()));
        //    }
        //    else
        //    {
        //        writer.WriteAttributeString("src", userControl.AppRelativeVirtualPath);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteElementString("importErrorMessage", webPart.ImportErrorMessage);
        //    writer.WriteEndElement();
        //    writer.WriteStartElement("data");
        //    IDictionary personalizablePropertyValues = PersonalizableAttribute.GetPersonalizablePropertyValues(webPart, PersonalizationScope.Shared, flag);
        //    writer.WriteStartElement("properties");
        //    if (!(webPart is GenericWebPart))
        //    {
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    else
        //    {
        //        this.ExportIPersonalizable(writer, control, flag);
        //        IDictionary personalizablePropertyValues2 = PersonalizableAttribute.GetPersonalizablePropertyValues(control, PersonalizationScope.Shared, flag);
        //        this.ExportToWriter(personalizablePropertyValues2, writer);
        //        writer.WriteEndElement();
        //        writer.WriteStartElement("genericWebPartProperties");
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //}

        private static void CreateDefaultWebPart(SPWeb web, SPLimitedWebPartManager webPartManager, WebpartDefinition wp, System.Web.UI.WebControls.WebParts.WebPart concerateWP)
        {
            //TODO : find a solution to create default webpart late
            return;

            if (wp is XSLTListViewWP)
            {
                XSLTListViewWP xstlWP = wp as XSLTListViewWP;
                if (xstlWP.CreateDefaultWP)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
                        concerateWP.ExportMode = System.Web.UI.WebControls.WebParts.WebPartExportMode.All;

                        webPartManager.ExportWebPart(concerateWP, writer);


                        var webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);

                        //var fileStream
                        SPFile spfile = webPartGallery.RootFolder.Files.Add(wp.Title + ".webpart", ms.GetBuffer(), true);

                        // Commit
                        webPartGallery.RootFolder.Update();
                        webPartGallery.Update();
                    }
                }
            }
        }
        public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager)
        {
            SPQuery qry = new SPQuery();

               qry.Query = String.Format(CultureInfo.CurrentCulture,
               "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{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);

               XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());

               string errorMsg;

               System.Web.UI.WebControls.WebParts.WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);

               return webPart;
        }
Example #27
0
        public static WebPart CreateWebPart(this SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, out string errorMsg)
        {
            var query = new SPQuery
            {
                Query = String.Format(CultureInfo.CurrentCulture,
                                      "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                                      webPartName),
                RowLimit = 1
            };

            SPList webPartGallery = web.IsRootWeb
                                        ? web.GetCatalog(SPListTemplateType.WebPartCatalog)
                                        : web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);

            SPListItemCollection webParts = webPartGallery.GetItems(query);

            if (webParts.Count == 0)
            {
                throw new SPException(string.Format("Web Part \"{0}\" not found in the gallery.", webPartName));
            }

            using (Stream stream = webParts[0].File.OpenBinaryStream())
            {
                XmlReader xmlReader = new XmlTextReader(stream);
                WebPart   webPart   = webPartManager.ImportWebPart(xmlReader, out errorMsg);
                xmlReader.Close();
                return(webPart);
            }
        }
        // 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);
                    }
                }
            }
        }
Example #29
0
        protected void btnViewAvailability_Click(object sender, EventArgs e)
        {
            SPLimitedWebPartManager webPartManager = null;

            try
            {
                SPList list = null;
                SPView view = null;

                // get WebPartManager to identify current List/View
                SPWeb web = SPContext.Current.Web;
                webPartManager = SPContext.Current.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
                foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts)
                {
                    XsltListViewWebPart xlvwp = wp as XsltListViewWebPart;
                    if (xlvwp != null)
                    {
                        list = web.Lists[xlvwp.ListId];
                        view = xlvwp.View;
                        break;
                    }
                }

                // get list data by Filters
                FieldFilterOperatorsLayer fol = new FieldFilterOperatorsLayer(this.FilterConditions);
                CamlFiltersLayer          fl  = new CamlFiltersLayer(list, this.FilterQuery, fol);
                string myQuery = fl.GetQueryByFilters();
                SPListItemCollection navigator = list.GetItems(new SPQuery()
                {
                    Query = myQuery, ViewFields = "<FieldRef Name=\"ID\" />", RowLimit = view.RowLimit
                });

                // get filter IDs
                string filteredIDs = string.Empty;
                if (navigator != null && navigator.Count > 0)
                {
                    filteredIDs = String.Join(",", navigator.Cast <SPListItem>().Select(x => x.ID.ToString()).ToArray());
                }

                string redigUrl = string.Format("{0}/{1}?FilteredIDs={2}&OrigSchiftId={3}{4}{5}",
                                                web.ServerRelativeUrl.TrimEnd('/'), this.RedirectUrl.TrimStart('/'),
                                                filteredIDs, this.Page.Request.QueryString["SchiftId"],
                                                string.IsNullOrEmpty(this.CalendarPeriod) ? "" : string.Format("&CalendarPeriod={0}", this.CalendarPeriod),
                                                FormatedCalendarDate);
                SPUtility.Redirect(redigUrl, SPRedirectFlags.Default, this.Context);
            }
            catch (Exception ex)
            {
                lblError.Text    = ex.Message;
                lblError.Visible = true;
            }
            finally
            {
                if (webPartManager != null)
                {
                    webPartManager.Web.Dispose();
                }
            }
        }
Example #30
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");
   }
 }
 private static void ConnectWebParts(SPLimitedWebPartManager _pageMgr, WebPart _prvdr, WebPart _cnsmr, string _providerConnectionPoints, string _consumerConnectionPoints)
 {
     _pageMgr.SPConnectWebParts(
         _prvdr,
         _pageMgr.GetProviderConnectionPoints(_prvdr)[_providerConnectionPoints],
         _cnsmr,
         _pageMgr.GetConsumerConnectionPoints(_cnsmr)[_consumerConnectionPoints]);
 }
Example #32
0
        /// <summary>
        /// Returns the list of webparts in mysite.
        /// </summary>
        /// <returns></returns>
        public SPLimitedWebPartCollection GetWebPartsList()
        {
            string             userAccount;
            UserProfileManager profileManager = new UserProfileManager(_context);

            if (ConfigurationSettings.AppSettings[Constants.userAccountSetting] != null)
            {
                userAccount = ConfigurationSettings.AppSettings[Constants.userAccountSetting];
                if (string.IsNullOrEmpty(userAccount))
                {
                    userAccount = Environment.UserName;
                }
            }
            else
            {
                userAccount = Environment.UserName;
            }
            UserProfile defProfile;

            try
            {
                defProfile = profileManager.GetUserProfile(userAccount);
            }
            catch (Microsoft.Office.Server.UserProfiles.UserNotFoundException)
            {
                throw new UserNotFoundException();
            }

            if (defProfile.PersonalSite == null)
            {
                throw new MySiteDoesNotExistException();
            }

            SPSite mySite = defProfile.PersonalSite;

            using (SPWeb myWeb = mySite.OpenWeb())
            {
                string defaultFileName;
                if (ConfigurationSettings.AppSettings[Constants.defaultFileSettings] != null)
                {
                    defaultFileName = ConfigurationSettings.AppSettings[Constants.defaultFileSettings];
                    if (string.IsNullOrEmpty(defaultFileName))
                    {
                        defaultFileName = Constants.defaultFile;
                    }
                }
                else
                {
                    defaultFileName = Constants.defaultFile;
                }

                SPFile defaultFile = myWeb.Files[defaultFileName];

                SPLimitedWebPartManager lmWpm = defaultFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

                return(lmWpm.WebParts);
            }
        }
Example #33
0
        internal static WebPart GetSourceWebPart(string url, string webPartTitle, string webPartId, out string zone)
        {
            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);
                        }
                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            WebPart webPart = null;
                            if (!string.IsNullOrEmpty(webPartTitle))
                            {
                                webPart = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                            }
                            else if (!string.IsNullOrEmpty(webPartId))
                            {
                                webPart = Utilities.GetWebPartById(web, url, webPartId, out manager);
                            }

                            if (manager != null)
                            {
                                zone = manager.GetZoneID(webPart);
                            }
                            else
                            {
                                zone = null;
                            }
                            return(webPart);
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsMinimal(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");
            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");
            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
                prop.InnerText = wp.Zone.ToString();
            else
                prop.InnerText = manager.GetZoneID(wp);
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return Utilities.GetFormattedXml(xmlDoc);
        }
Example #35
0
        public void Init(object spParent, SPLimitedWebPartManager manager)
        {
            this.Tag = manager;

            this.SPParent = spParent;

            int index = Program.Window.Explorer.AddImage(this.ImageUrl());
            this.ImageIndex = index;
            this.SelectedImageIndex = index;

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
        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);
            }
        }
        public System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
        {
            SPQuery query = new SPQuery();
            query.Query = string.Format(CultureInfo.InvariantCulture, "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>", webPartName);

            SPList webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);

            SPListItemCollection webParts = webPartGallery.GetItems(query);

            System.Web.UI.WebControls.WebParts.WebPart webPart = null;
            if (webParts.Count > 0)
            {
                XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                string errorMessage;
                webPart = manager.ImportWebPart(xmlReader, out errorMessage);
            }

            return webPart;
        }
        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;
        }
        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);
        }
        /// <summary>
        /// Replaces the content of a <see cref="SummaryLinkWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
            SPFile file,
            Settings settings,
            SummaryLinkWebPart wp,
            Regex regex,
            ref SPLimitedWebPartManager manager,
            ref bool wasCheckedOut,
            ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.SummaryLinkStore))
                return wp;

            bool isLinkMatch = false;
            string originalContent = wp.SummaryLinkStore;

            SummaryLinkFieldValue links = wp.SummaryLinkValue;

            // Make all appropriate changes here and then reset the value below.
            // We don't want to manipulate the store itself because we risk messing up the XML.
            foreach (SummaryLink link in links.SummaryLinks)
            {
                if (!string.IsNullOrEmpty(link.Description) && regex.IsMatch(link.Description))
                {
                    link.Description = regex.Replace(link.Description, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.ImageUrl) && regex.IsMatch(link.ImageUrl))
                {
                    link.ImageUrl = regex.Replace(link.ImageUrl, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.ImageUrlAltText) && regex.IsMatch(link.ImageUrlAltText))
                {
                    link.ImageUrlAltText = regex.Replace(link.ImageUrlAltText, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.LinkUrl) && regex.IsMatch(link.LinkUrl))
                {
                    link.LinkUrl = regex.Replace(link.LinkUrl, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.Title) && regex.IsMatch(link.Title))
                {
                    link.Title = regex.Replace(link.Title, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.LinkToolTip) && regex.IsMatch(link.LinkToolTip))
                {
                    link.LinkToolTip = regex.Replace(link.LinkToolTip, settings.ReplaceString);
                    isLinkMatch = true;
                }
            }
            if (!isLinkMatch)
                return wp;

            Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                              file.ServerRelativeUrl, wp.Title, originalContent, links.ToString());
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (SummaryLinkWebPart)manager.WebParts[wp.ID];

                wp.SummaryLinkValue = links;

                modified = true;
            }
            return wp;
        }
        private void SubstituteGuidInZone(SPWeb web, SPLimitedWebPartManager manager, DataFormWebPart dataForm, string filePath)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(filePath);
            }
            catch (XmlException)
            {
                return;
            }

            XmlNode xListInstances = doc.DocumentElement.SelectSingleNode("ListInstances");
            if (xListInstances == null)
            {
                return;
            }
            foreach (XmlNode xListInstance in xListInstances.ChildNodes)
            {
                if (xListInstance.Attributes["Id"] == null ||
                    xListInstance.Attributes["Title"] == null)
                {
                    return;
                }

                string oldId = xListInstance.Attributes["Id"].Value;
                string title = xListInstance.Attributes["Title"].Value;

                SPList list = null;
                try
                {
                    list = web.Lists[title];
                }
                catch (ArgumentException)
                {
                    continue;
                }

                if (list == null)
                {
                    continue;
                }
                string newId = list.ID.ToString();

                dataForm.ParameterBindings = Regex.Replace(dataForm.ParameterBindings, oldId, newId, RegexOptions.IgnoreCase);
                dataForm.DataSourcesString = Regex.Replace(dataForm.DataSourcesString, oldId, newId, RegexOptions.IgnoreCase);
                dataForm.Xsl = Regex.Replace(dataForm.Xsl, oldId, newId, RegexOptions.IgnoreCase);

                manager.SaveChanges(dataForm);
            }
        }
Example #42
0
        public static System.Web.UI.WebControls.WebParts.WebPart ResolveWebPartInstance(SPSite site,
           SPLimitedWebPartManager webPartManager,
           WebPartDefinition webpartModel)
        {
            System.Web.UI.WebControls.WebParts.WebPart webpartInstance = null;

            if (!string.IsNullOrEmpty(webpartModel.WebpartType))
            {
                var webPartType = Type.GetType(webpartModel.WebpartType);
                webpartInstance = Activator.CreateInstance(webPartType) as System.Web.UI.WebControls.WebParts.WebPart;
            }
            else if (!string.IsNullOrEmpty(webpartModel.WebpartFileName))
            {
                var webpartFileName = webpartModel.WebpartFileName;
                var rootWeb = site.RootWeb;

                // load definition from WP catalog
                var webpartCatalog = rootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                var webpartItem = webpartCatalog.Items.OfType<SPListItem>().FirstOrDefault(
                        i => string.Compare(i.Name, webpartFileName, true) == 0);

                if (webpartItem == null)
                    throw new ArgumentException(string.Format("webpartItem. Can't find web part file with name: {0}", webpartFileName));

                using (var streamReader = new MemoryStream(webpartItem.File.OpenBinary()))
                {
                    using (var xmlReader = XmlReader.Create(streamReader))
                    {
                        var errMessage = string.Empty;
                        webpartInstance = webPartManager.ImportWebPart(xmlReader, out errMessage);

                        if (!string.IsNullOrEmpty(errMessage))
                            throw new ArgumentException(
                                string.Format("Can't import web part foe with name: {0}. Error: {1}", webpartFileName, errMessage));
                    }
                }
            }
            else if (!string.IsNullOrEmpty(webpartModel.WebpartXmlTemplate))
            {
                var stringBytes = Encoding.UTF8.GetBytes(webpartModel.WebpartXmlTemplate);

                using (var streamReader = new MemoryStream(stringBytes))
                {
                    using (var xmlReader = XmlReader.Create(streamReader))
                    {
                        var errMessage = string.Empty;
                        webpartInstance = webPartManager.ImportWebPart(xmlReader, out errMessage);

                        if (!string.IsNullOrEmpty(errMessage))
                            throw new ArgumentException(
                                string.Format("Can't import web part for XML template: {0}. Error: {1}",
                                webpartModel.WebpartXmlTemplate, errMessage));
                    }
                }
            }
            else
            {
                throw new Exception("Either WebpartType or WebpartFileName or WebpartXmlTemplate needs to be defined.");
            }

            return webpartInstance;
        }
        /// <summary>
        /// Replaces the content of a <see cref="ContentEditorWebPart"/>.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
            SPFile file,
            Settings settings,
            ContentEditorWebPart wp,
            Regex regex,
            ref SPLimitedWebPartManager manager,
            ref bool wasCheckedOut,
            ref bool modified)
        {
            if (wp.Content.FirstChild == null && string.IsNullOrEmpty(wp.ContentLink))
                return wp;

            // The first child of a the content XmlElement for a ContentEditorWebPart is a CDATA section
            // so we want to work with that to make sure we don't accidentally replace the CDATA text itself.
            bool isContentMatch = false;
            if (wp.Content.FirstChild != null)
                isContentMatch = regex.IsMatch(wp.Content.FirstChild.InnerText);
            bool isLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ContentLink))
                isLinkMatch = regex.IsMatch(wp.ContentLink);

            if (!isContentMatch && !isLinkMatch)
                return wp;

            string content;
            if (isContentMatch)
                content = wp.Content.FirstChild.InnerText;
            else
                content = wp.ContentLink;

            string result = content;
            if (!string.IsNullOrEmpty(content))
                result = regex.Replace(content, settings.ReplaceString);

            Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                              file.ServerRelativeUrl, wp.Title, content, result);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (ContentEditorWebPart)manager.WebParts[wp.ID];

                if (isContentMatch)
                    wp.Content = GetDataAsXmlElement("Content", "http://schemas.microsoft.com/WebPart/v2/ContentEditor", result);
                else
                    wp.ContentLink = result;

                modified = true;
            }
            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);
        }
Example #45
0
        public static WebPart FindWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager, string webPartListName)
        {
            try
            {
                SPSite spSite = new SPSite(web.Url);
                SPWeb spWeb = spSite.RootWeb;

                SPQuery query = new SPQuery();
                query.Query = String.Format(CultureInfo.CurrentCulture,
                    "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                    webPartName);

                SPList webPartGallery = spWeb.Lists[webPartListName];
                if (null == spWeb.ParentWeb)
                {
                    webPartGallery = spWeb.GetCatalog(
                       SPListTemplateType.WebPartCatalog);
                }
                else
                {
                    webPartGallery = spWeb.Site.RootWeb.GetCatalog(
                       SPListTemplateType.WebPartCatalog);
                }
                SPListItemCollection webParts = webPartGallery.GetItems(query);

                if (webParts.Count == 0)
                {
                    EssnLog.logInfo(String.Format("Web part with name {0} is not exist on SpWeb {1}", webPartName, spWeb.Url));
                    return null; //check if webpart exist
                }

                XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                string errorMessage;
                WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
                webPart.ChromeType = PartChromeType.BorderOnly;
                return webPart;
            }
            catch (Exception ee)
            {
                EssnLog.logInfo("Error on FindWebPart in FeatureActivated.");
                EssnLog.logExc(ee);
                return null;
            }
        }
Example #46
0
        //public virtual void ExportWebPart(WebPart webPart, XmlWriter writer)
        //{
        //    if (webPart == null)
        //    {
        //        throw new ArgumentNullException("webPart");
        //    }
        //    if (!this.Controls.Contains(webPart))
        //    {
        //        throw new ArgumentException(SR.GetString("UnknownWebPart"), "webPart");
        //    }
        //    if (writer == null)
        //    {
        //        throw new ArgumentNullException("writer");
        //    }
        //    if (webPart.ExportMode == WebPartExportMode.None)
        //    {
        //        throw new ArgumentException(SR.GetString("WebPartManager_PartNotExportable"), "webPart");
        //    }
        //    bool arg_79_0 = (webPart.ExportMode != WebPartExportMode.NonSensitiveData) ? false : (this.Personalization.Scope != PersonalizationScope.Shared);
        //    bool flag = arg_79_0;
        //    writer.WriteStartElement("webParts");
        //    writer.WriteStartElement("webPart");
        //    writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/WebPart/v3");
        //    writer.WriteStartElement("metaData");
        //    writer.WriteStartElement("type");
        //    Control control = webPart.ToControl();
        //    UserControl userControl = control as UserControl;
        //    if (userControl == null)
        //    {
        //        writer.WriteAttributeString("name", WebPartUtil.SerializeType(control.GetType()));
        //    }
        //    else
        //    {
        //        writer.WriteAttributeString("src", userControl.AppRelativeVirtualPath);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteElementString("importErrorMessage", webPart.ImportErrorMessage);
        //    writer.WriteEndElement();
        //    writer.WriteStartElement("data");
        //    IDictionary personalizablePropertyValues = PersonalizableAttribute.GetPersonalizablePropertyValues(webPart, PersonalizationScope.Shared, flag);
        //    writer.WriteStartElement("properties");
        //    if (!(webPart is GenericWebPart))
        //    {
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    else
        //    {
        //        this.ExportIPersonalizable(writer, control, flag);
        //        IDictionary personalizablePropertyValues2 = PersonalizableAttribute.GetPersonalizablePropertyValues(control, PersonalizationScope.Shared, flag);
        //        this.ExportToWriter(personalizablePropertyValues2, writer);
        //        writer.WriteEndElement();
        //        writer.WriteStartElement("genericWebPartProperties");
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //}
        private static void CreateDefaultWebPart(SPWeb web, SPLimitedWebPartManager webPartManager, WebpartDefinition wp, System.Web.UI.WebControls.WebParts.WebPart concerateWP)
        {
            //TODO : find a solution to create default webpart late
            return;
            if (wp is XSLTListViewWP)
            {
                XSLTListViewWP xstlWP = wp as XSLTListViewWP;
                if (xstlWP.CreateDefaultWP)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {

                        XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
                        concerateWP.ExportMode = System.Web.UI.WebControls.WebParts.WebPartExportMode.All;

                        webPartManager.ExportWebPart(concerateWP, writer);

                        var webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);

                        //var fileStream
                        SPFile spfile = webPartGallery.RootFolder.Files.Add(wp.Title + ".webpart", ms.GetBuffer(), true);

                        // Commit
                        webPartGallery.RootFolder.Update();
                        webPartGallery.Update();

                    }

                }
            }
        }
Example #47
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();
        }
        public static void ConnectListViewWebParts(SPLimitedWebPartManager webPartManager, ListViewWebPart providerWebPart, ListViewWebPart consumerWebPart, SPRowToParametersTransformer transformer, string consumerInternalFieldName, string providerInternalFieldName)
        {
            webPartManager.RequireNotNull("webPartManager");
            providerWebPart.RequireNotNull("providerWebPart");
            consumerWebPart.RequireNotNull("consumerWebPart");
            transformer.RequireNotNull("transformer");
            consumerInternalFieldName.RequireNotNullOrEmpty("consumerInternalFieldName");
            providerInternalFieldName.RequireNotNullOrEmpty("providerInternalFieldName");

            ProviderConnectionPoint providerConnectionPoint = (from ProviderConnectionPoint conn in webPartManager.GetProviderConnectionPoints(providerWebPart)
                                                               where String.Equals("Provide Row To", conn.DisplayName, StringComparison.OrdinalIgnoreCase) && conn.InterfaceType == typeof(IWebPartRow)
                                                               select conn).FirstOrDefault();
            ConsumerConnectionPoint consumerConnectionPoint = (from ConsumerConnectionPoint conn in webPartManager.GetConsumerConnectionPoints(consumerWebPart)
                                                               where String.Equals("Get Sort/Filter From", conn.DisplayName, StringComparison.OrdinalIgnoreCase) && conn.InterfaceType == typeof(IWebPartParameters)
                                                               select conn).FirstOrDefault();

            consumerWebPart.Connections = consumerWebPart.ConnectionID + "," + providerWebPart.ConnectionID + "," +
                                             consumerConnectionPoint.ID + "," + providerConnectionPoint.ID + "," +
                                             consumerConnectionPoint.ID + "," + providerConnectionPoint.ID + "," +
                                              consumerInternalFieldName + "=" + providerInternalFieldName;

            webPartManager.SaveChanges(consumerWebPart);
        }
        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);
        }
        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);
        }
        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>
        /// Replaces the content of a <see cref="MediaWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           MediaWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.MediaSource) && string.IsNullOrEmpty(wp.TemplateSource) && string.IsNullOrEmpty(wp.PreviewImageSource))
                return wp;

            bool isMediaSourceMatch = false;
            if (!string.IsNullOrEmpty(wp.MediaSource))
                isMediaSourceMatch = regex.IsMatch(wp.MediaSource);

            bool isTemplateSourceMatch = false;
            if (!string.IsNullOrEmpty(wp.TemplateSource))
                isTemplateSourceMatch = regex.IsMatch(wp.TemplateSource);

            bool isPreviewImageSourceMatch = false;
            if (!string.IsNullOrEmpty(wp.PreviewImageSource))
                isPreviewImageSourceMatch = regex.IsMatch(wp.PreviewImageSource);

            if (!isMediaSourceMatch && !isTemplateSourceMatch && !isPreviewImageSourceMatch)
                return wp;

            string mediaSourceContent = wp.MediaSource;
            string templateSourceContent = wp.TemplateSource;
            string previewImageSourceContent = wp.PreviewImageSource;

            string mediaSourceResult = mediaSourceContent;
            string templateSourceResult = templateSourceContent;
            string previewImageSourceResult = previewImageSourceContent;

            if (!string.IsNullOrEmpty(mediaSourceContent))
                mediaSourceResult = regex.Replace(mediaSourceContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(templateSourceContent))
                templateSourceResult = regex.Replace(templateSourceContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(previewImageSourceContent))
                previewImageSourceResult = regex.Replace(previewImageSourceContent, settings.ReplaceString);

            if (isMediaSourceMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, mediaSourceContent, mediaSourceResult);
            if (isTemplateSourceMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, templateSourceContent, templateSourceResult);
            if (isPreviewImageSourceMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, previewImageSourceContent, previewImageSourceResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (MediaWebPart)manager.WebParts[wp.ID];

                if (isMediaSourceMatch)
                    wp.MediaSource = mediaSourceResult;
                if (isTemplateSourceMatch)
                    wp.TemplateSource = templateSourceResult;
                if (isPreviewImageSourceMatch)
                    wp.PreviewImageSource = previewImageSourceResult;

                modified = true;
            }
            return wp;
        }
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsSimple(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");
            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");
            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowClose");
            prop.InnerText = wp.AllowClose.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowConnect");
            prop.InnerText = wp.AllowConnect.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowEdit");
            prop.InnerText = wp.AllowEdit.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowHide");
            prop.InnerText = wp.AllowHide.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("TitleUrl");
            prop.InnerText = wp.TitleUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowMinimize");
            prop.InnerText = wp.AllowMinimize.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowZoneChange");
            prop.InnerText = wp.AllowZoneChange.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("CatalogIconImageUrl");
            prop.InnerText = wp.CatalogIconImageUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ChromeState");
            prop.InnerText = wp.ChromeState.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ChromeType");
            prop.InnerText = wp.ChromeType.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("HasSharedData");
            prop.InnerText = wp.HasSharedData.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("HasUserData");
            prop.InnerText = wp.HasUserData.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Subtitle");
            prop.InnerText = wp.Subtitle;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("TitleUrl");
            prop.InnerText = wp.TitleUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("TitleIconImageUrl");
            prop.InnerText = wp.TitleIconImageUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
                prop.InnerText = wp.Zone.ToString();
            else
                prop.InnerText = manager.GetZoneID(wp);
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return Utilities.GetFormattedXml(xmlDoc);
        }
        /// <summary>
        /// Replaces the content of a <see cref="CmsDataFormWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>
        /// The modified web part.  This returned web part is what must be used when saving any changes.
        /// </returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           CmsDataFormWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.HeaderXslLink) && string.IsNullOrEmpty(wp.ItemXslLink) && string.IsNullOrEmpty(wp.MainXslLink))
                return wp;

            bool isHeaderXslLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.HeaderXslLink))
                isHeaderXslLinkMatch = regex.IsMatch(wp.HeaderXslLink);

            bool isItemXslLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ParameterBindings))
                isItemXslLinkMatch = regex.IsMatch(wp.ItemXslLink);

            bool isMainXslLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ListName))
                isMainXslLinkMatch = regex.IsMatch(wp.MainXslLink);

            if (!isHeaderXslLinkMatch && !isItemXslLinkMatch && !isMainXslLinkMatch)
                return wp;

            string headerXslLinkContent = wp.HeaderXslLink;
            string itemXslLinkContent = wp.ItemXslLink;
            string mainXslLinkContent = wp.MainXslLink;

            string headerXslLinkResult = headerXslLinkContent;
            string itemXslLinkResult = itemXslLinkContent;
            string mainXslLinkResult = mainXslLinkContent;

            if (!string.IsNullOrEmpty(headerXslLinkContent))
                headerXslLinkResult = regex.Replace(headerXslLinkContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(itemXslLinkContent))
                itemXslLinkResult = regex.Replace(itemXslLinkContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(mainXslLinkContent))
                mainXslLinkResult = regex.Replace(mainXslLinkContent, settings.ReplaceString);

            if (isHeaderXslLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, headerXslLinkContent, headerXslLinkResult);
            if (isItemXslLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, itemXslLinkContent, itemXslLinkResult);
            if (isMainXslLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, mainXslLinkContent, mainXslLinkResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (CmsDataFormWebPart)manager.WebParts[wp.ID];

                if (isHeaderXslLinkMatch)
                    wp.HeaderXslLink = headerXslLinkResult;
                if (isItemXslLinkMatch)
                    wp.ItemXslLink = itemXslLinkResult;
                if (isMainXslLinkMatch)
                    wp.MainXslLink = mainXslLinkResult;

                modified = true;
            }
            return wp;
        }
        /// <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);
            }
        }
        /// <summary>
        /// Replaces the content of a <see cref="ContentByQueryWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           ContentByQueryWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.ListGuid) && string.IsNullOrEmpty(wp.WebUrl) && string.IsNullOrEmpty(wp.GroupBy))
                return wp;

            bool isListGuidMatch = false;
            if (!string.IsNullOrEmpty(wp.ListGuid))
                isListGuidMatch = regex.IsMatch(wp.ListGuid);

            bool isWebUrlMatch = false;
            if (!string.IsNullOrEmpty(wp.WebUrl))
                isWebUrlMatch = regex.IsMatch(wp.WebUrl);

            bool isGroupByMatch = false;
            if (!string.IsNullOrEmpty(wp.GroupBy))
                isGroupByMatch = regex.IsMatch(wp.GroupBy);

            if (!isListGuidMatch && !isWebUrlMatch && !isGroupByMatch)
                return wp;

            string listGuidContent = wp.ListGuid;
            string webUrlContent = wp.WebUrl;
            string groupByContent = wp.GroupBy;

            string listGuidResult = listGuidContent;
            string webUrlResult = webUrlContent;
            string groupByResult = groupByContent;

            if (!string.IsNullOrEmpty(listGuidContent))
                listGuidResult = regex.Replace(listGuidContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(webUrlContent))
                webUrlResult = regex.Replace(webUrlContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(groupByContent))
                groupByResult = regex.Replace(groupByContent, settings.ReplaceString);

            if (isListGuidMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, listGuidContent, listGuidResult);
            if (isWebUrlMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, webUrlContent, webUrlResult);

            if (isGroupByMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, groupByContent, groupByResult);

            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (ContentByQueryWebPart)manager.WebParts[wp.ID];

                if (isListGuidMatch)
                    wp.ListGuid = listGuidResult;
                if (isWebUrlMatch)
                    wp.WebUrl = webUrlResult;
                if (isGroupByMatch)
                    wp.GroupBy = groupByResult;

                modified = true;
            }
            return wp;
        }
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           PeopleCoreResultsWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.FixedQuery) && string.IsNullOrEmpty(wp.Xsl))
                return wp;

            bool isFixedQueryMatch = false;
            if (!string.IsNullOrEmpty(wp.FixedQuery))
                isFixedQueryMatch = regex.IsMatch(wp.FixedQuery);

            bool isXslMatch = false;
            if (!string.IsNullOrEmpty(wp.Xsl))
                isXslMatch = regex.IsMatch(wp.Xsl);

            if (!isFixedQueryMatch && !isXslMatch)
                return wp;

            string fixedQueryContent = wp.FixedQuery;
            string xslContent = wp.Xsl;

            string fixedQueryResult = fixedQueryContent;
            string xslResult = xslContent;

            if (!string.IsNullOrEmpty(fixedQueryContent))
                fixedQueryResult = regex.Replace(fixedQueryContent, settings.ReplaceString);
            try
            {
                if (!string.IsNullOrEmpty(xslContent))
                {
                    if (!settings.UnsafeXml)
                        xslResult = ReplaceXmlValues(regex, settings.ReplaceString, xslContent);
                    else
                        xslResult = regex.Replace(xslContent, settings.ReplaceString);
                }
            }
            catch (XmlException ex)
            {
                isXslMatch = false;
                string msg = string.Format(
                    "WARNING: An error occured replacing data in a PeopleCoreResultsWebPart: File={0}, WebPart={1}\r\n{2}",
                    file.ServerRelativeUrl, wp.Title, Utilities.FormatException(ex));
                Logger.WriteWarning(msg);
            }
            if (isFixedQueryMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, fixedQueryContent, fixedQueryResult);
            if (isXslMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, xslContent, xslResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (PeopleCoreResultsWebPart)manager.WebParts[wp.ID];

                if (isFixedQueryMatch)
                    wp.FixedQuery = fixedQueryResult;
                if (isXslMatch)
                    wp.Xsl = xslResult;

                modified = true;
            }
            return wp;
        }
        /// <summary>
        /// Replaces the content of a <see cref="ImageWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           ImageWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.ImageLink) && string.IsNullOrEmpty(wp.AlternativeText))
                return wp;

            bool isAltTextMatch = false;
            if (!string.IsNullOrEmpty(wp.AlternativeText))
                isAltTextMatch = regex.IsMatch(wp.AlternativeText);

            bool isLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ImageLink))
                isLinkMatch = regex.IsMatch(wp.ImageLink);

            if (!isAltTextMatch && !isLinkMatch)
                return wp;

            string altTextContent = wp.AlternativeText;
            string linkContent = wp.ImageLink;

            string altTextResult = altTextContent;
            string linkResult = linkContent;

            if (!string.IsNullOrEmpty(altTextContent))
                altTextResult = regex.Replace(altTextContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(linkContent))
                linkResult = regex.Replace(linkContent, settings.ReplaceString);

            if (isAltTextMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, altTextContent, altTextResult);
            if (isLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, linkContent, linkResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (ImageWebPart)manager.WebParts[wp.ID];

                if (isAltTextMatch)
                    wp.AlternativeText = altTextResult;
                if (isLinkMatch)
                    wp.ImageLink = linkResult;

                modified = true;
            }
            return wp;
        }
Example #59
0
 public static void DeployWebPartsToPage(SPLimitedWebPartManager webPartManager,
     IEnumerable<WebPartDefinition> webpartDefinitions)
 {
     DeployWebPartsToPage(webPartManager, webpartDefinitions, null, null);
 }
Example #60
0
 public static void DeployWebPartsToPage(SPLimitedWebPartManager webPartManager,
     WebPartDefinition webpartDefinitions)
 {
     DeployWebPartToPage(webPartManager, webpartDefinitions, null, null);
 }