Adding lookup column to list using CSOM - c#

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

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 get list of items in an entity using DiscoveryService in Dynamics CRM 2016?

I am trying to get the list of contacts using the DiscoveryServiceClient in CRM 2016 on-prem
I added service reference and created an object, but I am not sure on what method I should be using to get the list of Entity items
CRMService.DiscoveryServiceClient client = new CRMService.DiscoveryServiceClient();
client.Open();
var query = new QueryExpression();
query.EntityName = "Contact";
query.ColumnSet = new ColumnSet { AllColumns = true };
var coll = client.RetrieveMultiple(query);
Console.WriteLine("Retrieved {0} entities", coll.Entities.Count());
foreach (var item in coll.Entities)
{
Console.WriteLine("Contact: " + item);
}
client.Close();
When I used the above code it says
DiscoveryServiceClient does not contain a definition for
RetrieveMultiple
I also tried using the below code
QueryExpression qe = new QueryExpression();
qe.EntityName = "contact";
qe.ColumnSet = new ColumnSet();
qe.ColumnSet.Columns.Add("emailaddress1");
EntityCollection ec = organizationProxy.RetrieveMultiple(qe);
foreach (Entity act in ec.Entities)
{
Console.WriteLine("account email:" + act["emailaddress1"]);
}
This loads fine, but all values are null inside the items
Is there a special need for you to use the DiscoveryServiceClient?
If this is a job or so, you should/could use the IOrganizationService to retrieve your EntityCollection.
Here is a little Link, that might help you: https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg328029(v=crm.8)

Trouble Filtering Sharepoint List with Caml

I'm trying to filter a SharePoint list so that only the items with the Management field, which holds a string, as "Yes" will show up, but whenever I get to the ctx.ExecuteQuery() statement, my program blows up. I believe my CAMLQuery is structured correctly, so I'm not sure if I'm simply using it wrong or if I'm missing something. Any help would be great! thanks! The code I currently have is posted below:
Web myWeb = ctx.Web;
List myList = myWeb.Lists.GetByTitle("Company Employees");
SPClient.View view = myList.DefaultView;
CamlQuery qry = new CamlQuery();
qry.ViewXml = "<Query>" + "< Where >" + "<Eq>" + "< FieldRef Name='Management'/>" + "< Value Type='Text'>Yes</ Value >" + "</Eq>" + "</ Where >" + "</ Query >";
myList.GetItems(qry);
ListItemCollection listItems = myList.GetItems(qry);
ctx.Load(listItems);
ctx.ExecuteQuery();
Your code appears to be missing the <View> tag which would wrap around your <Query> tag in the CAML.
With the addition of the <View> root element, the correct CAML XML would be as follows:
qry.ViewXml =
"<View>"+
"<Query>"+
"<Where>"+
"<Eq>"+
"<FieldRef Name='Management'/>"+
"<Value Type='Text'>Yes</Value>"+
"</Eq>"+
"</Where>"+
"</Query>"+
"</View>";
Additional Troubleshooting
To help troubleshoot, you can try running the same query through the JavaScript client object model.
Visit the SharePoint site in Internet Explorer and hit F5 to open up the developer tools.
On the Console tab, enter the following lines of code and execute (by pressing Enter or Ctrl+Enter) them one line at a time:
-
var ctx = new SP.ClientContext();
var list = ctx.get_web().get_lists().getByTitle("Company Employees");
var qry = new SP.CamlQuery();
qry.set_viewXml("<View><Query><Where><Eq><FieldRef Name=\"Management\"/><Value Type=\"Text\">Yes</Value></Eq></Where></Query></View>");
var items = list.getItems(qry);
ctx.load(items);
ctx.executeQueryAsync(function(){alert("success!");},function(sender,args){alert(args.get_message());});
POST HELP SOLUTION Thanks to your help, I was able to figure out how to create a new view with the desired filtering by using the following code. The main problem was with the Caml Query--I had to remove the and tags and then delete a few of the lines before creating the view. Below is my working solution:
Web myWeb = ctx.Web;
List myList = myWeb.Lists.GetByTitle("Company Employees");
SPClient.View view = myList.DefaultView;
CamlQuery qry = new CamlQuery();
qry.ViewXml =
"<Where><Eq><FieldRef Name=\"Management\"/><Value Type='Text'>Yes</Value></Eq></Where>";
ViewCollection viewColl = myList.Views;
string[] viewFields = { "Title", "Promoted", "Intern", "Management" };
ViewCreationInformation creationInfo = new ViewCreationInformation();
creationInfo.Title = "Management";
creationInfo.RowLimit = 50;
creationInfo.ViewFields = viewFields;
creationInfo.ViewTypeKind = ViewType.None;
creationInfo.SetAsDefaultView = false;
creationInfo.Query = qry.ViewXml;
viewColl.Add(creationInfo);
ctx.ExecuteQuery();

