Reading existing field value from SharePoint Custom List fails - c#

I am trying to read the value of a particular field in a SharePoint Custom List.
The Custom List has the following fields: Field1, Field2 and Field3
When I call the code below:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
foreach (var fieldValue in listItem.FieldValues)
{
Console.WriteLine(fieldValue.Key + ":" + fieldValue.Value + Environment.NewLine);
}
}
targetColumnValue = listItem[targetColumnName] as string;
return targetColumnValue;
}
The error message is:
Additional information: 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.
The fields which are displayed in the foreach show "Field1" and "Field2". Do I have to explicitly request "Field3". If yes how?

I had to get the internal name before querying the value for some reason. Here is the code that worked:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var field = list.Fields.GetByInternalNameOrTitle(targetColumnName);
var textField = clientContext.CastTo<FieldText>(field);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(textField);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
targetColumnValue = listItem[textField.InternalName] as string;
}
return targetColumnValue;
}

Related

C# TFS SDK Get Items from changeset

I want to get the Content from an item from a specific Changeset. With my code, I get the correct number of items, but every property of the item is empty, only the correct URL is filled up. All other properties are set to null.
How can I solve this?
string collectionUri = #"https://tfs.myServer.de/MyProject";
using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(collectionUri)))
{
TfvcHttpClient tfvcClient = tpc.GetClient<TfvcHttpClient>();
var changedItems = tfvcClient.GetChangesetAsync(125453).Result;
IEnumerable<TfvcChange> changesetChanges=tfvcClient.GetChangesetChangesAsync(changedItems.ChangesetId).Result;
foreach (var itemsChange in changesetChanges)
{
Console.WriteLine(itemsChange.NewContent.Content);
}
}
This gets you the contents of the items of a changeset
private static async Task ReadContent(TfvcHttpClient tfvcClient)
{
var changesetId = 123456;
var changesetChanges = await tfvcClient.GetChangesetChangesAsync(changesetId);
var tfvcVersionDescriptor = new TfvcVersionDescriptor(null, TfvcVersionType.Changeset, changesetId.ToString());
foreach (var changesetChange in changesetChanges)
{
var path = changesetChange.Item.Path;
Stream contentStream = await tfvcClient.GetItemContentAsync(path, versionDescriptor: tfvcVersionDescriptor);
using (StreamReader streamReader = new StreamReader(contentStream))
{
var content = streamReader.ReadToEnd();
}
}
}

Sharepoint get content from list

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;
}

Sharepoint - uploading files with column values can't load Taxonomy fields in target

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()

Get Posts (Wall Facebook) of me and my friends

