Add to My Yahoo! | Google Reader or Homepage | Add to Windows Live | Add to Windows Live Alerts

Wictor Wilén

SharePoint Server MVP / Author / MCT / MCTS / MCP / MSc writing about SharePoint and other interesting Microsoft technologies

Latest postings

Visual guide to Windows Live ID authentication with SharePoint 2010 - part 1

Posted at 2010-09-08 01:39 by Wictor Wilén in LiveID , SharePoint 2010 with 1 comments.

Using Windows Live ID as login provider for SharePoint is a really huge thing. It makes the scenario for public facing web sites, extranets etc. much more easier, for instance there is no need to maintain passwords and users in the same degree. For SharePoint 2007 there is no native support for this, so I built a custom Live ID login provider (available at http://spwla.codeplex.com), but SharePoint 2010 has native support for claims based access. And that is what's on the menu for tonight...

This post, and the subsequent ones, will show you how to enable Windows Live ID on a SharePoint 2010 farm (SPF or SPS). I will do a visual approach using a lot of screenshots. It has not been an easy path since there are no official guidance on this subject (at the time of this writing), so I'm going to throw in a couple of steps where you can fail miserably while setting it up. Big thanks to Paul Schaeflein who also walked the hard path and took some hits to get this to work! Although there are a couple of available blog posts out there on this issue, some of the are very sparse on the details (why?) and some even contains faulty instructions. Just to safe up on this - the instructions works on my machines and I've been able to reproduce these steps a number of times. If you have any suggestions or comments, just leave them here and I'll try to (get someone to) answer them...

So what are we waiting for, let's get the party started. I have to warn you - if you don't like certificates - stop reading!

Background

While I will explain more in details as we move along I think it is important to have a little heads up on claims based access and Windows Live ID. First of all (passive) claims based access is based on the simple scenario where a client/user (subject) trying to access a site (also called Relying Party/RP). This RP has distributed the login procedure to one or more trusted parties called Identity Providers (IP). In our case SharePoint is the RP and Live ID is the IP and you of course are the subject. When the subject tries to access the RP, the subject will be redirected to the IP where the actual logon process is taking place. By attaching cookies to the response and redirecting the user back to the RP with a set of (encrypted) claims the RP can finally authenticate the user. For a better understanding I recommend you to read A guide to Claims-based Identity and Access Control.

A little bit of claims

Windows Live ID (WLID) will take care of the login and send back a unique ID to the SharePoint site. This unique ID is the only claim WLID will give you. (Unfortunately you cannot get the correct e-mail address or the name of the user.) SharePoint will first verify the validity of the encrypted security token (containing the claims) before actually starting the AuthN and AuthZ process using the unique ID as username in SharePoint. You will later see how we give access to these unique ID's.

Another important thing to keep in mind is that WLID have two "zones"; INT and PROD. The PROD zone is what you normally use when logging in to Hotmail etc. The INT zone is used for development and testing and have a completely different account database, so you need to have accounts in the INT zone to continue, more about this in a little bit. You cannot skip the INT zone, you have to register your site there first before applying for approval in the PROD zone.

The steps provided here is only for the INT environment. For PROD it is basically the same and the post is long enough as it is...

Registering the site

MSMBefore even starting to configure the SharePoint site we need to register our site for usage with Windows Live ID. This is done using the Microsoft Service Manager web application located at http://msm.live.com/. You log in to this service using you normal (PROD) Windows Live ID account.

In the left menu click on Register Your Site (1). This will bring up the Register Your Site page where you should enter the name of your site, use a descriptive name (2) and the DNS Name of your site (3). The DNS Name is important! Here you must specify a DNS Name, which we will later change into a URI, or rather URN. Write something random such as wictor.live.

The DNS Name will be used as a SAML Audience when the security token is sent back and it will be verified by SharePoint. According to the SAML specification the audience must be a URI (a URN or URL). If you use a URL then WLID will for some reason remove the protocol from the audience when sending it back to the RP and SharePoint will throw an exception ([InvalidOperationException: This operation is not supported for a relative URI.] System.Uri.GetLeftPart(UriPartial part)). This might change in the future.

Finally you have to specify that you will use Windows Live ID (4). Click Submit to continue.

MSM Config

You will get a confirmation screen. Click Yes to confirm and proceed to the next step

MSM Confirmation

After a few seconds you will be presented with the results. If anything goes wrong you need to go back and edit your registration accordingly - but it shouldn't if you followed these steps.

Congrats!

Click on the Go to Manage Your Site link. In the drop-down (1) select the site that you just registered and then click on the Modify Editable Site Properties link (2).

Manage your site

The next screen allows you to edit the properties of the site. First of all check the Show advanced properties check box to enable more options.

Advanced stuff ahead...

First we need to rename the Domain name (1) and set our real domain name to use. Then we need to replace the dummy DNS name (2) with a URN, in this case I use urn:wictorslivesite:int. Remember not to specify a URL, it just won't work as of now. The third thing to edit is the Default Return Url (3); this must be an HTTPS url pointing to the /_trust/default.aspx page, for instance https://extranet.corp.local/_trust/default.aspx. This is the URL that the IP will post back the results to. Finally we have to edit the Expire Cookie URL (4). Just fix the URL and never mind the actual page (you can implement such a page if you feel to at a later time).

Options, options, options...

Then scroll down a bit on the page until you reach Override Authentication Policy, this step is crucial. Select MBI_FED_SSL in the drop-down. And when you're done click Submit (at the top of the page).

MBI_FED_SSL

Verify and confirm your changes by clicking Yes on the next screen. Take a screenshot and/or notes all these changes.

Confirmation again

That's it. Your site is now configured. Actually you can configure a bunch of more features here - but stick to these as of now...

Wohoooo

Let's move on to the SharePoint Server.

Certificates

Claims based authentication uses certificates for encryption and signing and you have to trust the certificate of the IP on your SharePoint servers. The following steps must be done on all WFE's in the farm.

To get the IP certificate; browse to federation metadata URL: https://nexus.passport-int.com/federationmetadata2/2007-06/federationmetadata.xml (this is for the INT zone). Then copy the inner text from the first X509Certificate node. Open up the Notepad application and paste the text and then save the file as LiveID-INT.cer. Make sure that you only get the inner text of the element.

XML en masse

Now you have the certificate in a file and you need to import it to the correct locations on the SharePoint Server(s). It is actually required to be stored locally on three different locations. Open mmc.exe and add the Certificates snap-in. When you select to add it you must first select to use the Computer Account to manage the accounts for and select to use the Local computer as computer to manage.

Expand the tree until you reach SharePoint > Certificates then right-click on the node and Select All Tasks > Import...

Certificates

In the import wizard that appears locate the LiveID-INT.cer file you just created and then click Next > Next > Finish. That's the first one.

Repeat this procedure for the Trusted Root Certification Authority and Trusted People. Don't worry if you don't have a Certificates sub-node. It will be created when you import the certificate.

Even more certificates

Now we're one step closer and it is time to get dirty with some PowerShell. You could of course have done this step using PowerShell, but I leave that for another crafty blogger to show how... Just remember to do this on all WFE's!

Create the STS provider

To create the Trusted Identity Token Issuer, that we will use to configure as the login provider for the Web Applications, we fire up PowerShell. This step will not be that "visual" as the previous ones, since none of these commands can be run using the standard SharePoint user interface. I guess it's just a matter of time until someone makes a neat add-on with these simple commands...

I'll give you the script first and then explains all the involved steps:

1: asnp microsoft.sharepoint.powershell
2: $realm = "urn:wictorslivesite:int"
3: $certfile = "C:\Temp\LiveID-INT.cer"
4: $rootcert = Get-PfxCertificate $certfile
5: New-SPTrustedRootAuthority "Live ID INT Root Authority" -Certificate $rootcert
6: $emailclaim = New-SPClaimTypeMapping 
-IncomingClaimType "http://schemas.xmlsoap.org/claims/EmailAddress"
-IncomingClaimTypeDisplayName "http://schemas.xmlsoap.org/claims/EmailAddress"
-SameAsIncoming 7: $upnclaim = New-SPClaimTypeMapping
-IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
-IncomingClaimTypeDisplayName "UPN"
-LocalClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" 8: $authp = New-SPTrustedIdentityTokenIssuer -Name "LiveID INT"
-Description "LiveID INT" -Realm $realm -ImportTrustCertificate $certfile
-ClaimsMappings $emailclaim,$upnclaim -SignInUrl "https://login.live-int.com/login.srf"
-IdentifierClaim "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"

The first line just loads the SharePoint PowerShell Snapin (1), asnp is a shortcut for Add-PSSnapin and saves you a cpl of keystrokes. Then we set three local properties; realm corresponds to the DNS Name (that is the URN), certfile points to the location where you saved the LiveID-INT.cer file and the rootcert is the certificate loaded in as an object.

Make sure not to make any typos in the claims URN's - been there, done that!

Then we add the certificate to a SharePoint trusted Root Authority, using the New-SPTrustedRootAuthority cmdlet. You can verify that it is correctly imported by going to Central Adminitration > Security > Manage Trust:

Trusts in SharePoint

Then we need to create two claims mappings; one for e-mail (line 6) and one for the identifier (line 7). The claim mappings defines how the incoming claims are mapped to the SharePoint tokens. These two claims are then sent into the New-SPTrustedIdentityProvider cmdlet (line 8) and here is where the magic happens. This cmdlet creates a new trusted identity provider with a name and description, we instruct it which claims mappings to use and which claim is the identifier claim. We are also specifying the URL for the WLID (INT zone) login page.

Once these commands are executed, we are ready to head on over to the UI and create a Web Application. By all means, if you prefer to do the rest using PowerShell, feel free to do it.

If you are fiddling back and forwards using different registered Live ID services, you can switch the Realm using the DefaultProviderRealm property of the Trusted Identity Provider object (authp). Don't forget to call Update() on the object... You can only have one provider for each service, even if the realms differ.

Create the Web Application

Fire up Central Administration and go to Application Management > Manage web applications. Click New to create a new Web Application.

First of all you need to select to use Claims Based Authentication. Then enter a Name for your web application, use the port 443 (SSL) and (in this case) configure the host header to match the domain name that you entered while registering the WLID service. Just standard stuff so far.

Create the web application

Under Security Configuration make sure that you select Use Secure Sockets Layer (SSL).

SSL settings

Under Claims Authentication Types leave Windows Authentication enabled if you like, but make sure to check Trusted Identity Provider checkbox and then check the LiveID INT provider, the one we created using PowerShell.

Providers...

Once done click OK to create the Web Application.

We're almost there just a few steps more...

Create the Site Collection

Once the Web Application is created you can directly click on the Create Site Collection link. Enter name and description for the site, and also specify which template to use.

Now it is time to give some permissions to this site collection. Assume that we did not select any Windows Authentication when creating the Web Application, then we can only add Live ID users, right?

If you don't have a WLID account in the INT domain it is time to get one now. Open up a new browser window. Go to https://accountservices.passport-int.net/ and sign up for a new account or sign in using one of your existing INT accounts. (Stability of the INT domains are not 100% :-). When you have signed up or logged in click on Credentials and then View your unique ID.

Credentials

You will now see a screen with your unique ID; write it down, copy it or remember it...

Magin number

Close the browser and return to the Central Administration where you started creating a Site Collection. Now paste or write this unique ID and append @live.com in the Primary Site Collection Administrator. But, make sure to convert all characters to lowercase, otherwise you will not be able to log in later:

Magic number becomes an admin

Then click OK to create the Site Collection.

Final configurations

Before browsing to the site we need to make some final adjustment in the IIS. To be precise we will add a certificate to the site. You can use a certificate that you have acquired for your site or when testing just use a Self-Signed, which I will show you here.

To create a Self-Signed certificate start the IIS Manager and select the server. In the Features View double-click the Server Certificates module.

Ouch, more certificates

Then click Create Self-Signed Certificate in the Actions bar to the right and follow the instructions. Mostly next-next-finish.

I'll make one myself

The final configuration is to use this certificate on the Web Application. Choose the Web Application you created in SharePoint in the IIS Manager (1), then click on Bindings (2), select to edit the only binding you have (3) and choose the SSL certificate you just created in the drop-down (4). Click OK and close everything down.

Advanced stuff

That's it! Let's see how it behaves...

Taking it for a test drive

Now open up a web browser and go to the web application you have created using the domain name you specified when creating it, make sure to use https. You should see the standard warning in the browser that the certificate is not valid (add it as trusted if you want to skip this warning in the future), otherwise just click the continue link.

Bump, we just hit a certificate again...

If you have several authentication providers you will see the new SharePoint 2010 Sign In screen with a drop-down where you can choose the authentication provider you would like to use to log in with. If you only have one, in this case the WLID, you will be redirected to the WLID Log In screen - the same will happen if you select LiveID in the drop-down.

Signing in...

If you get an error stating We're unable to complete your request, like below, you most certainly have not used the correct Realm when creating the trusted identity provider using PowerShell. Make sure that the Realm and the DNS Name in the Live ID Service Manager are exactly the same, case sensitive and all.

Ooops, you made a mistake!

The Windows Live ID sign in screen should look as expected, just the same as logging in to other Live ID services. Enter your INT username and password (remember this is still the INT zone).

We're getting there

If you remembered your username and password correctly you will very soon see the beautiful SharePoint 2010 scenery:

Ahhh. So beatiful!

Note that your username and display name will be exactly the same as the unique id you have for that user. How to fix this is scheduled for a later post :)

