Tag Archives: best practices

Centralized exception handling

Exception handling is a very useful mechanism to improve a program’s robustness. In case an unexpected exception occurs, developers commonly write a code block as follows:

try
{
  // Do something
}
catch (Exception ex)
{
  // Log the exception
  // Notify the user about the exception
}

That code block is very often duplicated everywhere in the project. It is obviously not a good coding practice. Instead of duplicating, we should extract and promote it as a subroutine. That way, we can gain the following advantages:

  1. More maintainable; if the exception handling is kept in a single place, it is easy to apply future modifications.
  2. More productive; less amount of code to write (or copy) means less coding time and less possibility of error.
  3. Separation of concern; each routine will be much clearer since it is not polluted with exception handling, logging, and notification code blocks.

Centralized exception handling implementation

If you already have or willing to use Microsoft Enterprise Library, there is already the Exception Handling Application Block for you to use.

But you can easily implement your own. The basic idea is create a method with your exception handling block. This method must be able to accept and execute a code block. To achieve this we can use delegate. In .NET Framework 3.5, it is even simpler with the Action delegate.

The code executes inside the try block, while in the catch block, all necessary treatments (logging and notification) can be added.

The following is a sample skeleton of the implementation built as a method called TryExecute:

void TryExecute(Action code)
{
  try
  {
    code(); // Execute the passed code
  }
  catch (Exception ex)
  {
    // Log the exception
    // Notify the user
    // Add more things as required
  }
}

Then, in your client code, you can just call it as follows:

void SomeMethod()
{
  // Send the code inside the block to the TryExecute() method.
  TryExecute(() =>
  {
    // Do something
  });
}

Easy, right?

C# constants best practice

In C# there are two way to define constants, using const and readonly. Some may say that there is the enum keyword, but it’s actually a group of const. In case you don’t know, there are some important differences between these two keywords:

const readonly
It is always a static class member. It can be a static or instance class member.
The value is evaluated at compile time. Therefore, the only
possible values for constants of reference types are string and null.
The value is evaluated at run time and embedded to every assembly that uses it. Therefore, the values for
readonly fields can be the output of method calls.
It has to be initialized at the declaration. It can be initialized at the declaration or the class constructor.
It can be used to construct enumerated values. It cannot be used to construct enumerated values.
It can be used to construct attributes. It cannot be used to construct attributes.

Based on the differences, we can establish a practice when to use const and readonly.

Use const:

  1. To construct enumerated values.
  2. To construct attributes.
  3. When you are sure that the value will never change between releases, for example, mathematical constants (pi, Euler’s number, golden ratio, and so on).
  4. When declared inside a class with internal modifier. The internal modifier ensures the fields cannot be used in another assembly, thus eliminating versioning issues when the value is changed.

Use readonly:

  1. When you need to assign the value with an output of a function.
  2. When you need to assign the value in the constructor.
  3. When the fields are going to be used by other assemblies. This prevents the value from being embedded to the assembly, hence there will be no issues even if the value of the fields are changed.
  4. When declared inside a class with public modifier. The public modifier indicates that the class is available to be used by other assemblies, hence there can be a versioning issue if const is used instead of readonly.

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.