How do I get the SPListItem from absolute URL? - c#

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.

Related

Getting "BadRequest" when posting data to SharePoint Online list with HttpClient

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!

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
}

Setting a Sitecore Item Url by C# to a third party server

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.

How should I get the absolute URL in CsQuery?

I'm trying to get the absolute URI of each anchor tag on a Wikipedia page. I think the .href property should give the absolute URI but when I'm trying it in CsQuery I'm finding that it still gives me the relative URI. How should I get the absolute URI?
static void Main(string[] args)
{
string url = "https://en.wikipedia.org/wiki/Barack_Obama";
var dom = CQ.CreateFromUrl(url);
var selected = dom["div#mw-content-text a"];
foreach (var a in selected)
Console.WriteLine(a["href"]);
}
CsQuery shows you whatever exists in HTML page...
You can simply do that:
string domain = "https://en.wikipedia.org";
var dom = CQ.CreateFromUrl(url);
List<string> urls = new List<string>();
dom["a[href]"].Each(dom=>{
string url = dom.GetAttribute("href");
if(!url.StartsWith("https"))
url = domain + url;
urls.Add(url);
});
});

Calling node.NiceUrl gives me # in Umbraco

Doing a project in Umbraco, and i've encountered problems in one case that when calling node.NiceUrl I get # as the result. What is weird though is that if i debug it somehow it resolves into the correct url.
var pages = Pages.Select((item, index) => new
{
Url = item.NiceUrl,
Selected = item.Id == currentPage.Id,
Index = index
}).ToList();
Where Pages is obtained from:
CurrentPage.Parent.ChildrenAsList
If I do it this way, it works, but I don't know why.
Url = new Node(item.Id).NiceUrl,
I've encountered this error and it was because the id belonged to a media node.
Media is treated differently to other content and there's no easy way of getting the url because different types of media store the url in different ways depending on context. That's why the NiceUrl function doesn't work for media (according to the umbraco developers).
My specific scenario was using images that had been selected using a media picker. I got the url via the following code. I wrapped it up in an extension method so you can consume it from a template in a convenient way.
public static string GetMediaPropertyUrl(this IPublishedContent thisContent, string alias, UmbracoHelper umbracoHelper = null)
{
string url = "";
if (umbracoHelper == null)
umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var property = thisContent.GetProperty(alias);
string nodeID = property != null ? property.Value.ToString() : "";
if (!string.IsNullOrWhiteSpace(nodeID))
{
//get the media via the umbraco helper
var media = umbracoHelper.TypedMedia(nodeID);
//if we got the media, return the url property
if (media != null)
url = media.Url;
}
return url;
}
Try like this
Url = umbraco.library.NiceUrl(Item.Id);

Categories

Resources