How to Get the Title of a SharePoint List? - sharepoint

I am trying to retrieve a list from SharePoint using the web services. I ran into the problem described in this blog post, i.e. the GetList method apparently expects to be passed the list's title instead of the list's name (even though the parameter is called "listName"). I have the list's name, but I cannot figure out how to get the list's title. Where can I find that?
I'm using the SharePoint in Office 365, which I believe is 2010.

A little over head but try this code. Its just a sample code, you might want to mould it to your logic.
string listName = "MyList";
Lists.Lists listSvc = new Lists.Lists();
listSvc.UseDefaultCredentials = true;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(listSvc.GetListCollection().OuterXml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable);
nsmgr.AddNamespace("A", "http://schemas.microsoft.com/sharepoint/soap/");
XmlNode requiredList = xDoc.SelectSingleNode("//A:List[contains(#DefaultViewUrl,'" + listName + "')]", nsmgr);
string listTitle = requiredList.Attributes["Title"].Value;
XmlNode list = listSvc.GetList(listTitle);

strListName: Can be either a list name, such as "Documents", or a GUID of the list, with or without curly braces, in the following format:
{318B9E8F-1EF4-4D49-9773-1BD2976772B6}
you may find more info here - the above info is an excerpt from this document

Related

Sharepoint C# How to retrieve all pictures and their name by Title of Picture library

