How to retrieve list items from SharePoint 2013 - c#

At work we had to move from SharePoint 2010 to 2013 and my code for retrieving list items doesn't work anymore. Here is my code for SP 2010:
com.mycompany.intranet.Lists listService = new com.mycompany.intranet.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = "url";
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
string listName = cbxMailDistributionList.SelectedValue.ToString();
string viewName = "";
string rowLimit = "0";
System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
viewFields.InnerXml = "<FieldRef Name='Title' />";
System.Xml.XmlNode nodeListItems =
listService.GetListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, null);
xmlDoc.LoadXml(nodeListItems.InnerXml);
xlNodeList rows = xmlDoc.GetElementsByTagName("z:row");
List<string> recipients = new List<string>();
foreach (XmlNode attribute in rows)
{
if(attribute.Attributes["ows_Title"].Value == null){}
else {
if (recipients.Contains(attribute.Attributes["ows_Title"].Value)){}
else {
recipients.Add(attribute.Attributes["ows_Title"].Value);
}
}
}
recipients.Sort();
distributionList = recipients;
Can you please help me to get it working with a SharePoint 2013 list again?
URL has already been updated but i get the following error: https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=DE-DE&k=k(EHNullReference);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.0);k(DevLang-csharp)&rd=true
But the list has no empty fields.
listName
is the ID of the list element.
Please help.
Thanks in advance!

Finally it works again with this code:
List<string> recipients = new List<string>();
string siteURL = #"myurl/";
ClientContext cc = new ClientContext(siteURL);
cc.Credentials = System.Net.CredentialCache.DefaultCredentials;
Web web = cc.Web;
List list = web.Lists.GetById(new Guid(cbxMailDistributionList.SelectedValue.ToString()));
CamlQuery caml = new CamlQuery();
ListItemCollection items = list.GetItems(caml);
cc.Load<List>(list);
cc.Load<ListItemCollection>(items);
cc.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
if(item.FieldValues["Title"] == null) { }
else
{
if (recipients.Contains(item.FieldValues["Title"].ToString())) { }
else
{
recipients.Add(item.FieldValues["Title"].ToString());
}
}
}
recipients.Sort();
distributionList = recipients;
}
else
{
distributionList = null;
}
New day, new luck. Sorry for the prematurely posting of this question. I should have slept on it for a night. ;)
BR

Related

How to load two fields from ListItemCollection into Datatable

Below I am accessing a SharePoint list and feeding it into a ListItemCollection which is working, but what I would like to do is feed two fields from the list into a DataTable (so the dt would have two columns), but I couldn't find anything that meets my requirements online. I'm also new to this. What would be the best way to do this?
static void Main(string[] args)
{
string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
string clientID = ConfigurationManager.AppSettings["ClientId"];
string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
using (ClientContext cc = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientID, clientSecret))
{
Web site = cc.Web;
List targetList = site.Lists.GetByTitle("Companies");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='CompanyID'/><Value Type='Text'>Cumbria</Value></Contains></Where></Query></View>";
ListItemCollection collListItem = targetList.GetItems(query);
cc.Load(collListItem);
cc.ExecuteQuery();
if (collListItem.Count == 0)
{
Console.WriteLine("No items found.");
}
else
{
Console.WriteLine("Items found:\n");
foreach (ListItem targetListItem in collListItem)
Console.WriteLine(targetListItem["Reference"]);
Console.ReadLine();
}
}
}

caml query not working properly in sharepoint online

