sharepoint 2013 create document library using List Template C# - c#

It is possible to used a list template to create new document library, I am trying following code but its is not working.it just create library without using template.
ListTemplateCollection listTemplates1 = context.Site.GetCustomListTemplates(context.Web);
ListTemplate li1;//
context.Load(listTemplates1);
context.ExecuteQuery();
context.Load(site.ListTemplates);
context.ExecuteQuery();
var listTemplate = listTemplates1.First(lt => lt.Name == "<Test>");
ListCreationInformation li = new ListCreationInformation();
li.Title = "XYZZ2";
li.Description = "Created through Code";
li.TemplateFeatureId = listTemplate.FeatureId;
li.TemplateType = listTemplate.ListTemplateTypeKind;
List newList = context.Web.Lists.Add(li);
context.Load(newList);
context.ExecuteQuery();

Can you directly try to fetch the template instead of getting the entire collection like the following:
ListTemplate listTemplate = context.web.ListTemplates.GetByName("templateName");
context.Load(listTemplate);
context.ExecuteQuery();
Then create your list,
ListCreationInformation li = new ListCreationInformation();
li.Title = "XYZZ2";
li.Description = "Created through Code";
li.TemplateFeatureId = listTemplate.FeatureId;
li.TemplateType = listTemplate.ListTemplateTypeKind;
List newList = context.Web.Lists.Add(li);
context.Load(newList);
context.ExecuteQuery();
This may be because the listTemplate, in your case, has not been initialized properly which is why the List was getting created with the default template.

Related

How to get all items in ListItemCollection when using an AppOnlyAuthenticatedContext

I am trying to use an AppOnlyAuthenticated context in order to loop over all the documents in a specific list in Sharepoint. The reason to use the AppContext is that this needs to be automated (part of a script) and using an actual user accounts seems like the wrong choice.
Repro:
// using OfficeDevPnp.Core;
// using Microsoft.SharePoint.Client;
var webUrl = "https://company.sharepoint.com/sites/test";
var appId = "xXXXX-xxxx-.....";
var appSecret = "longSecret";
var listTitle = "ListTitle";
var am = new AuthenticationManager();
using (var context = am.GetAppOnlyAuthenticatedContext(webUrl, appId, appSecret))
{
var lists = context.Web.Lists;
var list = lists.GetByTitle(listTitle);
var listItems = list.GetItems(CamlQuery.CreateAllItemsQuery(rowLimit = 5));
context.Load(lists);
context.Load(list);
context.Load(listItems, items => item.Include(i => i.Id));
context.ExecuteQuery();
var list_ItemCount = list.ItemCount;
var listItems_Count = listItems.Count;
}
}
The list_ItemCount has the correct value of items in that list of files but listItems_Count is zero. Obviously, when trying to loop over listItems, there is nothing to enumerate.
Could it be a permission thing? Or is something else causing the issue?

How to iterate through IMongoCollection<> and print all the elements?

I followed this tutorial but the nuget package is old and a new package is used now MongoDB.Driver https://www.codeproject.com/Articles/656093/Connecting-MongoDB-with-ASP-NET So the syntax is different and i can itterate through the elements. Here's what I've got till now.
List<Info> list = new List<Info>();
var server = new MongoClient(MongoUrl.Create("mongodb://localhost:27017"));
IMongoDatabase database = server.GetDatabase("DB");
IMongoCollection<Info> valuti = database.GetCollection<Info>("Vals");
We could use Find(_=>true) method of IMongoCollection<> and iterate it
List<Info> list = new List<Info>();
var server = new MongoClient(MongoUrl.Create("mongodb://localhost:27017"));
IMongoDatabase database = server.GetDatabase("DB");
IMongoCollection<Info> valuti = database.GetCollection<Info>("Vals");
vaulti.Find(_=>true).ToList().ForEach(vault => {
//Iteration
});

Adding lookup column to list using CSOM

I have a list called "Books" with columns 'Name','AuthorName','ISBN' with type as text. Now I have another list called "BillTokenStore" and i want to add lookup column 'AuthorName' in "BillTokenStore". Below is what i have done.
using (ClientContext context = new ClientContext(webFullUrl: siteUrl))
{
context.Credentials = new SharePointOnlineCredentials(userName, GetPassWord());
Web web = context.Web;
ListCollection listCollection = web.Lists;
List list = listCollection.GetByTitle("BillTokenStore");
string schemaLookupField = #"<Field Type='Lookup' Name='InStock' StaticName='InStock' DisplayName='InStock' List = 'Books' ShowField = 'Title' /> ";
Field lookupField = list.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.DefaultValue);
context.ExecuteQuery();
}
When i run this code, i am getting the error "value does not fall within the expected range sharepoint 2013". What is wrong here? Thanks in Advance.
Note: I am able to achieve the same thing thorough UI. I am also able to add other type of fields like choice,boolean and all through code.
You need to explicitly load the list and the fields of that list.
Also, we need to pass the GUID of the lookup column list.
Please try the below modified code:
using (ClientContext context = new ClientContext(webFullUrl: siteUrl))
{
context.Credentials = new SharePointOnlineCredentials(userName, GetPassWord());
Web web = context.Web;
List booksList = context.Web.Lists.GetByTitle("Books");
List list = context.Web.Lists.GetByTitle("BillTokenStore");
context.Load(list, l => l.Fields);
context.Load(booksList, b => b.Id);
context.ExecuteQuery();
string schemaLookupField = #"<Field Type='Lookup' Name='InStock' StaticName='InStock' DisplayName='InStock' List='"+ booksList.Id +"' ShowField = 'Title' />";
Field lookupField = list.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.DefaultValue);
lookupField.Update();
context.Load(lookupField);
context.ExecuteQuery();
}

