Find document in Sharepoint - sharepoint

Looking for a way to find a document registered in Sharepoint. I can find document in a documet library or list by following code.
SPSite oSPSite = new SPSite(_serverUrl);
SPWeb oSPWeb = oSPSite.OpenWeb();
SPList oSPList;
SPListItemCollection oSPListItemCollection;
oSPList = oSPWeb.Lists["Listname"];
SPListItem listItem = null;
listItem = oSPList.GetItemByUniqueId(new Guid(spGuid));
But do i need to iterate trough all list if i dont know in which list the document is registered or is there a more efficient way.

If the UniqueId is the only information you have then you have to create a SPSiteDataQuery to retrieve the URL of the document:
SPWeb web = // ...
SPSiteDataQuery q = new SPSiteDataQuery();
q.Query = String.Format(
"<Where><Eq><FieldRef Name='UniqueId' /><Value Type='Lookup'>{0}</Value></Eq></Where>",
spGuid);
q.Lists = "<Lists BaseType="1" />"; // restrict to document libraries
q.RowLimit = 1;
// q.Webs = "<Webs Scope='SiteCollection' />"; add to broaden the search on the whole site collection
q.ViewFields = "<FieldRef Name='EncodedAbsUrl' />";
DataTable tbl = web.GetSiteData(q);
if (tbl.Rows.Count == 0) throw new FileNotFoundException(...);
return tbl.Rows[0]["EncodedAbsUrl"];
Then you can load the SPFile (the document) with SPWeb.GetFile(string). If you just need the SPListItem you can access this via SPFile.Item.

If you don't know in what list the document is placed you will need to iterate over the available SPList objects from the SPWeb.

Related

SharePoint 2013 update fieldvalue

I have sharepoint list I have added a column "DistributionId" as a single line of text. I can see it in the fieldvalues when I debug. I can see it being set by the line listItem.FieldValues["DistributionId"] = "test";. However this is not updated in SharePoint and reverts to a blank value when the execute query is fired underneath. Also value is not set in SharePoint when checked directly. Any idea what I am doing wrong?
using (ClientContext clientContext = new ClientContext(SpEndPointUri))
{
Site site = clientContext.Site;
Web web = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle(library);
CamlQuery query = new CamlQuery();
query.ViewXml = #"<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + documentId + #"</Value></Eq></Where></Query></View>";
ListItemCollection items = list.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
clientContext.Load(items, ic => ic.Include(i => i, i => i["DisplayName"], i => i["Id"], i => i["HasUniqueRoleAssignments"]));
clientContext.ExecuteQuery();
ListItem listItem = items[0];
clientContext.Load(listItem);
clientContext.ExecuteQuery();
listItem.FieldValues["DistributionId"] = "test";
listItem.Update();
clientContext.ExecuteQuery();
clientContext.Load(listItem);
clientContext.ExecuteQuery();
}
Use ListItem.Item property to set field value instead. ListItem.FieldValues property is used only for getting a collection of key/value pairs containing the names and values for the fields of the list item.
How to update ListItem field value:
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
listItem[fieldName] = fieldValue;
listItem.Update();
ctx.ExecuteQuery();

Need to find a SPItem without knowing the ID of the item

I have two lists and one event receiver. The event receiver sets a column of the list to a unique identifier (combo of the content type and the item id).
In the other list I use query string and the newform to set a field to the very same unique identifier above. I also gather some more info in that newform I want to work with.
How can I query a list without knowing the ID, but I have another unique id to single out from the other items so I can work with it just as SPitem firstitem below so I can find the other fields.
Getting my first item to get the unique title:
SPSite currentSite = SPContext.Current.Site;
SPWeb web = currentSite.OpenWeb();
string queryString = Request.QueryString["uniqueID"];
SPList firstList = web.Lists["My First List"];
SPItem firstItem = firstList.Items.GetItemById(Convert.ToInt32(queryString));
this is the unique title I want to query second list with:
string uniqueTitle = firstItem["Title"].ToString();
getting my second list up, ready for action:
SPList secondList = web.Lists["My Second List"];
Thanks
ANSWER:
// open the second list
SPList secondList = web.Lists["My Second List"];
// Query the second list for the item
SPQuery myQuery = new SPQuery();
myQuery.Query = "<Where><Eq><FieldRef Name = \"Title\"/>" +
"<Value Type = \"Text\">" + uniqueTitle +
"</Value></Eq></Where>";
// Get a collection of the second list items selected by the query and pick the first (0) value as it should only return one!
SPListItemCollection secondlistItemCol = secondList.GetItems(myQuery);
SPListItem secondItem = secondlistItemCol[0];
You will want to use the GetItems command with an SPQuery object. It is not too complex to sort out with the MS code example below.
using System;
using Microsoft.SharePoint;
namespace Test
{
class ConsoleApp
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Build a query.
SPQuery query = new SPQuery();
query.Query = string.Concat(
"<Where><Eq>",
"<FieldRef Name='Status'/>",
"<Value Type='CHOICE'>Not Started</Value>",
"</Eq></Where>",
"<OrderBy>",
"<FieldRef Name='DueDate' Ascending='TRUE' />",
"<FieldRef Name=’Priority’ Ascending='TRUE' />",
"</OrderBy>");
query.ViewFields = string.Concat(
"<FieldRef Name='AssignedTo' />",
"<FieldRef Name='LinkTitle' />",
"<FieldRef Name='DueDate' />",
"<FieldRef Name='Priority' />");
query.ViewFieldsOnly = true; // Fetch only the data that we need.
// Get data from a list.
string listUrl = web.ServerRelativeUrl + "/lists/tasks";
SPList list = web.GetList(listUrl);
SPListItemCollection items = list.GetItems(query);
// Print a report header.
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
"Assigned To", "Task", "Due Date", "Priority");
// Print the details.
foreach (SPListItem item in items)
{
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
}
}
}
Console.ReadLine();
}
}
}

