Search This Blog

Wednesday, May 4, 2016

How to add a custom webpart and their custom properties in the wiki page of sharepoint 2013 programmatically

     

Here I have added an sample code for how to add a custom webpart and their custom properties in the wiki page of sharepoint 2013 progrmmatically                              


                                               
 AddWebPartToPage("http://Testserver/sites/Test", "http://Testserver/sites/Test/Client", "http://Testserver/sites/Test/Client/SitePages/Home.aspx","Test Details", "Test Details", "wpz", 0, lstDetails);
                                               



  /// <summary>
        /// Adds the Web Part to Page
        /// </summary>
        /// <param name="site">SPSite Object</param>
        ///  <param name="web">SPWeb Object</param>
        /// <param name="pageUrl">Page Url for the Page</param>
        /// <param name="WebpartName">WebpartName</param>
        /// <param name="WebpartTitle">WebpartTitle</param>
        /// <param name="Zone">Zone</param>
        /// <param name="ZoneIndex">ZoneIndex</param>
        /// <param name="lstProperties">Custom list with webpart property and values</param>
 
 public static void AddWebPartToPage(SPSite Site, SPWeb Web, string PageUrl, string WebpartName, string WebpartTitle, string Zone, int ZoneIndex, List<WebpartDetails> lstProperties)
        {
            // TO DO : Check for existence of web part
            bool webpartExistance = false;
            SPFile page = default(SPFile);
            try
            {
                Web.AllowUnsafeUpdates = true;
                page = Web.GetFile(PageUrl);
                if (page.Exists)
                {
                    if (page.Level == SPFileLevel.Published)
                    {
                        page.CheckOut();
                    }

                    using (SPLimitedWebPartManager manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
                    {
                        Guid storageKey = Guid.NewGuid();
                        string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));

                        string errorMessage = string.Empty;
                        if (!Web.IsRootWeb)
                        {
                            Web = Web.Site.RootWeb;
                        }

                        SPLimitedWebPartCollection webparts = manager.WebParts;
                        foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in webparts)
                        {
                            if (webpart.Title == WebpartTitle)
                            {
                                // Web Part found!
                                webpartExistance = true;
                                break;
                            }
                        }
                        if (!webpartExistance)
                        {
                            Console.WriteLine("Adding Webpart" + WebpartName + " in " + PageUrl + " Please wait...");
                            SPList webpartlist = Site.GetCatalog(SPListTemplateType.WebPartCatalog);
                            SPQuery oQuery = new SPQuery();
                            oQuery.Query = "<Where><Eq><FieldRef Name='Title' />" +
                            "<Value Type='Text'>" + WebpartName + "</Value></Eq></Where>";
                             SPListItemCollection oCatalogItems = webpartlist.GetItems(oQuery);
                            if (oCatalogItems != null)
                            {
                                foreach (SPListItem oCatalogItem in oCatalogItems)
                                {
                                    SPFile oWebPartFile = Web.Folders["_catalogs"].SubFolders["wp"].Files[oCatalogItem["Name"].ToString()];
                                    XmlReader xml = XmlReader.Create(oWebPartFile.OpenBinaryStream());
                                    var wp = manager.ImportWebPart(xml, out errorMessage);
                                    wp.ID = wpId;
                                    wp.Title = WebpartTitle;
                                    wp.AllowEdit = true;
                                    wp.AllowClose = true;
                                    wp.AllowHide = true;
                                    wp.AllowMinimize = true;
                                    wp.AllowConnect = true;
                                    wp.AllowZoneChange = true;
                                    wp.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                                    wp.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.Default;
                                    PropertyInfo[] pinProperties = wp.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField);

                                    foreach (PropertyInfo pinProperty in pinProperties)
                                    {
                                        foreach (WebpartDetails item in lstProperties)
                                        {
                                            if (pinProperty.Name == item.Property)
                                            {
                                                pinProperty.SetValue(wp, item.Value, null);
                                            }
                                        }
                                    }
                                    manager.AddWebPart(wp, Zone, ZoneIndex);
                                    manager.SaveChanges(wp);
                                    oWebPartFile.Update();
                                    Web.Update();
                                    string marker = string.Empty;

                                    marker = String.Format(CultureInfo.InvariantCulture, "<div id=\"div" + WebpartTitle.Replace(" ", "") + "\" class=\"ms-rte-layoutszone-outer\" style=\"width: 100%;\"><div aria-haspopup=\"true\" class=\"ms-rte-layoutszone-inner\" role=\"textbox\" aria-multiline=\"true\" aria-autocomplete=\"both\"><div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-notify  ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div></div></div>", new object[] { storageKey.ToString("D") });
                                    SPListItem item1 = page.Item;
                                    item1[SPBuiltInFieldId.WikiField] += marker;
                                    item1.Update();
                                    page.Update();
                                }
                            }
                            Console.WriteLine("Added Webpart " + WebpartTitle + " in " + PageUrl + " Successfully");
                        }
                        else
                        {
                            Console.WriteLine("This " + WebpartTitle + " already exists in " + PageUrl);
                        }
                    }
                    if (page.Level == SPFileLevel.Checkout)
                    {
                        page.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
                    }
                }
                else
                {
                    Console.WriteLine(PageUrl + " Doesn't Exists");
                 }
            }
            catch (Exception ex)
            {
               Console.WriteLine(Exception "+ ex.ToString());
            }
       }

No comments:

Post a Comment