Forms Authentication

If you come across a project that requires you to setup forms based authentication on a SharePoint site, its actually kind of simple. This post will walk you through creating a new database that will handle storing user information like usernames, passwords, and roles. The steps taht we’re going to take are:

  1. Create a database to store user info
  2. Extend a site
  3. Create the necessary web.config entries
  4. Create users and roles
  5. Configure the extended site for forms based authentication
  6. Grant the new users and roles permissions on the extended site

Creating the Database

Luckily, we don’t have to do alot to get a database up and running. You can run the Aspnet_regsql.exe tool to start a wizard that will create this database for you. The exe is found in \WINDOWS\Microsoft.NET\Framework\v2.0.50727. Double-click the file and let’s begin.

Once you run that tool, the ASP .NET SQL Server Setup Wizard will open. Click next to get started.

Make sure the “Configure SQL Server for application services” radio button is selected and click next.

Next, you’ll need to specify the server that will store the database and the database name. Now, for the database name, you have 1 of 3 options. You can leave it blank, like I do for this demo and it will create a generic name for your database “aspnetdb”. You also have the option of selecting a database from the dropdown. When you select a database, it will add the necessary tables and stored procedures without affecting your existing database’s content. The last option is to type in a new database name and it will create your database with the appropriate tables and stored procedures.

The next page will display your selections in the previous page. Confirm that everything is ok, and click Next.

Click Finish.

Once your database is created, you can go view it and inspect the tables and stored procedures provided. Below is an image of the tables created.

Extend a Site

In Central Admin, go to the Application Management tab and click on the Create or extend Web application link. This will take to to the following page. On this page, you’ll need to select the site that you want to extend. This part is pretty straight forward. Just select the Create a new IIS web site radio button, assign an unused port, provide a host header if needed and select a zone from the available items in the dropdown.

Configure the Web.Config

The next thing that we’ll need to do is setup the web.config by adding a connectinoStrings element, a membership element and a rolemanager element. We’re going to want to test the connection before we start to modify the SharePoint web.config. In order to do this, you’ll want to use Visual Studio to create a new website. Open the site’s web.config file and before the section, add your connection string information. Inside add your membership and roleManager.

A few things to pay attention to: In the connectionStrings’ add element, the name attribute’s value is whatever you want it to be. The same goes for the membership’s and roleManager’s defaultProvider.

Go ahead and copy the data, with your particular modifications to the connectionstring. For additional help, you can visit msdn to learn more on the connectionStrings element, the membership element and the roleManager element.

Note: Do not edit the web.config used by your site without creating a backup. If you make a mistake either in the sections that we’re going to add or even if you accidently add/remove a character from some random line in the file, you can break your site.

Create Users and Roles

Now that your web.config is setup in your test website, we’ll need to go to the ASP .NET Configuration. In the image below, it is located under the Project menu item. This will open the ASP.NET Web Site Administration Tool.

When the tool loads, you’ll see 3 sections in the bottom. We’re going to worry about the 1st two (Users and Roles).

First, click on the Select authentication type under the Users section. Make sure, From the Internet is selected. Go back to the previous page, and in the Users section, you’ll see a new link to create users. Click on the link, and create a couple of users. Then click Create or Manage Roles under the Roles section to create roles and assign users to each role. This part is simple, so I’ll leave that to you.

Enable Forms Authentication on the Extended Site

Now we go back to Central Admin. Go to Application Management > Authentication Providers (found under the application security section) and select your extended site. If you don’t see it, make sure that the original web application (the one that you extended) is in the dropdown on the page. When you select your extended site, you’ll see the following page. I’ve highlighted the important sections. You’ll see that the zone that appears is the zone that I selected when I extended the site. You’ll have to select Forms under the authentication type and then you’ll have to provide the Membership Provider and the Role Manager information. This information comes from your web.config file under the provider sections for each.

Once you click the save button, go back to the Application Management page and click the Site collection administrators link under the SharePoint Site Management section.

Make sure the correct web application appears in the dropdown and you can add one of the accounts created earlier in the Secondary site colleciton administrator section. If you use the Check Names button, it should find the account in your database. I created an admin user and admin group earlier and I’ll add the admin here.

Now you can log into the site as the administrator and add the other users from the database to your site.

Best Practice: In my opinion, and I’m sure most will agree with me, it is best to do everything through groups. You’ll want to create a SharePoint group and add users to the group instead of adding them directly to a site or list.

Note: The roles that we created earlier behave like domain groups and you should think of them as such. When you created your roles in the ASP.NET Web Site Administration Tool, you associated individual accounts to each role. Now you can go to a SharePoint group and add the role that you created. This will bring in all the users assigned to that role without you having to add them one by one.

When the user’s attempt to access your new forms authenticated site, they will be greeted with the following page asking for credentials. The system will handle validating the credentials against the database that we created in the beginning without you having to write any code.

Microsoft Certified Technology Specialist

I’ve been keeping very busy lately, hence the infrequent posts. I just took my Windows SharePoint Services – Application Development (70-541) exam this morning and passed it. I have another side project that I’m putting a lot of focus towards but with the exam out of the way, I should have more time on my hands to start posting more content. I have a few things in mind so I expect to have something up within a day or two.

Getting Started with Site Definitions

Site Definitions allow you to create you own sites templates that can be selected when creating new sites and contain their own lists/document libraries/webparts/features. (see image below) I’m going to show you how to quickly and easily create your own Site Definition from an existing Site Definition. If you want to add default functionality to your custom site definition, visit my post on Feature Stapling.

The first thing that you’ll want to do is create your own copy of an existing site template. To do this, go to the 12 Hive’s TEMPLATE\SiteTemplates folder. In here, we’re going to create a copy of the sts folder and rename the copy SHAREPOINTLESSONS. (I recommend you use all caps to make it semi-consistent with the rest of the folders; however, your site will work if you use lowercase or mixed case.)

Next, you’ll want to go to the TEMPLATE\1033\XML folder. (1033 for English. For other languages, use the appropriate LCID. If you have multiple LCID’s in your TEMPLATE folder, here is a chart to help you find the appropriate one.)

In this folder, create a new copy one of the webtemp xml files and rename it. In this example, I’ve renamed mine WEBTEMPSPL.xml.

The following image contains the contents of WEBTEMPSPL.xml before I edit it. As you can see, the format is as follows:

I’m going to remove all of the Template elements and create my own. First, create your new Template element and give it a Name attribute, as well as an ID attribute. The name that you use here must be the name of the new folder you created in the SiteTemplates directory. In this example, my template name must be SHAREPOINTLESSONS. As for the ID, it is recommended that you use a number above 10,000 to avoid conflicting with any ID’s that Microsoft may already be using. My ID is 10002 (I’ve already used 10001).

Now we’ll move on to the Configuration element. This one has 6 attributes that will need to be provided.

  1. ID – Unique ID for this particular configuration
  2. Title – Name that will appear for in the list box when users are creating new sites
  3. Hidden – Duh
  4. ImageUrl – Image displayed to the left of the listbox when you select this item
  5. Description – Text that appears beneath the image when you select this item
  6. DisplayCategory – Tab that this item will appear under

Once you are done filling in those attributes, save your xml file and run an IISReset. Now, when you go to create a new site, if you’ve followed this example to the letter, you’ll see a new tab called “Custom SPL Templates” in the Template Selection Section. When you click on that tab, you’ll see “SharePointLessons Site” which came from the Title attribute in the Configuration. To the left, you’ll see the image that I specified in the configuration and just below the image you’ll see the description.

So as you can see, its not difficult to get started. Now, if you want, you can go in and create a ton of features and “staple” them to your new Site Definition so that future uses of your Site Definition will contain default functionality. Here’s a link for a lesson in Feature Stapling.

Object Model Best Practices

Up until this point, I’ve been whipping up demos for my readers to show you how to get started. Well, I was recently called out by a colleague about some of the code that I’ve written in my posts. (I haven’t always been disposing my objects.) From now on, I will try to do things the correct way for your benefit.

Rule of thumb. If there is a Dispose() method in your object, USE IT. Since SPSite and SPWeb are the most used objects, you’ll need to make sure you dispose of these objects when you’re done with them.

“But won’t the garbage collector deal with them?”

Yes, but not quickly. SPSite and SPWeb both have references to the SPRequest object which heavily relies on unmanaged code that is used to read/write to the content database.

Sometimes, you may forget to dispose of your objects (like I have on this site a few times). So, what should you do to make sure you don’t forget.

Get used to working with Using statements. A Using statement will automatically dispose of your objects as soon as your code falls out of the block.

An example of this would be:

using (SPSite site = new SPSite(“http://local”))
using (SPWeb web = site.OpenWeb())
//your code here

MSDN has a good article on Best Practices using disposable SharePoint objects. You should definately take a look at the article.

Content Types and CAML Queries

It’s nice to be able to put different types of items in a single location without having to create “category” fields or folders within document libraries to store them. But what if you need to create a webpart that needs to query a list/library for items in a specific content type? Using CAML queries can help you here.
We’ll need to create a CAML query, but before we can start, we need to find our target content type id. To do this, go to your content type’s settings page. Check out the query string on this page. Find ctype. This is your content type’s ID.
For the purpose of this demo, I’ll use a console app. When you create your query, use the element. The rest of the query is pretty basic.

My document library contains 2 documents. 1 uses the Reports content type and the other users the Documents content type. When I run the code, my results return correctly.

Now, to slightly change the code, instead of searching by content type id, let’s switch over to ContentType. This will allow you to use the content type’s name. You’ll see that my code is going to return all items where the content type is NOT equal to Reports.

Looking at my results, you’ll see that the report document correctly does not appear.

How to Create A Content Type using Visual Studio

If you try to use an “Out-of-the-Box” content type as an example, you may get confused. For this example, I’m going to use a template to make it easier on us. This example will show you how to create a content type using the base Document content type to store presentations.

First, I’m going to select SharePoint from my project types, and select an Empty template.

After I name it, I’m going to add a new item to the project. We’re going to select Content Type and name it Presentation.

A Content Type Settings window will open and it will contain a dropdown with a list of base content types. We’re going to select Document. If you want, you can add an event receiver if you’d like to write custom code that will do some work with the fields in your content type. I’m not going to do that in this demo.

When you click OK in the Content Type Settings window, the following xml template will be created. Notice that there are 2 sections that are commented out. These locations are where we are going to define the fields that are associated with our content type. In the FieldRef’s section, we only need to provide the Fields with a name and id. The second commented section contains the details, like the underlying name and the type.

First things first. Let’s remove the 1st comment and add 3 fields. Location, PresentationType, and Presenter. Give each field a unique GUID.

Now we can provide the details. Remove the 2nd commented section and add the following code. The attributes are identical to the commented code that you just removed. Make sure the GUID’s provided in this section match the corresponding fieldRef’s GUID. Notice that the first field is a Single line text, the second field is a Choice, and the third is a Person or Group field. Pay attention to The Choice field. You’ll need to add a Choices child element that contains each choice. As you can see, the choices that I’m adding are “Business” and “Classroom”.

Now we can create our feature file to deploy our feature. Nothing out of the ordinary here.

When we install and activate our feature, the new Presentation content type will be available. Make sure you go to the document library settings and make sure that you allow the document library to manage content types. [See: Content Types – What and Why? for more information on this]

You can see Presentation available in the menu below.

When I click on the menu item, a new document will open with the new fields in the DIP. Notice that a dropdown is available for our choice field and Presenter has its own controls for searching/verifying usernames.

That wasn’t so bad. Take a peak at some of the default content types in the FEATURES folder of the 12 hive. They’re scary.