I need to get list items which is older than say 7 days and delete them. I tried using caml query and it worked well in sharepoint 2010 but when I tried to use the same in Sharepoint Online, its getting all list items and deleting it regardless of the condition.
public static bool removeOldEntries(string listName, int offset)
{
bool successFlag = true;
try
{
using (var context = new ClientContext(siteURL))
{
SecureString password = ToSecureString(pwd);
context.Credentials = new SharePointOnlineCredentials(userName, password);
Web web = context.Web;
var list = context.Web.Lists.GetByTitle(listName);
if (list != null)
{
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<Where><Leq><FieldRef Name='Modified'/><Value Type='DateTime'><Today OffsetDays='-" + offset + "'/></Value></Leq></Where>";
ListItemCollection collListItem = list.GetItems(camlQuery);
context.Load(collListItem, items => items.Include(
item => item["ID"]));
context.ExecuteQuery();
if (collListItem.Count > 0)
{
foreach (ListItem oListItem in collListItem)
{
ListItem itemToDelete = list.GetItemById(int.Parse(oListItem["ID"].ToString()));
itemToDelete.DeleteObject();
context.ExecuteQuery();
}
}
}
}
}
catch (Exception ex)
{
successFlag = false;
}
return successFlag;
}
Thanks in advance for any help.
First try adding a Tag in your view xml
So it should look like
camlQuery.ViewXml = "<Query><Where><Leq><FieldRef Name='Modified'/><Value Type='DateTime'><Today OffsetDays='-" + offset + "'/></Value></Leq></Where></Query>";
If it doesn't help try adding a view tag
camlQuery.ViewXml = "<View><Query><Where><Leq><FieldRef Name='Modified'/><Value Type='DateTime'><Today OffsetDays='-" + offset + "'/></Value></Leq></Where></Query></View>";
you can make use of the PNP.PowerShell Module.
$CreationDate = Get-Date "16.06.2021 20:04" -Format s
Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Eq></Where></Query></View>"
For more check out the reference:
https://sposcripts.com/sharepoint/sharepointonline/filtering-for-sharepoint-items-with-caml-queries/#If_DateTime_should_exactly_match_a_specific_date

How to add/update milestones in a feature using rally rest API and C#?

