Tag Archives: tips

Common coding issues when working with anonymous SharePoint sites

Update Oct 4, 2012:
Added the usage of UnsecuredLayoutsPageBase class.

Working with anonymous SharePoint sites can be tricky sometimes. If you’re not careful, your customization codes (Web parts, custom controls, custom pages, etc.) can popup the login dialog box to anonymous users. As anonymous users they don’t have a user account, so obviously they won’t be able to enter their user ID and password. Or it simply produces an error page that either way, prevents anonymous users from accessing your site.

This post addresses some common coding issues when you work with anonymous SharePoint sites, so you can avoid it earlier.

1. Determining whether the current user is an anonymous user

How to check whether the current user is an anonymous user? I may have overlooked it, but as far as I know there is no built-in API methods for this purpose. Fortunately it’s very easy and terse. You can test the value of SPContext.Current.Web.CurrentUser. If it is null then it is accessed by an anonymous user. Here is a sample code:

if (SPContext.Current.Web.CurrentUser == null)
{
	// Anonymous user section
}
else
{
	// Authenticated user section
}

2. Beware when using SPWeb.CurrentUser

As described on the previous point, when an anonymous user is accessing a Site, the value of SPContext.Current.Web.CurrentUser will always be null. Double-check whenever you are using the property. Always make sure that you have checked for the null value, or you will end up getting the nasty “System.NullReferenceException – Object reference not set to an instance of an object.” exception.

3. Anonymous user does not have a user profile

It is an obvious yet easily overlooked one. It is a common practice to utilize the UserProfile API to store user’s personalization. Since an anonymous user does not have a user profile, provide another mean to store his/her personalization data. It could be SharePoint lists, database tables, files, or even browser cookies.

4. Working with the Publishing Feature API

I’m referring to the API under the Microsoft.SharePoint.Publishing assembly and namespace. I haven’t checked all of the API members, but not all will work with anonymous users. For example, the PublishingWeb.IsPublishingWeb(SPWeb web) works, but the PublishingWeb.GetPublishingWeb(SPWeb web) doesn’t. In fact, it will prompt the anonymous user to login by entering the user ID and password. The workaround is get an elevated SPWeb instance that has the System Account’s credential and then use the GetPublishingWeb() method on that instance. The following snippet illustrates it:

var currentWeb = SPContext.Curent.Web;
 
// the method is available to anonymous users
if (PublishingWeb.IsPublishingWeb(currentWeb))
{
	SPSecurity.RunWithElevatedPrivileges(delegate()
	{
		using (var site = new SPSite(curentWeb.Url))
		{
			using (var web = site.OpenWeb())
			{
				// the method is not available to anonymous users
				var pubWeb = PublishingWeb.GetPublishingWeb(web);
 
				// Do something with pubWeb
			}
		}
	});
}

5. Creating a custom page layout.

Your custom page layout has to inherit from the UnsecuredLayoutsPageBase class if you want to allow anonymous users to access the page, and inherit the LayoutsPageBase class if the page layout is intended only for authenticated users.

I will update this post when I find more things related to anonymous SharePoint sites. Please leave a comment if you have something to contribute, too.

Flowchart: which open source license should I use?

Choosing open source license flowchart This is a common question when one wants to publish a new open source project, especially if he/she is new to open source licensing scheme. The many available choices of the license can be very confusing and many people simply pick a license without really understanding the meaning or the clauses in the license. Some choose a license by the popularity. Some because a particular license is used in their favorite projects. Even worse, some even choose a license because it looks or sounds cool.

There are many resources on the Web that provide comparison of the available licenses. I want to make it simpler by creating a flowchart to guide you to pick the right license for your project. To reduce confusion, I’ll only list the most common open source licenses. You can click on the flowchart to enlarge it.

System.Net.WebException: An exception occurred during a WebClient request

When using either WebClient or HttpWebRequest to download file from a remote location, sometimes I got the following exception:

System.Net.WebException: An exception occurred during a WebClient request

For some reasons, IIS (the Web server) may deny to serve a request that doesn’t specify the user-agent property in the request header. So, although it’s not really obvious, this can be solved pretty easily by specifying the particular user-agent property. You can set it to anything, it doesn’t matter as long as it exists.

For example, here how you provide the property using WebClient:

using (var wc = new WebClient())
{
	wc.Credentials = CredentialCache.DefaultCredentials;
	wc.Headers.Add(HttpRequestHeader.UserAgent, "anything");
	wc.DownloadFile(fileUrlToDownload, fileNameToSafe);
}

And, here how to do it with HttpWebRequest:

var req = (HttpWebRequest)HttpWebRequest.Create(fileUrlToDownload);
req.Credentials = CredentialCache.DefaultCredentials;
req.UserAgent = "anything";
 
var resp = (HttpWebResponse)req.GetResponse();
 
using (var stream = resp.GetResponseStream())
{
	using (var fstream = new FileStream(fileNameToSafe)
	{
		var buffer = new byte[8192];
		var maxCount = buffer.Length;
		int count;
		while ((count = stream.Read(buffer, 0, maxCount)) > 0)
			fstream.Write(buffer, 0, count);
	}
}
 
resp.Close();

You may also notice that downloading a file using WebClient is much simpler than using HttpWebRequest. The later, however, gives you much more control.