Upload Items To SharePoint List

I have a custom sharepoint list called VSList, from which I can retrieve all items (4 columns altogether) using the following code:
string siteUrl = url2;
ClientContext clientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("VSList");
CamlQuery camlQuery = new CamlQuery();
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem, items => items.Include(item => item["Title"], item => item["qf2a"], item => item["_x0077_830"], item => item["u6zl"]));
clientContext.ExecuteQuery();
Is there any way to reverse it somehow, so I can upload data, and not download it?
Thanks in advance.!
This is fairly simple to do with the following code (edited my code to fit your list).
// Open client context to the site
var clientContext = new ClientContext(siteUrl);
// Use client context to open the list
var oList = clientContext.Web.Lists.GetByTitle("VSList");
var listCreationinformation = new ListItemCreationInformation();
var oListItem = oList.AddItem(listCreationinformation);
// Push information to individual tables in the selected list
oListItem["Title"] = value1;
oListItem["qf2a"] = value2;
oListItem["_x0077_830"] = value3;
oListItem["u6zl"] = value4;
oListItem.Update();
clientContext.ExecuteQuery();
To get a better overview on how to do this see - How to: Create, Update, and Delete List Items

Converting a SharePoint SPListItem into a Drop down ListItem

I am trying to convert a SharePoint SPListItem into a ListItem to put into a Drop Down List. My problem is that the data in the SharePoint list is stored like this:
;#Daylight;#
;#Design;#Employee Engagement;#
But Obviously this does not work for me. I need to remove the ;# symbols which should be as simple as String.Replace but where I am running into some problems is what should I do for list items that contain multiple selections (my second example above). The ultimate goal here is to generate a drop down list (that does not contain duplicates) of all the items in the SharePoint List. Any ideas?
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
using (SPWeb oWebsiteRoot = site.OpenWeb())
{
SPList oList = oWebsiteRoot.Lists["WplData"];
SPListItemCollection items = null;
SPQuery query = new SPQuery();
query.Query = "<Where><IsNotNull><FieldRef Name='Topic' /></IsNotNull>" +
"</Where><OrderBy><FieldRef Name='Topic' Ascending='True' /></OrderBy>";
items = oList.GetItems(query);
DataTable tmpTable = new System.Data.DataTable();
tmpTable = items.GetDataTable();
DataView view = new DataView(tmpTable);
String[] columns = { "Topic" };
DataTable table = view.ToTable(true, columns);
foreach (DataRow row in table.Rows)
{
foreach (var item in row.ItemArray)
{
ListItem listItem = new ListItem();
listItem.Value = item.ToString();
listItem.Text = item.ToString();
TopicDropDownList.Items.Add(listItem);
}
}
}
Instead of a DataTable, try SPFieldLookupValueCollection:
SPList oList = oWebsiteRoot.Lists["WplData"];
SPListItemCollection items = null;
SPQuery query = new SPQuery();
query.Query = "<Where><IsNotNull><FieldRef Name='Topic' /></IsNotNull>" +
"</Where><OrderBy><FieldRef Name='Topic' Ascending='True' /></OrderBy>";
items = oList.GetItems(query);
foreach (SPListItem item in items)
{
SPFieldLookupValueCollection values =
new SPFieldLookupValueCollection(item["Topic"].ToString());
foreach (SPFieldLookupValue value in values)
{
ListItem listItem = new ListItem();
listItem.Value = value.LookupId.ToString();
listItem.Text = value.LookupValue;
TopicDropDownList.Items.Add(listItem);
}
}
Note, since you specified SharePoint 2007, I am avoiding the use of LINQ because that requires the .NET Framework 3.5. Also, as long as each list item contains a distinct set of topics, you will be fine. But if topics can be repeated among list items, you will want to modify this code so that TopicDropDownList contains a distinct set of topics.
LINQ it, something like (psuedocode)
...
var ddlItems = (from i in items
select i["Topic"]).Distinct();
TopicDropDownList.Items.AddRange(ddlItems);
...
If Topic is a multi-choice field you can split the field value by ;#:
var listItems = items.Cast<SPListItem>()
.SelectMany(i => Convert.ToString(i["Topic"]).Split(";#", StringSplitOptions.RemoveEmptyEntries))
.Distinct();
TopicDropDownList.Items.AddRange(listItems);
You can directly operate on the SPListItemCollection returned by oList.GetItems(query). You do not need to convert it in a DataTable.
You might considering including the Topic field as ViewField in your query.
If you don't want to split the field value manually, you could use the SPFieldMultiChoiceValue class. Unfortunately there is no handy way to access the choices in this class. There is only a count and an indexer so you have to use a for-loop.

Categories

Resources