Search code examples
c#visual-studio-2013sharepoint-2010.net-4.0

Getting SharePoint Site Title


I've having difficulty following this guide

http://dotnetbyexample.blogspot.co.uk/2011/03/sharepoint-client-object-model-sites.html

I've created the helper class as advised:

namespace TestSharepoint
{
  public class SharepointHelper
  {
    private ClientContext clientContext;
    private Web rootWeb;

    public SharepointHelper(string url, string username, string password)
    {
      clientContext = new ClientContext(url);
      var credentials = new NetworkCredential(username, password, "oshirowanen.com");
      clientContext.Credentials = credentials;
      rootWeb = clientContext.Web;
      clientContext.Load(rootWeb);
    }
  }
}

However, I do not want to create another site, as I already have a site, so I wanted to test the next part by retrieving the existing sites title:

public Web GetWebByTitle(string siteTitle)
{
  var query = clientContext.LoadQuery(
    rootWeb.Webs.Where(p => p.Title == siteTitle));
  clientContext.ExecuteQuery();
  return query.FirstOrDefault();
}

and added this to the form load event:

var sh = new SharepointHelper("https://sharepoint.oshirowanen.com/sites/oshirodev/", "sharepoint_admin_user", "sharepoint_admin_password");
var w = sh.GetWebByTitle("Oshirowanen SharePoint");
Console.WriteLine(w.Title);

What I am getting confused about is, why I am typing in the title of the site which I want to receive the title of??? So I think I am not using this properly?

The error I get is:

An unhandled exception of type 'System.NullReferenceException' occurred in SharePointProgramming.exe

Additional information: Object reference not set to an instance of an object.

Any idea what I am doing wrong?

The username and password I have used has full SharePoint privileges.

I am using Visual Studio 2013, C#, .NET 4.0, and SharePoint 2010.


Solution

  • To fetch the title of the site your just need the value of the variable web.title.

      namespace TestSharepoint
    {
      public class SharepointHelper
      {
        private ClientContext clientContext;
        private Web rootWeb;
    
        public SharepointHelper(string url, string username, string password)
        {
          clientContext = new ClientContext(url);
          var credentials = new NetworkCredential(username, password, "oshirowanen.com");
          clientContext.Credentials = credentials;
          rootWeb = clientContext.Web;
          clientContext.Load(rootWeb,web=>web.title);
        clientContent.ExecuteQuery();
        string siteTitle=web.title;
                }
              }
            }