Retrieve all items from a SharePoint Field Choice Column with using ObjectModel - c#

I know a similar question has already been asked, but that retrieves all the items for Choice field using Sharepoint Object Model. I dont have object model available to me. I want to do this using CAML or something. I couldnt figure out a CAML query to get all the items for a choice field.
Any pointers in the right direction will be really appreciated.
Regards.

Can you use web service calls? This thread explains reading multi-choice choices from a web service: http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/04a00936-7102-4ddc-aa7d-0be7e14e7692
This follow-up post might be useful, too: http://mysharepointwork.blogspot.com/2009/10/sharepoint-web-services-get-choice.html

There is actually another way of getting the values using Xelements
using (var service = new SharePoint.Services.ListsSoapClient())
{
service.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var listName = "MyList";
var xelement = service.GetList(listName);
var fieldName = "Category"; //My Field name
XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/";
var selectedField = xelement.Descendants(ns + "Fields").Elements().Where(x => x.Attribute("Name").Value == fieldName).FirstOrDefault();
if (selectedField != null)
{
var choices = selectedField.Elements(ns + "CHOICES").Elements().Where(x => x.Name == ns + "CHOICE").Select(x => x.Value).ToList();
//Do something with choices
}
}

Related

How can i access to the Value that i scraped and Add it to my DataGrid? Pls Look at the screenshot