Next steps

So, there you have it. It's a handful of steps to complete and you have to make sure not to mistype anything. I will continue this series with some more info that could be of great use when setting this up - hopefully not as long as this one though...

SharePoint 2010 and Visio 2010 - better together

Posted at 2010-09-06 07:52 by Wictor Wilén in SharePoint 2010 , Microsoft Visio with 0 comments.

This is the first post in a series about SharePoint 2010 and Visio 2010 and how the two products integrate with each other.

Viso Premium 2010I remember when I first saw Visio many, many years ago. It was before Microsoft acquired it from Visio Corporation. It was my dad using it to make blue prints of our summer house. As most of the gadgets and software he buys he needs a helping hand, not saying he is not technical, but I tend to catch up on such stuff faster than him, so I learnt the basics. I have used Visio since then, during my years in school and university and especially in my job as a developer and architect. (I have also made exact blue prints of our house, including the electrical wiring - call me crazy but I do love that product.) Visio is a great tool for technical diagrams and representations and extremely effective in drawing flowcharts and business processes.

It was with great joy that I last summer; when SharePoint 2010 and Visio 2010 was let out of the gates in Redmond saw how my two favorite products SharePoint and Visio finally found each other. Not only as a client integration, Visio was also a service application for SharePoint, called Visio Services. There was no longer need for an Active X control to view Visio drawings in the browser.

Visio 2010, part of the Office family, but not included in the Office suite is a diagramming, drawing and process modeling tool. The latest release of Visio includes new features such as for SharePoint integration, Business Process Modeling Notation and finally the Fluent user interface (aka the Ribbon and friends). Visio 2010 comes in three flavors Standard, Professional and Premium.

This series will cover most of the connection points between SharePoint 2010 and Visio 2010, starting with the demo friendly workflow creation using the Visio to SharePoint Designer 2010 integration. Then I will show you how to use the Visio client and service application to provide the end users with a visual snapshot representation of a SharePoint workflow. After that we will take a look on how you can use SharePoint 2010 as an effective storage for process diagrams before looking into the BI aspects of Visio Services.


This post was originally posted on EndUserSharePoint.com at http://www.endusersharepoint.com/2010/08/30/sharepoint-2010-and-visio-2010-better-together-part-1/

Understanding folders and namespaces in Visual Studio 2010 SharePoint Solutions, Packages and Features - part 2

Posted at 2010-09-04 04:11 by Wictor Wilén in Visual Studio , SharePoint 2010 with 0 comments.

This is a follow-up post to the Understanding folders and namespaces in Visual Studio 2010 SharePoint Solutions, Packages and Features (probably my longest blog post title, except this one...). In that post I discussed how folders and namespaces are handled in Visual Studio 2010 SharePoint projects. I will continue to show some details and tips on how you can affect the outcome of your project/packages.

Long feature folder names

As the previous post showed the features generated by Visual Studio ends up as a subfolder in the {SharePoint Root}\TEMPLATE\FEATURES folder. The feature folder will get the name as the concatenation of the project and the feature - which possibly can be quite long.

Autogenerated feature name

In the image above the project is called Wictor.Customer.Intranet.Services and the feature IntranetServicesWebParts. There is a good reason to have these auto generated names; it will avoid collisions of features. But if you are in control of the target farm you might consider having shorter names of your feature folders. This is easily done using Visual Studio;
Deployment PathOpen up the feature in the Feature Designer and select the Properties tool window. (Note you cannot right-click the feature(s) node in the Solution Explorer and select Properties - that will just give you the properties of the Visual Studio feature file.) If you take a look at the Deployment Path property you will see that it has a default value of:

$SharePoint.Project.FileNameWithoutExtension$_$SharePoint.Feature.FileNameWithoutExtension$

As you can see it uses the Visual Studio replaceable parameters to generate the feature folder name. Just edit this to something that fits your "style of coding". It can be a combination of strings and replaceable parameters. For instance this:

Intranet_$SharePoint.Feature.FileNameWithoutExtension$

will generate a feature folder like this:

Optimized feature folder name

Just remember that it is a reason that the default value of the feature folder name is a combo of the project and feature names.

Project Assemblies

By default all SharePoint projects in Visual Studio generates an assembly which is registered in the GAC when deployed. This is done even if we don't write a single line of compiled code. SharePoint allows you to do really neat stuff using only a declarative approach - such as adding content types, list templates, list instances etc. For these projects it is totally unnecessary to install an assembly in the GAC. Fortunately Visual Studio allows you to configure your project so no assembly is generated or rather included in the WSP package (an assembly will still be compiled and created but not deployed with the package).

If you have a fully declarative package and do not want to add an "empty" assembly to the GAC then you go to the Properties of the project (right-click the project node in the Solution Explorer for instance) and set the value of the Include Assembly In Package property to False.

No, I don't want any assembly this time...

Now when you package your solution no assembly will be created and you can deploy your solution using PowerShell without the -GACDeployment argument.

That's all for today - have a great weekend!

SharePoint 2010 August 2010 Cumulative Update makes User Profile Service Application inaccessible (Updated)

Posted at 2010-09-02 05:25 by Wictor Wilén in SharePoint 2010 with 10 comments.

UPDATED 2010-10-03: Obviously the KB2276339 is not a Aug CU hotfix KB2352342 is the correct one.

The second Cumulative Update (CU) is out for SharePoint 2010. It contains two hotfixes; one for Foundation and one for Server. The Foundation fix contains the really important update that should fix the problem with LINQ to SharePoint and anonymous users. You can get the fixes here:

Caution when installing hotfixes (as usual), they are not that thoroughly tested as Service Packs and only install them if you experience the problems mentioned in the KB articles. Nevertheless since this SPF hotfix contains the above mentioned fix for LINQ to SharePoint - this one is pretty important!

After installing the CU's you should have version 14.0.5123.5000.

SNAGHTML1e29fd7e

So, what's the problem I'm talking about?

UPDATE: The problem I and several others experienced is that the User Profile Service Application started generating errors. This was due to the fact that an incorrect hotfix for the August CU was floating around. So if you get these errors below, you know that you have installed the wrong hotfix.  (Question remains on what the KB2276339 does!)

CONTENT BELOW SHOULD BE CONSIDERED OBSOLETE
As the title of this blog post implies I have (once again) discovered a really nasty bug in the hotfix that makes your User Profile Service Application (UPA) inaccessible. After installing the binaries and upgraded the farm (including reboot and a very long wait for the content databases to update) this is what is presented when going to the UPA administration web page (ManageUserProfileServiceApplication.aspx):

image

File not found, correlation id...yup, you know what to do next. Just search the ULS logs for the correlation id and discover this sweet little error message:

UserProfileServiceUserStatisticsWebPart:LoadControl failed, Exception: System.IO.FileNotFoundException: Could not load file or assembly 
'Microsoft.ResourceManagement, Version=4.0.2450.11, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The system cannot find the file specified.
File name: 'Microsoft.ResourceManagement, Version=4.0.2450.11, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
at Microsoft.Office.Server.UserProfiles.UserProfileConfigManager.InitializeIlmClient(String ILMMachineName, Int32 FIMWebClientTimeOut)
at Microsoft.Office.Server.UserProfiles.UserProfileConfigManager..ctor(UserProfileApplicationProxy userProfileApplicationProxy, Guid partitionID)
at Microsoft.SharePoint.Portal.WebControls.UserProfileServiceStatisticsWebPartBase.LoadControl(Object sender, EventArgs e)
Ok, it cannot locate the Microsoft.ResourceManagement.dll assembly with this version number; 4.0.2450.11. And that's correct, the GAC does not contain that version of the assembly:

SNAGHTML1e2172cc

So where did the 4.0.2450.11 version of this assembly go then, I have no idea! But, if you take a look at the KB2276339 you will see that the pplwfe-x-none.msp package should contain just that specific assembly and version (.11). A search amongst the local files on the server also discovered that the assembly is located in two different locations, but not in the GAC:

  • C:\Program Files\Microsoft Office Servers\14.0\Synchronization Service\Bin
  • C:\Program Files\Microsoft Office Servers\14.0\Service

This assembly is required by the Microsoft.Office.Server.UserProfiles.dll, also present in the GAC.

UPDATE: Do not follow these steps, instead install the correct hotfix.

My first reaction was - just register the new assembly to the GAC and everything will be fine. But not! That really funks up the User Profile Service Application. You will see the user interface in Central Administration but the synchronization service will seriously fail and eventually refuse to start, with even more exceptions in the ULS and application logs.

So instead I decided to use some assembly redirection in Central Administration and forcing CA to use the older version of the assembly. This was done by editing the web.config of Central Administration and adding the following under the runtime/assemblyBinding element:


<dependentAssembly xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity name="Microsoft.ResourceManagement"
publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="4.0.2450.11" newVersion="4.0.2450.9" />
</< span>dependentAssembly>

As you can see I'm forcing Central Administration to use 4.0.2450.9 instead of 4.0.2450.11.

Once the web.config is saved the CA app pool will automatically be recycled and SharePoint, UPA and the profile sync should run as usual.

Interesting note: Also, looks like there is a lot of updates to User Profile Service Application in the Server hotfix, but no clues about that (except the files) in the KB!!!!

