get guid of a listitem - sharepoint

I have text file with List Name and item name. I need to get item guid by it's name. how? (not using foreach splistitem item in splist cause the text file is large and the loop is going to take a toll)

You may have enough information to use the SPWeb function GetListItem, otherwise you will need to try SPWeb.SearchListItems. Neither of which is going to be all the fast either.
The web services have a decent search function that I have used such as:
public static string GetPageId(string listName, string webPath, string pageTitle)
{
string pageId = "";
IntranetLists.Lists lists = new IntranetLists.Lists();
lists.UseDefaultCredentials = true;
lists.Url = webPath + "/_vti_bin/lists.asmx";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + pageTitle + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
Guid g = GetWebID(webPath);
XmlNode items = lists.GetListItems(listName, string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, g.ToString());
foreach (XmlNode listItem in SPCollection.XpathQuery(items, "//sp:listitems/rs:data/z:row"))
{
XmlAttribute id = listItem.Attributes["ows_Id"];
if (id != null)
{
pageId = id.Value;
}
}
return pageId;
}
public static XmlNodeList XpathQuery(XmlNode xmlToQuery, string xPathQuery)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlToQuery.OuterXml);
XmlNamespaceManager mg = new XmlNamespaceManager(doc.NameTable);
mg.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
mg.AddNamespace("z", "#RowsetSchema");
mg.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
mg.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois");
mg.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
mg.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory");
return doc.SelectNodes(xPathQuery, mg);
}

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsitedataquery.aspx or CamlQuery
SPListItemCollection items = web.Lists.GetItems(new SPQuery() { Query = "YOUR QUERY" });

Go to the list settings page. Right click on "Title, description and navigation" and copy the URL. Paste that into notepad and copy everything after "List=" in the string. That's your URL Encoded GUID for the list. All you need to do is decode it here http://www.albionresearch.com/misc/urlencode.php
source: http://weblogs.asp.net/jimjackson/archive/2008/02/11/get-a-sharepoint-list-guid-from-the-browser.aspx
this is for manually getting each GUID of a certain list.

Related

Add a lookup field for a list in Sharepoint Client Model

This is what I've achieved do far:
Field parent = list.Fields.AddFieldAsXml(
#"<Field Type='Lookup' DisplayName='ParentContentType'
Required='FALSE' EnforceUniqueValues='FALSE'
List= 'ContentTypes'
ShowField='Title' UnlimitedLengthInDocumentLibrary='FALSE'
RelationshipDeleteBehavior='None'
StaticName='ParentContentType' Name='ParentContentType'/>",
true, AddFieldOptions.DefaultValue);
But I am not able to set the Get information from: value for this lookup field.
Can anyone please suggest how to achieve it?
Code added:
var listCreationInfo = new ListCreationInformation();
listCreationInfo.Title = "New List";
listCreationInfo.TemplateType = (int)ListTemplateType.CustomGrid;
List list = web.Lists.Add(listCreationInfo);
list.Update();
ctxt.ExecuteQuery();
Field parent = list.Fields.AddFieldAsXml(
#"<Field Type='Lookup' DisplayName='ParentContentType'
Required='FALSE' EnforceUniqueValues='FALSE'
List= 'ContentTypes'
ShowField='Title' UnlimitedLengthInDocumentLibrary='FALSE'
RelationshipDeleteBehavior='None'
StaticName='ParentContentType' Name='ParentContentType'/>",
true, AddFieldOptions.DefaultValue);
Please try this.
public static void AddLookupField()
{
string lookupSchema = #"<Field Type='Lookup' DisplayName='mylookup2'
Required='FALSE' EnforceUniqueValues='FALSE'
List='{70d6098c-6ba0-4e9e-b101-a60b88fc226a}'
ShowField='Title' UnlimitedLengthInDocumentLibrary='FALSE'
RelationshipDeleteBehavior='None'
StaticName='mylookup' Name='mylookup2'/>";
ClientContext clientContext = new ClientContext("http://sharepoint10");
List list = clientContext.Web.Lists.GetByTitle("listtitle");
FieldCollection fields = list.Fields;
clientContext.Load(list);
clientContext.Load(fields);
clientContext.ExecuteQuery();
Field lookupField = fields.AddFieldAsXml(lookupSchema, true, AddFieldOptions.AddToDefaultContentType);
lookupField.Update();
clientContext.Load(lookupField);
clientContext.ExecuteQuery();
}

How to add a Web Part into a SitePages/Home.aspx using CSOM