I use
https://developers.facebook.com/tools/access_token/
I create an App. I want get Posts of the wall of me and my friends.
I try me/feed and me/posts but I get nothing.
I have this unit test.
Any suggestions?
[TestMethod]
public void Basic_using_SDK()
{
// http://blog.prabir.me/posts/facebook-csharp-sdk-making-requests
var fb = new Facebook.FacebookClient();
var result = (IDictionary<string, object>)fb.Get("4");
var id = (string)result["id"];
var name = (string)result["name"];
var firstName = (string)result["first_name"];
var lastName = (string)result["last_name"];
var link = (string)result["link"];
var username = (string)result["username"];
var gender = (string)result["gender"];
var male = (string)result["locale"];
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,name";
result = (IDictionary<string, object>)fb.Get("4", parameters);
id = (string)result["id"];
name = (string)result["name"];
dynamic result2 = fb.Get("4");
id = result2.id;
name = result2.name;
firstName = result2.first_name;
lastName = result2.last_name;
link = result2.link;
username = result2.username;
gender = result2.gender;
male = result2.locale;
dynamic parameters2 = new ExpandoObject();
parameters2.fields = "id,name";
dynamic result3 = fb.Get("4", parameters);
id = result3.id;
name = result3.name;
dynamic me = fb.Get("zuck");
firstName = me.first_name;
lastName = me.last_name;
var client = new FacebookClient(AccessToken);
dynamic me2 = client.Get("me");
string aboutMe = me2.about;
dynamic result4 = client.Get("/me/feed");
foreach (dynamic post in result4.data)
{
var fromName = post.from.name;
Console.WriteLine(fromName);
}
dynamic result5 = client.Get("/me/posts");
for (int i = 0; i < result5.Count; i++)
{
}
// https://www.facebook.com/profile.php?id=xxxxxxx
// https://graph.facebook.com/xxxxxxx
var uidKiquenet = "xxxxx";
var query = string.Format(#"SELECT status_id,message,time,source,uid,place_id
FROM status WHERE uid IN (SELECT uid FROM status WHERE uid = '" + uidKiquenet + "') ORDER BY time DESC");
dynamic parameters6 = new ExpandoObject();
parameters6.q = query;
dynamic results6 = fb.Get("/xxxxx?fields=id,name,age_range,about,email,first_name,gender");
string myMessage = "Hello from Test";
fb.PostTaskAsync("me/feed", new { message = myMessage }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
string message = "Great, your message has been posted to you wall!";
Console.WriteLine(message);
}
});
fb.GetTaskAsync("me").ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result11 = (IDictionary<string, object>)t.Result;
string myDetails = string.Format("Your name is: {0} {1} and your Facebook profile Url is: {3}",
(string)result11["first_name"], (string)result11["last_name"],
(string)result11["link"]);
Console.WriteLine(myDetails);
}
});
// This uses Facebook Query Language
// See https://developers.facebook.com/docs/technical-guides/fql/ for more information.
query = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY name ASC", "me()");
fb.GetTaskAsync("fql", new { q = query }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result1 = (IDictionary<string, object>)t.Result;
var data = (IList<object>)result1["data"];
var count = data.Count;
var message = string.Format("You have {0} friends", count);
Console.WriteLine(message);
foreach (IDictionary<string, object> friend in data)
Console.WriteLine((string)friend["name"]);
}
});
}
You must authorize with the correct permission in order to get access to feed posts. Try authorizing with user_posts, as it is explained in the docs: https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed#read
Be aware that this does not get you access to posts of friends, unless they posted on the wall of the authorized user.
About review, you may want to read this: https://developers.facebook.com/docs/facebook-login/review/faqs#what_is_review
Btw, FQL is deprecated and will only work in v2.0 Apps - not in newer ones.
Same thing happened to me . Here is my Solution
I made my project registered on Facebook developer console. Then I did my code same as you but could not get posts / information . After some time i submitted my application for app review to facebook team (it was still in early development phase) and after their feedback I got my code working . So pending Application review can be your issue also . This option is available in application setting . Give it a shot
Update
Another code sample is here
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
FB_app_id, Request.Url.AbsoluteUri, FB_scope));
return false;
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}&perms=status_update"
, FB_app_id, Request.Url.AbsoluteUri, FB_scope, Request["code"].ToString(), FB_secret_id);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader rd = new StreamReader(response.GetResponseStream());
string vals = rd.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf('=')), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf('=') - 1));
}
string access_token = tokens["access_token"];
Session["fb_access_token"] = access_token;
return true;
}
}

adding a user to a list programmatically

i have a list which is being populated from a program that takes user input, i am having a problem when it comes to adding a person or group to one of the columns in the list. does anybody know how to do this?
have a look at this article: http://blogs.msdn.com/b/uksharepoint/archive/2009/02/17/quick-tip-using-the-sharepoint-person-or-group-field-in-code-part-1.aspx
it shows you how to use it:
Console.WriteLine("Enter a ; delimited list of domain\alias that need to be added:");
string sAliases = Console.ReadLine(); //captures whatever the user entered
string sValueToAddToFieldInSP = ""; //used to build the full string needed for the person field
string sAllContacts = "";
using (SPSite site = new SPSite(“http://sites/site/yoursite”))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
string[] aAliases = sAliases.Split(';');
foreach (string sAlias in aAliases)
{
SPUser user = web.EnsureUser(sAlias);
sAllContacts += user.ID.ToString() + ";#" + user.LoginName.ToString() + ";#";
}
web.Update();
}
}
if (sAllContacts.EndsWith(";#"))
{
sAllContacts = sAllContacts.Substring(0, sAllContacts.Length - 2);
}
//add the list item
SPList l = web.Lists["<name of your list>"];
SPListItem li= l.Items.Add();
li["Title"] = sAllContacts ;
li["MyPerson"] = sAllContacts ;
li.Update();
Console.WriteLine("Done");

Categories

Resources