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"]);
Related
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();
I want to display files from a sharepoint folder that were modified by username. please help me for this. Also tell me how to show this file with sorting order by datetime.
I tried using
docName.Add(file.ModifiedBy);
property but its not available, here is the code:
public List<string> getFiles(ClientContext CContext,string INVOICENO)
{
List list = CContext.Web.Lists.GetByTitle("Documents");
CContext.Load(list);
CContext.Load(list.RootFolder);
CContext.Load(list.RootFolder.Folders);
CContext.Load(list.RootFolder.Files);
CContext.ExecuteQuery();
FolderCollection fcol = list.RootFolder.Folders;
List<string> docName = new List<string>();
foreach (Folder f in fcol)
{
if(INVOICENO==null)
{
INVOICENO = "";
}
string foldername = INVOICENO.ToString();
if (f.Name == foldername)
{
CContext.Load(f.Files);
CContext.ExecuteQuery();
FileCollection fileCol = f.Files;
foreach (File file in fileCol)
{
docName.Add(file.Name);
docName.Add(file.TimeLastModified.ToShortDateString());
}
}
}
return docName.ToList();
}
According to my testing and research, you can use CAML Query to display the files modified by the username from the SharePoint folder.
Here is an example you can refer to:(sorted by modification time in ascending order)
static void Main(string[] args)
{
var clientContext = GetonlineContext();
Web site = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle("Library Name");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Editor' /><Value Type='User'>UserName</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='True' /></OrderBy></Query><ViewFields /><QueryOptions /></View>";
ListItemCollection collListItem = list.GetItems(query);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
foreach (ListItem item in collListItem)
{
Debug.WriteLine("Name:"+item["FileLeafRef"]+"\n"+"Modified"+item["Modified"]);
}
clientContext.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()