Connecting to a SharePoint list I'm pulling back a ListItemCollection, which is being fed into a DataTable, however I only want to select certain fields from the ListItemCollection into the DataTable. Can anyone advise how to do this. New to C#.
Web site = cc.Web;
List targetList = site.Lists.GetByTitle("Team");
DataTable dtData = new DataTable();
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='TeamClass'/><Value Type='Text'>Retail</Value></Contains></Where></Query></View>";
ListItemCollection collListItem = targetList.GetItems(query);
cc.Load(collListItem);
cc.ExecuteQuery();
for (int iCntr1 = 0; iCntr1 < collListItem.Count; iCntr1++)
{
foreach (var field in collListItem[0].FieldValues.Keys)
{
dtData.Columns.Add(field);
}
foreach (var item in collListItem)
{
DataRow dr = dtData.NewRow();
}
}
Iterating through a collection of list items is not a good solution.
If you're interested in the graph API, then you can just return specific fields when getting a collection of list items.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var queryOptions = new List<QueryOption>()
{
new QueryOption("expand", "fields(select=Name,Color,Quantity)")
};
var items = await graphClient.Sites["{site-id}"].Lists["{list-id}"].Items
.Request( queryOptions )
.GetAsync();
Related
I am trying to retrieve all items from a Sharepoint library with CSOM and create a list of it. I am sure it has something to do with the order of the code. The question is how?
ListItemCollection collListItem = oList.GetItems(camlQuery);
var newList = new List<Item>();
var items = oList.GetItems(camlQuery);
context.Load(collListItem);
context.ExecuteQuery();
foreach (var col in items)
{
newList.Add(new Item()
{
ID = Convert.ToInt32(col["ID"]),
});
}
I get the following error:
The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested
You should have loaded the items object not the collListItems thus your code should look following:
ListItemCollection collListItem = oList.GetItems(camlQuery);
var newList = new List<Item>();
var items = oList.GetItems(camlQuery);
context.Load(items);
context.ExecuteQuery();
I have a same problem, then I recalled ExecuteQuery() below foreach loop and that worked for me
ListItemCollection recruitmentItems= Recuitment.GetItems(camlQuery);
cc.Load(recruitmentItems, items => items.Include(
x => x.Id,
x => x["Title"],
x => x["Email"],
x => x["Phone"]
));
cc.ExecuteQuery();
foreach (ListItem item in recruitmentItems)
{
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = Applicant.AddItem(itemCreateInfo);
newItem["Title"] = item["Title"];
newItem["Email"] = item["Email"];
newItem["PhoneNumber"] = item["Phone"];
newItem.Update();
}
cc.ExecuteQuery();
Hi i try to write a little application for sharepoint 2013 where we can backup our projects on an SQL Server. Now i try to loop trough all projects on sharepoint so i can get the content of the fields. Like country = austria.
I tried to follow this guide but had no luck: https://msdn.microsoft.com/en-us/library/office/fp179912.aspx
Here is that what i got:
//Loads only a Projeclist from sharepoint
public SPpowerPlantList loadProjectFromSharePoint()
{
SPpowerPlantList pplist = new SPpowerPlantList();
ClientContext context = new ClientContext(powerPlantSite);
Web web = context.Web;
context.Load(web.Lists);
context.ExecuteQuery();
foreach (List list in web.Lists)
{
SPpowerPlant pp = new SPpowerPlant();
//Stuff like this one should work but dont....
pp.country = list.country
}
return pplist;
}
Any advice would be great and sorry for my english
EDIT: SPpowerPlantList should be a List of all Projects of the Project-List from Sharepoint. And the loadProjectsFromSharepoint is supposed to get a list of Projects wich the i can start to add the values to the sql Server. Stuff like SQL Table value = Sharepoint Field Value.
EDIT2 So the access to the files now work for a few fields but know i get an The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested exeption.
Here is the new code: (some fields work like currency)
//Loads only a Projeclist from sharepoint
public SPpowerPlantList loadProjectFromSharePoint()
{
SPpowerPlantList powerPlantList = new SPpowerPlantList();
ClientContext context = new ClientContext(powerPlantSite);
List powerPlantsList = context.Web.Lists.GetByTitle("Power Plants");
CamlQuery query = CamlQuery.CreateAllItemsQuery();
query.ViewXml = #"<View><Query> </Query></View>";
ListItemCollection items = powerPlantsList.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
SPpowerPlant powerPlant = new SPpowerPlant();
powerPlant.projectName = listItem["Project"].ToString();
powerPlant.location = listItem["Loacation"].ToString();
powerPlant.country = listItem["Country"].ToString();
powerPlant.currency = listItem["Currency"].ToString();
powerPlant.shortName = listItem["Short Name"].ToString();
powerPlant.spaceUrl = listItem["Space"].ToString();
powerPlant.numberOfWtgs = Convert.ToInt32(listItem["Number of WTGs"]);
powerPlant.mwWtg = Convert.ToDouble(listItem["MW WTG"]);
powerPlant.mwTotal = Convert.ToDouble(listItem["MW Total"]);
powerPlant.projectShareWeb = Convert.ToDouble(listItem["Project Share "]);
powerPlant.mwWeb = Convert.ToDouble(listItem["MW "]);
powerPlant.phaseDescription = listItem["Phase Description"].ToString();
powerPlant.projectProgress = Convert.ToDouble(listItem["Project Progress"]);
powerPlant.mwDeveloped = Convert.ToDouble(listItem["MW developed"]);
powerPlant.possibleWtgTypes = listItem["Possible WTG Types"].ToString();
powerPlant.hubHeight = listItem["Hub Height"].ToString();
powerPlant.allPermits = Convert.ToDateTime(listItem["All Permits"]);
powerPlant.cod = Convert.ToDateTime(listItem["COD"]);
powerPlant.projectManager = listItem["Project manager"].ToString();
powerPlant.technology = listItem["Technology"].ToString();
powerPlant.state = listItem["State"].ToString();
powerPlant.stateSince = Convert.ToDateTime(listItem["State since"]);
powerPlant.visibility = listItem["Visibillity"].ToString();
powerPlant.phase = listItem["Phase"].ToString();
powerPlant.phaseNumber = listItem["Phase Number"].ToString();
//Console.WriteLine(listItem["Currency"]);
powerPlantList.Add(powerPlant);
}
return powerPlantList;
}
I tied it with an lambda expression but no success.
Well the problem was that my listitem["names"] where not correct.
To get that stuff to work you need to go to the sharepoint site and look at the link when you sort it there you see the right name for the listitem.
New and working form:
//Loads only a Projeclist from sharepoint
public SPpowerPlantList loadProjectFromSharePoint()
{
SPpowerPlantList powerPlantList = new SPpowerPlantList();
ClientContext context = new ClientContext(powerPlantSite);
List powerPlantsList = context.Web.Lists.GetByTitle("Power Plants");
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
//query.ViewXml = #"<View><Query> </Query></View>";
ListItemCollection items = powerPlantsList.GetItems(query);
//context.Load(web.Lists,
// lists => lists.Include(list => list.Title, // For each list, retrieve Title and Id.
// list => list.Id,
// list => list.Description));
context.Load(items);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
SPpowerPlant powerPlant = new SPpowerPlant();
powerPlant.projectName = listItem["Title"].ToString();
powerPlant.location = listItem["Location"].ToString();
powerPlant.country = listItem["Country"].ToString();
powerPlant.currency = listItem["Currency"].ToString();
powerPlant.shortName = listItem["Short_x0020_Name"].ToString();
powerPlant.spaceUrl = listItem["Space"].ToString();
powerPlant.numberOfWtgs = Convert.ToInt32(listItem["Number_x0020_of_x0020_WTGs"]);
//Console.WriteLine(listItem[""]);
//powerPlantList.Add(powerPlant);
}
return null;
}
I am using the following code to get users from a SharePoint list:
private ClientContext clientContext = new ClientContext(siteUrl);
private SP.List oList = clientContext.Web.Lists.GetByTitle("SharePoint List");
private CamlQuery camlQuery = new CamlQuery();
private ListItemCollection collListItem = oList.GetItems(camlQuery);
private ArrayList names = new ArrayList();
clientContext.Load(collListItem, items => items.Include(
item => item["UserNames"]));
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
titles.Add(oListItem["UserNames"]);
}
I am retrieving data from another columns, too, and I get those data just fine. But when it comes to names, the return value is the Microsoft.SharePoint.Client.FieldUserValue.
Any suggestions on how to get the actual usernames?
It's supposed to return FieldUserValue, you can get the users name or ID from the object. Here's a quick example:
FieldUserValue user = (FieldUserValue)listItem["Author"];
string name = user.LookupValue;
I am trying to transfer files from one document library on one farm to another. Since both are accessible from same network, I thought of getting column values from source and directly add it into a item on destination. Also upload the file along with the item.
List list = ccSource.Web.Lists.GetByTitle("Source Library");
ccSource.ExecuteQuery(); // ccSource is initialized with source Site collection
CamlQuery query = new CamlQuery();
ListItemCollection itemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery()); //Query can also be selective
ccSource.Load(list);
ccSource.Load(itemCollection);
ccSource.ExecuteQuery();
ccSource.Load(ccSource.Web);
string[] coloumnsList = System.IO.File.ReadAllLines(#"E:\Coloumns.txt");
foreach (ListItem item in itemCollection)
{
ClientContext ccTarget. = new ClientContext("http://TargetSC/sites/mysite");
ccTarget.Credentials = new NetworkCredential("username", "pass", "domain");
ccTarget.ExecuteQuery();
var targetList = ccTarget.Web.Lists.GetByTitle("TargetLibrary");
string diskFilePath = #"E:\downloadedFile.docx"; //I have skipped the download code
var fileInfo1 = new FileCreationInformation
{
Url = System.IO.Path.GetFileName(diskFilePath),
Content = System.IO.File.ReadAllBytes(diskFilePath),
Overwrite = true
};
var file = targetList.RootFolder.Files.Add(fileInfo1);
var itemTar = file.ListItemAllFields;
//update list values
foreach (var allFields in item.FieldValues)
{
if (allFields.Key == "FileLeafRef" || checkColoumn(coloumnsList,allFields.Key))
itemTar[allFields.Key] = allFields.Value;
}
itemTar.Update();
ccTarget.ExecuteQuery(); //Exception here
}
public static bool checkColoumn(string[] arr,string query)
{
bool flag = false;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].Equals(query))
{flag = true; break;}
}
return flag;
}
I am getting exception:
The given guid does not exist in the term storeon
ccTarget.exceuteQuery()
I want to read a specific SharePoint list into a datatable. I am struggeling to read the Lookup Values.
Example:
Customer list, each customer is assigned to a team member. The Team members are a lookup of the Team member list.
I have the following questions:
1.) How can I get the Information which list is linked to this lookup field?
2.) How can read the field, gets the value or the index?
I added my function below, many thanks for helping a desperate novice in SharePoint...
Regards
Volker
public System.Data.DataTable ReadDatafromSPList(ClientContext clientContext, string ListName, string ViewName)
{
Web site = clientContext.Web;
List list = site.Lists.GetByTitle(ListName);
View view = list.Views.GetByTitle(ViewName);
ViewFieldCollection viewFields = view.ViewFields;
clientContext.Load(view);
clientContext.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = view.ViewQuery;
ListItemCollection ListColletion = list.GetItems(camlQuery);
clientContext.Load(list);
clientContext.Load(ListColletion);
clientContext.Load(viewFields);
clientContext.ExecuteQuery();
string[] headers = view.ViewFields.ToArray();
System.Data.DataTable dTable = new System.Data.DataTable();
foreach (string header in headers)
{
dTable.Columns.Add(header);
}
string str="";
foreach (ListItem item in ListColletion)
{
dTable.Rows.Add(dTable.NewRow());
foreach (string header in headers)
{
try
{
str = item[header].ToString();
if (str == "Microsoft.SharePoint.Client.FieldLookupValue")
{
//??????????????????
//??????????????????
}
dTable.Rows[dTable.Rows.Count - 1][header] = str;
}
catch
{
dTable.Rows[dTable.Rows.Count - 1][header] = "";
}
}
}
return dTable;
}
Do try this..
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection items = list.GetItems(query);
context.Load(list);
context.Load(items);
context.ExecuteQuery();
DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Title");
foreach (ListItem item in items)
table.Rows.Add(item.Id, item["Title"]);