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
Related
Is there a Sharepoint API to get entire content of files/folders for a particular folder at once ?
I don't want to use GetFolderByServerRelativePath recursively.
If don't want to use GetFolderByServerRelativePath, you can use CSOM with CAML Query like this:
string password = "pwd";
string account = "user#Tenant.onmicrosoft.com";
var secret = new SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename"))
{
ctx.Credentials = new SharePointOnlineCredentials(account,secret);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle("Documents");
ctx.Load(list);
ctx.ExecuteQuery();
Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/shared%20documents/");
ctx.Load(folder);
ctx.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'>
<Query>
</Query>
</View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (var item in listItems)
{
Console.WriteLine(item.FieldValues["FileRef"].ToString());
}
}
will return all folders/subfolders/files together, hopefully, this is what you need.
I have created event receiver with C# coding in SharePoint.when item should match is already have. it showing massage like this is my code..
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
SPList oList = null;
string strCarName = string.Empty;
using (SPWeb web = properties.Web)
{
oList = web.Lists["Cars"];
string dropdwnvalue = web.Lists[properties.ListId].Fields["CarName"].InternalName;
String lookupFieldStringValue = Convert.ToString(properties.AfterProperties[dropdwnvalue]);
SPListItem item = oList.Items[Convert.ToInt32(lookupFieldStringValue) - 1];
strCarName = Convert.ToString(item["LinkTitle"]);
}
string strStartdate = Convert.ToString(properties.AfterProperties["EventDate"]);
SPQuery existingItemsQuery = new SPQuery();
existingItemsQuery.Query = "<Where><And><Eq><FieldRef Name='EventDate'/><Value Type='DateTime'>" + strStartdate + "</Value></Eq><Eq><FieldRef Name='Car_x0020_Name'/><Value Type='Lookup'>" + strCarName + "</Value></Eq></And></Where>";
SPListItemCollection existingItems = properties.List.GetItems(existingItemsQuery);
if (existingItems.Count >= 1)
{
properties.Cancel = true;
properties.ErrorMessage = "Item is already exists";
properties.Status = SPEventReceiverStatus.CancelWithError;
// ClientScript.RegisterStartupScript(typeof(Page), "test", "<script>alert('Hello');return false;</script>");
}
output:-
item is already exists.
that item adding only one time in a day.again i cant add another item. But i want add another item in a day change time
any one can help me out.
As I can see, you have problem with the query string, you should use this:
existingItemsQuery.Query = "<Where><And><Eq><FieldRef Name='EventDate'/><Value Type='DateTime' IncludeTimeValue='TRUE'>" + strStartdate + "</Value></Eq><Eq><FieldRef Name='Car_x0020_Name'/><Value Type='Lookup'>" + strCarName + "</Value></Eq></And></Where>";
and you should have strStartdate with format like this '1971-01-01T00:00:00Z'
you can use this method:
SPUtility.CreateISO8601DateTimeFromSystemDateTime(properties.AfterProperties["EventDate"])
Hope this helps!
Not sure that you can register script because the page will be redirected.
But you can use properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl and add custom parameter to query string. Also script must be always on the page.
So you just check necessary parameter in QS and show alert if it is present.
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();
}
}
}
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'";
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();
}
}
}