I got the following error while running SharePoint ClientObject Model. I went through my code and checked if I missed any thing to load, but didn't see.
"Process is Terminated: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
I am not sure what I am missing after searching about this for a couple of hour.
The following is my code. Hope any one can help.
public static void UpdatePackageStatus(string Teamsite, string Libname, string Packagename, string User, string Password, string Domain, string PackageStatus, string DeploymentSucceeded, string query)
{
using(clientOM.ClientContext Ctx = new clientOM.ClientContext(Teamsite))
{
Ctx.Credentials = new System.Net.NetworkCredential(User, Password, Domain);
clientOM.Web Web = Ctx.Web;
Ctx.Load(Web);
Ctx.ExecuteQuery();
clientOM.List list = Web.Lists.GetByTitle(Libname);
Ctx.Load(list);
Ctx.ExecuteQuery();
clientOM.CamlQuery CamlQuery = new clientOM.CamlQuery();
CamlQuery.ViewXml = query;
clientOM.ListItemCollection Items = list.GetItems(CamlQuery);
Ctx.Load(Items);
Ctx.ExecuteQuery();
if(Items.Count > 0)
{
clientOM.ListItem Item = Items.GetById(Items[0].Id);;
Ctx.Load(Item);
Ctx.ExecuteQuery();
if(Item.DisplayName == Packagename)
{
Item[PackageStatus] = DeploymentSucceeded;
Item.Update();
Ctx.ExecuteQuery();
}
}
}
}
All used fields like DisplayName, Id and PackageStatus should be specified manually. You can use CAML query and write something like this:
string queryText = #"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='{0}'/>
<Value Type='Text'>{1}</Value>
</Eq>
</Where>
</Query>
</View>";
CamlQuery query = new CamlQuery();
query.ViewXml = string.Format(queryText, 'DisplayName', Packagename); //FieldRef = internal field name
ListItemCollection listItems = list.GetItems(query);
Ctx.Load(listItems, items => items.Include(item => item[PackageStatus]);
Ctx.ExecuteQuery();
if (listItems.Count > 0)
{
listItems[0][PackageStatus] = DeploymentSucceeded;
Item.Update();
Ctx.ExecuteQuery();
}
I see a fix.
Instead of using Item.DisplayName, I can use File object. It works when I use File and instantiating it by load(File) like other property.
clientOM.File file = Item.File;
Ctx.Load(file);
Ctx.ExecuteQuery();
if(file.Name == Packagename)
{
Item[PackageStatus] = DeploymentSucceeded;
Item.Update();
Ctx.ExecuteQuery();
}
Related
private static void sharepointConnection()
{
try
{
Console.WriteLine("Trying to connect");
const string rootUrl = "";
const string reqUrl = "";
const string pwd = "";
const string username = "";
SecureString securestring = new SecureString();
pwd.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));
ClientContext context = new ClientContext(reqUrl);
context.Credentials = new SharePointOnlineCredentials(username, securestring);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Use CSOM code in below format after authentication:
public static List<ListItem> GetAllDocumentsInaLibrary()
{
List<ListItem> items = new List<ListItem>();
string sitrUrl = "https://spotenant.sharepoint.com/sites/yoursite";
using (var ctx = new ClientContext(sitrUrl))
{
//ctx.Credentials = Your Credentials
ctx.Load(ctx.Web, a => a.Lists);
ctx.ExecuteQuery();
List list = ctx.Web.Lists.GetByTitle("Documents");
ListItemCollectionPosition position = null;
// Page Size: 100
int rowLimit = 100;
var camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'>
<Query>
<OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy>
</Query>
<ViewFields>
<FieldRef Name='Title'/><FieldRef Name='Modified' /><FieldRef Name='Editor' />
</ViewFields>
<RowLimit Paged='TRUE'>" + rowLimit + "</RowLimit></View>";
do
{
ListItemCollection listItems = null;
camlQuery.ListItemCollectionPosition = position;
listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
position = listItems.ListItemCollectionPosition;
items.AddRange(listItems.ToList());
}
while (position != null);
}
return items;
}
References:
Get all files from a SharePoint Document Library using CSOM
Download all files from Sharepoint Online Document Library using C# CSOM
Is there a Sharepoint API to get entire content of files/folders for a particular folder at once ?
I don't want to use GetFolderByServerRelativePath recursively.
If don't want to use GetFolderByServerRelativePath, you can use CSOM with CAML Query like this:
string password = "pwd";
string account = "user#Tenant.onmicrosoft.com";
var secret = new SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename"))
{
ctx.Credentials = new SharePointOnlineCredentials(account,secret);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle("Documents");
ctx.Load(list);
ctx.ExecuteQuery();
Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/shared%20documents/");
ctx.Load(folder);
ctx.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'>
<Query>
</Query>
</View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (var item in listItems)
{
Console.WriteLine(item.FieldValues["FileRef"].ToString());
}
}
will return all folders/subfolders/files together, hopefully, this is what you need.
I have a list named "Designation" that contains a Designation Code and Designation Name.
I have another list named "Employee" that contains Employee Name and Designation Name (as a Lookup Field).
I am able to insert values to "Employee" list using the following code.
protected void AddEmp(object sender, EventArgs e)
{
string emp_name = txtEmployeeName.Text;
string emp_designation = ddlDesignation.SelectedValue;
using (SPSite site = new SPSite("My Site"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
web.AllowUnsafeUpdates = true;
SPList splist_employees = web.Lists["Employee"];
SPList splist_designations = web.Lists["Designations"];
SPListItemCollection splc_items = splist_employees.Items;
SPListItem spli_item = splc_items.Add();
SPFieldLookup lookup = splist_employees.Fields["Designated"] as SPFieldLookup;
string fieldName = lookup.LookupField;
spli_item["Employee Name"] = emp_name;
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations);
spli_item.Update();
});
}
}
}
public static string GetLookFieldIDS(string lookupValues, SPList lookupSourceList)
{
string id = string.Empty;
SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Designation' /><Value type='Text'>"+lookupValues + "</Value></Eq></Where>";
SPListItemCollection listItems = lookupSourceList.GetItems(query);
foreach (Microsoft.SharePoint.SPListItem item in listItems)
{
id = item.ID.ToString();
}
return id;
}
Here I have given the field name as 'Designation' inside the query.
But, I want to find the field name based on the value given from the user end instead of hard-coding the field name as 'Designation'.
Any help is greatly appreciated. Thanks in advance.
Not sure about your request but, you could pass SPFieldLookup.LookupField property to your GetLookFieldIDS method and use that variable instead of "Designation"
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations, lookup.LookupField);
Does anyone know how to read the number of attachments, and the names etc for a ListItem using the Client .Net Object model in SharePoint?
Thanks
// For getting the list item field information
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
// Pass the item id here for getting the attachments
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName, id);
}
Your can try this link too.
http://helpmetocode.blogspot.com/2011/11/managed-client-object-models-in.html
I'm using Sharepoint 2010 Object Model. I'm trying to retrive the content of a Custom List. Everything works fine except if when I try to retrieve a Choice Field.
When I try to retrieve the choice field, I got an PropertyOrFieldNotInitializedException exception...
Here is the code I'm using:
ClientContext clientContext = new ClientContext("https://mysite");
clientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("aaa", bbb");
clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
List list = clientContext.Web.Lists.GetByTitle("mylist");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (ListItem listItem in listItems)
{
listBoxControl1.Items.Add(listItem["Assigned_x0020_Company"]);
}
var list = clientContext.Web.Lists.GetByTitle(listName);
clientContext.ExecuteQuery();
clientContext.Load(list.Fields, fields => fields.Include(field => field.Title));
clientContext.ExecuteQuery();
foreach (var field in list.Fields)
{
if (field.Title == "YourChoiceFieldName")
{
clientContext.Load(field);
clientContext.ExecuteQuery();
return ((FieldChoice) field).Choices;
}
}
When you read a ChoiceField in code , It will return a string array of selected choices. For example if you entered in the choice box of the column when you create it : "Company 1" ,"Company 2","Company 3 " , if user select option 1 & 2 , then returned array in code will contain "Company 1" and "Company 2" .You must change the code to the below :
foreach (ListItem listItem in listItems)
{
string[] values = (string[])listItem["Assigned_x0020_Company"];
foreach(string s in values)
{
listBoxControl1.Items.Add(s);
}
}