Retrieve a list of web parts on a page - sharepoint

I am trying to get a list of webparts deployed on a web page in sharepoint 3.0. Is there way I can retrieve it from sharepoint content database or can I do it programmatically?

You can use the SPWebPartManager to iterate thru a list of web part in a page.
See this MSDN example.
EDIT:
This is maybe a better example:
private static void GetWebParts()
{
using (SPSite site = new SPSite("<YOUR SITE URL>"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("default.aspx"); // or what ever page you are interested in
using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
foreach (WebPart wp in wpm.WebParts)
{
Console.WriteLine("Web part: {0}", wp.Title);
}
}
}
}
}

Adding web parts programmatically is simple:
SPWeb site = SPContext.Current.Web;
SPFile page = web.GetFile("Pages/somepage.aspx");
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
// logic to get web parts here.
ContentEditorWebPart webPart = new ContentEditorWebPart();
webPart.Title = "Test Web Part";
webPartManager.AddWebPart(webPart, "Zone 1", 0);
}
finally
{
// SPLimitedWebPartManager has known memory leak where it does not dispose SPRequest object in its SPWeb, so dispose it
webPartManager.Web.Dispose();
}
}

Related

How to Update properties of sharepoint 2010 feature

I have a problem with updating properties of sharepoint 2010 feature
this is my code :
using (SPSite site = new SPSite("http://vm-pc:2000"))
{
foreach (SPFeatureDefinition def in SPFarm.Local.FeatureDefinitions)
{
if (def.Scope == SPFeatureScope.WebApplication)
{
if (def.GetTitle(System.Threading.Thread.CurrentThread.CurrentCulture) == "Configure Site Settings")
{
((SPFeatureProperty)def.Properties[0]).Value = "5";
def.Properties.Update();
def.Update();
}
}
}
}
The problem with def.Properties.Update();
It throws an exception :
Updating the properties of a feature definition is not supported.
Why dont you use the Property bag?
SPSite site = new SPSite("URL");
SPWeb web = site.RootWeb;
web.Properties.Add("Key", "Value");
web.Properties.Update();
and get value:
web.AllProperties["Key"]

How to access List from Sub Site in SharePoint 2010

I have created a Site Named Application Test. In this site i again Create a Sub site Named Sub Application.
I add in site url "http://SP2010:2222/" in Visual Studio Project
Project Scope is Site.
Now i when i try to access the List ( TestList ) From Sub site ( Sub Application ) it give error List Does not Exist.
Following Code to Access the List( TestList ):
using (SPSite sites = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = sites.OpenWeb())
{
SPList CurrentList = web.Lists["TestList"]; // Error comes here
}
}
anybody have solution?
Try this,
using (SPSite sites = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = sites.OpenWeb())
{
SPWebCollection subsites= web.GetSubwebsForCurrentUser(); //get subsites
for (int i= 0; i< subsites.Count; i++)
{
SPWeb subSiteWeb= subsites[i];
SPList CurrentList = subSiteWeb.Lists["TestList"];
if (CurrentList != null)
break;
}
}
}
Well SPContext.Current.Site is the current site you deployed your thing to - whatever it is. But when you do sites.OpenWeb() without any parameters is opens the RootWeb and if the root web doesn't have your list you won't find it there.
Try to open the web and the site explicitly by using their respective URLs e.g. http://SP2010:2222/

webpart is working on local server but not working on production when "SPSite" class is uesd in the webpart

webpart is working on local server but not working on production server when "SPSite" class is uesd in the web part. On the production server it throws error. If I do not use that class in the webpart the web part also works on live machine.
Any idea what might be causing the error?
the code in the webpart is this:
namespace CompanyNews
{
[Guid("40de3c60-9e30-4050-b9f3-01e71868f522")]
public class CompanyNews : System.Web.UI.WebControls.WebParts.WebPart
{
private HtmlTextWriter writer;
public CompanyNews()
{
}
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
string listName = "News Display";
writer.Write(listName);
SPList list = null;
foreach (SPList currentList in web.Lists)
{
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase))
{
list = currentList;
break;
}
}
writer.WriteBeginTag("ul");
foreach (SPListItem item in list.Items)
{
writer.Write("<li style=\"font-size:12px;padding:1px\">");
writer.Write(item["Title"].ToString() + "... ");
writer.Write("<a class=\"smallerred\" href=\"#\">Read More</a>");
writer.Write("</li>");
}
writer.WriteEndTag("ul");
}
}
}
}
}
The dll of the webpart is in the bin folder and in the web.config file there is an entry for the web par as a safe control.
Other webpart which displays a "hellow world" message is also uploaded to production the same way.
I i guess its the code that is causing the problem.
The error message is: "An error occurred while previewing the web part"
just something I noticed, you shouldn't wrap objects from the Current Context in a using statement. Good article here Clicky
Better practice would be to use the following
using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
{
...
}
Also you should look at packaging up your solution in a WSP, allowing stsadm to deploy it. Dragging into the GAC isn't very good practice.
Shane
The SPSite object isn't getting reference anywhere that I can see. Why don't you remove it anyway as it's superflous to your needs?
SPWeb web = SPContext.Current.Web;
string listName = "News Display";
writer.Write(listName);
SPList list = null;
foreach (SPList currentList in web.Lists)
{
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase))
{
list = currentList;
break;
}
}
writer.WriteBeginTag("ul");
foreach (SPListItem item in list.Items)
{
writer.Write("<li style=\"font-size:12px;padding:1px\">");
writer.Write(item["Title"].ToString() + "... ");
writer.Write("<a class=\"smallerred\" href=\"#\">Read More</a>");
writer.Write("</li>");
}
writer.WriteEndTag("ul");

Retrieve all Master Pages for a SharePoint Site?

How can I determine programmatically what master pages (custom and OOTB) that are available for to use for a web site in SharePoint?
Thanks, MagicAndi
I came up with this solution, making use of a SPQuery object to query the team site collection's Master Page Gallery list:
try
{
using (SPSite site = new SPSite(this.ParentSiteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists["Master Page Gallery"];
SPQuery oQuery = new SPQuery();
oQuery.Query = string.Format("<Where><Contains><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">.master</Value></Contains></Where><OrderBy><FieldRef Name=\"FileLeafRef\" /></OrderBy>");
SPListItemCollection colListItems = myList.GetItems(oQuery);
foreach (SPListItem currentItem in colListItems)
{
// Process master pages
}
}
}
}
catch (Exception ex)
{
}
Use reflection and check whether the type's base type equals System.Web.UI.MasterPage.
So something along the lines of:
foreach(Type t in Assembly.GetExecutingAssembly().GetTypes())
{
if (t.BaseType==typeof(MasterPage))
{
// do something, add to collection - whatever
}
}
But, depending on in what assembly your MasterPages are defined, and the fact it iterates over all the types in a specific assembly, it may definitely not be the best solution.
I am blissfully ignorant about SharePoint, but this solution is somewhat more generic I guess.

Find out the URL for the document library of a SharePoint document

If i know the URL for a document, can I find the URL for sharepoint document library in which the document is present. The following are two sample URLs for a SharePoint site. The first document is present under the root of a document library. The second document is present under a folder "folder1" within the document library. Appreciate if there is anyway to know the URL for a document library (http:///sites/site1/DocLib/Forms/AllItems.aspx).
http:///sites/site1/DocLib/a.doc
http:///sites/site1/DocLib/folder1/a.doc
Thanks for your replies. I am looking for a solution with MOSS OOTB web service or based on the URL pattern. Can we use any of these to acheive this please?
Thanks.
The SPWeb object has a GetFile method, which takes the full file url.
SPFile file = web.GetFile(yoururl);
Now it's easy to get to the SPList's url, by using the following:
string listUrl = file.Item.ParentList.DefaultViewUrl;
So, in a method together:
public string GetListUrlFromFileUrl(string fullFileUrl)
{
using (SPSite site = new SPSite(fullFileUrl))
{
using(SPWeb myWeb = site.OpenWeb())
{
SPFile file = myWeb.GetFile(fullFileUrl);
return file.Item.ParentList.DefaultViewUrl;
}
}
}
Make sure to reference Microsoft.Sharepoint.dll in your project as well.
There are two different ways I do this, depending on the situation. Neither performs extremely well (important to note), though the second solution typically performs fairly well for our use cases.
The first is extremely simple:
private SPList GetListForFile(string fileUrl)
{
using (SPSite site = new SPSite(fileUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile(fileUrl);
if (file.Exists)
{
return file.Item.ParentList;
}
}
}
return null;
}
The second is a little more complex. It does require you first chopping off the file part of the URL, then passing it in to the method to get the correct SPWeb, then finding the right list in the web.
private SPList GetListForFile(string fileUrl)
{
using(SPWeb web = OpenWeb(GetFolderUrl(fileUrl)))
{
string listName = fileUrl.Replace(web.ServerRelativeUrl, "");
listName = listName.Substring(0, listName.IndexOf('/'));
return web.Lists[listName];
}
}
private string GetFolderUrl(string fileUrl)
{
return Regex.Replace(fileUrl, #"/[^/]+?\.[A-Z0-9_]{1,6}$", "",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
private SPWeb OpenWeb(string folderUrl)
{
SPWeb web = null;
while(web == null)
{
web = Site.OpenWeb(folderUrl);
if (!web.Exists)
{
web.Dispose();
web = null;
}
folderUrl = folderUrl.Substring(0, folderUrl.LastIndexOf("/"));
if (folderUrl.Length == 0)
{
folderUrl = "/";
}
}
return web;
}

Resources