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.
Related
I was successfully able to update one of the fields (which was of type boolean) from infopath for library item using sharepoint object Model as if it was a list item.
But for another field which is of type text, the same code just gets executed but does not change the field value !!!!
I am using following code, which works for that boolean field but for another field of type string , not sure why it is not working. Any idea ?
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb web;
SPSite site = new SPSite("http://sharepointsite");
web = site.OpenWeb();
SPList formLibList = web.Lists["FormLibraryName"];
SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + titleName + "</Value></Eq></Where>";
web.Site.WebApplication.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;
SPListItemCollection col = formLibList.GetItems(query);
if (col.Count > 0)
{
col[0]["CustomerName"] = "test customer name";
col[0].Update();
}
web.Site.WebApplication.FormDigestSettings.Enabled = true; web.AllowUnsafeUpdates = false;
});
Thanks,
Nikhil
I had to declare SPListItem and set it instead of directly modifying list item collection.
It's not an answer to your question (you already found the solution yourself), but you may want to put your SPSite and SPWeb objects in a using block. In your example code you are not disposing them, which results in a memory leak. The correct way would be like this:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://sharepointsite"))
{
using (SPWeb web = site.OpenWeb())
{
// the rest of your code
}
}
});
am working on a project where I want to pull data from different lists in SharePoint and have these data imported into a single list. The list has the same attribute everywhere; it is located in different sites.
I have a list which contains all the site names and URL to those sites. The idea is to read from this list all the site names and then go to each one of those sites and try and pull the information from the list under that particular site, in synchronies matter. Data that are pulled from last week’s process do not need to be pulled again.
Can someone guide me in explaining what would be the best way to doing this solution?
Am using SharePoint 2007
You may be better off looking at the Data View Web Part (DVWP) and rollups
A common topic that is asked about in
SharePoint, is how to roll up
information from sub-sites to a top
level site, and just generally how to
show data from one site on another
site.
I have this scenario. I made a webpart that sends the information for my consolidation list, through the sharepoint web services.
I installed the webpart in each sharepoint site, this webpart get the data (when it's outdated) and make a insert in the consolidation list through the lists.asmx webservice. See http://msdn.microsoft.com/en-us/library/lists(v=office.12).aspx. Then a I create a user with permission to write in the consolidation list in my consolidation site, and used this to authenticate my webpart when it will do the insert on the list.
I did something like this, in Visual Studio 2005, with Sharepoint dll referenced.
public void InsertToPainel(string strID, string user, string password)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
//WSPainel is the WebReference to http://<site>/_vti_bin/Lists.asmx.
using (WSPainel.Lists lstPainel = new webPartSender.WSPainel.Lists())
{
lstPainel.UseDefaultCredentials = true;
lstPainel.Credentials = new System.Net.NetworkCredential(user, password);
#region Make the fields in consolidation list
Dictionary<string, string> fieldsNamesAndValues = new Dictionary<string, string>();
fieldsNamesAndValues.Add("ID", strID);//Recuperar quando for atualizar ou incluir New
fieldsNamesAndValues.Add("URL", SPContext.Current.Web.Url + ", " + splInfGerItems[0]["Title"].ToString()); //The link of the actual site that is sending the information
fieldsNamesAndValues.Add("Comments", splStatusItems[0]["Title"].ToString());//In my case, I just need the last result.
#endregion
//It will make the register in CAML format and updates the lists.
lstPainel.UpdateListItems(_listaPainel, NewCAMLRegister(fieldsNamesAndValues, strID));
}
}
catch (Exception e)
{
//Exception
}
});
}
private XmlNode NewCAMLRegister(Dictionary<string, string> FieldsNamesAndValues, string strID)
{
try
{
XmlDocument xdMensagem = new XmlDocument();
XmlElement xeBatch = xdMensagem.CreateElement("Batch");
XmlNode xnMethod = xdMensagem.CreateElement("Method");
xdMensagem.AppendChild(xeBatch);
xeBatch.AppendChild(xnMethod);
XmlAttribute xaID = xdMensagem.CreateAttribute("ID");
XmlAttribute xaCmd = xdMensagem.CreateAttribute("Cmd");
xaID.Value = "1"; //Id do comando no Batch.
if (strID == "New")
{
xaCmd.Value = "New";
}
else
{
xaCmd.Value = "Update";
}
xnMethod.Attributes.Append(xaID);
xnMethod.Attributes.Append(xaCmd);
foreach (KeyValuePair<string, string> strfieldname in FieldsNamesAndValues)
{
XmlNode xnField = xdMensagem.CreateElement("Field");
XmlAttribute xaName = xdMensagem.CreateAttribute("Name");
xaName.Value = strfieldname.Key;//Nome do Campo
xnField.Attributes.Append(xaName);
xnField.InnerText = strfieldname.Value;//Valor do Campo
xnMethod.AppendChild(xnField);
}
//"<Method ID=\"1\" Cmd=\"New\">" + "<Field Name=\"ID\">New</Field>" + "<Field Name=\"Title\">This is a test</Field>" + "</Method>";
return xdMensagem;
}
catch (Exception e)
{
//Exception
return null;
}
}
I hope it helps.
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();
}
}
After reading Stefan Gossner's post about disposing objects and this question about Cross method dispose patterns, I found that I was guilty of accidentally reopening some SPWebs. I know in Stefan Gossner's post he mentions you should dispose of an SPWeb after you are finished with any child object. However, the microsoft documentation mentions Caching the SPListItemCollection object. Is the following code correct? Would the returned SPListItemCollection reopen an SPWeb object? Is there any way to tell for sure?
// is this correct????
private SPListItemCollection GetListItems()
{
SPListItemCollection items = null;
try
{
using (SPSite site = new SPSite(GetListSiteUrl()))
{
using (SPWeb web = site.OpenWeb())
{
// retrieve the list
SPList list = web.Lists[_ListName];
// more code to create the query...
items = list.GetItems(query);
}
}
}
catch (Exception e)
{
// log error
}
return items;
}
Edit 09/09/09
I am mainly referring to this part of Stefan Grossner's post:
You should dispose a SPWeb or SPSite
object after the last access to a
child object of this object.
I believe what he is saying is that if I use the SPListItemCollection after I dispose of the SPWeb that I used to get it... the SPWeb will be reopened automatically.
I found out after asking Stefan directly that the SPListItemCollection can indeed reopen the SPWeb after you dispose of it. This means that my code posted above is INCORRECT and I would only be able to dispose of the SPWeb after I use the SPListItemCollection.
Update: It is better to convert to the SPListItemCollection to something else and return that instead.
private DataTable GetListItems()
{
DataTable table = null;
try
{
SPListItemCollection items = null;
using (SPSite site = new SPSite(GetListSiteUrl()))
{
using (SPWeb web = site.OpenWeb())
{
// retrieve the list
SPList list = web.Lists[_ListName];
// more code to create the query...
items = list.GetItems(query);
// convert to a regular DataTable
table = items.GetDataTable();
}
}
}
catch (Exception e)
{
// log error
}
return table;
}
As far as I know the answer is no, but I would have written the code something like
private void FetchItems(Action<SPListItemCollection> action)
{
using(...)
{
var items = list.GetItems(query);
action(items);
}
}
By doing this, to call this method you would need to send a method along (delegate) that the SPListItemCollection should be used for, an example:
FetchItems( items => ....) or FetchItems( DoStuffWithItems(SPListItemCollection) )
If you are talking about whether you need an SPWeb in the same scope when you get around to using the SPListItemCollection, I think the answer is no.
For example, I routinely do the following:
private IEnumerable<SPListItem> AllItems;
public void GetItems()
{
var results = SPContext.Current.Web.Lists[ListName].Items.Cast<SPListItem>();
this.AllItems = results;
}
and then I use AllItems all over the place, and it works fine.
Incase you are wondering, the cast is done so I can use Linq on the result set - much much faster than submitting a query to the list, especially if you are doing multiple subselects on the data.
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;
}