public void ScrapeData(string page)
{
var web = new HtmlWeb();
var doc = web.Load(page);
var Articles = doc.DocumentNode.SelectNodes("//*[#class = 'b-product-grid-tile js-tile-container']");
foreach (var article in Articles)
{
var Sneaker = HttpUtility.HtmlDecode(article.SelectSingleNode(".//span[#class ='b-product-tile-link js-product-tile-link']").InnerText);
var Preis = HttpUtility.HtmlDecode(article.SelectSingleNode(".//div[#class ='b-product-tile-price']").InnerText);
var hrefList = doc.DocumentNode.SelectNodes("//a").Select(p => p.GetAttributeValue("href", "not found"));
Debug.Print(Sneaker + Preis + hrefList);
_entries.Add(new EntryModel { Products = Sneaker, Preis = Preis, Link = hrefList }); // canĀ“t convert string implicitly (Sory i have Visual Studio in German i try to translate the Error)
}
All the Links But how can i access to them? and get them in my DataGrid
I found the Links but idk how i access to them and get it into my DataGrid
After i add .ToArray i got the same problem the Debugger Print alwayse (System.Linq.Enumerable+WhereSelectEnumerableIterator`2[HtmlAgilityPack.HtmlNode,System.String])
Here some screenshots of the edited code
Same Problem
The Edit Code
And again i am very sorry how i ask my questions i am very new and i am happy if you correct me
It's not completely clear which of the links you want; you've highlighted only one. However if you do:
var hrefList = doc.DocumentNode.SelectNodes("//a")
.Select(p => p.GetAttributeValue("href", "not found"))
.ToArray();
(added .ToArray())
Then you can access e.g. the second one via hrefList[1]
If you only ever want the second one you;d be better off doing:
var href = doc.DocumentNode.SelectNodes("//a")
.Select(p => p.GetAttributeValue("href", "not found"))
.Skip(1)
.First();
No need to copy the whole lot to an array if all you want is one

Sitefinity: Dynamic Content query optimization with field values

I will attempt to be as specific as possible. So we are using Sitefinity 8.1.5800, I have a couple dynamic content modules named ReleaseNotes and ReleaseNoteItems. ReleaseNotes has some fields but no reference to ReleaseNoteItems.
Release Note Items has fields and a related data field to ReleaseNotes.
So I can query all ReleaseNoteItems as dynamic content pretty quickly less than a second.
I then use these objects provided by sitefinity and map them to a C# object so I can use strong type. This mapping process is taking almost a minute and using over 600 queries for only 322 items (N+1).
In Short: I need to get all sitefinity objects and Map them to a usable c# object quicker than I currently am.
The method for fetching the dynamic content items (takes milliseconds):
private IList<DynamicContent> GetAllLiveReleaseNoteItemsByReleaseNoteParentId(Guid releaseNoteParentId)
{
DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(String.Empty);
Type releasenoteitemType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.ReleaseNoteItems.Releasenoteitem");
string releaseNoteParentTypeString = "Telerik.Sitefinity.DynamicTypes.Model.ReleaseNotes.Releasenote";
var provider = dynamicModuleManager.Provider as OpenAccessDynamicModuleProvider;
int? totalCount = 0;
var cultureName = "en";
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);
Type releasenoteType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.ReleaseNotes.Releasenote");
// This is how we get the releasenote items through filtering
DynamicContent myCurrentItem = dynamicModuleManager.GetDataItem(releasenoteType, releaseNoteParentId);
var myMasterParent =
dynamicModuleManager.Lifecycle.GetMaster(myCurrentItem) as DynamicContent;
var relatingItems = provider.GetRelatedItems(
releaseNoteParentTypeString,
"OpenAccessProvider",
myMasterParent.Id,
string.Empty,
releasenoteitemType,
ContentLifecycleStatus.Live,
string.Empty,
string.Empty,
null,
null,
ref totalCount,
RelationDirection.Parent).OfType<DynamicContent>();
IList<DynamicContent> allReleaseNoteItems = relatingItems.ToList();
return allReleaseNoteItems;
}
This is the method that takes almost a minute that is mapping sitefinity object to C# object:
public IList<ReleaseNoteItemModel> GetReleaseNoteItemsByReleaseNoteParent(ReleaseNoteModel releaseNoteItemParent)
{
return GetAllLiveReleaseNoteItemsByReleaseNoteParentId(releaseNoteItemParent.Id).Select(rn => new ReleaseNoteItemModel
{
Id = rn.Id,
Added = rn.GetValue("Added") is bool ? (bool)rn.GetValue("Added") : false,
BugId = rn.GetValue<string>("bug_id"),
BugStatus = rn.GetValue<Lstring>("bugStatus"),
Category = rn.GetValue<Lstring>("category"),
Component = rn.GetValue<Lstring>("component"),
#Content = rn.GetValue<Lstring>("content"),
Criticality = rn.GetValue<Lstring>("criticality"),
Customer = rn.GetValue<string>("customer"),
Date = rn.GetValue<DateTime?>("date"),
Grouped = rn.GetValue<string>("grouped"),
Override = rn.GetValue<string>("override"),
Patch_Num = rn.GetValue<string>("patch_num"),
PublishedDate = rn.PublicationDate,
Risk = rn.GetValue<Lstring>("risk"),
Title = rn.GetValue<string>("Title"),
Summary = rn.GetValue<Lstring>("summary"),
Prod_Name = rn.GetValue<Lstring>("prod_name"),
ReleaseNoteParent = releaseNoteItemParent,
McProductId = GetMcProductId(rn.GetRelatedItems("McProducts").Cast<DynamicContent>()),
}).ToList();
}
Is there any way to optimize this all into one query or a better way of doing this? Taking almost a minute to map this objects is too long for what we need to do with them.
If there is no way we will have to cache the items or make a SQL query. I would rather not do caching or SQL query if I do not have to.
Thank you in advance for any and all help you can provide, I am new to posting questions on stackoverflow so if you need any additional data please let me know.
Is there a reason why you are doing a .ToList() for the items? Is it possible for you to avoid that. In my opinion, most of the time(of the 1 minute) is taken to convert all your items into a list. Conversion from Sitefinity object to C# object is not the culprit here.
Look Arno's answer here: https://plus.google.com/u/0/112295105425490148444/posts/QrsVtxj1sCB?cfem=1
You can use the "Content links manager" to query dynamic modules relationships (both by parent -ParentItemId- or by child -ChildItemId-) much faster:
var providerName = String.Empty;
var parentTitle = "Parent";
var relatedTitle = "RelatedItem3";
DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);
Type parentType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.ParentModules.ParentModule");
Type relatedType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.RelatedModules.RelatedModule");
ContentLinksManager contentLinksManager = ContentLinksManager.GetManager();
// get the live version of all parent items
var parentItems = dynamicModuleManager.GetDataItems(parentType).Where(i => i.GetValue<string>("Title").Contains(parentTitle) && i.Status == ContentLifecycleStatus.Live && i.Visible);
// get the ids of the related items.
// We use the OriginalContentId property since we work with the live vesrions of the dynamic modules
var parentItemIds = parentItems.Select(i => i.OriginalContentId).ToList();
// get the live versions of all the schedules items
var relatedItems = dynamicModuleManager.GetDataItems(relatedType).Where(i => i.Status == ContentLifecycleStatus.Live && i.Visible && i.GetValue<string>("Title").Contains(relatedTitle));
// get the content links
var contentLinks = contentLinksManager.GetContentLinks().Where(cl => cl.ParentItemType == parentType.FullName && cl.ComponentPropertyName == "RelatedField" && parentItemIds.Contains(cl.ParentItemId) && cl.AvailableForLive);
// get the IDs of the desired parent items
var filteredParentItemIds = contentLinks.Join<ContentLink, DynamicContent, Guid, Guid>(relatedItems, (cl) => cl.ChildItemId, (i) => i.OriginalContentId, (cl, i) => cl.ParentItemId).Distinct();
// get the desired parent items by the filtered IDs
var filteredParentItems = parentItems.Where(i => filteredParentItemIds.Contains(i.OriginalContentId)).ToList();
I would imagine that every release note item under a single release note would be related to the same product wouldn't it?
If so, do you need to do the GetMcProductId method for every item?

c# xml parsing - conversion from php

I currently have my application/project setup on PHP and I am trying to get it working in c# so I can build an application around it.
I have come across some parts of the code which I am looking help with.
XML data from: http://api.eve-central.com/api/marketstat?usesystem=30000142&hours=48&typeid=34&typeid=456
Above is XML data from a certain system containing 2 typeids (same as the other XML), again this will be around 100 items at a time.
I am using this code at the moment:
XDocument doc = XDocument.Load("http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&usesystem=30000142");
var id = from stats in doc.Root.Elements("marketstat")
from type in stats.Elements("type")
select new
{
typeID = type.Attribute("id").Value
};
foreach (var itemids in id)
{
kryptonListBox4.Items.Add(itemids.typeID);
};
Which populates the ListBox as 34 and 456.
What I need is to be able to add the other xml data such as min sell and max buy
I can get the first min sell like this:
string minSell = doc.Descendants("sell")
.First()
.Element("min")
.Value;
But I need to have the minsell in relation to the typeID and being able to work with the data.
Second Problem
XML data from http://api.eve-marketdata.com/api/item_history2.xml?char_name=demo&days=10&region_ids=10000002&type_ids=34,456
Above is XML data from a certain region and contains 2 type_ids (this will be a much larger list when completed around 100 items at a time).
I have tried to use similar code as above but I cannot get it to return the correct data.
I need to be able to get the volume in total for each typeid
In PHP I use this:
foreach ($xml -> result -> rowset-> row as $row)
{
$id = (string)$row['typeID'];
$volume = $row['volume'];
if (!isset($volumes[$id]))
{
$volumes[$id] = 0;
}
$volumes[$id] = $volumes[$id] + $volume;
}
Any help would be greatly appreciated!
//Edit: Looks like I can use
var vRow = from xmlRow in marketstats.Descendants("emd").Descendants("result").Descendants("rowset").Descendants("row")
select xmlRow;
for the 2nd problem but I cannot seem to get the multidimensional array to work
For your second problem if my understanding is right this will be close to ur need.
var strxml = File.ReadAllText(#"D:\item_history2.xml");
var xml = XElement.Parse(strxml);
var typeIDs = (from obj in xml.Descendants("row")
select obj).Select(o => o.Attribute("typeID").Value).Distinct();
Dictionary<string, long> kv = new Dictionary<string, long>();
foreach (var item in typeIDs)
{
var sum = (from obj in xml.Descendants("row")
select obj).Where(o => o.Attribute("typeID").Value == item).Sum(p => long.Parse(p.Attribute("volume").Value));
kv.Add(item, sum);
}
In the dictionary you will have the sum of volumes against each typeID in such a way
typeID as key and sum of volume as value in Dictionary kv.
For your first problem,
Checkout this,
var minsell = (from obj in xml.Descendants("type")
select new
{
typeid = obj.Attribute("id").Value,
minsell = obj.Descendants("sell").Descendants("min").FirstOrDefault().Value
}
).ToArray();
This will give you minsell value in relation with typeid.
I guess this what you expects ?
If wrong please comment it.

How to get data from xml, by linq, c#

Hi,
I have a problem with getting data from youtube xml:
address of youtube xml: http://gdata.youtube.com/feeds/api/videos?q=keyword&orderby=viewCount
I try this, but the program doesn't go into the linq inquiry.
key = #"http://gdata.youtube.com/feeds/api/videos?q="+keyword+#"&orderby=viewCount";
youtube = XDocument.Load(key);
urls = (from item in youtube.Elements("feed")
select new VideInfo
{
soundName = item.Element("entry").Element("title").ToString(),
url = item.Element("entry").Element("id").ToString(),
}).ToList<VideInfo>();
Anyone has idea, how to solve this?
Thanks!
Searching for elements in Linq to XML requires that you fully qualify with the namespace. In this case:
var keyword = "food";
var key = #"http://gdata.youtube.com/feeds/api/videos?q="+keyword+#"&orderby=viewCount";
var youtube = XDocument.Load(key);
var urls = (from item in youtube.Elements("{http://www.w3.org/2005/Atom}feed")
select new
{
soundName = item.Element("{http://www.w3.org/2005/Atom}entry").Element("{http://www.w3.org/2005/Atom}title").ToString(),
url = item.Element("{http://www.w3.org/2005/Atom}entry").Element("{http://www.w3.org/2005/Atom}id").ToString(),
});
foreach (var t in urls) {
Console.WriteLine(t.soundName + " " + t.url);
}
Works for me. To avoid writing out the namespace, one option is to search by local name (e. g. youtube.Elements().Where(e => e.LocalName == "feed"). I'm not sure if there's a more elegant way to be "namespace agnostic".

List 'areas' used in TFS project

I've been playing about with the WorkItem objects from the Microsoft.TeamFoundation schemas in C#, but was wondering if anyone knows how I would refer to an object of type 'Area' or, for that matter, 'Iteration'.
It seems that these are treated as objects in TFS, but I haven't come across any information on how to refer to these in C#.
You can filter WorkItems by [Area] or [Iteration] using WIQL, but what if I wanted to populate a ComboBox with all Areas or Iterations?
Also, how can I view the database structure of my workplace's TFS project?
Thanks guys,
Andy
Have a look at this Blog Post. There's sample code and a demo.
Here's a quick LINQPad Query that should do the job (download VS2010 / VS2012):
void Main()
{
const String CollectionAddress = "http://tfsserver:8080/tfs/MyCollection";
const String ProjectName = "MyProject";
using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri(CollectionAddress)))
{
tfs.EnsureAuthenticated();
var server = tfs.GetService<ICommonStructureService>();
var projectInfo = server.GetProjectFromName(ProjectName);
var nodes = server.ListStructures(projectInfo.Uri).Dump();
// You should be able to re-factor this with "Iteration"
// for getting those too.
var nodesXml = server.GetNodesXml(
nodes
.Where(node => node.Name == "Area")
.Select(node => node.Uri).ToArray(),
true);
var areaPathAndId =
XElement.Parse(nodesXml.OuterXml)
.Descendants("Node")
.Select(xe => new
{
Path = xe.Attribute("Path").Value,
ID = xe.Attribute("NodeID").Value,
})
.Dump();
}
}

Categories