List Template not getting applied to the new Sharepoint list - c#

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();
}

Related

Why FieldLookupValue of an item can not be initialized in csom?

I am going to initialize items of a sharepoint list. One of field is a lookup one, but when I'm going to initialize it, no value is set to it.
Here is my code:
var clientContext =
new ClientContext(aURL)
{
Credentials = new System.Net.NetworkCredential(somestring)
};
Web oWebsite = clientContext.Web;
List teachersList = oWebsite.Lists.GetByTitle("Teachers");
FieldLookupValue lookupField = new FieldLookupValue();
lookupField.LookupId = anInteger;
teacherInfoListItem["ProfessorID"] = lookupField;
teacherInfoListItem["Title"] = value;
teacherInfoListItem["LastName"] = value;
teacherInfoListItem.Update();
clientContext.ExecuteQuery();
Your code logic should be fine, make sure the anInteger item exists in your lookup list.
My tested code.
using(var clientContext =new ClientContext("http://sp"))
{
var web = clientContext .Web;
var oList = web.Lists.GetByTitle("TestDetails");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
FieldLookupValue lookupField = new FieldLookupValue();
lookupField.LookupId = 1;
oListItem["Title"] = "My New Item!";
oListItem["Name"] = lookupField;
oListItem.Update();
clientContext.ExecuteQuery();
Console.WriteLine("complete");
}

Rally .NET: Query for project admins that belong to a specific project?

I am looking for a List object that is populated with project admins for a specific project that is within a specific workspace.
Would like some sample code that can query the API for to retrieve all the project admins email addresses.
Here is some sample code I have tried.
public void getProjectAdmins(string workspaceRef, string projectRef)
{
this.EnsureRallyIsAuthenticated();
Request projectAdminRequest = new Request("User");
projectAdminRequest.Workspace = workspaceRef;
projectAdminRequest.Project = projectRef;
projectAdminRequest.ProjectScopeUp = RallyConstant.ProjectScopeUp;
projectAdminRequest.ProjectScopeDown = RallyConstant.ProjectScopeDown;
projectAdminRequest.Fetch = new List<string>()
{
"Admin", "Email"
};
try
{
//query the items in the list
projectAdminRequest.Query = new Query();
QueryResult result = _rallyRestApi.Query(projectAdminRequest);
//iterate through the result set
foreach (var admin in result.Results)
{
var adminResult = admin[RallyConstant.Owner];
if (adminResult != null)
{
var x = adminResult[RallyQueryConstant.ReferenceObject];
}
}
}
catch (WebException)
{
Console.WriteLine(RallyQueryConstant.WebExceptionMessage);
}
}
You should be able to query the ProjectPermission endpoint filtered to your project in question like so:
Request projectAdminRequest = new Request("ProjectPermission");
projectAdminRequest.Workspace = workspaceRef;
projectAdminRequest.Fetch = new List<string>() {"User", "EmailAddress"};
projectAdminRequest.Query = Query.And(
new Query("Project", Query.Operator.Equals, "/project/12345"),
new Query("Role", Query.Operator.Equals, "Project Admin"));
Fetching User and EmailAddress should include the data you're looking for in your request.

How to retrieve list items from SharePoint 2013

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

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();
}
}

Categories