How to Host a WCF Service in SharePoint

January 1st, 2009

Sometimes you need to create a WCF service to provide a SharePoint functionality to a remote client. However, hosting a WCF service in a SharePoint box does not look so easy. At least, there are two options — one is to create a custom VirtualPathProvider and the other is to deploy it as a separate web site. Which way to go depends on an IT governance policy, stakeholders, etc., but my quick recommendation is to go with a 2nd option of deploying it as a separate web site.

First, let’s see why you need to create a custom WCF service at all. The out-of-box SharePoint web services under the _vti_bin folder are quite limited in terms of the available functions and power. For example, you really cannot leverage the OOB SharePoint web service to upload a document remotely with a check-in and check-out functionality. Also, in many cases, the OOB SharePoint web services are too granular (or too chatty) to be used as a true SOA service. You will need to consider creating a custom web service, or better, a custom WCF service which will utilizes the SharePoint APIs rather than the OOB SharePoint web services.

So, you created a WCF service, and now need to think about where you will expose the endpoint of your WCF services. Unfortunately, the current version of SharePoint, WSS 3.0 and MOSS 2007, does not support the hosting of WCF services right out-of-the-box. To host a WCF service in a SharePoint environment, you will need to choose from the following two options:

Option 1 - Hosting a WCF service under _layouts folder or under a Virtual Path.

This option requires a hack — you will need to create a VirtualPathProvider and register it to the SharePoint web.config. The following blogs show how to do it.

Even though there is a growing popularity to use this option, I do not recommend this one because this option requires you to create your own VirtualPathProvider (or at least need to use someone’s code) to intercept a WCF service because SharePoint does not handle WCF service files (*.svc) right out of the box. The VirtualPathProvider needs to be deployed to GAC. Also, I found that there is almost no benefit to host a WCF service inside a SharePoint web application since a WCF service really cannot share SPContext, HttpRequest,  Cookies, Sessions, etc. with Asp.net applications effectively (technically, you can if you turn on the Asp.Net compatible mode…, but the mode is turned off by default).

 

Option 2 - Hosting a WCF service as a separate web site under the same SharePoint farm

This option is really straightforward. You simply host a WCF service as a separate web application on the IIS. Since the WCF service will live in the same SharePoint farm, the WCF service can have a full access to SharePoint APIs.

 

My recommendation is Option 2.

My recommendation is to deploy your WCF service as a separate web service which requires no custom VirtualPathProvider, no web.config manipulation for registering the custom VirtualPathProvider, and no deployment to GAC.

How to Create a Calendar View Through Code?

December 30th, 2008

 

For those who need to programmatically create a SharePoint calendar view, I posted the full sample code below. Since a Calendar view requires many special fields, the code below will not work against a custom list:

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

namespace CalendarView

{

    class Program

    {

        static void Main(string[] args)

        {

            using (SPSite site = new SPSite(http://localhost/Site1))

            using (SPWeb web = site.OpenWeb())

            {

                SPList list = web.Lists["Calendar"];

                SPViewCollection views = list.Views;

                System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();

                viewFields.Add(“EventDate”);

                viewFields.Add(“EndDate”);

                viewFields.Add(“fRecurrence”);

                viewFields.Add(“EventType”);

                viewFields.Add(“Attachments”);

                viewFields.Add(“WorkspaceLink”);

                viewFields.Add(“Title”);

                viewFields.Add(“Location”);

                viewFields.Add(“Description”);

                viewFields.Add(“Workspace”);

                viewFields.Add(“MasterSeriesItemID”);

                viewFields.Add(“fAllDayEvent”);

 

                string query = @”<Where><DateRangesOverlap><FieldRef Name=”"EventDate”" /><FieldRef Name=”"EndDate”" /><FieldRef Name=”"RecurrenceID”" /><Value Type=”"DateTime”"><Month /></Value></DateRangesOverlap></Where>”;

                SPView view = views.Add(“Calendar View Test”, viewFields, query, 100, false, false, SPViewCollection.SPViewType.Calendar, false);

                view.ViewData = @”<FieldRef Name=”"Title”" Type=”"CalendarMonthTitle”" /><FieldRef Name=”"Title”" Type=”"CalendarWeekTitle”" /><FieldRef Name=”"Location”" Type=”"CalendarWeekLocation”" /><FieldRef Name=”"Title”" Type=”"CalendarDayTitle”" /><FieldRef Name=”"Location”" Type=”"CalendarDayLocation”" />”;

                view.Update();

            }

        }

    }

}

 

 

[SharePoint] How To Make A Filmstrip a Default View For A Picture Library?

November 30th, 2008
  

A Thumbnails view is a default view for a SharePoint Picture Library, and SharePoint does not provide an easy way to set a Filmstrip view as a default view. Technically, the All Pictures view is a default view for a Picture Library, and both Thumbnails and Filmstrip are kind of subviews inside the All Picture view. If you examine the behavior of these subviews closely, you will soon find that the subviews are handled from a client side using a JavaScript, javascript:SwitchViewStyle(’filmstrip’) and javascript:SwitchViewStyle(’thumnail’). With these findings, I will describe the steps how to make a Filmstrip a default view of a Picture Library.

Please perform the following steps to make the Filmstrip a default view of a Picture Library:

  1. Click Site Actions -> Edit Page.
    Click Edit Page to add a webpart

    Click Edit Page to add a webpart

     

  2. Click a Add a Web Part button to launch a Add Web Parts dialog box.

  3. Find and Check a Content Editor Web Part and Click OK.

  4. Drag the Content Editor Web Part below the Picture Library Web Part.
  5. Click open the tool pane link on the Content Editor Web Part
  6. On the Content Editor section, click the Source Editor… button.
  7. Type the following javascript inside the Source Editor:
    <script type=”text/javascript”>
    <!–
    SwitchViewStyle(’filmstrip’);
    //–>
    </script>

  8. Click Save to close the Source Editor.
  9. On the Appearance section of the tool pane, set the Chrome Type to None.

    Set Chrome Type to None to hide a Title and Border
  10. Click OK to close the tool pane of the Content.
  11. Click Exit Edit Mode link right below the Site Actions.
    Filmstrip is now set to a default view

    That's it! Filmstrip is now set to a default view.

     

A SharePoint Site “CON” Returns “An unexpected error has occurred.”

October 11th, 2008

I tried to create a SharePoint site for contact records with CON as a site name, i.e. http://[server]/sites/CON. A site returned “An unexpected error has occurred.” After contacting Microsoft product support service team, I found out that it is a product issue — You can call it a bug or a feature by design.

This is a response from Microsoft product support service:
“MS-DOS device names are reserved words and cannot be used as folder or file names. When parsing a reference to a file or folder, Windows checks for the case in which a single MS-DOS device name is used in the path, and treats it as invalid.”

The support team also provided this KB article.

The following words are reserved in MS-DOS. You will not be able to use the following words as a sub site name or folder name:

CON, COM1 - COM4, PRN, AUX, LPT1

How to Update Created, Created By, Modified and Modified By field?

September 9th, 2008
I stumbled upon this Technet Forum post. Using the SPListItem.UpdateOverwriteVersion method, you can overwrite Created, Created By, Modified and Modified By fields. Here is a code snippet from this MSDN article:
 
using (SPSite sps = new SPSite(http://server/))
using (SPWeb spw = sps.OpenWeb())
{
SPList spSharedDocs = spw.Lists["Shared Documents"];
SPListItem spli = spSharedDocs.Items[0];
spli["Created"] = new DateTime(2007, 1, 1);
spli["Author"] = “-1;#domain\user”;
spli["Editor"] = “-1;#domain\user”;
spli["Modified"] = new DateTime(2007, 2, 1);
spli.UpdateOverwriteVersion();
}

 

How to Create a Login/Registration System Using FBA with Active Directory in a SharePoint Server 2007

September 8th, 2008
To use the forms based authentication(FBA) against an Active Directory(AD) for a SharePoint Server 2007, you will need to use the ActiveDirectoryMembershipProvider in ASP.NET 2.0. I outlined key steps to enable FBA against an AD for a SharePoint Server 2007.


Step 1 - Edit the AD Schema

To suppport Password Reset (Password Recovery), you will need to edit the AD schema by running the following command: regsvr32.exe schmmgmt.dll. The detailed step to edit the AD is defined in Password Reset section of this article.


Step 2 - Set up Intranet and Extranet Zone

Once the AD schema has been edited, you will need to set up a SharePoint Site with Intranet and Extranet Zones. Here is a quick how-to:

2.1. Create the Web Application for the Extranet Zone
  1. On your SharePoint server, open up SharePoint Central Administration
  2. Click on the Application Management tab
  3. Click Create or Extend Web Application
  4. Click Create a new Web application
  5. Fill out the fields as appropriate for your web application and click OK
  6. After the operation completes, open up a command prompt and run iisreset /noforce command
  7. On the Application Created page, clik on the Create Site Collection link
  8. Fill out the fields as appropriate for your site collection and click OK
  9. After the operation completes, on the Application Management tab, click Authentication providers
  10. Make sure your newly-created web application is selected and click on the Default zone
  11. Select Forms as the Authentication Type
  12. Check the Enable anonymous access checkbox
  13. Type in the name of your membership provider name (i.e. PortalMembershipProvider) in the Membership provider name textbox
  14. Type in the name of your role manager name (i.e. PortalRoleManager) in the Role manager name textbox
  15. Select No for Enable Client Integration
  16. Click Save

2.2. Extend the Web Application to the Intranet Zone

  1. On your SharePoint server, open up SharePoint Central Administration
  2. Click on the Application Management tab
  3. Click Create or Extend Web Application
  4. Click Extend and existing web application
  5. Select your newly-created web application in the Web Application dropdown
  6. Fill out the fields are appropriate for your web application
  7. Select Intranet from the Zone dropdown
  8. Click OK
  9. Click on Authentication providers
  10. Click Intranet zone
  11. Make sure the Authentication Type is set to Windows
  12. Make sure Enable anonymous access is unchecked
  13. Click Save


Step 3 - Create Roles with AzMan

Windows Authorization Manager (AzMan) is a Windows tool for defining application roles and mapping them to Windows users/AD groups defined in your AD store. This article explains in details how to create roles with AzMan. I recommend to configure an AzMan policty store in an an xml file for quick development. For a test, staging and production environment, I recommend to configure an AzMan policy store in AD.


Step 4 - Edit SharePoint Web.config Files

You will need to mofidy the following three web.config files:

  • Exranet web.config
  • Intranet web.config
  • SharePoint Central Administration web.config.

Each web.config file needs to have different modifications made to it, depending on what each web application needs to be configured for.

4.1 Extranet web.config

The extranet web.config needs four modifications made to it: changes must be made to the &lt;connectionstrings&gt;, &lt;membership&gt;, &lt;rolemanager&gt;, and &lt;authentication&gt; sections.&lt;connectionstrings&gt;&lt;membership&gt;&lt;rolemanager&gt;&lt;authentication&gt;
&lt;/authentication&gt;&lt;/rolemanager&gt;&lt;/membership&gt;&lt;/connectionstrings&gt;

4.1.1 Connection Strings

In order to connect to the AD store for authentication and the AzMan-provided XML file for role definitions, the &lt;connectionstrings&gt; section of the extranet web.config must be modified to include connection string values that point to said resources. The connection string for the AD connection should be an LDAP string to your domain, and the AzMan connection string should be in the format “msxml://

”.
The &lt;connectionstrings&gt; section is a child of the root &lt;configuration&gt; section.&lt;/configuration&gt;&lt;/connectionstrings&gt;&lt;/connectionstrings&gt;



&lt;connectionstrings&gt;
&lt;add name=”PortalAdConnection” connectionstring=”LDAP://portal.test.com “&gt;
&lt;add name=”AzManConnection” connectionstring=”msxml://c:/Roles/AzManRoles.xml”&gt;
&lt;/add&gt;&lt;/add&gt;&lt;/connectionstrings&gt;


4.1.2 Membership Provider

The &lt;membership&gt; section needs to have a membership provider added to it that specifies that AD will be used as the membership store for the SharePoint portal site.
The &lt;membership&gt; section is under &lt;configuration&gt;/&lt;system.web&gt;&lt;/system.web&gt;&lt;/configuration&gt;&lt;/membership&gt;&lt;/membership&gt;


&lt;membership defaultprovider=”PortalMembershipProvider”&gt;
&lt;providers&gt;
&lt;add name=”PortalMembershipProvider” type=”System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” connectionstringname=”PortalAdConnection” connectionusername=”UserWithAppropriateRights” connectionpassword=”PasswordForUser” connectionprotection=”Secure” enablepasswordreset=”true” enablesearchmethods=”true” requiresquestionandanswer=”true” applicationname=”/” description=”Default AD connection” requiresuniqueemail=”true” clientsearchtimeout=”30″ serversearchtimeout=”30″ attributemappasswordquestion=”department” attributemappasswordanswer=”division” attributemapfailedpasswordanswercount=”singleIntAttribute” attributemapfailedpasswordanswertime=”singleLargeIntAttribute” attributemapfailedpasswordanswerlockouttime=”singleLargeIntAttribute” attributemapemail=”mail” attributemapusername=”userPrincipalName” maxinvalidpasswordattemps=”20″ passwordattemptwindow=”20″ passwordanswerattemptlockoutduration=”30″>&lt;/add&gt;
&lt;/providers&gt;&lt;/membership&gt;


4.1.3 Login URL

The

section needs to have a login URL specified. This will allow the SharePoint web application to know what web form will be used to authenticate the user with. When authenticated users attempt to access a resource they are not authorized for, they will be redirected to the specified login page and asked to sign in as a different user.
The

section is under &lt;configuration&gt;/&lt;system.web&gt;/&lt;authentication&gt;


&lt;authentication mode=”Forms”&gt;
&lt;forms loginurl=”/_layouts/Portal/login.aspx”&gt;
&lt;/forms&gt;&lt;/authentication&gt;&lt;/authentication&gt;&lt;/system.web&gt;&lt;/configuration&gt;&lt;/forms&gt;&lt;/forms&gt;

 

4.2 Intranet web.config

The Intranet web.config needs two modifications made to it: changes need to be made to the &lt;connectionstrings&gt; and &lt;rolemanager&gt; sections.&lt;/rolemanager&gt;&lt;/connectionstrings&gt;

4.2.1 Connection Strings

In order to connect to the AzMan-provided XML file for role definitions, the &lt;connectionstrings&gt; section of the extranet web.config must be modified to include a connection string value that points to said resource. The connection string for the AzMan XML file should be in the format “msxml://&lt;path&gt;”.
The &lt;connectionstrings&gt; section is a child of the root &lt;configuration&gt; section.&lt;/configuration&gt;&lt;/connectionstrings&gt;&lt;/path&gt;&lt;/connectionstrings&gt;


&lt;connectionstrings&gt;
&lt;add name=”AzManConnection” connectionstring=”msxml://c:/Roles/AzManRoles.xml”&gt;&lt;/add&gt;&lt;/connectionstrings&gt;


4.2.2 Role Provider

The &lt;rolemanager&gt; section needs to have a role provider added to it that specifies that the AzMan-created XML file will supply roles to the SharePoint web application.
The &lt;rolemanager&gt; section is under &lt;configuration&gt;/&lt;system.web&gt;
&lt;/system.web&gt;&lt;/configuration&gt;&lt;/rolemanager&gt;&lt;/rolemanager&gt;


&lt;rolemanager enabled=”true” defaultprovider=”PortalRoleProvider” cacherolesincookie=”true” cookieprotection=”All” cookietimeout=”10″ cookiename=”.PortalRole”&gt;
&lt;providers&gt;
&lt;clear&gt;
&lt;add connectionstringname=”AzMan” applicationname=”AzManPortal” name=”PortalRoleProvider” type=”System.Web.Security.AuthorizationStoreRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, publicKeyToken=b03f5f7f11d50a3a”&gt;
&lt;/add&gt;
&lt;/clear&gt;&lt;/providers&gt;&lt;/rolemanager&gt;


4.3 SharePoint Central Administration web.config

The SharePoint Central Administration web.config only needs a modification to the &lt;rolemanager&gt; &lt;/rolemanager&gt;

4.3.1 Role Provider

The &lt;rolemanager&gt; section needs to be enabled and have its default provider set to the ASP.NET Windows token provider.
The &lt;rolemanager&gt; section is under &lt;configuration&gt;/&lt;system.web&gt;

&lt;rolemanager enabled=”true” defaultprovider=”AspNetWindowsTokenProvider”&gt;
&lt;/rolemanager&gt;&lt;/system.web&gt;&lt;/configuration&gt;&lt;/rolemanager&gt;&lt;/rolemanager&gt;

Step 5 - Map AzMan Roles to SharePoint Site Groups

Without performing this mapping, you may notice that users can authenticate against the AD store, but will not be authorized to view any restricted SharePoint content not configured for anonymous access. The reason for this is that the SharePoint web application can confirm the username/password combination against AD, but it cannot know the role(s) of the user without them being somehow mapped to security groups within SharePoint.

5.5 Mapping Application Roles to Site Groups

  1. As an administrator of the SharePoint portal site, open up the Intranet home page
  2. Click on Site Actions -> Site Settings
  3. Click on People and groups
  4. Click on one of your SharePoint site groups, i.e. Site Members
  5. Click New
  6. In the Users/Groups multi-line textbox, you should be able to add the roles that you defined with AzMan and successfully perform a check name operation against them.

You finished all the steps necessary to create a login/registration system. Now, using Microsoft Visual Studio, you can create a login, registration, password recovery, etc. by following this article.

 


Summary

In this post, I outlined key steps to create a login/registration system using FBA against AD in a SharePoint Server 2007. I did not necessary go through detailed steps, and refered to other articles instead for further details. Creating a login/registration system in a SharePoint Server 2007 is not a trivial task, but it is certainly possible to do it. Once it is implemented, a SharePoint Server 2007 can act as a great platform for an internet-facing web site or an extranet, supporting all necessary functionalties required for a login and registration process.


Other useful links:

Good SharePoint Server 2007 resources

September 7th, 2008
Performance and Capacity Planning Resource Center for SharePoint Server 2007
This page contains resources to help you with performance and capacity planning for your SharePoint Server deployment—map your solution design to a farm size and set of hardware that supports your business goals.
It contains many technical articles organized By:

  • Planning
  • Recommendations
  • Estimate performance based on test results
  • Demos
  • Tools from Microsoft
  • Tools and Papers from Partners and the Community

Best Practices Resource Center for SharePoint Server 2007
To avoid common pitfalls and keep your Office SharePoint Server 2007 environment available and performing well, follow these best practices based on real-world experience from Microsoft Consulting Services and the product team.
It contains best practices for:

  • Operational Excellence
  • Team Collaboration Sites
  • Publishing Portals
  • Search
  • My Sites
  • Developing Custom Applications
  • Additional Resources

Microsoft and Cloud computing

September 6th, 2008
Microsoft and Cloud computing

Cloud computing is here to stay. Amazon Elastic Compute Cloud (EC2), Google’s recent release of Chrome and its internet-based applications, Salesforce.com, NetSuite, Apple’s MobileMe, etc. are good examples of cloud computing services. Wikipedia has a good article on Cloud computing. Microsoft is providing Cloud computing services and executing its own vision of Cloud computing, software plus service(S+S). Here are several examples of Microsoft’s S+S:

  • Red Dog: Microsoft is known to be working on a low-level “Cloud OS” that is code-named Red Dog.
  • Zurich: At the highest level, Zurich is Microsoft’s Software+Services platform.
  • Microsoft Volta : In a nutshell, Volta is Microsoft’s version of Google Web Toolkit(GWT). GWT uses Java to generate JavaScript. Volta uses .Net language such as C# to generate JavaScript. As of today, Microsoft volta is technology preview (pre-beta).
  • Microsoft Dynamics CRM Online: Microsoft offers a CRM hosting service through Microsoft Dynamics CRM Online.
  • Microsoft SkyDrive - This is a storage in the Clouds. Once you sign up through Windows Live, you get 5GB of free storage.
  • Microsoft Popfly - It is a Microsoft mash-up tool similar to Yahoo’s Pipes.

Useful links

So you became a team lead? Here are books and podcast I recommend

September 6th, 2008
Becoming a lead means becoming a manager. By definition, a manager is a person who makes things happen through others. A developer lead or team lead can make a project successful only if he can make his team members work effectively. I mentored many newbie leads who felt lost when they began to work as a lead. Here is a list of books that I recommend for young managers and leads:

* Leadership and Self Deception: Getting Out of the Box by The Arbinger Institute - You need to read this book if you ever blamed others or if you feel you work harder than your team members. I think the definition of a bad manager is a manager in the box.
* The Five Dysfunctions of a Team A Leadership Fable by Patrick M Lencioni - This is a best book which explains what the team is. A true team is based on trust and built on conflicts.
* Manager Tools - This is a podcast site. The podcast series guides you to become a good manager. I recommend to use an iTunes to download and listen to all podcasts.

The above three items will be a good starting point, and I am sure you will discover other great books on the course of reading or listening to the above books and podcasts.

Sample code acceptance checklist for SharePoint from Microsoft

August 30th, 2008

Microsoft recently released the following article: http://technet.microsoft.com/en-us/library/cc707802.aspx#Section2 It is a sample code acceptance checklist. I think it is a good checklist to start with for assuring the quality of your team’s code. Just like any guidance and checklist, you will need to change the checklist by adding or removing checklist items.