Friday, 21 October 2011

Unexpected Error on SharePoint Web Analytics Page

We have recently deployed another new branded look and feel to our SharePoint 2010 intranet.  It comes with heavy customization and of course a custom master page.  Everything works fine until we hit the web analytics report under site settings – the famous SharePoint unexpected error. 

We went to the ULS log and found the following error:

System.ArgumentException: Could not find the sitemap node with URL '/_layouts/WebAnalytics/WebAppSelection.aspx'.  

This seems strange to me as we used to have an old customized master page and it didn’t have the same problem.  It’s quite a common problem after some Google, but none of the mentioned solutions (http://social.technet.microsoft.com/Forums/en/sharepoint2010setup/thread/2022cff0-e2cf-4702-bb2a-17dc91dd4247) really works for us.

Just a quick run down of our custom master page: we have 3 heavy customized navigation control: Global navigation, side navigation, as well as a footer (doormat) navigation. 

I start to remove these navigation one by one from the master page – and eventually I found that the footer navigation is the one that is causing the problem. And what’s more, it is the SiteMapDataSource object that is causing the problem.  This is strange, because the global navigation and the side navigation is using the same site map provider. 

After bit of playing around, I found the solution – by moving the footer data source control before the QuickLaunchDataSource delegate control (or the side side navigation).  I don’t have any explanation, but it looks like you cannot declare any SiteMapDataSource after the Quick Launch (or Side Nav) data source.

Friday, 10 June 2011

SharePoint 2010 Ribbon stuck at “Loading…”

Do you experience the following:
  • The ribbon is stuck at “Loading…” and never comes up, even you are using out of the box SharePoint site template and master page. 
  • Your site is setup with a DNS/host header, rather than the actual machine name.
  • There is a “.” in your DNS host (e.g. sp2010.dev). 
  • The ribbon works if you access the site using FQDN (e.g. sp2010.dev.domain.com)
  • Your SharePoint environment is running on either Windows 7 or Windows 2008 R2. 

If you answer “Yes” for all of the questions above, you are in the right place. 

image
This problem is actually caused by a new concept called DNS Devolution that Microsoft introduced in Windows 7 and Windows 2008 R2.  This concept give a finer controls over how far you search up the tree with an unqualified name.  For example, if you host name is sp2010, Windows will resolve it to sp2010.domain.com.  However, if you have a “.” in your hostname, e.g. sp2010.dev, Windows 7 and Windows 2008 R2 will not append the DNS search suffix to it. 

To solve the ribbon “Loading…” problem, you need to allow DNS suffix append to unqualified multi-label name.  To do that, run gpedit.msc on the server, Browse Local Computer Policy > Computer Configuration > Administrative Templates > Network > DNS Client.  Enable “Allow DNS Suffix Appending to Unqualified Multi-Label Name Queries”.  Then flush the DNS by running a ipconfig /flushdns in command prompt.  Refresh your site and your ribbon should work!


image

Monday, 31 January 2011

Reverting Claim Based Authentication to Classic Mode Authentication

Let me start with my story first: I have 3 different SharePoint environments:

  • Development with Classic Mode (Windows)
  • Testing with Claim Based
  • Production with Classic Mode (Windows)

Sometimes I will need to move a site from development to the testing environment, and since they are using different types of authentication, I will need to execute the $webApp.MigrateUsers($true) to convert the stored username in the content database from the “Windows” format (DOMAIN/username) to Claim based format (i:0#.w|DOMAIN/username). 

And now here’s a very stupid things that I have done last week.  I tried to move a site from Testing to the Production environment.  I went to the site permission and noticed the most of the username are stored in the Claim Based format, and the user is getting access denied error.  Immediately I think of the MigrateUsers($true) command that I mentioned above and I executed it (Yes, a real stupidity as a SharePoint guy).  Ops, other sites sit under the same Web Application starts to bound users off with an “Access Denied” error.  I can’t even login to the site with the farm administrator account. 

I immediately search for any information about MigrateUsers and found the Microsoft Official description here.  It says “true to move users to claims authentication; false to move users from claims authentication”.  Cool, this is a life saver and all I need to do is execute this command passing in false.  Run this and I am getting “Operation is not valid due to the current state of the object”. 

image

No good again.  My colleague opened up reflector and tried to look at the MigrateUsers method, and what we have noticed is the method intentionally throws an exception when we pass in false as the parameter.  Why??? I did more searching and found out that Claims to Classic mode is not currently supported by Microsoft. 

I went into the content database and checked the UserInfo table and have noticed that all logins had been converted to claim based format.  I tried to change one of the login back to Windows format (by the way, modification directly to SQL is not supported), but still not success. 

I did another test by creating a new site collection in a new content database under the same web application, and setting my Windows account as the site collection administrator.  In theory, this should work as everything is clean, however I am still getting “Access Denied”. 

Based on the above testing and investigation, we can prove that:

  • MigrateUsers($true) convert all username to “Claim-Based” format and this change applies to every content database under the same web application. 
  • Since the site is still using Windows Classic mode, when a user access the site, it will take the username in Windows format.  However, when it compares the “Windows” username with the converted claim based format username in the content database.  Since they are different, it returns an access denied error. 
  • Based on the result of the new site collection testing mentioned above, the MigratedUsers command will also do something to the web application, making it no longer accept “Windows” username.  Hence the web application is corrupted. 

After spending whole night in the office, finally I found a solution to roll back the changes: A command already existed in SharePoint 2007 fixed the problem, and it is MigrateUser.  Basically this command will convert one login to a new login. However this only works on single user every time. 

So here is my strategy for the problem:

  1. As mentioned, the web application is corrupted.  We will need to delete the corrupted web application and recreate a new one.  Make sure you keep an backup of the database
  2. After you recreate the web application, mount the content database(s). 
  3. Reset the Site Collection Administrator in Central Administration. 

Up to this point, you should be able to login to the site using the site collection administrator account that you defined in 3.).  And the next/final step that we need to do is to run the MigrateUser command to every users in the site collection.  To do that, I have implemented the following console application:

Code Snippet
  1. public Program(string url)
  2. {
  3.     using (SPSite site = new SPSite(url))
  4.     {
  5.         using (SPWeb web = site.RootWeb)
  6.         {
  7.             foreach (SPUser user in web.AllUsers)
  8.             {
  9.                 string username = GetClaimBasedUserName(user);
  10.                 if (!username.Equals(string.Empty))
  11.                 {
  12.                     Console.Write("Migrating {0} to {1}...", user.LoginName, username);
  13.                     try
  14.                     {
  15.                         SPFarm Farm = SPFarm.Local;
  16.                         Farm.MigrateUserAccount(user.LoginName, username, false);
  17.                         Console.WriteLine("Done");
  18.                     }
  19.                     catch (Exception ex)
  20.                     {
  21.                         Console.WriteLine(ex.Message);
  22.                     }
  23.                 }
  24.             }
  25.         }
  26.     }
  27. }
  28.  
  29. private string GetClaimBasedUserName(SPUser user)
  30. {
  31.     string username = string.Empty;
  32.     try
  33.     {
  34.         if (user.IsDomainGroup)
  35.         {
  36.             if (user.LoginName.StartsWith("c:0+.w|"))
  37.             {
  38.                 username = user.Name;
  39.             }
  40.         }
  41.         else
  42.         {
  43.             if (user.LoginName.StartsWith("i:0#.w|"))
  44.             {
  45.                 username = user.LoginName.Substring(7);
  46.             }
  47.         }
  48.     }
  49.     catch
  50.     {
  51.  
  52.     }
  53.     return username;
  54. }
  1. Basically the above code does the following:
  2. Grab all the users in the site collections,
  3. Get the current username which is in the claim based format
  4. Extract the “Windows” user name from the claim based username (Just trim the first 7 characters)
  5. Run the MigrateUser method

And after running this console application, your site is back up and running with Classic mode.

Thursday, 6 January 2011

Error Creating User Profile Connection - Unable to process Create Message

I have managed to setup User Profile Synchronisation in a few different environments without any problem - Connection created, FIM services are running, user profiles are imported successfully. 

Recently I was trying to setup a new server farm in the production environment.  I followed the exact same procedure as I always do, but this time I am getting a new error message when I tried to create a new User Profile Connection - Unable to process Create Message:


And I was getting these errors in the error log:


Microsoft.ResourceManagement.Service: System.InvalidOperationException: Retrieve schema failed
   at Microsoft.ResourceManagement.ActionProcessor.SyncConfigActionProcessor.Create(String typeName, IList`1 createParameters, Guid creator, Guid cause)
   at Microsoft.ResourceManagement.ActionProcessor.SyncConfigActionProcessor.ProcessInputRequest(RequestType request)
   at Microsoft.ResourceManagement.ActionProcessor.ActionDispatcher.ProcessInputRequest(RequestType request)
   at Microsoft.ResourceManagement.WebServices.RequestDispatcher.ExecuteAction(RequestType request)
   at Microsoft.ResourceManagement.WebServices.RequestDispatcher.ExecuteAction[ResponseBodyType](RequestType request)
   at Microsoft.ResourceManagement.WebServices.RequestDispatcher.DispatchRequest[ResponseBodyType](RequestType request, Guid requestIdentifier, Object redispatchSingleInstanceKey)
   at Microsoft.ResourceManagement.WebServices.RequestDispatcher.DispatchRequest[ResponseBodyType](RequestType request)
   at Microsoft.ResourceManagement.WebServices.ResourceManagementService.Create(Message request)

This is weird because I followed the exactly same procedure as the other environments.  FIM services are running, service accounts are setup properly, Net Bios Name flag enabled for the UPS, what was going wrong? Someone got the same error as me here and they fixed the problem by pointing the Sync to a Windows 2008 Domain Controller:
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010setup/thread/6c68c067-5b2a-482f-925b-5a0a25759344

However I have confirmed both the domain controller of production environment and other environments Windows 2003.  So what was wrong?  I spent 2 overnights, and one premium support called was raised and I was still going no where, where I was 4 days away from the production launch. 

I didn't install the August cumulative updates due to an error I posted earlier (link).  Then I thought....well, worth a try as I have tried out every thing already.  And you know what? That fixed the problem! And this also fixed the August CU problem that I had earlier (it broke the User Profile Service Application). 

So if you are getting this error when you create an user profile synchronisation connection, here are the two things that you should do:
  1. Check your domain controller
  2. Install the August (or later) Cumulative Updates

SharePoint 2010 August Cumulative Updates breaks ForeFront Identity Manager

I have recently came across a bug in the Newsfeed Settings. I have gone into my newsfeed setting and unchecked some of the activity types. The first time I done it, it was fine. However when I try to do it again, I noticed that my changes doesn't get saved.

Found nothing out there, so I decided to apply to SharePoint 2010 August Cumulative Updates:
SharePoint Foundation 2010: kb2266423
SharePoint Server 2010: kb2352342

After I applied the updates, my problems gone! I can now save my newsfeed settings.

BUT!!!! (You know that I am going to say this, right?) It produces another problem.

As usual, after the reboot required by the updates, my two ForeFront Identity Manager services have stopped. The Forefront Identity Manager Service has started successfully, but I couldn't get the Synchronization Service start.

I am getting the following error:


And when I checked my error log, I am getting a WorkflowManagerException: Forefront Identity Management Service does not support workflows of type 'Microsoft.ResourceManagement.Workflow.Activities.SequentialWorkflow, Microsoft.ResourceManagement, Version=2.0.2450.5" error:


To fix this problem, simply delete your User Profile Service Application, and recreate a new one.  Somehow the cumulative update does not work with the service application that was created using the old binary?

Fixing SharePoint 2010 Lookup Drop Down 20 Items Limit

As you might have noticed already, SharePoint (both 2007 and 2010) will render your lookup drop down column differently depends on the number of item in the drop down list. If you have less than 20 items, SharePoint will just render the drop down using the normal drop down list control.

However SharePoint will change the rendering style when there is more than 20 items. Instead of the simple drop down list control, it will be changed to a textbox + ajax + filtering list, like the following:



So when you start typing in the textbox, it filters the options, allows the user to select an item from a large list. There are pros, and of course there are cons:
- If you decide to select from the list, you need to do a double click in order to pick an option
- The free-text box gives an impression that you can free-text, which ends up saving empty string
- Inconsistent user experience if you have other drop down list in the form that has less than 20 items.
- There are some rendering issue for the Ajax Drop Down list in SharePoint 2010

To get around this, I have implemented a JQuery solution. Basically the script does the following if the drop down has more than 20 items:
- Hide the text box
- Hide the drop down arrow
- Provision the options in a simple drop down list, register an OnChange event to set the lookup hidden field that SharePoint is using.
- Add the drop down to the page.

Insert the following script to the New/Edit form (by using a content editor web part or custom ribbon javascript). I am assuming that you have a reference to the JQuery library in your master page.

Code Snippet
  1. <script>
  2. $(document).ready(function () {

  3. // Name of the column (Display Name)
  4. var columnName = "Lookup";

  5. // Override the Drop Down List
  6. OverrideDropDownList(columnName);

  7. // Main Function
  8. function OverrideDropDownList(columnName) {

  9. // Construct a drop down list object
  10. var lookupDDL = new DropDownList(columnName);

  11. // Do this only in complex mode...
  12. if (lookupDDL.Type == "C") {

  13. // Hide the text box and drop down arrow
  14. lookupDDL.Obj.css('display', 'none');
  15. lookupDDL.Obj.next("img").css('display', 'none');

  16. // Construct the simple drop down field with change trigger
  17. var tempDDLName = "tempDDLName_" + columnName;
  18. if (lookupDDL.Obj.parent().find("select[ID='" + tempDDLName + "']").length == 0) {
  19. lookupDDL.Obj.parent().append("<select name='" + tempDDLName + "' id='" + tempDDLName + "' title='" + tempDDLName + "'></select>");

  20. lookupDDL.Obj.parent().find("select[ID='" + tempDDLName + "']").bind("change", function () {
  21. updateOriginalField(columnName, tempDDLName);
  22. });
  23. }

  24. // Get all the options
  25. var splittedChoices = lookupDDL.Obj.attr('choices').split("|");

  26. // get selected value
  27. var hiddenVal = $('input[name=' + lookupDDL.Obj.attr("optHid") + ']').val()
  28. if (hiddenVal == "0") {
  29. hiddenVal = lookupDDL.Obj.attr("value")
  30. }

  31. // Replacing the drop down object with the simple drop down list
  32. lookupDDL = new DropDownList(tempDDLName);

  33. // Populate the drop down list
  34. for (var i = 0; i < splittedChoices.length; i++) {
  35. var optionVal = splittedChoices[i];
  36. i++;
  37. var optionId = splittedChoices[i];

  38. var selected = (optionId == hiddenVal) ? " selected='selected'" : "";
  39. lookupDDL.Obj.append("<option" + selected + " value='" + optionId + "'>" + optionVal + "</option>");
  40. }
  41. }
  42. }

  43. // method to update the original and hidden field.
  44. function updateOriginalField(child, temp) {
  45. var childSelect = new DropDownList(child);
  46. var tempSelect = new DropDownList(temp);

  47. // Set the text box
  48. childSelect.Obj.attr("value", tempSelect.Obj.find("option:selected").val());

  49. // Get Hidden ID
  50. var hiddenId = childSelect.Obj.attr("optHid");

  51. // Update the hidden variable
  52. $('input[name=' + hiddenId + ']').val(tempSelect.Obj.find("option:selected").val());
  53. }

  54. // just to construct a drop down box object. Idea token from SPServces
  55. function DropDownList(colName) {
  56. // Simple - when they are less than 20 items
  57. if ((this.Obj = $("select[Title='" + colName + "']")).html() != null) {
  58. this.Type = "S";
  59. // Compound - when they are more than 20 items
  60. } else if ((this.Obj = $("input[Title='" + colName + "']")).html() != null) {
  61. this.Type = "C";
  62. // Multi-select: This will find the multi-select column control on English and most other languages sites where the Title looks like 'Column Name possible values'
  63. } else if ((this.Obj = $("select[ID$='SelectCandidate'][Title^='" + colName + " ']")).html() != null) {
  64. this.Type = "M";
  65. // Multi-select: This will find the multi-select column control on a Russian site (and perhaps others) where the Title looks like 'Выбранных значений: Column Name'
  66. } else if ((this.Obj = $("select[ID$='SelectCandidate'][Title$=': " + colName + "']")).html() != null) {
  67. this.Type = "M";
  68. } else
  69. this.Type = null;
  70. } // End of function dropdownCtl
  71. });
  72. </script>
The script will then turn the complex drop down list (if it has more than 20 items) to the simple drop down list:



Originally I extended the SPServices JQuery Library to fix the drop down issue. So you may find that my scripts contains little portion of the library. I have integrated the above solution with the Cascading Drop Down list function provided by the SPServices library. Let me know if you want to obtain the extended script.
Update:
Since there are request for the Extended SPServices, I have make it available for download. You can download it from here. (Please rename the extension from .txt to .js)
Few notes before you use this:

1. This extended version is based of SPServices version 0.5.7

2. I have extended SPCascadeDropDowns and called the new function SPCascadeDropDownsEx

3. The original SPServices expects you to have the parent-child list in the following format:
Parent1 - Child1a
Parent1 - Child1b
Parent1 - Child1c
Parent2 - Child2a
Parent3 - Child3a
Parent3 - Child3b

However I have changed this so that it works with a child list and a parent list. For example, I have a child list with list item Child1a, Child1b, Child1c, Child2a, Child3a, Child3b. And then I create a parent list with a multi-valued lookup child colume like this:

Parent1 - Child1a, Child1b, Child1c
Parent2 - Child2a
Parent3 - Child3a, Child3b

(Sorry for the rough explanation, I will include screenshots when I have the system around)

And this is how I invoked the function:
// Enable Cascading Drop down for Department
$().SPServices.SPCascadeDropdownsEx({
relationshipList: "Department",
relationshipListParentColumn: "Title",
relationshipListChildColumn: "AreaOfImpact",
parentColumn: "Department",
childColumn: "Area Of Impact",
relationshipListType: "LookupMultiValue",
promptText: "--- Please select ---",
debug: false
});
So in the above script:
- relationshipList is the parent list
- relationshipListParentColumn is the name of the parent column in the parent list
- relationshipListChildColumn is the name of the childLookup column in the parent list
- parentColumn is the display name of the parent drop down list
- childColumn is the display name of the child drop down list
- relationshipListType is the type of the relationshipListChildColumn in the parent list

Thursday, 28 October 2010

Disable MySite and Tagging in SharePoint 2010

SharePoint 2010 provides some cool social features like social tag, note board, and ratings which nicely integrated with MySite. However there might be chance that you don’t want to roll out these features, due to various reasons like change management, training, and governance.

You can disable these features in your server farm and enable them when you are ready. Here are the instructions to disable the features.

  1. Logon to Central Administration web site, go to the Application Management section, and click Manage service applications.
  2. Click the user profile service application item in your farm (by default, it is “User Profile Service Application”)
  3. Click “Manage User Permissions” under People.
  4. In the “Permissions for User Profile Service Application” pop up, select a user group, e.g. All authenticated Users.
  5. Uncheck the “Permissions” item, base on what you want to disable. For your information
    • Use Personal Features – My Links, My Colleagues, Personalization.
    • Create Personal Site – My Site
    • Use Social Features – Tagging, Note Board, and Ratings
  6. Click OK to save the settings.

ManageUserPermissions

Please note, unselect Social Features does not remove the “Tags and Notes” group from the ribbon. It will still show up on the page but it will grey out.

Grey_Out_Tags_and_Notes

To hide the “Tags and Notes” from your site, there’s actually a farm feature that you need to disable. To disable this feature:

  1. Logon to Central Administration web site, go to the System Settings section, and click Manage farm features.
  2. There is a feature called “Social Tags and Note Board Ribbon Controls”. Deactivate it to hide the “Tags and Notes” group from the ribbon.
  3. Now go to your site and the “Tags and Notes” should be removed from the Ribbon.

SocialTagsFeature

Tuesday, 26 October 2010

Creating Term Set in SharePoint 2010 Programmatically

Managed Metadata is a very nice feature introduced in SharePoint 2010. It allows you to define terms in a hierarchical collection centrally, and create a managed metadata field that is reference a term sets.

By using the Term Store Management Tool found in Managed Metadata Service, you can create a term set either manually, or by importing a CSV file. You can also create a term set programmatically, either by a feature receiver or a console application. You may ask “Why do I want to provision a term set programmatically?”. Well, by creating the term set programmatically, you are able to define a fixed ID/GUID for you term set or term, and this becomes handy if you want to provision a managed metadata field in a feature (Angus has created an excellent article on how to do this).

First, you will need to add a reference to “Microsoft.SharePoint.Taxonomy.dll”, which should not be too hard to find in Visual Studio 2010. Next, an obviously, you will need to put the following line:

Code Snippet
  1. using Microsoft.SharePoint.Taxonomy;

And here is the code:

Code Snippet
  1. string siteUrl = "http://sharepoint2010";
  2. Guid newTermSetId = new Guid("{60F494A0-C31C-4D7C-9C9B-D8AF3191F3D5}");
  3. Guid newTermId = new Guid("{E39C3477-500E-4EB0-9891-0785F840DF53}");
  4. using (SPSite site = new SPSite(siteUrl))
  5. {
  6. TaxonomySession session = new TaxonomySession(site);
  7. if (session.TermStores.Count > 0)
  8. {
  9. // Get a reference to the store
  10. TermStore store = session.TermStores["Managed Metadata Service"];
  11. // Create a group
  12. Group group = store.CreateGroup("SharePointEgg.Test");
  13. // Create a term set in the group, with a pre-defined ID
  14. TermSet termSet = group.CreateTermSet("Term Set Test", newTermSetId, 1033);
  15. // Create a term in the term set in the newly created term set, with a pre-defined ID
  16. Term term = termSet.CreateTerm("Term 01", 1033, newTermId);
  17. // Save everything by calling CommitAll
  18. store.CommitAll();
  19. }
  20. }

And here is the end result:

Wednesday, 3 February 2010

Remove button from the Ribbon in SharePoint 2010

In SharePoint 2007, I have quite a few requests from different client to remove button from the document list view, such as the “Edit in Datasheet” and “Open with Windows Explorer” button. I was able to solve the problem by writing a Javascript to hide the button.

Ribbon is introduced in SharePoint 2010. We can easily make customization it by using the Feature Infrastructure. For example, we can create a new button, delete an existing button, as well as replacing an existing button. Hence I can easily get around with the problem that I had in SharePoint 2007.

In order to hide a button, say the “Open with Explorer”, we will need to create a feature. We start by creating a new folder called “DisableRibbonButton”. Create a new file called “feature.xml” in the new folder and insert the following XML into the file

<?xml version="1.0" encoding="utf-8" ?>
<Feature Id="33057CD9-6D14-45c9-83ED-5E1FE066AC92"
         Title="DisableRibbonButton"
         Description="DisableRibbonButton"
         Version="1.0.0.0"
         Scope="Web"
         xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="Manifest.xml" />
  </ElementManifests>
</Feature>

Then create another file called “Manifest.xml” and insert the following XML:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="RemoveExplorerButton"
    Location="CommandUI.Ribbon"
    RegistrationType="List"
    RegistrationId="101">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Library.Actions.OpenWithExplorer" />
      </CommandUIDefinitions>
    </CommandUIExtension>
  </CustomAction>
</Elements>

The above XML is to remove the “Open with Explorer” button from the Ribbon for all list with type ID 101, hence all the Document Library type. The location “Ribbon.Library.Actions.OpenWithExplorer” is the ID that is registered in the default Ribbon button XML, which can be found in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\GLOBAL\XML\CMDUI.XML”

Now we will execute the following Cmdlet using the “SharePoint 2010 Management Shell” to install and active the feature:

Install-SPFeature DisableRibbonButton

Enable-SPFeature DisableRibbonButton –url http://<servername>

After that, go to any document library in your site, click the “Library” tab at the top and you should see the “Open with Explorer” button is now disappeared from the Ribbon.

Friday, 8 January 2010

Notes on Installing SharePoint 2010 Beta 2 on Windows 7 Ultimate

I have just bought a new Sony VAIO laptop for SharePoint 2010 development. It has Windows 7 Ultimate on it and obviously it is 64 bit. Even though there were some problems with the SharePoint 2010 Beta 2 installation, but fortunately I am able to get SharePoint 2010 Beta 2 running on my laptop now without any problem.

I am going to list out the installation steps in this post, as there are lots of article around about the installation steps already. Instead I will list out the problem that I had and how I got around them.

I followed the MSDN article “Setting Up the Development Environment for SharePoint Server” to prepare the installation and most of the things work fine.

For your information, here are the detail of my development environment:

  • Windows 7 Ultimate – 64 bit, with 6GB RAM
  • SQL Server 2008 Standard Edison – with SP1 and latest cumulative updates
  • SharePoint 2010 Beta 2
  • Visual Studio 2010 Ultimate Beta 2
  • Office 2010 Beta
  • No Active Directory

Here are the problems that I had when I setup my SharePoint 2010 development environment.

1. SQL 2008 Install Error: Invoke or BeginInvoke cannot be called on a control

When I run the SQL Server 2008 installation wizard, I got the error message “Invoke or BeginInvoke cannot be called on a control”. After a bit of research, I found the solution mentioned in this post works. All you need to do is minimize all other windows when the installer is running, and make sure the SQL 2008 installer windows is always active by clicking the installer dialog.

Well, this is a weird problem…

2.) Cannot Create New Web Application and Running the Configuration Wizard in Central Admin

This one is easy, just turn off User Access Control and you will be fine.

3.) Visual Studio 2010 Install Error: VC 10.0 Runtime (x86)

I was trying to install Visual Studio 2010 Beta 2 using the ISO file that I downloaded from MSDN. However I was getting an error when the installer try to install the “VC 10.0 Runtime (x86)” component.

After Google for a while, I found this post suggesting using the web installer will fix the problem. I have tried this and it works fine for me.

Tuesday, 24 November 2009

Create Custom Service Application in SharePoint 2010 – Part 3

Creating Service Administration Pages

We will need to create two administration pages for our Hello service application. One will be used for service application instance creation, and the other one for managing existing application instance. As a reference we will use the pages for Excel Service, which can be located in the ADMIN folder (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\ADMIN).

First we will create a mapped folder to the ADMIN folder and this is the folder where the administration pages will deploy. To do this, right click the HelloServiceApplication > Add > SharePoint Mapped Folder..., then expand the “TEMPLATE” node and select the “ADMIN” folder. A new ADMIN folder “HelloServiceApplication” will be added to the project.

We will first create the service creation page. Right click the newly created “HelloServiceApplication” folder under “ADMIN” and add a new item. Select the “Application Page” template and give the page a name “CreateApplication.aspx”

I am using Visual Studio 2010 Beta 2 and notice a funny thing. VS2010 will create the CreateApplication.aspx in “Layouts/HelloServiceAplication”. If you have this problem, just drag the aspx file to ADMIN\HelloServiceApplication, as this is the location where we referencing in out Service Application implementation (HelloService.cs).

Put the following code in the aspx file:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateApplication.aspx.cs" Inherits="SharePointEgg.Layouts.HelloServiceApplication.CreateApplication" MasterPageFile="~/_layouts/dialog.master" %>

<%@ Assembly Name="Microsoft.Office.Excel.Server.MossHost, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Assembly Name="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Register TagPrefix="wssuc" TagName="LinksTable" src="/_controltemplates/LinksTable.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" src="/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" src="/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="LinkSection" src="/_controltemplates/LinkSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" src="/_controltemplates/ButtonSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ActionBar" src="/_controltemplates/ActionBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBar" src="/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" src="/_controltemplates/ToolBarButton.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="Welcome" src="/_controltemplates/Welcome.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="IisWebServiceApplicationPoolSection" src="~/_admin/IisWebServiceApplicationPoolSection.ascx" %>

<asp:Content ID="Content1" contentplaceholderid="PlaceHolderDialogHeaderPageTitle" runat="server">
    <asp:Literal ID="CreateASAppTitle" Text="Create New Hello Service Application" runat="server"/>
</asp:Content>

<asp:Content ID="Content2" contentplaceholderid="PlaceHolderDialogDescription" runat="server">
    <asp:Literal ID="CreateASAppDesc" Text="Specify the name, application pool, and default for this Application." runat="server"/>
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderId="PlaceHolderDialogBodyMainSection" runat="server">    
    <TABLE border="0" cellspacing="0" cellpadding="0" width="100%" class="ms-authoringcontrols">
        <wssuc:InputFormSection
            Title="<%$Resources:xlsrv, ManagementUI_ServiceAppNameLabel%>"
            runat="server">
            <Template_InputFormControls>
                <wssuc:InputFormControl LabelText="" LabelAssociatedControlID="TextBoxAppName" runat="server">
                    <Template_control>
                        <wssawc:InputFormTextBox title="<%$Resources:xlsrv, ManagementUI_ServiceAppNameLabel%>" class="ms-input" ID="TextBoxAppName" Columns="35" Runat="server" MaxLength=256 />
                        <wssawc:InputFormRequiredFieldValidator ID="AppNameValidator"
                            ControlToValidate="TextBoxAppName"
                            ErrorMessage="<%$Resources:xlsrv, ManagementUI_RequiredFieldErrorMessage%>"
                            width='300px'
                            Runat="server"/>
                        <wssawc:InputFormCustomValidator ID="UniqueNameValidator"
                            ControlToValidate="TextBoxAppName"
                            ErrorMessage="<%$Resources:xlsrv, ManagementUI_DuplicateNameErrorMessage%>"
                            OnServerValidate="ValidateUniqueName"
                            runat="server" />
                    </Template_control>
                </wssuc:InputFormControl>
            </Template_InputFormControls>
        </wssuc:InputFormSection>

        <wssuc:IisWebServiceApplicationPoolSection id="AppPoolSection" runat="server" />

        <wssuc:InputFormSection
            Title="<%$Resources:xlsrv, ManagementUI_DefaultLabel%>"
            Description="<%$Resources:xlsrv, ManagementUI_DefaultDescription%>"
            runat="server">
            <Template_InputFormControls>
                <wssuc:InputFormControl LabelText="" LabelAssociatedControlID="CheckBoxDefault" runat="server">
                    <Template_control>
                        <asp:CheckBox Checked="True" ID="CheckBoxDefault" Text="<%$Resources:xlsrv, ManagementUI_DefaultCheckboxDescription%>" Runat="server" />
                    </Template_control>
                </wssuc:InputFormControl>
            </Template_InputFormControls>
        </wssuc:InputFormSection>

        <SharePoint:FormDigest ID="FormDigest1" runat=server/>        
</asp:Content>

Put enter the following for the code behind:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server.Internal.UI;

namespace SharePointEgg.Layouts.HelloServiceApplication
{
    public partial class CreateApplication : GlobalAdminPageBase
    {
        // Fields
        protected RequiredFieldValidator AppNameValidator;
        protected IisWebServiceApplicationPoolSection AppPoolSection;
        protected Button ButtonOk;
        protected CheckBox CheckBoxDefault;
        protected TextBox TextBoxAppName;
        protected CustomValidator UniqueNameValidator;

        // Methods
        protected void OkButton_Click(object sender, EventArgs e)
        {
            //ULS.SendTraceTag(0x39766663, UlsInformation.Management, ULSTraceLevel.Verbose, "ExcelServerCreateApplication.ButtonNext_Click: Entering ButtonNext_Click...");
            this.Page.Validate();
            if (this.Page.IsValid)
            {
                string applicationName = this.TextBoxAppName.Text.Trim();
                SPLongOperation.Begin(delegate(SPLongOperation longOperation)
                {
                    try
                    {
                        SharePointEgg.HelloServiceApplication serviceApplication = null;
                        serviceApplication = HelloService.Local.CreateApplication(applicationName, this.AppPoolSection.GetOrCreateApplicationPool());
                        serviceApplication.Update();
                        IAsyncResult asyncResult = serviceApplication.BeginProvision(null, null);
                        serviceApplication.EndProvision(asyncResult);
                        HelloServiceApplicationProxy proxy = HelloService.Local.CreateProxy(applicationName, serviceApplication);
                        proxy.Update();
                        proxy.AddToDefaultGroup(this.CheckBoxDefault.Checked);
                    }
                    catch (Exception exception)
                    {
                        //ULS.SendTraceTag(0x39766664, UlsInformation.Management, ULSTraceLevel.High, "ExcelServerCreateApplication.ButtonNext_Click: {0}", new object[] { exception.Message });
                        throw;
                    }
                    longOperation.EndScript("window.frameElement.commonModalDialogClose(1, null);");
                });
            }
            //ULS.SendTraceTag(0x39766665, UlsInformation.Management, ULSTraceLevel.Verbose, "ExcelServerCreateApplication.ButtonNext_Click: Exiting ButtonNext_Click.");
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ((DialogMaster)this.Page.Master).OkButton.Click += new EventHandler(this.OkButton_Click);
        }

        protected void ValidateUniqueName(object sender, ServerValidateEventArgs eventArgs)
        {
            if (eventArgs == null)
            {
                throw new ArgumentNullException("eventArgs");
            }
            SharePointEgg.HelloServiceApplication applicationByName = SharePointEgg.HelloServiceApplication.GetApplicationByName(this.TextBoxAppName.Text.Trim());
            eventArgs.IsValid = applicationByName == null;
        }
    }
}

We also need to remove some of the control’s declaration in teh designer.cs because we declared these controls in the code behind. CreateApplication.aspx.designer.cs looks like this:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SharePointEgg.Layouts.HelloServiceApplication {


    public partial class CreateApplication
    {

        /// <summary>
        /// CreateASAppTitle control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Literal CreateASAppTitle;

        /// <summary>
        /// CreateASAppDesc control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Literal CreateASAppDesc;

        /// <summary>
        /// FormDigest1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Microsoft.SharePoint.WebControls.FormDigest FormDigest1;
    }
}

Next we will create a management page for our service application. For demonstration purpose, this page is just a dummy page that doesn’t do anything. Right click the newly created “HelloServiceApplication” folder under “ADMIN” and add a new item. Select the “Application Page” template and this time we call it “HelloServiceAdmin.aspx”. Due to the bug that I mentioned above, you may need to drag the page from “Layouts/HelloServiceApplication” back to “ADMIN\HelloServiceApplication”.

Put the following code in the aspx file:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloServiceAdmin.aspx.cs" Inherits="SharePointEgg.Layouts.HelloServiceApplication.HelloServiceAdmin" MasterPageFile="~/_admin/admin.master" %>

<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages.Administration, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="LinksTable" src="/_controltemplates/LinksTable.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" src="/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" src="/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="LinkSection" src="/_controltemplates/LinkSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" src="/_controltemplates/ButtonSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ActionBar" src="/_controltemplates/ActionBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBar" src="/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" src="/_controltemplates/ToolBarButton.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="Welcome" src="/_controltemplates/Welcome.ascx" %>

<asp:Content ID="Content1" contentplaceholderid="PlaceHolderPageTitle" runat="server">
    Test Service Admin Page
</asp:content>

<asp:Content ID="Content2" contentplaceholderid="PlaceHolderPageTitleInTitleArea" runat="server">
    Test Service Admin Page
</asp:Content>

<asp:content ID="Content3" contentplaceholderid="PlaceHolderPageDescription" runat="server">
    <asp:Literal ID="m_pathPageDescription" runat="server" />
</asp:content>

<asp:content ID="Content4" contentplaceholderid="PlaceHolderMain" runat="server">
    <table width="100%" class="propertysheet" cellspacing="0" cellpadding="0" border="0"> <tr> <td class="ms-descriptionText"> <asp:Label ID="LabelMessage" Runat="server" EnableViewState="False" class="ms-descriptionText"/> </td> </tr> <tr> <td class="ms-error"><asp:Label ID="LabelErrorMessage" Runat="server" EnableViewState="False" /></td> </tr> <tr> <td class="ms-descriptionText"> <asp:ValidationSummary ID="ValSummary" HeaderText="<%$SPHtmlEncodedResources:spadmin, ValidationSummaryHeaderText%>" DisplayMode="BulletList" ShowSummary="True" runat="server"> </asp:ValidationSummary> </td> </tr> </table>

    <P>
        <span style="font-size:140%"><asp:HyperLink ID="m_linkToSettingsPage" runat="server"/></span><br />
        Test Service Admin Page Description
    </P>
    <P>
        <span style="font-size:140%"><asp:HyperLink ID="m_linkToTrustedLocations" runat="server"/></span><br />
        Trusted Location
    </P>
    <P>
        <span style="font-size:140%"><asp:HyperLink ID="m_linkToTrustedDataProviders" runat="server"/></span><br />
        Trusted Data Provider
    </P>
    <P>
        <span style="font-size:140%"><asp:HyperLink ID="m_linkToTrustedDcls" runat="server"/></span><br />
        Trusted Data Connection Library
    </P>
    <P>
        <span style="font-size:140%"><asp:HyperLink ID="m_linkToUdfs" runat="server"/></span><br />
        User Defined Library
    </P>

</asp:content>

The code behind looks like this:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Internal.UI;

namespace SharePointEgg.Layouts.HelloServiceApplication
{
    public partial class HelloServiceAdmin : GlobalAdminPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

And we have completed the administration pages for our service application. However we are not there yet. We need to add our service application to the server farm so that we can create an instance of it. We will create a feature receiver to do this.

Feature Receiver: Create Service Application in Server Farm

Right click the “Features” folder in Visual Studio and select “Add Feature”. Then right click the newly created Feature1.feature node and select “Add Event Receiver”. This will create the event receiver class and xml file.

Open “Feature1.EventReceiver.cs” and uncomment the “FeatureActivated” method. Put the following code in the method:

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                HelloService service = HelloService.Local;
                if (service == null)
                {
                    service = new HelloService(SPFarm.Local);
                    service.Update();
                }
            }
            catch
            {
            }
        }

And there you go our service application is ready to be deployed!!!

Creating Client Page

Ops, just before we deploy, we will quickly create a page under the “Layouts\HelloServiceApplication” folder to call our service application. Right click the “Layouts” folder in Visual Studio and add a new item. Select “Application Page” and we will call this page “Test.aspx”. We will have a textbox, a button, and a literal control in our page. When the user clicks the button, the page will grab whatever value in the textbox and sends it to our custom service application. The literal control will be used to display whatever returns from the service application. We will insert the controls into “PlaceHolderMain” like this:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <SharePoint:InputFormTextBox ID="InputFormTextBoxName" runat="server" />
            <asp:Button runat="server" ID="OKButton" Text="Submit" />
            <asp:Literal runat="server" ID="ResultLiteral"></asp:Literal>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

The code behind is here:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SharePointEgg.Layouts.HelloServiceApplication
{
    public partial class Test : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            OKButton.Click += new EventHandler(OKButton_Click);
        }

        void OKButton_Click(object sender, EventArgs e)
        {
            try
            {
                HelloServiceApplicationProxy proxy = HelloServiceApplicationProxy.GetProxy(SPServiceContext.Current);
                SharePointEgg.HelloServiceApplication app = proxy.Application;
                string endPoint = app.DefaultEndpoint.ToString();

                ResultLiteral.Text = app.Hello(InputFormTextBoxName.Text);

            }
            catch (Exception ex)
            {
                ResultLiteral.Text = ex.Message;
            }
        }
    }
}
Deploying Service Application

Right click the “HelloServiceApplication” and select “Deploy”. Hopefully you will get a “Deploy succeeded” message.

Create an Hello Service Application Instance

First browse to the SharePoint Central Administration site. Under “Application Management”, click “Manage service applications”. In the “Manage Service Applications” page, click the “New” button in the ribbon and you should see “Hello Service Application” in there":

Select “Hello Service Application” and a dialog should show up. This is actually the CreateApplication.aspx that we created earlier.

Give it a name “Hello Service Application”. Create a new application pool called “HelloServiceAppPool”. Check the Default checkbox as well. Click “OK” to proceed.

After a while, a new service application called “Hello Service Application” is created, like shown as below.

Select the new service application and click “Manage” in the Ribbon. You will be redirect to the management page, however this page doesn’t really do anything now.

Now let see if everything is working by accessing the client page that we created. You can get to the client page via the URL http://yoursite/_layouts/HelloServiceApplication/Test.aspx

Enter a name say “Wilson” in the text box and click OK. If anything is working, you will get and message back like the following screen: