2

I'm developing a C# console application that queries some items from some lists.

Most lists are in a sub-site, but one of the list I need to query is in the root (or main) site.

Example:

  • The sub-site is: http://prod_01/human-resources/property/.
  • The root/main site is: http://prod_01/.

In the sub-site http://prod_01/human-resources/property/ I get the information I need by querying certain information from a few lists, but, in the root/main site http://prod_01/ there is a list called Holidays which I cannot get the list instance.

This is the code I found in this answer for connect to the site via CSOM:

// Variables used in this code:
string url_site = "http://prod_01/human-resources/property/";
string _user = "shpfarm";
string _password = "******";

// CSOM Authentication:
ClientContext clientContext = new ClientContext(url_site);
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(url_site), "NTLM", new NetworkCredential(_user, _password));
clientContext.Credentials = myCache;

I'm using this code for query the Holidays list:

try
{
    string HolidayDate = DateTime.Today.ToString("yyyy-MM-dd");
    string holiday_list_URL = "http://prod_01/human-resources/property/Lists/Holidays/AllItems.aspx";

    List lst_Holiday = clientContext.Web.GetList(holiday_list_URL);
    clientContext.Load(lst_Holiday);
    Console.WriteLine("List called succesfully");

    // Query: Get if current date is a holiday:
    CamlQuery cmlQueryHoliday = new CamlQuery();
    cmlQueryHoliday.ViewXml = string.Format(@"<View>
                                                   <Query>
                                                     <Where>
                                                        <Eq>
                                                           <FieldRef Name='HolidayDate' />
                                                           <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value>
                                                        </Eq>
                                                     </Where>
                                                  </Query>
                                               </View>", HolidayDate);
    ListItemCollection colItems = lst_Holiday.GetItems(cmlQueryHoliday);
    clientContext.Load(colItems);
    clientContext.ExecuteQuery();
}
catch (Exception ex)
{
    Console.WriteLine("Error calling list (using URL): " + ex.ToString());
}

But I get this exception (which really doesn't say much about the causes):

in Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx)
in Microsoft.SharePoint.Library.SPRequest.GetMetadataForUrl(String bstrUrl, Int32 METADATAFLAGS, Guid& pgListId, Int32& plItemId, Int32& plType, Object& pvarFileOrFolder)
in Microsoft.SharePoint.SPWeb.GetList(String strUrl)
in Microsoft.SharePoint.ServerStub.SPWebServerStub.InvokeMethod(Object target, String methodName, XmlNodeList xmlargs, ProxyContext proxyContext, Boolean& isVoid)
in Microsoft.SharePoint.Client.ServerStub.InvokeMethodWithMonitoredScope(Object target, String methodName, XmlNodeList args, ProxyContext proxyContext, Boolean& isVoid)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.InvokeMethod(Object obj, String methodName, XmlNodeList xmlargs, Boolean& isVoid)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.GetObjectFromObjectPath(XmlElement xe)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.GetObjectFromObjectPathId(String objectPathId)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessInstantiateObjectPath(XmlElement xe)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessOne(XmlElement xe)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessStatements(XmlNode xe)
in Microsoft.SharePoint.Client.ClientMethodsProcessor.Process()

I tried:

  • Use different user credentials.
  • Changing the URL of the Holidays list from http://prod_01/human-resources/property/Lists/Holidays/AllItems.aspx to http://prod_01/human-resources/property/Lists/Holidays.

But I get the same exception.

How can I get the list instance by using the URL of Holidays list? or which alternatives can I use for get the Holidays list and its items?

3 Answers 3

2

For GetList method, you should use server relative url. In your case it will be human-resources/property/Lists/Holidays.

However this method only works in SharePoint 2016 on onwards, In SharePoint 2013 it works starting from February 2015 Cumulative Update (probably also works in SharePoint 2013 Service Pack 1, but as far as I know it's not).

0

clientContext.Web.GetList() method will need list server relative url, in this case, it is "/human-resources/property/Lists/Holidays", change this line:

 string holiday_list_URL = "/human-resources/property/Lists/Holidays";

 List lst_Holiday = clientContext.Web.GetList(holiday_list_URL);
0

After trying the answers made by Sergei and Jerry, I couldn't make it work.

So, I ended by using the server-side object model.

These are the steps I follow for get and query the list instance:

  • Get the base URL of the site, using the code provided here.
  • Using the SPSite and related classes for get and query the Holidays list.

This is the logic I use for get the desired result:

/// <summary>
/// Mauricio Arias Olave
/// 12/10/2018: This special method receives the URL of the "Holidays" list
/// for query whether is current date is holiday. 
/// From the provided URL it gets the URL of the root site.
/// It returns the query results in a DataTable.
/// </summary>
/// <param name="url_lst_holiday">URL de la lista "holiday".</param>
/// <param name="shp_formatted_date">DateTime.Today.ToString("yyyy-MM-dd").</param>
public static DataTable CheckIfHoliday(string url_lst_holiday, string shp_formatted_date)
{
    // Inicializar variables.
    bool hasErrors = false;
    int parts = 0;
    string baseUri_rootSite = "";
    string nombreListaholiday = "";
    DataTable tbl_holidays = new DataTable();

    try
    {
        try
        {
            // Source: https://stackoverflow.com/a/15641846/4092887
            /// Using the given URL "Sample: http://prod_01/human-resources/Lists/Holidays/AllItems.aspx"
            /// get the URL root site and the name of the list to use.
            var uri = new Uri(url_lst_holiday);
            baseUri_rootSite = uri.GetLeftPart(UriPartial.Authority);
            parts = uri.OriginalString.Split('/').Length;
            nombreListaholiday = uri.OriginalString.Split('/')[parts - 2];
        }
        catch (Exception ex)
        {
            hasErrors = true;
            Console.WriteLine("Cannot get the list location. See log application file for details.");
            LogErrors("Cannot get the list location. Error: " + ex.ToString());
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("GLOGIC_Webparts", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "Cannot get the list location. Error: " + ex.ToString());
        }

        if (!hasErrors)
        {
            // Connect to root site.
            using (SPSite _site = new SPSite(baseUri_rootSite))
            {
                using (SPWeb _web = _site.OpenWeb())
                {
                    // Instance of "Holiday" list.
                    SPList lst = _web.Lists[nombreListaholiday];

                    if (lst != null)
                    {
                        // Query if "shp_formatted_date" is a holiday.
                        SPQuery qry = new SPQuery();
                        qry.Query = string.Format(@"<Where>
                                                       <Eq>
                                                          <FieldRef Name='HolidayDate' />
                                                          <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value>
                                                       </Eq>
                                                    </Where>", shp_formatted_date);
                        SPListItemCollection col = lst.GetItems(qry);

                        // if there are query results...
                        if (col != null && col.Count > 0)
                        {
                            // It is a holiday. Return DataTable.
                            tbl_holidays = col.GetDataTable();
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        tbl_holidays = new DataTable();
        Console.WriteLine("Cannot determine if (" + shp_formatted_date + ") is a holoday. See log application file for details.");
        LogErrors("Cannot determine if (" + shp_formatted_date + ") is a holoday. See log application file for details. Error: " + ex.ToString());
        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("GLOGIC_Webparts", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "Cannot determine if (" + shp_formatted_date + ") is a holoday. See log application file for details. Error: " + ex.ToString());
    }

    return tbl_holidays;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.