has anyone managed to add a Web Part into a Wiki page using CSOM?
Background: Home.aspx is a Wiki page and all its WPs are located in the rich text zone (in fact a "WikiField" column). Technically they are located in a hidden "wpz" web part zone and in addition to this there is always a placeholder with WP's ID in the WikiField column.
I've modified the existing server-side code seen on http://blog.mastykarz.nl/programmatically-adding-web-parts-rich-content-sharepoint-2010/ and http://640kbisenough.com/2014/06/26/sharepoint-2013-moving-webparts-programmatically-to-rich-content-zone/ into this:
using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;
public class Class1
{
void DeployWebPart(ClientContext clientContext, string zone, string pattern, string position)
{
List library = clientContext.Web.GetList("/sites/site/SitePages/");
clientContext.Load(library);
clientContext.ExecuteQuery();
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
ListItemCollection itemColl = library.GetItems(query);
clientContext.Load(itemColl, items => items.Include(i => i.Id, i => i.DisplayName, i => i["WikiField"]));
clientContext.ExecuteQuery();
ListItem item = itemColl.Where(i => i.DisplayName == "Home").First();
clientContext.ExecuteQuery();
File page = item.File;
LimitedWebPartManager lwm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
string xmlWebPart = #"<webParts>...</webParts>";
WebPartDefinition wpd = lwm.ImportWebPart(xmlWebPart);
WebPartDefinition realWpd = lwm.AddWebPart(wpd.WebPart, "wpz", 0);
List targetList = clientContext.Web.GetList("/sites/site/Announcements/");
clientContext.Load(targetList, l => l.Views);
clientContext.Load(realWpd);
clientContext.ExecuteQuery();
string wpId = String.Format("g_{0}", realWpd.Id.ToString().Replace('-', '_'));
if (zone == "wpz")
{
string htmlcontent = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contenteditable=\"false\"><div class=\"ms-rtestate-notify ms-rtestate-read {0}\" id=\"div_{0}\"></div><div id=\"vid_{0}\" style=\"display:none;\"></div></div>", new object[] { realWpd.Id.ToString("D") });
string content = item["WikiField"] as string;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(System.Text.RegularExpressions.Regex.Escape(pattern));
if (position == "before")
{
content = regex.Replace(content, (htmlcontent + pattern), 1);
}
else
{
content = regex.Replace(content, (pattern + htmlcontent), 1);
}
item.Update();
clientContext.ExecuteQuery();
}
}
}
Everything works fine until the last item.Update() and clientContext.ExecuteQuery() are being invoked. Before the Update() the new placeholder gets properly inserted into the WikiField contents. But after the Update() the WikiField contents reverts back to its original state (!)
Note: As an alternative it is possible to add the WP into another zone (eg. "Bottom"). In this case the WP gets displayed on the page. But it has two major drawbacks: The newly created zone is not well formatted and the WP cannot be moved or even deleted.
Thanks for any input on this.
The following example demonstrates how to add web part into Enterprise Wiki page:
public static void AddWebPartIntoWikiPage(ClientContext context, string pageUrl, string webPartXml)
{
var page = context.Web.GetFileByServerRelativeUrl(pageUrl);
var webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
var importedWebPart = webPartManager.ImportWebPart(webPartXml);
var webPart = webPartManager.AddWebPart(importedWebPart.WebPart, "wpz", 0);
context.Load(webPart);
context.ExecuteQuery();
string marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", webPart.Id);
ListItem item = page.ListItemAllFields;
context.Load(item);
context.ExecuteQuery();
item["PublishingPageContent"] = marker;
item.Update();
context.ExecuteQuery();
}
Usage
var webPartXml = System.IO.File.ReadAllText(filePath);
using (var ctx = new ClientContext(webUri))
{
AddWebPartIntoWikiPage(ctx, wikiPageUrl,webPartXml);
}
Result

Add/Create new document in SharePoint document Library programmatically

I have created a new Document Library and set up custom content type with MS Word Document Template. When i click on Create new template it works fine. but i need to be able to add some logic on a button event where it will go into that library and create a new document, so that when i go into that library i will see a new document that has been created by that button event.
i tried doing it as i would do a regular list item, but i got the following error on item.update:
To add an item to a document library, use SPFileCollection.Add()
Now i did some research but everywhere i see the code for uploading a file to the document library but no where i can find how to add a new document using my template that is associated in that doc library.
please help and thanks.
public static void colFileMtod()
{
using (SPSite objsite = new SPSite("http://smi-dev.na.sysco.net/SyscoFinance/FSR/"))
{
using (SPWeb objWeb = objsite.OpenWeb())
{
SPFileCollection collFiles = objWeb.GetFolder("BPCPublishRecord").Files;
SPList lst = objWeb.Lists["BPCPublishRecordCopy"];
if (lst != null)
{
if (objWeb.Lists.Cast<SPList>().Any(list => list.Title.Equals("BPCPublishRecordCopy", StringComparison.OrdinalIgnoreCase)))
{
foreach (SPFile file in collFiles)
{
string strDestUrl = collFiles.Folder.Url + "/" + file.Name;
byte[] binFile = file.OpenBinary();
SPUser oUserAuthor = file.Author;
SPUser oUserModified = file.ModifiedBy;
System.DateTime dtCreated = file.TimeCreated;
System.DateTime dtModified = file.TimeLastModified;
SPFile oFileNew = collFiles.Add(strDestUrl, binFile, oUserAuthor, oUserModified, dtCreated, dtModified);
SPListItem oListItem = lst.AddItem();
oListItem = oFileNew.Item;
oListItem["Created"] = dtCreated;
oListItem["Modified"] = dtModified;
oListItem.Update();
objWeb.AllowUnsafeUpdates = true;
}
}
}
}
}
}