I am not able to add or update milestones field for the Features in the Rally. If anyone having the code available using C# to update the same, please share with me. I am searching and doing from last one week with no luck.
When I am trying to add/Update milestones in the Features. I am getting the error as "Could not read: Could not read referenced object null". My code is as follows:-
public DynamicJsonObject UpdateFeaturesbyName(string fea, string bFun)
{
//getting list of Feature.
Request feat = new Request("PortfolioItem/Feature");
feat.Query = new Query("Name", Query.Operator.Equals, fea);
QueryResult TCSResults = restApi.Query(feat);
foreach (var res in TCSResults.Results)
{
var steps = res["Milestones"];
Request tsteps = new Request(steps);
QueryResult tstepsResults = restApi.Query(tsteps);
foreach (var item in tstepsResults.Results)
{
}
if (res.Name == fea)
{
var targetFeature = TCSResults.Results.FirstOrDefault();
DynamicJsonObject toUpdate = new DynamicJsonObject();
//toUpdate["Milestones"] = "";
// CreateResult createResult = restApi.Create(steps._ref, toUpdate);
// String contentRef = steps._ref;
//String contentRef = createResult._ref;
string[] value = null;
string AccCri = string.Empty;
if (!string.IsNullOrWhiteSpace(bFun))
{
value = bFun.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (string item in value)
{
//if (string.IsNullOrWhiteSpace(AccCri))
// AccCri = item;
//else
// AccCri = AccCri + "<br/>" + item;
if (!string.IsNullOrWhiteSpace(item))
{
//Query for Milestone.
Request ms = new Request("Milestone");
ms.Fetch = new List<string>() { "Name", "ObjectID" };
ms.Query = new Query("Name", Query.Operator.Equals, item);
QueryResult msResults = restApi.Query(ms);
var targetMLResult = msResults.Results.FirstOrDefault();
long MLOID = targetMLResult["ObjectID"];
DynamicJsonObject tarML = restApi.GetByReference("Milestone", MLOID, "Name", "_ref", "DisplayColor");
DynamicJsonObject targetML = new DynamicJsonObject();
targetML["Name"] = tarML["Name"];
//targetML["_ref"] = tarML["_ref"];
targetML["_ref"] = "/milestone/" + Convert.ToString(MLOID);
targetML["DisplayColor"] = tarML["DisplayColor"];
// Grab collection of existing Milestones.
var existingMilestones = targetFeature["Milestones"];
long targetOID = targetFeature["ObjectID"];
// Milestones collection on object is expected to be a System.Collections.ArrayList.
var targetMLArray = existingMilestones;
var tagList2 = targetMLArray["_tagsNameArray"];
tagList2.Add(targetML);//
//targetMLArray.Add(targetML);
targetMLArray["_tagsNameArray"] = tagList2;
toUpdate["Milestones"] = targetMLArray;
OperationResult updateResult = restApi.Update(res._ref, toUpdate);
bool resp = updateResult.Success;
}
}
}
//toUpdate["c_AcceptanceCriteria"] = AccCri;
//OperationResult updateResult = restApi.Update(res._ref, toUpdate);
}
}
var features = TCSResults.Results.Where(p => p.Name == fea).FirstOrDefault();
var featuresref = features._ref;
return features;
}
Now that v3.1.1 of the toolkit has been released you can use the AddToCollection method to do this.
Otherwise, you can still always just update the full collection. The value should be an arraylist of objects with _ref properties.
Check out this example (which adds tasks to defects, but should be very similar to what you're doing): https://github.com/RallyCommunity/rally-dot-net-rest-apps/blob/master/UpdateTaskCollectionOnDefect/addTaskOnDefect.cs

How to get Sharepoint List using c#

How to get fields values from a particular list item.In my case i want to get all form fileds of Workplan list.Actually i want to get Workplan all list item and insert to sharepoint 2013 associated database.
I try the following code.
string strUrl = "http://example.com/default.aspx";
using (SPSite site = new SPSite(strUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[52];
SPQuery myquery = new SPQuery();
myquery.Query = "";
SPListItemCollection items = list.GetItems(myquery);
foreach (SPListItem item in items)
{
if (item != null)
{
var Name = item.ListItems.Fields.List;
Console.WriteLine("Name is :" + Name);
}
}
}
}
This is the easiest way I can think of using Server Object Model:
string strUrl = "http://example.com";
using(SPSite oSite = new SPSite(strUrl))
{
using(SPWeb oWeb = oSite.OpenWeb())
{
SPList list = oWeb.Lists["Workplan"];
foreach(SPField field in list.Fields)
{
Console.WriteLine(field.Title);
}
}
}
Btw, as for your site-URL "http://example.com/default.aspx" it is enough to do it like "http://example.com".
For more information on Sharepoint I recommend using this site in the future.
using (SPSite site = new SPSite("URL")
{
using (SPWeb web = site.OpenWeb("sitecollection/subsite"))
{
//to get specific list type
string listUrl = "/sites/sitecollection/subsite/Lists/Announcements";
SPList list = web.GetList(listUrl);
Console.WriteLine("List URL: {0}", list.RootFolder.ServerRelativeUrl);
}
}
//To get all lists from spweb use this:
SPSite oSiteCollection = SPContext.Current.Site;
using(SPWebCollection collWebs = oSiteCollection.AllWebs)
{
foreach (SPWeb oWebsite in collWebs)
{
SPListCollection collSiteLists = oWebsite.Lists;
foreach (SPList oList in collSiteLists)
{
//get your each list here
}
oWebsite.Dispose();
}
}

List Template not getting applied to the new Sharepoint list

A SharePoint list is being created using Sharepoint.client but the template is not getting applied. I don't see any fields/columns in the new list. A similar questions was asked here but it's answer did not work for me. Any help is greatly appreciated!
using (ClientContext context = new ClientContext(SITE))
{
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
ListTemplate template = null;
ListTemplateCollection ltc = context.Site.GetCustomListTemplates(web);
//ListTemplateCollection ltc2 = web.ListTemplates;
context.Load(ltc);
context.ExecuteQuery();
foreach (ListTemplate t in ltc)
{
if (t.Name == "My_Template")
{
template = t;
break;
}
}
var listCreationInfo = new ListCreationInformation
{
Title = "Test_List",
Description = "Test"
};
//ListTemplate listTemplate = ltc.First(listTemp => listTemp.Name.Contains("My_Template"));
listCreationInfo.TemplateFeatureId = template.FeatureId;
listCreationInfo.TemplateType = template.ListTemplateTypeKind;
listCreationInfo.QuickLaunchOption = QuickLaunchOptions.On;
List oList = web.Lists.Add(listCreationInfo);
context.ExecuteQuery();
}

Categories