Do I really need foreach loop for this?! (foreach probably overkilling)

I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem li in list.items and loop through each item (if li.name==myitemname then assign strguid=li.uniqueid.tostring()
Is there a way not to use foreach loop since I know the name of the item? This will save time to loop throught items.
If you are creating a spquery on your unique item in splistcollection you would be returned only one element which you can obtain without foreach
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList apps = web.GetList(web.Url + "/Lists/MyList");
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='String'>{0}</Value></Eq></Where>", _title);
items = apps.GetItems(query);
if(items.Count > 0)
{
Guid id = items[0].UniqueId;
}
}
}
Works but I have 11 files and they all have the same file name "license.txt" and they are in the same document library. 1 file "license.txt" is under the root document library and other 10 in 10 different folders within a document library. so what if i am looking for the license.txt file that's in Demo folder?
This code works but only finds license.txt under the root.
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
Trying the following and it seems to be working.
query.ViewAttributes = "Scope=\"Recursive\"";
or
query.ViewAttributes = "Scope='RecursiveAll'";

Item count should be 10 but is 0

the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
SPQuery only searches a particular folder - to recursively search through subfolders you need to set
SPQuery.ViewAttributes = "Scope=\"Recursive\"";
So your code should be
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
query.Query=".... REST OF YOUR CODE HERE "
query.Query="" + fileName + "";
This line is wrong. This should be CAML query and not name of filename.
You need to make a recursive call use the solution provided in question link provided below
i would recommend use qry.ViewAttributes = "Scope='RecursiveAll'"; to get documents and folders as well
query to get all items in a list including items in the sub folders in sharepoint

How to access List Items in a list

I'm trying to display the ListItems in a gridview.
Please help me in finding a way to access the list items.
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
.......
.......
}
}
Please help me in accessing the list item values.
The below code should do the trick, get the full article from msdn here
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
SPListItemCollection collListItems = list.Items;
foreach (SPListItem oListItem in collListItems)
{
string value = SPEncode.HtmlEncode(oListItem["Field1_Name"]);
// do something with value
}
}
}
You may use any of the below:
SPList list;
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
SPQuery query = new SPQuery();
query.ViewFields = "<FieldRef Name='Title'/>";
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
for (int i = 0; i < list.Items.Count; i++ )
{
string title = list.Items[i]["Title"];
}
From the performance point of view, I suggest using the SP Query as then you can specify which fields to fetch and whether or not to fetch any associated metadata with the list items. This results in fewer db calls.
Kind regards,
Use SPDataSource to display list items in a grid view, i.e. create and configure an SPDataSource object and bind it to a SPGridView control.
For displaying items in a gridview (if you don't want to use SPGridView), I would use the GetDataTable method, instead of using a foreach loop as many of the answers do.
if (items.Count > 0)
{
DataTable dt = items.GetDataTable();
GridView1.DataSource = dt;
GridView1.DataBind();
}
Well, I haven't done any sharepoint work, but I believe you can use:
foreach (SPListItem item in list.Items)
or
foreach (SPListItem item in list.GetItems(view)) // or query
or access by index or guid:
SPListItem item = list.Items[10];
SPListItem item = list.Items[guid];
The SPQuery approach as suggested by unknown(yahoo) is the way to go, however you should remember that the default rowlimit of SPQuery is 100:
try
{
using (SPSite site = new SPSite(theURL))
{
SPWeb web = site.OpenWeb();
SPList list = web.Lists["TheNameOfTheList"];
//search each ListItem where the date is after 1/1 2009
SPQuery query = new SPQuery();
//the default is 100, which is less then the expected max
query.RowLimit = 500;
// The U2U CAML Query builder rules :-)
query.Query = "<Where><Gt><FieldRef Name='StartDate' /><Value Type='DateTime'>";
query.Query += "2009-01-01T00:00:00Z</Value></Gt></Where>";
SPListItemCollection resultset = list.GetItems(query);
foreach (SPListItem item in resultset)
{
// do something
}
}
}
If you´re using .NET 3.5 I would recommend using the linq datasource together with the spgridview to bind splistitems to a gridview. Saves you a lot of time.
I have an example of this on my blog.
To display images you have to get the url of the image. Here is an example of that:
SPListItem item = GetItem();
string imagefieldhtml = item["NameOfImageField"].ToString();
ImageFieldValue imagefield = new ImageFieldValue(imagefieldhtml);
var url = imagefield.ImageUrl;
The url variable will now hold the image url.
Ok, I have solved the above issue. In my case I did not need to use the SPEncode.HTML, so I have commented out everything that's not needed. Here is the fixed code if anyone else needs it:
using (SPSite site3 = SPContext.Current.Site)
{
using (SPWeb web2 = site3.OpenWeb())
{
// SPWeb site3 = SPContext.Current.Site.RootWeb;
SPList list2 = web2.Lists["Configuration"];
SPListItemCollection collListItems = list2.Items;
foreach (SPListItem oListItem in list2.Items)
{
//string value = SPEncode.HtmlEncode.ToString(oListItem["List name"]);
string valueListName = oListItem["List name"].ToString();
string valueListURL = oListItem["List URL"].ToString();
}
}
}

Resources