Who knows about how to get the image by the Title of the Picture Library (List) using SP C #. Can guide me.
Hope everybody know about SharePoint can help me.
Thanks so much.
You can use CSOM to achive this, demo code is here: https://www.codesharepoint.com/csom/get-all-items-in-sharepoint-using-csom
using Microsoft.SharePoint.Client;
using (ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection"))
{
// clientcontext.Web.Lists.GetById - This option also can be used to get the list using List GUID
// This value is NOT List internal name
List targetList = clientContext.Web.Lists.GetByTitle("List Name");
// Optioanlly you can use overloaded method CreateAllItemsQuery(int rowlimits, params viewfields): where using "rowlimits" you can limit the number of rows returned and viewfields will return only specified fields in the result set
// This method will get all the items from all the folders and sub folders including folders and sub folders too
CamlQuery oQuery = CamlQuery.CreateAllItemsQuery();
ListItemCollection oCollection = targetList.GetItems(oQuery);
clientContext.Load(oCollection);
clientContext.ExecuteQuery();
foreach (ListItem oItem in oCollection)
{
Console.WriteLine(oItem["Title"].ToString());
}
}

Enterprise Keyword not updating in SharePoint 2010

Any idea how to inject values to the Enterprise Keywords column of a List / Doc Lib Item using code?
Tried the following, it didn't give any error, but that column wouldn't update, while the Title did.
using (var site = new SPSite("http://testweb"))
{
using (var web = site.OpenWeb("testsite1"))
{
var list = web.Lists["testlist1"];
var item = list.AddItem();
item["Title"] = string.Format("Injected from code on {0}", DateTime.Now.ToString());
item["Enterprise Keywords"] = "1;#Opera|4eed0518-9676-4afc-be20-9027b3b69e42";
item.Update();
}
}
In this code, Opera keyword has been added previously, I've checked it against the TaxonomyHiddenList list as well using code to extract the correct ID and IdForTerm (the GUID).
What am I missing here?
To add a taxonomy field value the approach is a little bit different. Please try:
TaxonomyField entKeyword = (TaxonomyField)item.Fields["Enterprise Keywords"];
TaxonomyFieldValue term = new TaxonomyFieldValue("1;#Opera|4eed0518-9676-4afc-be20-9027b3b69e42");
entKeyword.SetFieldValue(item,term);
in stead of:
item["Enterprise Keywords"] = "1;#Opera|4eed0518-9676-4afc-be20-9027b3b69e42";

Accessing SPLIstItem properties in SharePoint

I'm trying something very simple - accessing my SharePoint list's items and their properties.
However, SPListItem.Properties count is zero for all normal lists. Everything works as expected for document and pages libraries. So, if the list items are based on document type, all is good. If they are based on item, properties are not returned.
I've tried in two environments, with new sites created from OOTB publishing templates, with new lists which are based on OOTB content types etc. Always the same thing.
Right amount of SPListItems is always returned. Title and Name are fine. It's just that the .Properties hashtable is totally empty.
In desperation, I wrote a web part that outputs the following (ugly!) diagnostics.
foreach (SPList list in SPContext.Current.Web.Lists)
{
foreach (SPListItem item in list.Items)
{
Label label = new Label();
label.Text = "Name: " + item.Name + "Property count: " + item.Properties.Count;
this.Controls.Add(label);
}
}
The only observation is that it works exactly as I described earlier. I just share the code to show that this is the most basic operation imaginable.
Here is sample output - I've added the line breaks for readability ;-)
Name: Test Property count: 0
Name: default.aspx Property count: 21
Obviously item "Test" is an item based list item and default.aspx is a page.
Has anyone ever encountered anything like this? Any ideas?
item["FieldName"] is the canonical way to get a value of a metadata column in a SharePoint list. If you need to get the list of available fields for a SharePoint list, check the parent SPList object's Fields property which is a collection of the fields in this list. Each of those field objects will have a property called InternalName and that is what you should use to access its value when you are working with an instance of SPListItem.
Are you trying to get the field Values? Sadly, they are not strongly typed:
string ModifiedBy = (string)item["Author"];
To get the proper names of the fields (they have to be the internal names), go to the List and then List Settings. You will find the List of Columns there. Click on any Column Name to go to the Edit Page, and then look at the URL in the Address Bar of your Browser. At the very end, there should be a parameter "Field=Editor" or similar - that's your internal field name.
If you wonder why a field like "Test Field" looks strange, that is because Sharepoint encodes certain characters. A Space would be encoded to x0020 hence the Internal Name for "Test Field" is "Test_x0020_Field".
In order to get the proper field type to cast to:
string FieldType = item["Author"].GetType().FullName;
(The Intermediate Window in Visual Studio is tremendously helpful for this!)
I have found the following extension to the SPListItem class to be very helpful.
internal static class SharePointExtensions
{
internal static Dictionary<string, object> PropertiesToDictionary(this SPListItem item)
{
// NOTE: This code might be temping - but don't do it! ...itdoes not work as there are often multiple field definitions with the same Title!
// return item.Fields.Cast<SPField>().ToDictionary(fld => fld.Title, fld => item[fld.Title]);
Dictionary<string, object> dict = new Dictionary<string, object>();
var fieldNames = item.Fields.Cast<SPField>().Select(fld => fld.Title).Distinct().OrderBy(sz => sz).ToArray();
foreach (fieldName in fieldNames)
dict.Add(sz, item[fieldName]);
return dict;
}
}
with it you can simply do:
item.PropertiesToDictionary()
...and you will have a nice Linq dictionary object that will work just the way you'd expect. Is it a little heavy-weight / low-performance? Sure. Are most people willing to make that trade-off? I think so...
Do you run SPListItem.Update() or .SystemUpdate() after setting the properties?
If you want to get an object out of a SPField of a SPListItem you've got to do like this:
SPField field = ((SPList)list).Fields.GetField("FieldName");
object fieldValue = field.GetFieldValue(((SPListItem)item)[field.Title].ToString());
The ListItem.Properties hashtable will be empty unless you assign to it.
SPListItem item = properties.ListItem;
item.Properties["Key"] = "value";
int total = item.Properties.Count;
Answer:
"total == 1"
SPList yourList = web.Lists["Your list name"];
string sColumnValue = oSPListItem[yourList.Fields["yourSiteColumn display
name"].InternalName].ToString();

SharePoint URL retrieval for SPListItem

When I try to retrieve a column which is a hyperlink I get two items that are comma delimited instead of one.
When I pull item["ColumnName"] I get its value:
http://www.google.com/article/583,%20title%20gets%20stars
Why is it showing the link, and title?
You can extract the actual Url and the Description from the column value this way:
SPFieldUrlValue fieldValue = new SPFieldUrlValue(myItem["URL"].ToString());
string linkTitle = fieldValue.Description;
string linkUrl = fieldValue.Url;
Because at the lowest level, all Sharepoint fields are stored as strings. The GetFieldValue method of an SPField accepts a string, and it is up to the logic of that field class to read that string and convert it into a meaningful value object.
item["FieldName"] returns a generic object that represents the field value. By itself the object is usually useless, except as the raw string representation of the data.
If you use the GetFieldValueAsHtml() method, it will return title:
//if field is of type Hyperlink, returns title
item.Fields["FieldName"].GetFieldValueAsHtml(item["FieldName"])
Or
//if field is of type Hyperlink, returns Url, Title
item.Fields["FieldName"].GetFieldValueAsText(item["FieldName"])
Or
//if field is of type Hyperlink, returns Url
item.Fields["FieldName"].GetValidatedString(item["FieldName"])
The SPListItem URL property does return the URL for the SPListItem including the List/Documetn Library name, but it doesn't return the full URL including the server and site names.
To get the full URL, you can either concatenate the SPLIstItem.Web.Url and the SPListItem.URL, or extract the full URL from the SPListItem.XML data like this:
foreach (SPListItem item in list.Items)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(item.Xml);
XmlNamespaceManager nsm = new XmlNamespaceManager(xmlDoc.NameTable);
nsm.AddNamespace("z", "#RowsetSchema");
string fullURL = xmlDoc.SelectSingleNode("z:row", nsm).Attributes["ows_EncodedAbsUrl"].Value;
}
http://insomniacgeek.com/code/how-to-get-the-full-url-from-splistitem-in-sharepoint/
That is how SharePoint stores links. First the URL and then the Title that's actually shown on the page.
From the SharePoint documentation:
"The URL field uniquely consists of two strings separated by a comma and space. One string contains the URL path and the other contains the description used as hyperlinked text."
You have to split the string to get two parts.
string url = field["URL"].Split(',')[0];
string title = field["URL"].Split(',')[1];
Code is not optimal, but just to show you exactly what I mean.
Oliver, you didn't specify SharePoint version. My answer is for 2003 version. If you have MOSS, take a look at SPFieldUrl and SPFieldUrlValue classes.

Read/write Person metadata from a Word doc stored in SharePoint using VBA or VSTO?

Scenario: Document library in SharePoint with column x of "Person or Group" type. From within a VBA macro (or VSTO add-in) we're trying to access the MetaProperty on the document to set/get the user name. Any attempt to access the value via the ContentTypeProperties collection throws a
Type MisMatch error (13).
The Type property of the MetaProperty object says it's msoMetaPropertyTypeUser. I cannot find any examples of how to work with MetaProperties of this type. Anyone have any experience with this?
Thanks!
You should be able to just do something like this:
using (SPSite site = new SPSite("http://yoursite/subsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["DocLibraryName"];
SPListItemCollection items = list.GetItems(list.Views["All Documents"]);
foreach (SPListItem item in items)
{
item["Modified By"] = "Updated Value";
}
}
}
Any metadata for a document should be available by indexing the column name of the SPListItem.
I did it.
The trick here is actually to know that if you put a string corresponding to the user index in MOSS users in the custom property of the Word document, MOSS will recognize it and find the corresponding user to map the field.
so you just need to call http:///_vti_bin/usergroup.asmx
use the function GetUserInfo and retrieve the user index (ID) from it.
MOSSusergroup.UserGroup userGroupService = new MOSSusergroup.UserGroup();
userGroupService.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode node = userGroupService.GetUserInfo(userLogin);
string index = node.FirstChild.Attributes["ID"].Value;

Resources