sharepoint 2013 create document library using List Template 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.

To fetch a specific SharePoint Office 365 list item using CAML query?

I am creating a sample program to check ListItem existence at Sharepoint list.
My SharePoint list has one of column (field) named 'Title' or it can be any other name with text type.
I Know that when we create a list at SharePoint for each item in the list a "ID" field is assigned by SharePoint list item itself.
I am creating my sample application in C# using Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime dlls.
PROBLEM: I want to get a specific item in the list on the basis of the value of 'Title' column using CAML query.
My List may contains thousands of items,
Using CAML Query :
"<View><Query><Where><Leq>" +
"<FieldRef Name='ID'/><Value Type='Number'>100</Value>" +
"</Leq></Where></Query><RowLimit>7000</RowLimit></View>"
I am successfully retrieving ListItemCollection and throw that I can get ListItem. But its very time consuming and inefficient way, to traverse whole list to get particular item.
Although it is possible to get a specific item in list through the ID field using CAML query, but as i don't know what is the ID of the Item, therefore i want to fetch it through my "Title" field,
for this i tried the following CAML Query
`
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><eq>" +
"<FieldRef Name='TITLE'/><Value Type='TEXT'>2</Value>" +
"</eq></Where></Query></View>";`
but I get the following exceptions when I run the code
1. Value does not fall within the expected range. this exception is generated when I try to fetch Item through the 'Title' instead of 'ID' field, in the FieldRef Name parameter.
2. One or more field types are not installed properly when i created a coloumn manually in the list, and passed it in the FieldRef Name parameter
My code snippet is as follows
class sharepoint1
{
ClientContext context = null;
string OBJECTMETATADTA_ID = "Title";
private class Configuration
{
public static string ServiceSiteUrl = "";
public static string ServiceUserName = "";
public static string ServicePassword = "";
}
private ListItemCollection getListItemCollectionFromSP(String listName)
{
Web oWebsite = context.Web;
ListCollection collList = oWebsite.Lists;
List oList = collList.GetByTitle(listName);
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><eq>" +
"<FieldRef Name='Title'/><Value Type='Text'>abc</Value>" +
"</eq></Where></Query></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
context.Load(collListItem,
items => items.IncludeWithDefaultProperties(
item => item.DisplayName));
context.ExecuteQuery();
return collListItem;
}
ListItem checkItem(string listname, string fileName)
{
ListItem result = null;
ListItemCollection collListItem =
getListItemCollectionFromSP(listname);
string itemName = fileName.Substring(0, 3);
foreach (ListItem oListItem in collListItem)
{
if (oListItem[OBJECTMETATADTA_ID].Equals(itemName))
{
{
// my business logic;
}
}
}
context.Dispose();
return result;
}
}
It would be great if I get some help on this Issue from any person who knowns about this.
Did you try with 'Eq' instead of 'eq' in your query? CAML query is case sensitive

Categories

Resources