Search This Blog

Wednesday, May 18, 2016

Cross Site List Query using SPSiteDataQuery in SharePoint 2013

SPSiteDataQuery can be used to perform cross-site and cross-list queries. In order to use it, you must call SPWeb.GetSiteData method on the appropriate web and provide a SPSiteDataquery object.

We can use this class to retrieve data from selected lists or from all the lists in the current site  collection. We have to set the following before we start.

  • Specify the scope of the query by setting the Webs property (Site collection, site etc). 
  • Specify the lists to participate in the query by setting the Lists property 
  • Specify the fields to return by setting the View Fields property. 
  • We have to Control data selection and order by setting the Query property.


SPSiteDataQuery and SPQuery differ SPSiteDataQueries ability to search more than a single site or single list. SPSiteDataQuery can be configured to search in all lists of a particular list type or list base type located in either

1) The complete site collection

2) a particular site and sub-sites

Using SPSiteDataQuery.Webs property you can specify where the data will be retrieved from. This property can have one of the following values:

“” (or string.Empty) – default value : will search only the SPWeb on which you run GetSiteData

“<Webs Scope=’SiteCollection’ />” : will search on all webs in the site collection

“<Webs Scope=’Recursive’ />” : will search the SPWeb on which you run GetSiteData and all subwebs

You can restrict the search using Lists and Query properties. In the following example we query all contacts lists in the site collection for items containing John in the Last Name field:SPSiteDataQuery query = new SPSiteDataQuery();

//query contacts list.

query.Lists = “<Lists ServerTemplate=’105′ />”;

query.ViewFields = “<FieldRef Name=’Title’ />”;

query.Query = “<Where><Contains>” +

“<FieldRef Name=’Title’ /><Value Type=’text’>John</Value>”+

“</Contains></Where>”;

query.Webs = “<Webs Scope=’SiteCollection’ />”;

DataTable dt = SPContext.Current.Web.GetSiteData(query);

For the Lists property you can use constructs like:

<Lists ServerTemplate=’10001′ /> – query lists with template 10001

<Lists BaseType=’5′ /> – Issues lists

<Lists><List ID=”960BF6F6-F264-4305-B3CB-BDB9BF8F67DF” /></Lists> – query a specific list

Wednesday, May 4, 2016

How to remove the webpart in the site pages of sharepoint 2013 progrmmatically

Here i have given a sample code to remove the webpart in the pages of sharepoint 2013 programmatically


 RemoveWebPart(oSPWeb, "http://TestServer/sites/Test/Sitepages/Home.aspx","Test details");

///<summary> /// Remove a web part based on its title
        /// </summary>
        ///Web site to remove the web part from
        ///Web page to remove the web part within
        ///Title of the web part(s) to remove
        public static void RemoveWebPart(SPWeb web, string page, string webPartTitle)
        {
            try
            {
                using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(web.Url + page, PersonalizationScope.Shared))
                {
                    IEnumerable webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts
                                              where webPart.Title == webPartTitle
                                              select webPart;

                    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList)
                    {
                        Console.WriteLine("Removing Webpart" + webPartTitle + " in " + web.Url + page + " Please wait...");
                        webPartManager.DeleteWebPart(webPart);
                        break;
                    }

                    web.Update();
                }

            }
            catch (Exception ex)
            {
                     Console.WriteLine("Exception =" + ex.ToString() );
            }
        }

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());
            }
       }