Databind to dropdownlist from Sharepoint using client object model - c#

Situation:
I´m currently adding items to a sharepointlist via a .Net page and i can´t get them to display properly.
I get all the items (printer modells) from the list but displaying them in a dropdown list (modell) is not going well and the list only displays "Microsoft.Sharepoint.Client.ListItem".
Without datavaluefield and datatextvalue commented out I get errors about the fields not being found. This despite having recreated the column (to ensure that the internal name is correct) and trying both "value" and "key" in both fields with the same result.
Frankly, I´m out of ideas and googling the problem haven´t helped, even more so since most solutions refer to SPlists which is not an option.
using (ClientContext context = new ClientContext("[mysite]"))
{
context.Credentials = new SharePointOnlineCredentials(username, password);
Web site = context.Web;
List list = site.Lists.GetByTitle("Printers");
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection collection = list.GetItems(query);
context.Load(collection);
context.ExecuteQuery();
modell.DataSource = collection;
//modell.DataValueField = "Printermodell";
//modell.DataTextField = "Printermodell";
modell.DataBind();
}
Thankfull for any idéas / recommendations!

Sample code for your reference.
using (ClientContext context = new ClientContext("https://domain.sharepoint.com/sites/Developer/"))
{
string userName = "user.onmicrosoft.com";
string password = "pw";
SecureString securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(userName, securePassword);
Web site = context.Web;
List list = site.Lists.GetByTitle("MyList2");
CamlQuery query = CamlQuery.CreateAllItemsQuery();
Microsoft.SharePoint.Client.ListItemCollection collection = list.GetItems(query);
context.Load(collection);
context.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in collection)
{
string text = string.Format("{0}",item.FieldValues["Title"]);
modell.Items.Add(new System.Web.UI.WebControls.ListItem(text, item.Id.ToString()));
}
//modell.DataSource = collection;
//modell.DataValueField = "Printermodell";
//modell.DataTextField = "Printermodell";
//modell.DataBind();
}

Related

Extracting folder/sub folder name from SharePoint document library URL

I'm newbie to Sharepoint and currently using Sharepoint Online. I'm in need of retrieving files under a sharepoint document library in C#.
We have couple of document library urls as follows:
https://customer1.sharepoint.com/DocumentFolder/Forms/AllItems.aspx
https://customer2.sharepoint.com/sites/sitename/DocumentFolder/SubFolder/Forms/AllItems.aspx
I need to extract DocumentFolder name in case of URL 1 above, and DocumentFolder/SubFolder name in case of URL 2
Using Sharepoint REST service, I then would like to list files under DocumentFolder :
http://site url/_api/web/GetFolderByServerRelativeUrl('/DocumentFolder')
The challenge I have is to extract the DocumentFolder for the above URLs, as I could not find any API/method call to extract the DocumentFolder. I could try regex on the url, but it'll be helpful, if there is a right way to extract the DocumentFolder/SubFolder, that will be helpful.
We can use CSOM C# with CAML query to achieve it, set the view as < View Scope='RecursiveAll'>, thus gets the documents from root folder and its sub folders.
string targetSiteURL = #"https://xxx.sharepoint.com/sites/sitename";
var login = "xxx#xxx.onmicrosoft.com";
var password = "xxx";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
ClientContext ctx = new ClientContext(targetSiteURL);
ctx.Credentials = onlineCredentials;
List list = ctx.Web.Lists.GetByTitle("Documents");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'><Query></Query></View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (var item in listItems)
{
if (item.FileSystemObjectType == FileSystemObjectType.File)
{
// This is a File
}
else if (item.FileSystemObjectType == FileSystemObjectType.Folder)
{
// This is a Folder
}
}
More information for your reference:
http://www.sharepointpals.com/post/How-to-Get-All-the-Files-within-a-Folder-using-CAML-Query-in-SharePoint-Office-365-using-C-CSOM

How can I download the list item versions

My question is about sharepoint online.
In my project I want to download the list item with its versions. I am able to download the current list item version but not able to download its version. I have referred this answer which shows how to calculate the Canonical and Revision paths. But while fetching the data I am getting error as
The remote server returned an error: (403) Forbidden.
and in response header getting value as "Access denied. Before opening files in this location%2c you must first browse to the web site and select the option to login automatically."
string url = "https://test.sharepoint.com/teams/Mycompany";
ScureString f_SecurePass = new SecureString();
foreach (char ch in password)
f_SecurePass.AppendChar(ch);
clientcontext = new ClientContext(url);
var credentials = new SharePointOnlineCredentials(userid, f_SecurePass);
clientcontext.Credentials = credentials;
Web web = clientcontext.Web;
clientcontext.Load(web, website => website.Lists);
clientcontext.ExecuteQuery();
CamlQuery camlQ = new CamlQuery();
camlQ.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
"<Value Type='Number'>0</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
var cq = _list.GetItems(camlQ);
clientcontext.Load(cq, items => items.Include(item => item.Id,
item=>item.EffectiveBasePermissionsForUI,
item=>item.EffectiveBasePermissions));
clientcontext.ExecuteQuery();
var itm = _list.GetItemById(itemid);
clientcontext.Load(itm, r => r.Id, r => r.DisplayName);
clientcontext.ExecuteQuery();
foreach (FileVersion itemVersion in itm.File.Versions)
{
int size = itemVersion.Size;
string versionlbl = itemVersion.VersionLabel;
string newversion = url + itemVersion.Url;
System.WebClient client = new System.Net.WebClient();
client.Credentials = new NetworkCredential(userid, f_SecurePass);
System.IO.Stream Data = client.OpenRead(newversion);// Throws exception
}
How can I download the list item versions?
UPDATE: If I try to download file version by using
File.OpenBinaryDirect(clientcontext, newversion);
it throws following error
Message = "Specified argument was out of the range of valid values.\r\nParameter name: serverRelativeUrl"
I am able to download file version using update CSOM apis.
Please refer
https://social.msdn.microsoft.com/Forums/en-US/802ecc6f-4a4d-4933-bf54-e68e5882203b/how-can-i-download-the-list-item-versions?forum=appsforsharepoint