WARNING! This is not a tested or validated solution for this problem. It is an intermediate solution for experienced SharePoint administrators to temporarily work around the issues. I expect that an updated CU hotfix will be released as soon as possible.

Understanding folders and namespaces in Visual Studio 2010 SharePoint Solutions, Packages and Features

Posted at 2010-08-25 03:16 by Wictor Wilén in Visual Studio , SharePoint 2010 with 2 comments.

Yesterday Todd Bleeker (SharePoint MVP) wrote a post about the SharePoint Project SPI's where he explains how SPI effectively are folders within a SharePoint solution. I thought that I should continue that discussion a bit and looking at how these folders and other things such as packages and features affects the actual deployed artifacts.

Packages

Badly named project :-)A package (#3 in the figure to the right) is the actual WSP file that will be created containing all your objects from your solution that will deployed to the SharePoint application servers. The project can only contain one package.

The package is by default named as your project (#1), that is in this case it gets the name AnotherSharePointProject.wsp.

If you are using longer names on your projects, such as including client name, purpose of the project etc and  you feel it is to cumbersome to remember or type in when deploying. You can then use the Package designer to give it another name, without changing the project name. Double click on the package and edit the name in the Name textbox. Easily done!

Features

You use features (#2) to collect and target your artifacts to different scopes, such as Site Collection, Site or Farm. When you add an SPI to the project and you do not have any Features created; then Visual Studio creates a default one for you. What is important here is that each feature will be unpacked from the Package and copied to the SharePoint Root TEMPLATE\FEATURES folder on each SharePoint application server. FEATURE folderThe name of the folder will be a combination of your project name and the feature name. It will not use the name of the package. So for the sample in the image above it will be named AnotherSharePointProject_Feature1.

Once again long names can make this not look good and there are path name length restrictions (260 characters I believe, can anyone confirm). Remember that the path to the TEMPLATE folder is about 90 characters and you should have space left to place your SPI produced items within the folder as well.

SharePoint Project Items

As Todd describes in his post, each SPI is a contained within a folder (#4). The folder has the name of the SPI. And what's annoying is that the namespace of the SPI items is based on that folder name as well. So if you create a Web Part with the name WebPart5114, then the SPI will be called WebPart5114 as well as the folder, the class file and the Web Part class itself. This leads to a full name of the class like this: AnotherSharePointProject.WebPart5114.WebPart5114. I previously blogged about this (unfortunately bad) design which is not allowed through the code analysis without a warning (CA1724). Do not change the namespace unless you really know what you are doing!

Tip: you can workaround the namespace problem and write your own namespace, for instance for a Web Part. Just make sure that you update the Web Part Control Description file (.webpart), and even better use the [Guid] attribute and replaceable tokens in it like described in an earlier post, in case you change it again. (Should have been like that OOB IMHO.)

This SPI folder will end up beneath your Features folder in the SharePoint Root with the same name as the SPI, as in the figure below. The files in this example have an approximate path length of 150-160 characters.

SPIs in FEATURES folder

Renaming an SPI only affects the name of the SPI and the folder in the FEATURES folder. It does not change the namespaces or class names of a Web Part for instance.

Nested SPIsYou can also nest SPI's to group them better together or use project folders. Fortunately(?) this has no impact on the resulting files and folders in the FEATURES folder.

Summary

You should carefully think of how you are naming your projects, packages, features and SPIs. You should make sure that you change the name of your features so they are not called Feature1, Feature2 etc., since this will end up in the FEATURES folder and having thoughtfully selected names makes it easier to find information and troubleshoot problems.

How to create a SharePoint 2010 application using Visual Studio 2010 LightSwitch

Posted at 2010-08-23 01:39 by Wictor Wilén in Visual Studio , SharePoint 2010 with 4 comments.

Visual Studio 2010 LightSwitch is a new kid on the block in the Visual Studio suburbs. Basically it is a rich client application editor for Visual Studio that allows you to develop (or should I say "click-through") an application very easy without any programming skills at all. You can create a custom database, attach to an external data source or WCF RIA service and last but not least hook it up to SharePoint. And this is what I'm going to give you a quick peek at.

Install LightSwitch

First of all you need to install Visual Studio LightSwitch (I do not recommend to do it on your primary machine, as of now, since it is beta - I did it though). I failed a couple of times until I uninstalled the already existing pre-requisite WCF RIA Services and re-tried the LightSwitch installation.

Installing LightSwitch

Create a LightSwitch application

Once it is installed you are ready to create your first application. Start Visual Studio! LightSwitch installs as a project template in Visual Studio if you already have it installed. Select to create a LightSwitch project using one of your favorite languages; C# or Visual Basic. We're going for C# here (even though we're not going to write a single line of code...).

LightSwitch project templates

If you have been building SharePoint 2010 solutions previously using Visual Studio, your Framework dropdown is most certainly set to .NET Framework 3.5. Switch that to 4.0 to see the project templates for LightSwitch.

Connect to your data source

Connect to data sourceOnce your project is created by Visual Studio you have the option to create a new data source or connect to an existing. Since we will connect this application to SharePoint; select Attach to external database.

You will then be presented with a wizard where you can choose the type of data source you would like to connect to. You have the following options; Database, SharePoint and WCF RIA Service. We'll go for SharePoint, of course!

LightSwitch data sources

SharePoint ListsNext you have to provide the address to the SharePoint site you would like to connect to and how you are going to log in (current credentials or custom). After clicking Next (it's a lot of next-next) you will see all the available lists in the SharePoint site you specified.

Choose the list or lists that you want to use in your LightSwitch application, as in the image to the right.  When you are done click Finish to complete the wizard. If you have tables using lookups you will get a warning that says it will include these lists in your app as well. As the matter of fact you will always get this warning for SharePoint data sources since all lists contains created by and modified by which are connected to the user information list. Accept the warning by clicking Continue. Depending on how your lists are built you can get other warnings here as well, read the thoroughly and act accordingly.

When the wizard is finished you will see the designer of your application (see image below). You will see all the lists (tables) and the relationships between them. You can also configure the tables and relationships here. For instance you can configure validations and appearance.

image

If you need to add filters, sorting or parameters to the lists this is done by clicking on the Query toolbar button. Also if you want additional columns you can use the Computed Property toolbar button to add custom columns. You can then calculate these in your code behind for the app (but no code this time as I earlier said).

We will make a small change here and change the default property of the user information list. Double click on the UserInformationList entity in the designer and then select the entity and view the properties (F4). As you can see in the Appearance group, the default property is the ContentType column, duh!. Change that to Name instead.

Properties of a LightSwitch entity

Build the interface

LightSwitch UI templatesSo now you have the data and you need some interface for this. It's just as easy as clicking on Screen toolbar button. When this button is clicked you will see a dialog that allows you to choose from a set of pre-defined interface templates. In this case we select the List and Details Screen. Then in the Screen Data drop-down select the data source which should be the list (or one of the lists) that you choose in the wizard. Also check the checkboxes to include additional data and finally click OK.

When Visual Studio has finished loading you will see a hierarchical view of the interface - very much like the control tree of a WPF application. Depending on which template that was previously selected the default control tree looks different. It is this control tree that controls the magic of LightSwitch.

LightSwitch control tree

Change column in LightSwitchTo customize the default experience a bit we'll do a small change to the application. The selected data source only shows the Summary Property of the items (just as we changed for the user information list). To show all columns instead it is as easy as switching the Sales node of the left column from Summary to a horizontal stack. LightSwitch will then add controls in the tree for all the columns in the list. You can then of course remove those you don't want in the list.

Take it for a test drive

I think we are good for a test drive now. Hit F5 and wait for your brand new application to start. Voila!

Done!

You can now easily browse the list and check out the details of each item. You can even edit the rows and persist the changes back to SharePoint.

Conclusion

So what's the big deal here? LightSwitch allows you to very easy and fast create an application (using this even Todd Klindt can call himself a developer).

But. There is always a but..

Even though Microsoft is all in for LightSwitch, I have hard to see where it actually fits. It's a little bit to "technical" to let this app loose amongst your business users and far to LightWeight for an advanced developer. We've seen how easy it is to do the same thing in Silverlight or WPF. Under the hood LightSwitch uses the SharePoint REST services (/_vti_bin/listdata.svc) so basically any other "data-wizard" in Visual Studio can do the same magic. It very much feels like a hybrid of Access and Visual Studio and I would have preferred to see this integrated to Access than into Visual Studio - that would (IMHO) be a far better experience for business users.

Then we have another problem with these kind of apps (just like Excel, Access etc) - if the users adopt this tool they will create another stack of data sources (if they don't use SharePoint as data source and instead create new ones) that eventually becomes necessary for the business - which leads to that they must be backed up, migrated, integrated, you name it into SharePoint or other systems.

As of now I can't see the business case for a professional developer to use this tool. But it's ok - and for some it looks like magic...perhaps it might be used as a prototyping tool?!

Upcoming speaking engagements - Stockholm to Singapore

Posted at 2010-08-10 11:58 by Wictor Wilén in SharePoint 2010 , Presentations with 0 comments.

Summer is not yet over (at least not according to the calendar) and this autumn is already being planned and filled with some great stuff. Part from working on a great SharePoint 2010 project, waiting for the book to be ready and some other stuff I also have planned a few speaking events - which I'm really thrilled about.

SharePoint and Exchange Forum 2010

Stockholm - 18th-19th October

SharePoint and Exchange Forum 2010For the second consecutive year I will speak at the largest SharePoint and Exchange event in Scandinavia, arranged by my good friend and SharePoint MVP Göran Husman - the SharePoint Exchange Forum 2010 (#SEF). I will do a session called Playing in the Sandbox where I discuss the SharePoint 2010 Sandbox and how you can use it and how it affect you as a developer.
There will be a lot of good speakers and great content - and if you're around I hope to see you there!

Southeast Asia SharePoint Conference 2010

Singapore  - 26th-27th October

Southeast Asia SharePoint Conference 2010I will be travelling down to Singapore for the Southeast Asia SharePoint Conference (#SPCSEA) and do two sessions about SharePoint 2010 - Playing in the Sandbox and SharePoint and Silverlight - new BFFs. This is a great event organized by Steve Sofian (MVP), Randy Williams (MVP) and Debbie Ireland. This will be the conference to attend to in the Southeast Asia if you are in to SharePoint! Early bid is only $SGD 300 - so hurry!
I'm really looking to this event and to meet up with the great lineup of speakers ranging from local experts and MVPs to international SharePoint superstars.
For you attending - how about a SharePint at Raffles?

That's what I have planned for now. And for sure you will see me at some upcoming local SharePoint User Group meetings.

About the SharePoint 2010 certifications

Posted at 2010-08-09 01:04 by Wictor Wilén in SharePoint , SharePoint 2010 with 6 comments.

A little more than a year ago I wrote a post after finishing all four SharePoint 2007 exams called "70-640 passed! Do you really call this a certification!". I thouht the exams were to easy and did not say much about your SharePoint skills at all and I had hopes for the new SharePoint 2010 exams. I did hope that they would stop focusing on IntelliSense and API knowledge and more focus on best practices, design decisions and problem solving. Unfortunately I can't say that my hopes became reality.

The SharePoint 2010 exams have been improved (apart from focusing on 2010 instead of 2007). Instead of having four Technical Specialist (TS) exams and focusing on SKU's, there are now two Technical Specialist exams and two Professional exams (MCPD and MCITP). One track for developers and one for IT-professionals, see image below. To achieve the Professional titles you have to succeed on the TS exams first.

SharePoint 2010 certifications

The TS exams (573 & 667) are just as bad as previously, even though the Configuring (667) exam is slightly better. The PRO exams (576 & 668) on the other hand are actually worth (at least) something, especially the Administrator (668) - which I think is the most interesting of them all.

I did all four of these exams during the beta period, in which some questions were really weird and dubious. For the 573 exam (Intellisense exam) I had the great joy of taking it twice - beta and final release, due to that Prometric "lost" my exam and then claiming I did not show up (even though I got a receipt for it).

No show!

So why taking these exams you might think? Some people I know refuse to take them just because they are to easy and they say nothing about your skills. But for me there are many reasons for this. First of all I am a consultant. Many clients I meet have no idea about SharePoint and its technology - having a few certifications to show opens the door faster and they believe in the validity of the certifications. Secondly I am a Microsoft Certified Trainer (MCT) - some classes requires that you have the certifications and most students take the classes to later take the exams - then I think it's good to know what the exams contains. There are more reasons for taking them such as your company will get Microsoft Partner points, some companies also pay a bonus for achieving new titles, you need them to even apply for the Certified Masters program etc etc, the list can go on. I think that you should at least try them - you might even learn something!

To sum it up - if you're into the SharePoint business - there is no harm in taking these exams. You could do it the easy and fast way as Bjørn Furuknap shows or you can do it because you want to learn more about the amazing product SharePoint. The first SharePoint exams that I took really gave me time (forced me) to study on all areas of SharePoint (workflow is still my weakness, got to read Phil Wicklunds book about it soon).

So this is my 2 cents (or ören as we say in Sweden) of these exams - and here I am with nine different SharePoint exams (TS in SharePoint 2003, 4x TS in SharePoint 2007 and 2x TS plus 2x PRO in SharePoint 2010). And I like it!

Minifying custom JavaScript files in SharePoint 2010

Posted at 2010-08-07 06:01 by Wictor Wilén in Visual Studio , Scripting , AJAX , SharePoint 2010 with 2 comments.

As you know the usage of JavaScript has been more and more used in web applications over the past years for technologies such as AJAX. JavaScript can accomplish really cool stuff on the client side and make the user interface more interactive and responsive. Just take a look at SharePoint 2010 - that's some heavy JavaScripts there (a bit to heavy IMHO).

So lets assume that you are building some new cool stuff, in SharePoint of course, and why not a Page Component for a contextual Web Part. That's a lot of JavaScript (apart from the server side XML chunks)! So now you are making your web page payload even heavier. This is when minifying comes in. Minifying is a way to minimize the payload of a resource such as removing unnecessary comments and whitespace, shortening function and variable names etc - all to make the payload as small as possible. The only problem with these minified scripts are that they are virtually impossible to debug (and believe me if you are building a Page Component for SharePoint - you need to debug).

If you have noticed SharePoint 2010 supports production and debug JavaScripts side-by-side. When you are debugging your SharePoint site you will see that all JavaScript files have a name like SP.debug.js, SP.Ribbon.debug.js etc. These are files that you actually can debug (even though they are obfuscated somewhat). All this is thanks to the SharePoint ScriptLink control which loads the production or debug version depending on if you are debugging or not.

To use minified JavaScrips (or CSS files) in your SharePoint 2010 solutions you can do it easy with the Microsoft Ajax Minifier 4.0 and a pre-build event in Visual Studio 2010. Just follow these simple steps when you have installed the Minifier.

Layouts folderCreate a new SharePoint 2010 project (farm solution - ScriptLink is not supported in the Sandbox)and then add the Layouts SharePoint Mapped folder to the project. Add two empty JavaScript files to the folder that is created. One with the .js extension and one ending with debug.js.

Add some smart JavaScript code to the debug.js file - this is the file that you will edit from now on. The .js file will automatically be updated with the minified code. Then head on over to Project Properties and the Build Events tab. In the pre-build event enter the following:

"C:\Program Files (x86)\Microsoft\Microsoft Ajax Minifier 4\ajaxmin.exe" 
    -JS $(ProjectDir)\Layouts\Wictor.Minified\TheScript.debug.js 
    -out $(ProjectDir)\Layouts\Wictor.Minified\TheScript.js  
    -CLOBBER

This will before building the project invoke the Ajax Minifier and create/update the minified JavaScript file. The -CLOBBER option allows the minifier to overwrite existing files. Replace the file name and folder with your file name and folder.

Then add a Visual Web Part to your project and add code as follows:

<SharePoint:ScriptLink runat="server" Name="Wictor.Minified/TheScript.js" Localizable="false"/>
<asp:Button runat="server" Text="Click me!" OnClientClick="thisIsMyFunction('Hello mini!');" />

The ScriptLink control will load the correct version of the script. Notice that you do not specify the debug version. Also Localizable is set to false here, since this is not a localized JavaScript (the Ajax Minifier actually supports localization of your JavaScripts - cool huh).

Make sure that your SharePoint web application does not have debugging configured in the web.config and hit Ctrl-F5. This will start Internet Explorer and you can add the Web Part to a page. Then take a look at the source and look for your script. It should look something like this.

Uses minified JavaScript file
Then you go back to Visual Studio and compare the two JavaScript files. In my case it looks like this:

Visual Studio 2010 comparing JavaScript files

The debug JavaScript is 380 characters and the minified is only 147!

Then hit F5 to run the project in debug mode and inspect the source of the page. You can now see that the debug version is loaded.

And now in debug mode...

That's it! Simple! Now go on minifying!

Nifty trick with Visual Studio 2010 replaceable parameters for SharePoint 2010 Web Parts

Posted at 2010-08-03 01:38 by Wictor Wilén in Visual Studio , Web Parts , SharePoint 2010 with 2 comments.

MP900408848[1]If you have been working with SharePoint 2010 development using Visual Studio 2010 you have most certainly stumbled upon the new replaceable parameters that replaces data in your solution files during the packaging process. For instance Visual Studio uses $SharePoint.Project.AssemblyFullName$ in the Web Part control description (.webpart) files and this is replaced with the assembly full name (strong name) during packaging. By default it looks like this when you create a new Web Part:

<type name="Project.MyWebPart, $SharePoint.Project.AssemblyFullName$" />

After the packaging and when deployed into SharePoint it looks like this:

<type name="Project.MyWebPart, Project, Version=1.0.0.0, Culture=neutral, PublicKeyToken=54c0c201dd8d1c31" />

This saves you some time when changing versions etc of the assembly.

But what about if you change the name of the class or the namespace, then you have to rename a whole lot of things; the CS file, the .webpart file, optionally the element manifest and of course all references. A better way is to use another replaceable parameter that replaces the token with the full name of the type. First of all you need to specify a Guid attribute on the type (Web Part class in this case) like this:

[ToolboxItemAttribute(false)]
[Guid("A4D3BE9B-E2D6-42A4-B4F9-D78911C214E8")]
public class MyWebPart : WebPart{...}

Then you update the .webpart file to use the replaceable parameter that has the format of:

$SharePoint.Type.GUID.FullName$

The GUID must be lower-case and your updated .webpart file should look like this after copying the Guid value from the attribute:

<type name="$SharePoint.Type.a4d3be9b-e2d6-42a4-b4f9-d78911c214e8.FullName$, $SharePoint.Project.AssemblyFullName$" />

Visual Studio 2010 will now replace this during runtime with whatever you Web Part class name and namespace is, so you can feel safe renaming and refactoring.

Even better is that this works for all other cases where you need to reference a type in an element manifest, user control or similar. Out-of-the-box the following file types will be parsed and parameters replaced; XML, webpart, DWP, ASCX and ASPX. For instance you might have added a event receiver for a content type - just add the same two tokens used in the sample above in the Assembly and Class elements of the Receiver element.

SharePoint 2010 June 2010 Cumulative Update installation failed

Posted at 2010-07-30 01:05 by Wictor Wilén in SharePoint 2010 with 1 comments.

PatchingI have been updating a couple of SharePoint 2010 servers and farms to the latest June 2010 Cumulative Update (CU) as well as installing a slipstreamed package. The slipstreamed install worked flawless using the same technique as with SharePoint 2007. But patching some of my servers seriously failed on both Windows Server 2008 R2 and Windows 7 with both SharePoint Foundation 2010 and SharePoint Server 2010. Here are some of my experiences of the patching.

Reboot required

Even though all June 2010 CU knowledge base articles says that a reboot is not required after applying the patches I indeed was required to boot after applying KB2028568 and KB983497 respectively. This doesn't bother me more than that it should have been told in the KB article. I don't know why I had to reboot and have not either tried to figure out why. It can have something to do with my configurations (even though I tried it on several different ones). Just reboot before running the SharePoint Configuration Wizard or psconfig and you will fine (almost - continue reading..).

Configuration Wizard fails

After rebooting the machines the troubles really started for me. I started the Configuration Wizard and it let me know that I needed to update so I went ahead. It starts going through the steps and on the final step where it usually takes some time it failed after a while. I opened up the PSCONFIG log files and found the following errors noted:

The exclusive inplace upgrader timer job failed.

Followed by:

An exception of type System.InvalidOperationException was thrown.  Additional exception information: Cannot open SPTimerV4 service on computer '.'.
System.InvalidOperationException: Cannot open SPTimerV4 service on computer '.'. ---> System.ComponentModel.Win32Exception: Access is denied
   --- End of inner exception stack trace ---
   at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
   at System.ServiceProcess.ServiceController.Stop()
   at Microsoft.SharePoint.PostSetupConfiguration.ServiceHelper.Stop(String serviceName)

I can't say I hate error messages, contrary it gives me a challenge :-). Thankfully I had taken backups and even made snapshots just before updating the servers. The first thing I that came to my mind was that I was using a Farm administrators account to do this - but it was not the account that actually installed SharePoint 2010. As you know it is recommended to always have a separate account that you use for installation, patching and updating - and for nothing else. So I rolled back to where my snapshot was taken and used my install account instead - same error! Hmmm. Then I fired up another virtual machine - which also is a "least privilege" install of SharePoint and tried updating it - same error! Ok, now this is getting annoying! Tried updating SharePoint Foundation on my laptop - same error! @$$80!3 (censored)

After a lot of retries, Binging and chatting with some of the brightest. I run the Configuration Wizard again and even psconfig using the force argument (to see if I could see any difference). For one of the servers the Configuration Wizard actually completed. Yes! I went to Central Administration and unfortunately it reported that the server needed an upgrade. Back to square one! I also noticed the following in the PSCONFIG log file:

An exception of type System.InvalidOperationException was thrown.  Additional exception information: Cannot open SPTimerV4 service on computer '.'.
System.InvalidOperationException: Cannot open SPTimerV4 service on computer '.'. ---> System.ComponentModel.Win32Exception: Access is denied
   --- End of inner exception stack trace ---
   at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
   at System.ServiceProcess.ServiceController.Stop()
   at Microsoft.SharePoint.PostSetupConfiguration.ServiceHelper.Stop(String serviceName)
   at Microsoft.SharePoint.PostSetupConfiguration.InitializeTask.StopServicesListedInRegistry(RegistryHelper registry, Boolean disableService)
   at Microsoft.SharePoint.PostSetupConfiguration.InitializeTask.StopAllServices()
   at Microsoft.SharePoint.PostSetupConfiguration.InitializeTask.Validate(Int32 nextExecutionOrder)
   at Microsoft.SharePoint.PostSetupConfiguration.TasksQueue.Validate(Boolean useDefaultExecutionOrder)

By the looks of the error messages this must have something to do with security. I verified that all accounts had the correct permissions, was correctly configured etc.

User Account Control is the culprit!

Finally I installed the CU on a server where I did not use a plethora of service accounts but instead used the domain admin to run SharePoint and that update worked like a charm. In Windows Server 2008 R2 the built-in Administrators account by default have User Account Control (UAC) disabled.

I went back to the other servers, disabled the UAC and repeated the update procedure using the installation account - and it worked flawlessly! Did the same procedure on another machine, and it worked there to.

Without to must investigation I assume that the account running the timer jobs is performing tasks that fires up the UAC. But since that is a non-interactive session you are not able to allow the operation.

So in order to get your CU (or other updates for that matter) for SharePoint 2010 to install correctly I recommend you to disable the User Account Control for you service accounts.

Anyone with similar experiences or comments to this?

How to provision SharePoint 2010 Rating columns in Content Types

Posted at 2010-07-28 06:43 by Wictor Wilén in SharePoint 2010 with 2 comments.

This post continues in the same neighborhood as yesterdays post about provisioning Managed Metadata columns. This time we take a look at the Ratings in lists (and while we're at it check out another earlier post about how to customize the look and feel of ratings).

The ratings allows anybody to rate items in lists and libraries in SharePoint 2010 Server. This is another highly usable and awesome feature tied to the Managed Metadata Service Application (MMS). To turn on ratings on a list you normally go to Library/List Settings > Rating Settings.

Rating Settings

When you enable this on a list or a library SharePoint adds two columns to your list called:

  • Rating (0-5)
  • Number of Ratings

But what do you do if you want to provision the rating with your Content Types and solution packages? It is quite simple - the only thing you have to do is to add the two rating columns to your content type.

How do I do it?

To create a content type with rating enabled create a new Empty SharePoint project in Visual Studio 2010 and add a new Content Type project item. Select a content type to derive your new content type from. Once the item is added then you will see the content type XML manifest. Add the following FieldRef elements which represents the rating site columns needed to enable rating.

<FieldRefs>
  <FieldRef ID="{5a14d1ab-1513-48c7-97b3-657a5ba6c742}" Name="AverageRating" />
  <FieldRef ID="{b1996002-9167-45e5-a4df-b2c41c6723c7}" Name="RatingCount" />
</FieldRefs>

Add a new item to the project of the type List Definition from Content Type and use your newly created content type. Also check the checkbox to create a list instance. Then deploy your solution (F5) to SharePoint and navigate to the new list that should have been created. If you create a new list item or upload a document you will see that the Rating has been enabled.

Ratings enabled for Content Type and list

You can also check the Rating Settings for the list or the library and verify that Ratings has been enabled.

Did you ever think that something could be that easy in SharePoint?

How to provision SharePoint 2010 Managed Metadata columns

Posted at 2010-07-27 03:57 by Wictor Wilén in SharePoint 2010 with 8 comments.

This post will show you how to provision Site Columns that uses Managed Metadata in SharePoint 2010. Managed Metadata is one of the new and exciting features of SharePoint Server 2010. It allows you to centrally manage metadata terms and keywords. Creating Managed Metadata columns using the SharePoint web interface is a simple task but the problem is that it does not allow you to move your Site Columns from one farm to another that easily. The reason is that these Site Columns definitions contains references to the unique IDs of the terms in the current Managed Metadata Service Application (MMS).

Exporting Site Columns

If you export a Managed Metadata Column and a Content Type using it to Visual Studio (SharePoint Designer > Export > Visual Studio Import, you know the drill) then you end up with definitions like below.

The Site Column is based on the TaxonomyFieldType and contains a Customization element which contains an array of properties (I've omitted most of them here). These properties contains IDs of the Managed Metadata group, term store and service application. Since these are unique for each MMS this definition cannot be provisioned to another farm (for instance from dev to stage, stage to prod etc).

<Field 
    Type="TaxonomyFieldType" 
    DisplayName="Custom (web)" 
    List="Lists/TaxonomyHiddenList" 
    WebId="~sitecollection" 
    ShowField="Term1033" 
    Required="FALSE" 
    EnforceUniqueValues="FALSE" 
    Group="_Custom" 
    ID="{fce6a8e2-23e8-49c2-9bad-a534555296bb}" 
    SourceID="{5e68c9eb-5efe-4bcc-b8db-93d38d797fbe}" 
    StaticName="__Custom" 
    Name="__Custom" 
    Overwrite="TRUE">
    <Default />
    <Customization>
        <ArrayOfProperty>
            <Property>
                <Name>SspId</Name>
                <Value 
                    xmlns:q1="http://www.w3.org/2001/XMLSchema" 
                    p4:type="q1:string" 
                    xmlns:p4="http://www.w3.org/2001/XMLSchema-instance">b98dd270-8577-4db8-99e1-b9e894624fdb
                </Value>
            </Property>
            <Property>
                <Name>GroupId</Name>
            </Property>
            <Property>
                <Name>TermSetId</Name>
                <Value 
                    xmlns:q2="http://www.w3.org/2001/XMLSchema" 
                    p4:type="q2:string" 
                    xmlns:p4="http://www.w3.org/2001/XMLSchema-instance">b7ae10cd-6c7c-4386-a1f2-7abec8e759e1
                </Value>
            </Property>
            <Property>
                <Name>AnchorId</Name>
                <Value 
                    xmlns:q3="http://www.w3.org/2001/XMLSchema" 
                    p4:type="q3:string" 
                    xmlns:p4="http://www.w3.org/2001/XMLSchema-instance">00000000-0000-0000-0000-000000000000
                </Value>
            </Property>
            ...
        </ArrayOfProperty>
    </Customization>
</Field>
     

And if you examine the XML further you will also notice that a second field is defined for this Site Column. This field is of the type Note and is hidden.

<Field Type="Note" DisplayName="__Custom_0" StaticName="__CustomTaxHTField0" Name="__CustomTaxHTField0" 
    ID="{a6eae615-9835-4b75-97bf-d4e7a938b892}" ShowInViewForms="FALSE" Required="FALSE"     Hidden="TRUE" CanToggleHidden="TRUE" 
    SourceID="{5e68c9eb-5efe-4bcc-b8db-93d38d797fbe}" Overwrite="TRUE" />

A lot of XML but quite useless for reuse...

So how do I do then?

To provision the Site Columns and Content Types without these hardcoded Guids and IDs you basically have two options:

  1. Create an event receiver (or similar) that creates the Site Columns and Content Types programmatically
  2. A combination of declarative and the programmatic approach above

Solution ExplorerI prefer the second approach and I will show you how to do it (the first one can quite easily be done based on the code that will follow).

First you need to create a new SharePoint 2010 project in Visual Studio 2010, create a new Empty SharePoint project. Then add a new Content Type SharePoint Project Item (SPI) to the project and inherit it from the Item content type. Then add a new XML file to the SPI and name it Fields.xml. This elements manifest will contain the Site Column definition, but in order to make it into a manifest file you need to select the file and press F4 to edit the properties of the file. Change the Deplyment Type from NoDeployment to ElementManifest. Your solution should look like the image to the right. Also make sure to set the feature to be scoped to Site (Site Collection) level - we're talking about deploying Site Columns and Content Types here.

Then it is time to write the declarative part (i.e. the XML). You need to add a new Field element of the type TaxonomyFieldType (or TaxonomyFieldTypeMulti). Configure it as follows or as it suits your needs. Notice that I have set the ShowField attribute to Term1033, this is needed by the MMS to select the correct term value.

xml version="1.0" encoding="utf-8" ?> 
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"> 
  <Field ID="{749DA0D1-4649-4C25-871B-05F0C07221FC}" 
    Type="TaxonomyFieldType" 
    DisplayName="Home Country" 
    ShowField="Term1033" 
    Required="TRUE" 
    EnforceUniqueValues="FALSE" 
    Group="_Custom" 
    StaticName="HomeCountry" 
    Name="HomeCountry" 
     /> 
</Elements>

To add this field to the content type there is no rocket science, just do as you normally do:

<FieldRef ID="{749DA0D1-4649-4C25-871B-05F0C07221FC}" Name="HomeCountry"/>

That's all that you can do declarative. If this would be deployed a field would be created of the type Managed Metadata but you have to manually connect it to the MMS.

Now we have to dig into some programming to connect the field to the MMS. This is done in an Event Receiver for the feature. Right-click the feature and select Add Event Receiver. Uncomment the FeatureActivated method and implement it as follows:

public override void FeatureActivated(SPFeatureReceiverProperties properties) { 
    SPSite site = properties.Feature.Parent as SPSite; 
    Guid fieldId = new Guid("{749DA0D1-4649-4C25-871B-05F0C07221FC}"); 
    if (site.RootWeb.Fields.Contains(fieldId)) { 
        TaxonomySession session = new TaxonomySession(site);

        if (session.TermStores.Count != 0) { 
            var termStore = session.TermStores["Managed Metadata Service"]; 
            var group = termStore.Groups.GetByName("Wictors Group"); 
            var termSet = group.TermSets["Countries"];

            TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField;

            // Connect to MMS 
            field.SspId = termSet.TermStore.Id; 
            field.TermSetId = termSet.Id; 
            field.TargetTemplate = string.Empty; 
            field.AnchorId = Guid.Empty; 
            field.Update(); 
        } 
    } 
}

MMS configurationThis method will first check if the field has been deployed. The field is retrieved using the Guid of the Field, defined in the XML. Once that is confirmed that the field exists a TaxonomySession object is acquired using the SPSite object. The TaxonomySession object is declared in the Microsoft.SharePoint.Taxonomy assembly - so you have to add a reference to that assembly first. To connect the field to the MMS you need to retrieve the Term Store, Group and Term Set. All this is done using the names of them as defined in the MMS. The image to the right shows how the MMS looks like that this code is connecting the field to. It is very likely that you have the same structure of the MMS in your different environments - if not you have to come up with a more configurable way :-)

Note the GetByName method used above is a custom extension that looks like this:

public static Group GetByName(this GroupCollection groupCollection, string name) { 
    if (String.IsNullOrEmpty(name)) { 
        throw new ArgumentException("Not a valid group name", "name"); 
    } 
    foreach (var group in groupCollection) { 
        if (group.Name == name) { 
            return group; 
        } 
    } 
    throw new ArgumentOutOfRangeException("name", name, "Could not find the group"); 
}

Once you have a hold on the taxonomy objects then it is time to convert the Field to a TaxonomyField object. This object is then configured with a set of properties. Specifically the ID of the Term Store and Term Set is set. Finally the field is updated to reflect the changes.

The Result!

That's it. All you now have to do is deploy it and test it out.

Final result

SharePoint 2010 June 2010 cumulative update

Posted at 2010-07-23 03:18 by Wictor Wilén in SharePoint 2010 with 2 comments.

The first cumulative update (CU) for SharePoint 2010 is here. The CU was promised in to be ready in June, but have not arrived until a couple of days ago. I've been on vacation (last day today actually) so it fits perfect starting out next week with patching some farms.

As you probably know by now the Microsoft SharePoint Team has improved the update cycle a bit compared to its predecessor. If you are not aware of the changes or need to get up to speed on the differences head on over to TechNet and read the following articles:

You can also always find the latest patch information for SharePoint at the TechNet Updates fro SharePoint 2010 Products page.

The June CU consist of the following KB articles and downloads:

  • SharePoint Foundation 2010 hotfix package (STS-x-none.msp), KB2028568
    Patch for SharePoint Foundation
  • SharePoint Server 2010 hotfix package (Osrchwfe-x-none.msp, Pplwfe-x-none.msp, Spswfe-x-none.msp), KB983497
    Patch for SharePoint Server
  • SharePoint Server 2010 hotfix package (Filterpack-x-none.msp), KB2124512
    Patch for SharePoint Server search filters
  • SharePoint Server 2010 hotfix package (osrchmui-ja-jp.msp, osrchmui-ko-kr.msp, osrchmui-zh-cn.msp, osrchmui-zh-tw.msp), KB2182938
    Japanese, Chinese and Korean SharePoint Server patch only
  • Search Server 2010 hotfix package (Word-x-none.msp), KB983319
    Search Server patch
  • SharePoint Server 2010 hotfix, KB2281364
    KB not live yet but you can request hotfix here.

In the Server package (KB983497) there are several fixes for the User Profile Service Application that you really need to install!

Prior to this CU Microsoft also released an update for SharePoint Foundation KB2032588. The following screenshot is from an SPF site before applying the June 2010 CU:

SNAGHTMLa495c48

After patching you should see that the new version number is 14.0000.5114.5003. Also notice how the update has been superseded by the CU.

SNAGHTMLa55ea54

SharePoint 2010 Web Parts in Action - 15 chapters

Posted at 2010-06-25 02:04 by Wictor Wilén in SharePoint 2010 , SharePoint 2010 Web Parts in Action with 0 comments.

wilen_cover150

After about six months of writing I have now written a total of 400 pages and 15 chapters about SharePoint 2010 Web Parts for my book called SharePoint 2010 Web Parts in Action. This is a book focusing on Web Part development in SharePoint 2010 and I think that it covers all that is needed for developers who wants to enhance their SharePoint 2010 and Web Parts development skills.

The chapters are:

  1. Introducing SharePoint 2010 Web Parts
  2. Using and configuring Web Parts in SharePoint 2010
  3. Building Web Parts with Visual Studio 2010
  4. Building the user interface
  5. Making Web Parts customizable
  6. Web Part resources and configuration
  7. Packaging, Deployment and Security
  8. Tools for troubleshooting and logging
  9. Caching for performance
  10. Dynamic interfaces in Web Parts
  11. Client Object Model and Silverlight Web Parts
  12. Making Web Parts Mobile
  13. Web Part design Patterns
  14. Connecting Web Parts
  15. Building Pages and Dashboards

I have submitted all my chapters to my publisher (Manning) and I am waiting for the final technical review of it before I can let it go (for this time). Once I have reviewed the reviews the book will be sent to typesetting and then it will be on the way to the printers. You will see the book in your closest book shop during this fall.

But, if you are interested you can actually grab the preview pieces of it right now. Manning has an Early-Access program (MEAP) that allows you to purchase the book right away as a preview e-Book and once the book is hot from the presses it will be sent to you. Head on over to http://www.manning.com/wilen to get your copy. Currently there are the first seven chapters available with two more on the way. If you do get it and you have feedback on it, contact me or discuss it at the Manning Sandbox forums.

While some really smart guys are doing the review, I'm shutting down for a while for a long awaited vacation. See you on the other side...

(written using the new Windows Live Writer beta...)

Real Time Web Analytics