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
}
Related
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();
}
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
I am trying to post data to a list on SharePoint Online with the C# HttpClient. this is my code:
using (var client = new SPHttpClient(webUri, userName, password))
{
var listTitle = "HttpClientList";
var itemPayload = new
{
__metadata = new
{
type = "SP.Data.HttpClientListListItem"
},
Title = "test3",<--column name "Title"
_x0071_cr5 = "value3"<--column name "Value"
};
var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items", webUri, listTitle);
var data = client.ExecuteJson(endpointUrl, HttpMethod.Post, itemPayload);
Console.WriteLine("Task item '{0}' has been created", data["d"]["Title"]);
Console.ReadLine();
As of right now, I am getting status "400, BadRequest". My guess is that I am missing something or feeding the post request the wrong data.
I have been following this blogpost Blogpost
I can only execute the verb GET. All other verbs gives me "400, BadRequest"
Solved it with varoius solutions.
Added the right ListItem HttpClientListListItem.
created all columns thru the ListSettings panel.
Replaced the client.ExecuteJson() with client.ExecuteJson(endpointUrl, HttpMethod.Post, headers, default(string));.
Thanks for all the help!
In a specific kind of situation, I had to obtain certain data through a RESTful request from a cloud server and then process and present them along the normal Sitecore items. I converted the data from a RESTful request to Sitecore Item through the following code:
private static Item Itemize(HubSpotResult hubSpotResult)
{
Database webDb = Sitecore.Configuration.Factory.GetDatabase("web");
TemplateItem template = webDb.GetItem("/sitecore/templates/User Defined/Pages/HubSpotBlogs");
var id = ID.NewID;
var templateId = template.ID;
var titleFieldId = ID.NewID;
var dateFieldId = ID.NewID;
var navigationTitleFieldId = ID.NewID;
var def = new ItemDefinition(id,"HubSpotBlog", templateId, ID.Null);
var fields = new FieldList();
fields.Add(titleFieldId, "Title");
fields.Add(dateFieldId, "Date");
fields.Add(navigationTitleFieldId, "NavigationTitle");
var data = new ItemData(def, Language.Parse("en"),new Sitecore.Data.Version(1), fields);
var dateTime = GetPublicationDate(hubSpotResult.publish_date).ToString();
var sitecoreStyleDateTime = DateUtil.ParseDateTime(dateTime,DateTime.Now);
Item item;
using (new SecurityDisabler())
{
item = new Item(id, data, webDb);
item.Editing.BeginEdit();
item.Fields["Date"].Value =DateUtil.ToIsoDate(sitecoreStyleDateTime.Date);
item.Fields["Title"].Value = hubSpotResult.html_title;
item.Fields["NavigationTitle"].Value = hubSpotResult.html_title;
Sitecore.Data.Fields.LinkField link = item.Fields["NavigationTitle"];
link.Url = hubSpotResult.url;
link.Text = hubSpotResult.html_title;
item.Editing.EndEdit();
}
return item;
}
Currently, I can't get the Url to the items that are created in this way as the the items don't exist on the Sitecore tree, however to render the link I need to set the Url of the item to point to the cloud server.
Is there a good way to Set the Url, so LinkManager.GetItemUrl(item) can get the url to the cloud server and also renders the title of the link or item?
The way to do this would be to override the LinkProvider with a custom one. When it see's an item based on the template you are using to create the "virtual" items, you can then use the data on that item to workout what the link to create should be. If the item is not of that template, then you can just pass it through to the base LinkProvider
public class MyLinkProvider : Sitecore.Links.LinkProvider
{
public override string GetItemUrl(Item item, UrlOptions options)
{
var templateID = new ID("<your template Id >");
if (item == null)
{
return string.Empty;
}
Assert.ArgumentNotNull(options, "options");
if (item.TemplateID == templateID)
{
// Build your custom url here
return "custom url";
}
else
{
return base.GetItemUrl(item, options);
}
}
}
Then patch that in via an include file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<linkManager>
<providers>
<add name="sitecore">
<patch:attribute name="type">MyApplication.MyLinkProvider, MyApplication</patch:attribute>
</add>
</providers>
</linkManager>
</sitecore>
</configuration>
This will let normal items generate in the standard Sitecore way, and you can choose how the items link should be built.
I resolved my problem in quite an easier way.
I added a new field called Url with type of General Link to the template that I had created in Sitecore for these temporary virtual items.
I used it in my virtual item creation like this:
Sitecore.Data.Fields.LinkField link = item.Fields["Url"];
link.Url = hubSpotResult.url;
link.Text = hubSpotResult.html_title;
then, I grabbed the Url that I wanted in the same GetUrl extension like this:
if (i != null && i.Name == "HubSpotBlog")
{
LinkField link = i.Fields["Url"];
strUrl = link.Url;
}
the repeated took care of the rest of it and I was able to render values that I wanted on the view.
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.