xmlns to sharepoint api object

Is it possible to convert the following string to a Sharepoint API object like SPUser or SPUserValueField? (without parsing it)
"<my:Person xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD\"><my:DisplayName>devadmin</my:DisplayName><my:AccountId>GLINTT\\devadmin</my:AccountId><my:AccountType>User</my:AccountType></my:Person>"
Thanks,
David Esteves
Yes, the Microsoft.Office.Workflow.Utility assembly has Contact.ToContacts which will deserialize Person XML into an array of Contact instances.
http://msdn.microsoft.com/en-us/library/ms553588
-Oisin
Solved :)
(Just an example)
The following function retrieves the SPUser from person:
protected SPUser GetSPUserFromExtendedPropertiesDelegateTo(string xmnls_node)
{
StringBuilder oBuilder = new StringBuilder();
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(oBuilder);
System.Xml.XmlTextWriter oXmlWriter = new System.Xml.XmlTextWriter(oStringWriter);
oXmlWriter.Formatting = System.Xml.Formatting.Indented;
byte[] byteArray = Encoding.ASCII.GetBytes(xmnls_node);
MemoryStream stream = new MemoryStream(byteArray);
System.IO.Stream s = (Stream)stream;
System.IO.StreamReader _xmlFile = new System.IO.StreamReader(s);
string _content = _xmlFile.ReadToEnd();
System.Xml.XmlDocument _doc = new System.Xml.XmlDocument();
_doc.LoadXml(_content);
System.Xml.XPath.XPathNavigator navigator = _doc.CreateNavigator();
System.Xml.XmlNamespaceManager manager = new System.Xml.XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD");
System.Xml.XmlNode _node = _doc.SelectSingleNode("/my:Person/my:AccountId", manager);
if (_node != null)
{
return this.workflowProperties.Web.EnsureUser(_node.InnerText.ToString());
}
return null;
}

How to edit and read data in a SharePoint List

I want to query a SharePoint list and want to use the data to be displayed in a usercontrol that I have created.
Earlier I had the data coming from a database.
Now I need to modify it to work with a SharePoint list.
Can you please guide me.
Grace.
SPList list = null;
SPListItemCollection LIC = null;
SPListItem listItem = null;
using (SPSite mainSite = new SPSite("http://sitewhereyourlistis"))
{
using (SPWeb mainWeb = mainSite.OpenWeb())
{
list = mainWeb.Lists["ListNameHere"];
//**You will most likely want to limit your return to a single record so I have created the caml to do so with the List Item ID
String caml = String.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Counter\">{0}</Value></Eq></Where>", ListItemID);
SPQuery qry = new SPQuery();
qry.Query = caml;
LIC = list.GetItems(qry);
listItem = LIC[0];
//**Here is where you will fill your textboxes
txtTextBoxName.Text = listItem["ColumnNameHere"].toString();
//**The above statement likes to error out if the value is null so I like to use a custom Application Helper Function to prevent things like this.
//**My actual call to get the data would look like this.
txtTextBoxName.Text = EnsureTextValue(listItem, "ColumnNameHere");
// I added the Function Definition Below
}
}
public String EnsureTextValue(SPListItem item, String param)
{
String tmp = String.Empty;
try
{
tmp = item[param].ToString();
}
catch { "Run Debug Method or Whatever Here" }
return tmp;
}
I am not sure if I missed anything but this should get you close.
Hope it helps!
To get Distinct Values for the column Click Here
To edit the values in the list there is a nice post here
I have used this to Query the SharePoint List
using (SPWeb web = SPContext.Current.Site.RootWeb)
{
SPList mylist = web.Lists["listName"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='columnName' /><Value Type='Text'>" + strXYZ+ "</Value></Eq></Where>";
SPListItemCollection items = mylist.GetItems(query);
tempDT = items.GetDataTable();
return tempDT;
}

Resources