get image url from SharePoint genericlist with CSOM

I am trying to get the image url from a list but dont now how. the usual search on google didnt help. This is my code so far:
using(var context = MySession.Current.spcontext.CreateAppOnlyClientContextForSPHost())
{
List<Produkt> produkter = new List<Produkt>();
ListItemCollection listFromSharePoint = _foodRepo.RetriveList(context, PRODUKTER);
foreach(ListItem items in listFromSharePoint)
{
Produkt oneItem = new Produkt();
oneItem.bild = (string)items["Bild"]; <--Column name is "Bild" but how to get the url?
produkter.Add(oneItem);
}
ViewBag.Produkter = produkter;
}
image of what I want:
everything loads from sharepoint, but dont know how to reach the url. any ideas?
When accessing the itemvalues, they are always an object which has to be casted to the correct class:
using (ClientContext ctx = new ClientContext(url))
{
Web web = ctx.Web;
List list = web.Lists.GetById(listId);
ListItem item = list.GetItemById(itemId);
ctx.Load(item);
ctx.ExecuteQuery();
FieldUrlValue fieldValue = (FieldUrlValue)item["Bild"]; //<-- casting!
string bildUrl = fieldValue.Url; //<-- here you can access the values
}

C# CSOM Sharepoint Access with Tokens

I have been really struggling with getting Access Tokens working with our Sharepoint site and still no luck.
The problem is when I access our site using the SharepointOnlineCredentials it works fine, well I can query the sharepoint as follows and this works but I want to use the new token stuff that just doesn't work for me
using (ClientContext context = new ClientContext(sharepointSiteUrl))
{
context.Credentials = GetCredentials();
var web = context.Web;
context.Load(web, w => w.Title);
context.ExecuteQuery();
if (context.Web.IsPropertyAvailable("Title"))
{
Console.WriteLine("Found title");
}
Console.WriteLine("Title: {0}", web.Title);
}
private static SharePointOnlineCredentials GetCredentials()
{
SecureString password = new SecureString();
foreach (char c in "MyPassword".ToCharArray()) password.AppendChar(c);
return new SharePointOnlineCredentials("myname#mycompany.com", password);
}
So now for the code that doesn't work
authContext = new AuthenticationContext(authority, new FileCache());
ClientCredential clientCredentials = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = authContext.AcquireToken(resource, clientCredentials);
Console.WriteLine("Token Type: {0} \nExpires: {1} \nToken: {2}", authenticationResult.AccessTokenType, authenticationResult.ExpiresOn, authenticationResult.AccessToken);
using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(sharepointSiteUrl, authenticationResult.AccessToken))
{
var web = context.Web;
context.Load(web);
context.ExecuteQuery();
if (context.Web.IsPropertyAvailable("Title"))
{
Console.WriteLine("Found title");
}
Console.WriteLine("Title: {0}", web.Title);
}
Now when I run this the web.Title throws an error and the context.Web display 'Cannot find the method on the object instance.'
The web.Title in the debugger also states 'The property or field 'Title' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'
I really would love some help with this as it's turned impossible for me. Thanks :)
Do I need to be aware or granting access somewhere else? as its strange that the first one works!
In the first example you are explicitly requesting the Title property from the CSOM end-point:
context.Credentials = GetCredentials();
var web = context.Web;
context.Load(web, w => w.Title); // explicitly requesting the Title property
context.ExecuteQuery();
Whereas in the second example there is no context.Load(web, w => w.Title);
Maybe this is the issue?

How do I get the SPListItem from absolute URL?

I have problems when I try to use SPListItem.
This is the code:
string URL = "http://vstkmy36773/Lists/Permissions/DispForm.aspx?ID=6&ContentTypeId=0x0100F385377F0CAD6C438A23B301CE04E7BF"
using (SPSite cSite = new SPSite(URL))
{
using (SPWeb cWeb = cSite.OpenWeb())
{
// SPFile file = cWeb.GetFile(URL);
// SPListItem item = file.Item;
SPListItem item = cWeb.GetListItem(URL);
int id = item.ID;
item["Title"] = id+ " update and get " + URL;
}
}
And the output
System.NullReferenceException: Object reference not set to an instance of an object.
at Custom.Workflow.Activities.AddListItemPermissionAssigment.Execute(ActivityExecutionContext executionContext)
That's not the proper URL of the actual list item, from SharePoint's perspective. It's just the URL of some page that happens to display that item, which is different.
You're going to need to parse that URL, extract out the required information from it (namely the list and item ID), and then use that information to find the item:
var queryStrings = HttpUtility.ParseQueryString(url);
var listGuid = Guid.Parse(queryStrings["ListId"]);
var itemId = int.Parse(queryStrings["ID"]);
var item = web.Lists[listGuid].GetItemById(itemId);
If you're curious what the actual item URL is, print out the item.URL property to see what it actually is for that item. That's what your URL would need to contain for your code to actually work.

Categories

Resources