Thursday, October 20, 2011

How to get SharePoint Home Page URL without SharePoint API

This is a hint on how you can use .Net to get SharePoint Home Pages using .Net Code.

I was making a application to return all Sites and Sub-Site and the question came to my mind "What is the HomePage url for each Site?"

You don't have access to Server SharePoint API and you need to get the Home Page for each SharePoint Site.

When you list the Site Collection or Sub Sites on the SharePoint Site "can be using Out of the Box Web Services Webs.asmx" you will have something like this:
  • http://[site]
  • http://[site]/Sites/example1
  • http://[site]/Sites/example2
  • http://[site]/Sites/example3

But you don't have the Home Page url associated for each sub Site or Site Collection,

For example if you use a normal SharePoint 2010 template the default page is 
  • http://[site]/SitePages/home.aspx
SharePoint 2007 Template was:
  • http://[site]/default.aspx
If you use Publishing Template you will have something like this
  • http://[site]/Pages/default.aspx

One way to manage the Home Page for each site is using SharePoint Designer 2010.

Since we cannot assume the same default homepage and Hard code url is not a good Solution we can use the .NET Framework to get the HomePage associate for each Site...

Example with code:

HttpWebRequest httpWebrequest;
HttpWebResponse httpWebresponse;

//Create a request for the SharePoint Site
httpWebrequest = (HttpWebRequest)WebRequest.Create("url site example, https://example/sites/example1");
//Associate the correct Credential to you SharePoint Site
CustomCredential.Add(new Uri("url site example, https://example/sites/example1"), "NTLM", new NetworkCredential("UserLogin", "Password", "Domain"));
//or you can assume the current local Credential to authenticate
CustomCredential.Add(new Uri("url site example, https://example/sites/example1"), "NTLM", System.Net.CredentialCache.DefaultCredentials);
 //If you don't have the credentials you will get error 401

// Assume the credentials to you request
httpWebrequest.Credentials = CustomCredential;  
httpWebresponse = (HttpWebResponse)httpWebrequest.GetResponse();

//Get the Homepage associate to "https://example/sites/example1"
String HomePage = httpWebresponse.ResponseUri.AbsoluteUri.ToString();

//Popup a message with the HomePage url

For this example i create a application to list all Site Collection and Sub-Site and popup the HomePage of each one.

Hope you like... :)

No comments: