Pages

Monday, April 4, 2011

All About List/Site Definition– Part I: Create List Definition/Instance with Visual Studio 2010

Let’s say you need to create a site definition which will satisfy the following requirements:

Your client wants to have a site definition that will add a site template in the ‘create web site’ list and when user will create a site based on the site definition, a list will be created and few features will be activated. In this post I’ll focus on creating a list definition and list instance.

Create list definition and List Instance

Step 1: Add List Definition and List Instance to the project: To create a list definition along with list instance add a List Definition item in SharePoint Project as shown below. For easy understanding, you can put Def at the end of the list definition name.

image

Figure 1: Create List Definition item

 

Later you’ll be prompted for list name, list definition type and ‘if a list instance will be created’ option as shown below. You may need to modify the list definition name, and list definition type. Also make sure the ‘Add a list instance for this list definition’ is selected as shown below.

image

Figure 2: List Definition Creation dialog

Step 2: Set List Instance Name and Title: After the list definition and list instance are added to the project, you will find the list instance name is generated automatically which you want to rename as shown below:

image

Figure 3: Rename auto-generated list instance name

Then focus on modifying the List Instance elements.xml file. At least modify the list title and URL as shown below:

image

Figure 4: Rename list instance title and url in elements.xml file of the list instance.

Now you have added the list definition and list instance and your next step is to define the list

Step 3: Define Template Type: Now you have added the list definition and list instance. First of all make sure you have put a type id for list definition and used that type id in list instance as shown below. I’ve set the template type in the left file (list definition) as (Type=10001) and the same type is used in the right file (list instance) as shown below:

image

Figure 5: Template Type id in List definition and list instance Elements.xml file (side by side)

Step 4: Add fields in the list definition: Now you are ready to add fields to the list definition. For this open the Schema.xml file under list definition folder and move the position between <Fields></Fields> as shown below:

image

Figure 6: Add Fields in list definition

So you are ready to add fields but it’ll be tough to add all fields just by typing manually. There’s trick I use often:

  1. Create a test list with the required fields
  2. Save the list as template
  3. Download the list template from template gallery.
  4. Rename the template file extension from .stp to .cab
  5. Open the cab file and extract the Manifest.xml file.
  6. Finally I take the field definitions from the Manifest.xml file

Step 5: Add fields to default view: In this step, you will add the fields to the default view (or any other view you want). If you take a look at the schema.xml file you will find more than one views are defined in the schema file. However, the view with DefaultView=”True” is the default view. Normally the view with BaseViewID 1 is the default view as shown below:

image

Figure 7: Default View with BaseViewID property value set to 1

So you have found the default view and now you need to add the field reference in the default view. As shown below, you can either user GUID or Field Name for referencing a field in ViewFields:

image

Figure 8: Add Field Ref in ViewField either by Field Name or ID

Though you can use either Field Name or ID for referencing a field in ViewFields, I prefer ID as the name can be changed/modified or XML encoded.

Step 6: Associate List definition and list instance with Two Features: Now you have two elements files: One is for list definition and another one is for list instance. With SharePoint architecture in mind, we need to activate the list definition in Site collection. Whereas the list instance needs to be created in individual web. So add two features and associate the elements.xml (FYI, elements.xml file can be associated with features) with features.

  • We need to add a feature with site collection scope, and need to associate the list definition with that feature. In my case the feature ID is 574b2a16-b01d-4e30-97ed-d1c4a5aa37ea. You are not done yet with the list instance, you need to take the feature id (in which the list definition is attached) and put the value in List Instance elements.xml file as shown below:
    image
    Figure 9: List Instance Elements.xml file with list definition Feature ID
  • We need to add another feature with web scope and need to associate the list instance with the feature

The following Figure shows the List Definition Feature:

image

Figure 10: List Definition Feature with Site Collection Scope (left circle) and ListDef item added (right circle)

The following figure shows the List Instance Feature:

image

Figure 11: List Instance Feature with Web scoped (left circle) and list instance item added (right circle)

So after this steps we get two final outputs (i.e., two features) that will be used in site definition. So collect the two feature IDs (you can get the feature ID by selecting and then opening the properties window). In my case the List Definition feature ID was 574b2a16-b01d-4e30-97ed-d1c4a5aa37ea and List Instance Feature ID was 161c4ebd-97b7-4dff-9734-c930434d3e95.

Conclusion

Until now you have developed one list definition, one list instance and two features: one for list definition and one for list instance. in the next post I’ll explain how to staple these list definition/instance with site definition.

Wednesday, March 9, 2011

SharePoint 2010 Client Object Model: Manipulate Choice, Lookup field

After my few posts on Client Object Model, I had come to questions on how to manipulate choice and lookup field. I’ve tried to explain a bit on how you can manipulate these field values with Client Object Model.

 

Manipulate Choice Field Value (Single Choice)

You can manipulate the single choice field value as like string. For example, let’s consider a field, ProductStatus in Product list. The field values might be “In Stock, Out of Stock, Invalid” as shown below:

image

Figure 1: Single Choice Field (ProductStatus) in product list.

To access the value of the field using Client Object Model, you can use code shown below:

  • Get Field value: You can just get the field value as string
    var productStatus = productItem["ProductStatus"].ToString();

  • Set Field value: You can use any of the following statement to set the field value
    productItem["ProductStatus"] = "In Stock";
    productItem["ProductStatus"] = "Out of Stock";
    productItem["ProductStatus"] = "Invalid";

Manipulate Choice Field Value (Multiple Choice)

If the choice field support multiple values then you need to use string array to manipulate field values. For example, consider there’s a field ‘product types’  in product list whose values can be Foods, electronics, Cars etc. Also consider the field values can be multiple, that’s mean a product types can be more than one type. The following figure shows the field

image

Figure 2: Multiple Choice Field

In that case you need string array to access the multiple choice field value as shown as shown below:

  • Get Field Value:
    var productTypes = (string[]) (productItem["ProductType"]);

  • Set Field Value:
    productItem["ProductType"] = new string[] { "Furniture", "Toys" };

Manipulate Lookup Field Value

To manipulate lookup field you need to use the code as shown below:

  • Get Field Value:
    var lookupFieldValue = (productItem["FieldName"] as FieldLookupValue);

  • Set Field Value
    //100 here is the lookup field id value
    productItem["FieldName"] = new FieldLookupValue(){LookupId = 100};

The FieldLookupValue is part of SharePoint Client OM .

Sunday, March 6, 2011

SharePoint 2010: Create Custom WCF Service

In SharePoint 2007, creating a custom Web Service was not so easy. However, asp.net web services are obsolete in SharePoint 2010. Rather new and recommended approach is to develop WCF Service. So the question comes up, “How much difficult it is to create a custom WCF service in SharePoint 2010?”. I’m going to answer the question just right in this blog.

 

Install CKS development tools edition

For showing how easily you can develop your own Custom WCF Service in SharePoint 2010, I’m going to use a open source Visual Studio 2010 extension know as Community Kit for SharePoint: Development Tools Edition. This tool will make the WCF service development much easier. It’ll automate tasks that you would have to do manually. There are two version of the extensions: One for SharePoint Foundation and another one is for SharePoint Server. Download the appropriate version and install.

 

Create WCF Service

Once you installed the CKSDev Visual Studio extension, you can open a SharePoint Project. In the SharePoint Project, right click on the project and try to add a new item. In the “Add New Item” dialog, you will find some new items added by CKSDev Visual Studio extension. Please select the option “WCF Service (CKSDev)” for new item as shown below:

image

Figure 1: ‘Add New WCF Service’ option ‘add new item’ dialog

 

Once you add the WCF Service, two files will be added by the dialog. One is the service interface and another is the Service itself.

 

Modify Service Types

As defined in MSDN, there are three different service types. Most of the time you need SOAP service. But if you need REST or ADO.NET Data service you can modify the service types by modifying the service factory as sown in the figure 2. The following table shows the three service types and their service factory name.

Service Type

Service Factory

Description

SOAP service

MultipleBaseAddressBasicHttpBindingServiceHostFactory

Basic HTTP binding must be used, which creates endpoints for a service based on the basic HTTP binding.

REST Service

MultipleBaseAddressWebServiceHostFactory

The service factory creates endpoints with Web bindings.

ADO.NET Data Service

MultipleBaseAddressDataServiceHostFactory

A data service host factory can be used.

When you create service with CKSDev tool, the default service generated is SOAP service. If you want to change the service type, please modify the factory in .svc file as shown below:

image

Figure 2: Service Factory defined in SVC file.

 

Deploy the Service

Once you are done with the service development, you are ready to deploy. But where you want to deploy the service? By default SharePoint service are kept in ISAPI directory. However, CKSDev deploy the service in ISAPI\ProjectNameSpace path as shown below:

image

Figure 3: Service deployment location

Once you define the service deployment location as shown in the figure 3, you can deploy the solution.

 

Access the Custom WCF Service

After Service deploy, you need to use the service in another projects. First try to access the service in browser. But remember you need to access the MEX endpoint either you will not get the service accessible in browser. To access the MEX endpoint, you should add “/MEX” at the end of the service name as shown below:

image

Figure 4: Access WCF Service MEX endpoint.

 

Finally try to add the service reference in a project using Visual Studio’s ‘Add Service Reference’ dialog as shown below:

image

Figure 5: Add Service Reference

 

 

Conclusion

So the steps described in this post are pretty simple:

  • Make sure you have downloaded and installed CKSDev Visual Studio extension.
  • Create a WCF Service (CKSDev) in the project. And if necessary, modify the service type
  • Deploy the solution and if necessary, change the deployment path.
  • Access the service MEX endpoint.

You are done. Pretty simple, I think.

Wednesday, March 2, 2011

SharePoint 2010: Select the best option for accessing SharePoint data from clients

There are few ways you can access data stored in SharePoint from a non-SharePoint application.

  • Client Object Model (OM): SharePoint provides three flavors of Client OM (Managed, EcmaScript and Silverlight)
  • Asp.Net web Service: The legacy web services of SharePoint 2007 are still supported for backward compatibility. We should try to avoid using these legacy web services for green field development.
  • REST-based Service (SharePoint 2010 Provided): SharePoint 2010 provides new set of WCF service which is REST enabled.
  • Custom WCF Service: There’s another option of developing custom WCF service of your own.

Let’s discuss which options you’ll take into account in selecting the best suitable options for your applications:

 

Client Object Mode (OM)

I think Client Object Model is the best choice in most of the cases. If you want to access SharePoint data from SharePoint webpart, then you can use Client OM (EcmaScript) to access data in SharePoint. If you are trying to access SharePoint data from Silverlight then you can use  Client OM for Silverlight. And most of all you can use Managed Client OM, in supported .net language to access SharePoint data.

So Client OM is surely your first choice. But in many cases you can’t use Client OM, especially in cases where you are trying to access SharePoint data from non-Microsoft platform, like Java. Also if your migrating your application from SharePoint 2003/2007 and you are already using asp.net web service, then you don’t have much choice but to use the legacy web services.

 

Asp.Net Web Services

SharePoint 2007 comes with built-in web services. These legacy web services are still in SharePoint to support backward-compatibility but whenever you have the option to avoid them, please do so. The only reason I see to use these legacy web services is for applications migrating from pre-SharePoint 2010 to SharePoint 2010. Maybe this is the last version of SharePoint with the support of the legacy web services (at least I hope so). Few legacy asp.net services are listed below:

  • /_vit_bin/Lists.asmx
  • /_vit_bin/Copy.asmx

 

SharePoint WCF Services (REST-based)

The new addition of extensibility point in SharePoint 20l10 is WCF services. If you are planning to manipulate SharePoint data from different platforms, like Java, then these WCF services are the excellent option to go with. If you install WCF data service updates, then these WCF services enable REST-based request processing. For more information on REST-based interface of SharePoint WCF services, please follow the MSDN link. You can also use these WCF services from .net applications. You can get the help from MSDN on how to use these WCF services in .net applications. Few new WCF services available in SharePoint 2010, are listed below:

  • /_vti_bin/ListData.svc
  • /_vti_bin/Client.svc

 

Custom WCF Service

In real world, we rarely happy with out of the box functionalities. We need to customize a lot to happy our clients. Similarly we may need to develop our own WCF services. Writing a custom asp.net web service in SharePoint 2007 was a very difficult task. But in SharePoint 2010, writing a custom WCF service is much easier now. If you install Community Kit for SharePoint (CKS) Visual Studio extension from CodePlex, you can develop a custom SharePoint Service easily. There’s also manual process of developing custom WCF Server in SharePoint described in MSDN: WCF Services in SharePoint and Creating Custom WCF Service. I’ll try to post more details on how to use CKS add-in to develop custom WCF service in another post.

Tuesday, March 1, 2011

SharePoint 2010: Approve/Reject Content Programmatically with SharePoint Object Model

In SharePoint 2010, you can modify the moderation status (approve/reject) of an item programmatically. Once you have got the ListItem, you can access the ModerationInformation properties to know the status, as shown below:

SPListItem listItem = GetListItem();
var moderationInformation = listItem.ModerationInformation;
if (moderationInformation != null)
{
if (moderationInformation.Status == SPModerationStatusType.Approved)
{
//approved
}
else if (moderationInformation.Status == SPModerationStatusType.Denied)
{
//rejected
}
else if (moderationInformation.Status == SPModerationStatusType.Draft)
{
//item is in edit mode and yet send to pending state.
}
else if (moderationInformation.Status == SPModerationStatusType.Scheduled)
{
//approval is waiting to be processed by a timer service.
}
}

However, Remember to check the ModerationInformation for null. If versioning/content approval is not enabled then the moderationinformation will be null. You can modify the moderation status by editing the moderationinformation and updating the list item as shown below:

SPListItem listItem = GetListItem();
if (listItem.ModerationInformation != null)
{
listItem.ModerationInformation.Status = SPModerationStatusType.Approved;
listItem.ModerationInformation.Comment = "This is comment";
listItem.Update();
}

Hope someone will get this useful!

Thursday, February 17, 2011

IE9 and User Agent String

With new IE in market the web developer community has been in the danger of supporting another extra browser. Recently we have found our application is in problem with IE9. We have a client application that put some data in User Agent Post platform value in registry. From IE6 to IE8 the post platform value was passing from server to client in UserAgent. So basically we had put some value in UserAgent Post Platform in registry from a client application and from our web application we had found the value (as the post platform values are passed in User Agent from IE6 to IE8). But with IE the post platform values are not passed with User Agent automatically.

 

User Agent and Pre/Post Platform value

If you are interested on how the Pre and Post Platform values works with User Agent you can visit the MSDN link: http://msdn.microsoft.com/en-us/library/ms537503%28VS.85%29.aspx

 

IE9 introduces Default User Agent and Extended User Agent

In IE9 the user agent has been divided into two parts:

Default User Agent (UA): IE9 by default will not send the pre/post platform values from client to server. So if you have some values in client’s pre and post platform then your web site will not get those values (from pre and post platform) as IE9 will not pass those values to server. However IE6 to IE8 will work as usual (i.e., pass those pre and post platform values) .

Extended User Agent (UA): So the question is if IE9 doesn’t send the pre and post platform values by its own then how can we access the platform values? The answer to this question is simple but implementation is tricky. You can get the pre and post platform values on client side only with JavaScript by accessing Navigator.UserAgent. So IE9 will not take the responsibility of passing Extended UA from client to server. You need to do it by your own. You need to read the extended UA by javascript on the client side and need to pass to the server by using Hidden control or any other way.

 

How to get the Pre/Post platform vales IE9?

By following javascript code you can get the pre/post platform values on client side.

<script type="text/javascript">
    alert(navigator.userAgent);
</script>

You can get more details on this on MSDN IE blog: http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx

Wednesday, January 19, 2011

U2U CAML Query Builder for SharePoint 2010?

U2U CAML query builder is a great tool for SharePoint developer. I’ve used this tool frequently with SharePoint 2007 development. However, I’ve got into trouble with using the tool with SharePoint 2010. The tool is not updated for SharePoint 2010 yet. Though you can use U2U CAML builder with SharePoint 2010 (shown later in this post), you want to use new features of CAML (say join lists) and such new features are not supported in CAML builder. In this post I’ll show how you can generate CAML query for SharePoint 2010 using few tools and Linq query. First let’s discuss on how you can still use CAML builder to generate CAML for SharePoint 2010.

 

Use CAML Builder with SharePoint 2010 (I’ll not recommend)

Till now the CAML builder doesn’t support SharePoint 2010. However, you can make the tool working by using connecting via web service as shown below:

image

Figure 1: Use CAML builder with SharePoint 2010

 

However, you are not saved. As I mentioned already till the date I’m writing this post, the CAML builder is not updated to support SharePoint 2010. So new CAML features (like list joins) will not work in this old CAML builder.

 

Generate CAML from Linq-to-SharePoint (Better approach)

Though you can use old CAML builder with SharePoint 2010, since the CAML builder is not updated yet, you will not get the CAML new features when you will use CAML builder. Worried? Please don’t. There’s an way out. Let me explain

  1. Download CKS Visual Studio Extension: There’s an useful and handy Visual Studio Extension for SharePoint developers known as Community Kit for SharePoint (CKS): Development tool edition. You can download the extension for SharePoint Server or for SharePoint Foundation.

  2. Generate Entity classes from SharePoint site: Once you have installed the Community Kit for SharePoint, you can generate entity classes from Server Explorer. First open a SharePoint project in Visual Studio and then connect to the SharePoint server from Server Explorer ==> SharePoint Connections. Then right click on your web and click “Generate entity classes” as shown below. This will generate the entity classes in the current selected project of Visual Studio.

    image
    Figure 2: Generate entity class from SharePoint site/web


  3. Write Linq using Linq-to-SharePoint against generated entity classes: Once you have generated the entity classes as described on step2, you can use Linq to SharePoint to write your logic that you want to achieve through CAML. Once you write the Linq, you can run the code and log the CAML generated from the Linq. For example I have two lists Orders and Product. I want to join two lists to get order title and product name. The Linq will look like as shown below:

    using (var dataContext = new MySiteDataContext(siteUrl))
    {
        TextWriter textWriter = new StreamWriter(@"c:\caml.txt",false);
        dataContext.Log = textWriter;
        var result = from o in dataContext.Orders
                        join p in dataContext.Product on o.Product.Id equals p.Id
                        select new {OrderName = o.Title, p.ProductName};
        foreach (var v in result)
        {
            System.Console.WriteLine("{0}----{1}",v.OrderName,v.ProductName);
        }
    }
    Code snippet 1: Linq query using Linq to SharePoint


    As shown in the code snippet above, I have used the data context generated at step 2 and I have run a Linq query against two lists of the data context. The most import thing to notice in above code snippet is marked with yellow. I have instantiated a text writer (initialize with file stream) and then I had set it as the Log property of the datacontext. This will ensure that any CAML generated from the Linq query will be written in the writer. Once the query gets executed the CAML is dumped in the file (in my case C:\Caml.txt).

    So for generating any complex CAML query you can first write its equivalent Linq query and then get the CAML from log.


  4. Get the CAML from the Linq query: After running the Linq to SharePoint query, you have got the CAML query in the log file as shown in step 3. However, you need to work a bit to make the CAML usable in SPQuery. The CAML generated from code snippet 1 is shown below:


    <View>
      <Query>
        <Where>
          <And>
            <BeginsWith>
              <FieldRef Name="ContentTypeId" />
              <Value Type="ContentTypeId">0x0100</Value>
            </BeginsWith>
            <BeginsWith>
              <FieldRef Name="ProductContentTypeId" />
              <Value Type="Lookup">0x0100</Value>
            </BeginsWith>
          </And>
        </Where>
        <OrderBy Override="TRUE" />
      </Query>
      <ViewFields>
        <FieldRef Name="Title" />
        <FieldRef Name="ProductProductName" />
      </ViewFields>
      <ProjectedFields>
        <Field Name="ProductProductName" Type="Lookup" List="Product" ShowField="ProductName" />
        <Field Name="ProductContentTypeId" Type="Lookup" List="Product" ShowField="ContentTypeId" />
      </ProjectedFields>
      <Joins>
        <Join Type="INNER" ListAlias="Product">
          <Eq>
            <FieldRef Name="Product" RefType="ID" />
            <FieldRef List="Product" Name="ID" />
          </Eq>
        </Join>
      </Joins>
      <RowLimit Paged="TRUE">2147483647</RowLimit>
    </View>
    Code snippet 2: CAML generated from Linq query of Code Snippet 1

    In the above code snippet, the lines marked with yellow can be modified if you want. Specially the content type in where part is put in the CAML to ensure only list items are selected. FYI, Content type 0x0100 means list item type. 


  5. Use CAML query in SPQuery: Now you have got the CAML and you want to use the CAML in SPQuery. The following code snippet shows how I’ve used the CAML(from code snippet 2) in SPQuery:

    SPQuery query = new SPQuery();
    query.Query = @"<Where>
                        <And>
                        <BeginsWith>
                            <FieldRef Name='ContentTypeId' />
                            <Value Type='ContentTypeId'>0x0100</Value>
                        </BeginsWith>
                        <BeginsWith>
                            <FieldRef Name='ProductContentTypeId' />
                            <Value Type='Lookup'>0x0100</Value>
                        </BeginsWith>
                        </And>
                    </Where>
                    <OrderBy Override='TRUE' />";
    
    query.ViewFields = @"<FieldRef Name='Title' />
                        <FieldRef Name='ProductProductName' />";
    query.ProjectedFields = @"<Field Name='ProductProductName' Type='Lookup' 
                                     List='Product' ShowField='ProductName' />
                              <Field Name='ProductContentTypeId' Type='Lookup' 
                                     List='Product' ShowField='ContentTypeId' />";
    query.Joins = @"<Join Type='INNER' ListAlias='Product'>
                    <Eq>
                        <FieldRef Name='Product' RefType='ID' />
                        <FieldRef List='Product' Name='ID' />
                    </Eq>
                    </Join>";
    
    query.RowLimit = 2147483647;
    
    var list = web.Lists["Orders"];
    var items = list.GetItems(query);
    foreach (SPListItem item in items)
    {
        System.Console.WriteLine("{0}--{1}", item["Title"], item["ProductProductName"]);
    }
    Code Snippet 3: Using generated CAML in SPQuery

Integrating the Test Code in your Visual Studio Soltuion

You may need to generate the CAML from time to time in your development life cycle. My personal preference is to keep a devtest project in the Visual Studio solution to do work like this CAML generation. I keep a dev-test project (used for RnD like task), mainly console app, in the solution. So you can keep the dev-test project in your solution and in that project you can write the Linq to SharePoint query and generate the CAML. Since the project will always be in your Visual Studio solution, if you need to get the CAML anytime you can just write the Linq query in the dev-test project and run the project to get the CAML.



Conclusion

So here’s the summary on how to generate CAML query using the method described in this post:

  • Install Visual Studio extension - CKS for SharePoint Server or for SharePoint Foundation.
  • Generate entity classes from SharePoint site using the CKS feature
  • Write Linq to SharePoint query and log the CAML in a file/Console
  • Use the CAML in SPQuery

Though you can use Linq to SharePoint instead of CAML, but sometimes CAML is needed for raw query and this method will help you find out the CAML.

Thursday, January 13, 2011

SharePoint 2010: Configure Form Based Authentication (FBA)

I had worked with form based authentication in SharePoint 2007. However, in SharePoint 2010, there’s few changes in the way form based authentication works. In my another post “Form-Based Authentication with ADAM”, I had described how to implement ADAM form based authentication in SharePoint 2007. Today I’ll show you how you can implement Form Based authentication using Active Directory Lightweight Directory Service. From windows server 2008, ADAM is replaced by Active Directory Lightweight Directory Service and both are LDAP based.

 

FBA works for only for Claims based authentication sites

In SharePoint 2010 to use FBA, you need to create a web application with Claims based authentication as shown below. Form based authentication will not work for web application created with classical authentication.

image

Figure 1: Create web application in claims based authentication

 

If you don’t create the web application with Claims Based Authentication then you’ll find the Forms Authentication type disabled in Authentication Provider settings window as shown below:

image

Figure 2: Forms authentication is disabled for web application created with “Classic Mode Authentication”

 

Step 1: Create a web application with Claims Based Authentication

Since form based authentication doesn’t work with “Classical Mode Authentication”, you can’t configure form based authentication with web application created with “classic mode authentication”. So to configure Form based authentication you need to have an web application created with Claims based authentication. (If you want to use windows authentication now and have plan to use forms based authentication later, then the best will be to create the web application with Claims based authentication). FYI,

  • Creating a Claims based authentication will allow you to use both windows and form authentication.
  • Creating a site with classic authentication mode will not allow you to configure the site to use form authentication easily.

 

Summary: In this step we’ll create an web application using Claims Based Authentication but use windows authentication as shown below. Later we’ll configure the site to use form authentication.

image

Figure 3: Create Claims based authentication web application with only windows authentication enabled

 

Step 2: Add membership provider entries in web.config files

In this example I’m considering you have the member provider configured already. I’ve been used “Active Directory Lightweight Directory Service” to test this form authentication. You need to modify three different web.config files (your web application, central admin and STS config file). Modifications to the three files are adding two entries (providers, connectionstring) to web.config file which are described below for three different places:

Web Application’s web.config:

You need to put the following entries in the web.config file of your web application under Configuration node:

<connectionStrings>
    <add name="MyProviderConnectionString" 
         connectionString="LDAP://myserver/O=a,OU=b,C=c" />
</connectionStrings>

Code Snippet 1: Connection String to LDAP

 

Then find the <membership> node under <system.web> and add an entry for your provider (There should be an entry with name i, added by SharePoint already). As shown below I’ve added a provider “MyProvider” in the providers list. The provider with name “i" was already in the web.config file which is added by SharePoint when you create an web application with claims based authentication.

<membership defaultProvider="i">
  <providers>
    <add name="i" 
         type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    <add name="MyProvider" 
         type="System.Web.Security.ActiveDirectoryMembershipProvider,
System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MyProviderConnectionString" connectionUsername="CN=aa,CN=Admins,O=a,OU=b,C=c" connectionPassword="***" enableSearchMethods="true" connectionProtection="None" /> </providers> </membership>

Code Snippet 2: My custom provider (MyProvider) added alongside the default SharePoint provider (i).

 

SharePoint by default add the provider with name ‘i’. I’ve defined my provider with name MyProvider and the provider is using MyProviderConnectionString. so your web.config file will look like as shown below:

image

Figure 4: ConnectionString and Provider defined in web.config.

Security Token Service’s web.config file

You need to add the same entries for two other web.config files. One is central admin web.config file. Another one is Security Token Service (STS). You can find the STS web config file as shown below. The default location is “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebServices\SecurityToken\Web.config”.

image

Figure 5: Security Token Service (STS) web.cofig from IIS (Content View)

 

After opening the config file, add the two entries as shown in code snippet 1 and code snippet 2.

Central Admin’s web.config file

Finally you need to open the web.config file of central administration and add the two entries shown in code snippet 1 and 2.

 

Step 3: Change the web application’s security settings to use Form Authentication

So in Step 2, you have added the provider information (connection string, provider name, username etc) in three different web.config files. Now you need to tell the web application to use Form based authentication by connecting through your provider defined in web.config file. To do so follow the steps below:

  1. Login to central administration site and click “Application Management” from left side navigation.
  2. Select your web application from web application list and click “Authentication Providers” from ribbon as shown below:

    image

    Figure 6: Configure Authentication Provider from Central Administration

  3. From the “Authentication providers” dialog click on the zone (Default, internet etc) you want to configure the form authentication and then you will be redirected to “Edit Authentication” page.
  4. In the Edit Authentication page, Put your provider name as shown below. You can enable both form and windows authentication if you want. As shown in the read in the image below, if you don’t configure windows authentication in any zone of the web application then crawling will be disabled. If you want you can enable anonymous login from this “Edit Authentication” page.

image

Figure 7: Enable Form authetication

 

Step 4: Assign/change site collection administrators for the site collections

As soon you change the authentication type to form, you will have to assign an user (from your provider defined in web config file) to the site collection administrators.

  1. Click Application Management ==> Change Site Collection Administrators
  2. Then add the users from your providers in site collection administrator's group as shown below:

image

Figure 8: Add/Edit Site collection administrators

If you enable both windows and form authentication then it’ll be better to use one site collection administrator from windows and another from your form based authentication’s provider.

 

You are done!

And if you have followed the steps, you are done. If you try to access the site, you will be prompted for form login page. However, if you enabled both form and windows authentication then you will prompted for authentication  type first and based on the authentication type either you will be prompted for form or windows authentication.

 

For Your Information

Few points to notice here:

  • Form based authentication only works for web application created with Claims Based Authentication mode.
  • You need to modify three web.config files (your web application, central web app and Security Token Service) to add your provider settings.
  • Recommendation is to create an web application with Claims based Authentication mode but using windows authentication. Once you modify those three web.config files, switch the web app to form based.
  • You can enable both windows and form authentication in a web application. In that case try to add one site collection administrator from form authentication provider and another from windows.
  • If you want the site data to be crawled, then you need to make sure at lease one zone in the web application uses windows authentication.

Wednesday, January 5, 2011

SharePoint 2010: Add favicon icon to site

In SharePoint if you need to add favicon, you can do so easily by using SharePoint Out-of-box control SPShortcutIcon. The following code snippet shows how you can set the favicon:asdf

<SharePoint:SPShortcutIcon runat=”serverIconUrl=”YourIconUrl/> 

You are done…

Monday, January 3, 2011

Awarded Microsoft MVP

The very good news for me that I’ve come to know on 1st January is that I’ve been awarded Microsoft MVP for SharePoint Server: Development. My blog has got much popularity in last few months. On November there were almost 10000 visitors and on December around 9000 visitors visited my blog. Thanks all the visitors of the site for their comments and feedback. I’ll continue my efforts to help SharePoint community with blogs, MSDN forms etc.

Thanks again to all visitors who commented and provided feedback in my blog.