Archives

Archives / 2010
  • Summing up the year of 2010 and embracing 2011

    Tags: Personal, SharePoint 2010, SharePoint 2010 Web Parts in Action

    The time has come for me to do my summary post of 2010. This is my fifth summary post (2006, 2007, 2008 and 2009). This year has been truly amazing. Working in the SharePoint world has been so interesting and challenging with the brand new Office 2010 and SharePoint 2010 products.

    I have been knee-deep in SharePoint 2010 work both for my employer (Connecta) and for personal reasons (pure fun, book, learning...). A huge thanks to my wife and daughters that can put up with my constant chatter about this obscure thingie...

    As previous years let's sum up my year in a few sections.

    Blogging, books and other writings

    My blogging activities has been going up and down this year, but I think this year I have produced quite a few gems. I've seen the number of visitors steadily grow this year with about 700.000+ hits per month nowadays. The most popular posts of this year are the following ones:

    1. Create SharePoint 2010 Managed Metadata with Excel 2010 - the #1 hit this year. This post is also referenced in several TechNet/MSDN articles.
    2. Creating a SharePoint 2010 Ribbon extension - part 1 - I learned a lot while writing this
    3. Creating custom themable CSS files for SharePoint 2010 - really cool branding feature of SP2010
    4. How to provision SharePoint 2010 Managed Metadata columns - needed to document this...
    5. Visual guide to Windows Live ID authentication with SharePoint 2010 - part 1- my personal favorite and the one which took me the longest time to finish
    6. Creating a SharePoint 2010 Ribbon extension - part 2 - continuation of #2
    7. Plan your SharePoint 2010 Content Type Hub carefully - trial and error
    8. Local SharePoint 2010 development on Windows 7 - awesome experience - not everyone agree, but I still love doing POC's and tests on Win7
    9. Custom application pages in the SharePoint 2010 Sandbox - I needed to do this, and why not write about it
    10. Working with SharePoint 2010 Correlation ID in PowerShell and code - nice features of SP2010

    SharePoint 2010 Web Parts in ActionPart from blogging I've been writing on my book; SharePoint 2010 Web Parts in Action. It was not released this year as planned but watch out for an early release in 2011. I'm not going to write more about it now - that deserves its own post.

    Except for writing on my own blog and the book I also produced a series about Visio 2010 and SharePoint 2010 for EndUserSharePoint.com, nowadays NothingButSharePoint.com - check it out. I still have a couple of posts to complete, so keep an eye out for them. I also wrote an article for the 2nd edition of the DIWUG SharePoint eMagazine about the new SharePoint 2010 themes - download it here.

    SharePoint MVP

    MVPA personal and professional highlight of this year was of course when I was awarded with the prestigious SharePoint Server MVP award. April the 1st this year I got an e-mail that made me choke and burst out in joy. Hopefully I can keep this award for quite some time. Being a Microsoft MVP has really given me some great opportunities to meet new people and talk SharePoint with a bunch of extremely talented people - I really look forward to the MVP summit in a few months.

    Speaking engagements

    One thing I enjoy is to talk about things I like - SharePoint for instance. This year I continued to deliver quite a few sessions on several occasions:

    Looking forward to next year, hopefully I get invited to some more international conferences...

    Last year predictions

    Last years summary post contained a few predictions for 2010 - and all of them fell in. "Microsoft will have something extraordinary coming in Windows Mobile 7" - Windows Phone 7 was released! "Another thing we will see starting emerge from Redmond is a new Internet Explorer...I expect some major improvements in standards compatibility..." - Internet Explorer 9 was released as beta!

    Predictions for 2011

    So what about 2011? What's in my crystal ball for next year? The wave 14 of Office/SharePoint has just begun, I don't expect any new major announcements about the next wave, except for the Office 365 stuff going live. The release of IE9 and Silverlight 5 are no-brainers. This is what I think about next  year:

    • Microsoft will enter the pad/slate/tablet/huge-cellphone market with a special edition of Windows Phone 7. Yup, I don't think "Windows 8" will be the OS for the Win-pads.
    • Windows 8 will be communicated. Windows 8 will be like Windows 7 R2.
    • Virtual PC will be reborn as a client alternative to Hyper-V with x64 support etc.

    Thank you and a happy new year

    That's it for me! Thank you everyone who subscribed to my blog or Twitter feed or visited/listened to me at conferences. Next year will be awesome. I've already made some really interesting plans for next year that I'm anxious to talk about at a later time. Let's finish with a picture that I took today when I was out skating at our lake. Happy new year everyone!!

    snow-2

  • Understanding the SharePoint 2010 Sandbox limitations

    Tags: Web Parts, SharePoint 2010

    Recent discussions I've been involved with and blog posts have highlighted some of the SharePoint 2010 Sandbox limitations (either as bugs or as a feature). I have also talked about this during SEF 2010 and SPCSEA 2010. While writing my book SharePoint 2010 Web Parts in Action I had the opportunity to discover these limitations early on and  have learned to live with it. If you read my book you will find a lot of references to "this does not work in the Sandbox" (you've already ordered it huh? Otherwise it's just one click away).

    In this post I want to give you all a little head start on what really happens when executing SharePoint 2010 Sandboxed solutions. Focus is here on Web Parts.

    SharePoint 2010 Sandbox Execution flow

    Before building solutions for the Sandbox you have to know how it actually works, that will also make you understand in more details why some things work and some don't.

    1. The "real" Page object exists in the W3WP.exe process
    2. The Sandboxed Execution Manager serializes information from the fully-trusted objects (see below)
    3. The serialized is sent to the User Code Service (in the OnPageLoadComplete event). It can be on the same or a specific Sandboxed App Server
    4. The User Code Service reuses or spins up a Sandbox Worker process and sends request to the worker process
    5. The User Code Worker Process recreates a HttpContext and the Page object.
    6. It then creates a Form, Web Part Manager and a Zone before it processes the page.
    7. After processing the Sandboxed Page object it retrieves the Response, View State, Control State (execution depends on for instance it is a post-back, export of web part, edit web part etc)
    8. Data is once serialized and sent back to the execution manager
    9. The information is put back into the "real" objects (Web Part properties, view state, controls state...)

    Sandbox details

    Serialized information

    The information that is serialized includes but are not limited to:

    • ID's of Form, Web Part Manager, Zone, Toolpane
    • Web Part properties
    • Options and properties of the Web Part and zone, such as chrome, zone customization, width, height...
    • View state
    • Control state
    • Server Variables (except APPL_PHYSICAL_PATH and PATH_TRANSLATED)
    • Request Headers
    • Input Stream
    • Current context (List Id, Item Id)
    • Query String

    Non accessible or working stuff

    You cannot access the following things from a Sandboxed Web Part, even though it compiles fine and executes without any errors:

    • The Cache object (works but is not serialized back)
    • The ScriptManager (works but is not serialized back)
    • The ClientScriptManager (works but is not serialized back)
    • The HttpRequest.Files collection (will never contain anything) [Corrected] 
    • The Master Page (works but is not serialized back)
    • Other Web Parts (since it creates a new Page and Form object and only adds your SB:d Web Part to the page)
    • Embedded resources (these are requested by the WebResource.axd and they cannot resolve the Sandboxed assemblies from the W3WP.exe process) [Added after initial post] 
    • You cannot use redirection (Response.Redirect, Server.Transfer or SPUtility.Redirect) [Added after initial post - Thanks Todd Bleeker] 
    • You cannot export a Sandboxed Web Part (it will just export the SPUserCodeWebPart) [Added after initial post] 

    I hope this little post helps you out understanding why some of the stuff you expect to work doesn't.

    Feel free to comment on this and correct me if I wrote anything wrong...

  • Custom Health Rule for SharePoint 2010 that checks for Debug build assemblies

    Tags: SharePoint 2010

    Finally back in the blogging saddle, keep stacking ideas and post embryos but never time to finish them. This post is about how you create custom Health Rules for SharePoint 2010 and this health rule is of particular interest since it checks for debug build assemblies in all installed farm solutions.

    Health Rules

    Health Rules in SharePoint 2010 is a great way to make administrators aware of possible problems and issues with your farm; such as running out of disk space, living up to best practices etc. SharePoint 2010 comes with a bunch of out-of-the-box rules (of which some are good and some not that good). The best thing about the Health Rules is that you can write your own to fully satisfy your needs and live up to your governance standards.

    MSDN contains a guide on how to create these custom Health Rules in the "Developing and Deploying a Custom Health Rule" articles. Even though it covers the topic good it is not done using the Visual Studio 2010 SharePoint Developer Tools. This article actually uses MakeCab.exe and DDF files - like we did five years ago!

    I'm going to show you how to do it in a much easier way, but first something about the rule...

    Assemblies in Debug Mode

    This Health Rule that we are going to build will check all existing farm solutions for assemblies built in debug mode. Having assemblies built in debug mode in your production farm can severely hurt performance and even lock your processes down (think Assert dialogs on the server). I've seen debug builds on several production farms throughout the years (I have even put them there myself). It's kinda easy to miss to switch from Debug to Release when deploying a solution in a rush.

    Building the Health Rule

    So let's get to action and build our Health Rule. First of all you need Visual Studio 2010 and SharePoint Foundation 2010 or higher. Create a new Empty SharePoint project and select to deploy it as a farm solution. The Health Rule is implemented as a class, so go ahead and add a new class file to the project.

    First of all you need to derive the class from the SPHealthAnalysisRule:

    public class DebugAssemblies : SPHealthAnalysisRule

    Then you need to override a couple of methods and properties.

    The Summary property is the summary of the rule and is shown in Rule Definition (red box in image below):

    public override string Summary {
        get {
            return "One or more features contains assemblies built in Debug mode";
        }
    }

    Performance Rules

    The AutomaticExecutionParameters property defines the schedule and scope of the rule as well as if it should repair the "problem" automatically:

    public override SPHealthAnalysisRuleAutomaticExecutionParameters AutomaticExecutionParameters {
        get {
            SPHealthAnalysisRuleAutomaticExecutionParameters parameters = 
                new SPHealthAnalysisRuleAutomaticExecutionParameters { 
                    Schedule = SPHealthCheckSchedule.Daily, 
                    Scope = SPHealthCheckScope.Any, 
                    RepairAutomatically = false, 
                    ServiceType = typeof(SPTimerService) };
            return parameters;
        }
    }

    This rule is set to check for problems Daily and the checks should be done on any server where the Timer Service service is hosted. And no, we're not repairing this problem automatically

    The Category and ErrorLevel properties tells what category the rule ends up in and what severity a failed check causes:

    public override SPHealthCategory Category {
        get {
            return SPHealthCategory.Performance;
        }
    }
    public override SPHealthCheckErrorLevel ErrorLevel {
        get {
            return SPHealthCheckErrorLevel.Warning;
        }
    }

    For this rule we place it in the Performance category and only issue an warning when the check fails.

    The actual Health Rule check is done in the Check method, which we will look at in a second. First we define a custom class to store information about debug assemblies and a private property which contains all debug assembly information like this:

    List m_debuAssemblies = new List();
    class DebugAssembly{
        public string AssemblyName;
        public string SolutionName;
        public Guid SolutionId;
    }

    Now it's time to attack the Check method, which is the method that is executed when the rule is invoked. Here's the code for that one:

    public override SPHealthCheckStatus Check() {
        foreach (SPSolution solution in SPFarm.Local.Solutions) {
            // 1) Save file in temp
                    
            string tmp = System.IO.Path.GetTempPath();
            Guid guid = Guid.NewGuid();
            tmp = String.Format(@"{0}{1:D}\n", tmp, guid);
            System.IO.Directory.CreateDirectory(tmp);
    
            solution.SolutionFile.SaveAs(tmp + solution.Name);
    
            // 2) extract assemblies
            CabLib.Extract extractor = new CabLib.Extract();
            extractor.ExtractFile(tmp + solution.Name, tmp);
                    
            // 3) Open manifest
            NameTable nt = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
            nsmgr.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/");
            XmlDocument manifest = new XmlDocument();
            manifest.Load(tmp + "manifest.xml");
    
            foreach(XmlNode assembly in 
                manifest.SelectNodes("//sp:Assemblies/sp:Assembly", nsmgr)){
    
                XmlElement elm = assembly as XmlElement;
                // 4) Inspect assembly
                if (IsDebugBuild(tmp + elm.GetAttribute("Location"))) {
                    m_debuAssemblies.Add(new DebugAssembly() { 
                        AssemblyName = elm.GetAttribute("Location"),
                        SolutionId = solution.Id,
                        SolutionName = solution.Name
                    });
                }
            }
        }
        // 4) Return
        if (m_debuAssemblies.Count == 0) {
            return SPHealthCheckStatus.Passed;
        }
        else {
            return SPHealthCheckStatus.Failed;
        }
    }

    What this method actually does it that it retrieves all farm solutions, copies the WSP to the temp directory and then uses CabLib.dll and extract all the files. Once the files are extracted it looks in the solution manifest for all assemblies and run the IsDebugBuild method to check if it is a debug build. All debug build assemblies are stored in the local property. Finally if it finds any debug assemblies it returns a failure message and if not it says that the rule was ok.

    To be able to compile this code you need to add a reference to Cablib.dll (x64) and also make sure that you include that assembly in your SharePoint Solution Package (Advanced tab in the Package editor)

    The IsDebugBuild method is a derivative of Scott Hanslemans old blog post "How to Programmatically Detect if an Assembly is Compiled in Debug or Release mode". Where I only changed it to return true or false.

    If the rule fails we need someway to inform the administrators. First we override the Remedy property which informs the administrators on how to act on this problem:

    public override string Remedy {
        get {
            return "Redeploy features built in Debug mode as Release builds";
        }
    }

    Then we also need to include some detailed explanation on what solutions and assemblies that causes this rule to fail. This is done using the Explanation property:

    public override string Explanation {
        get {
            StringBuilder sb = new StringBuilder();
            if (m_debuAssemblies.Count > 0) {
                sb.Append("The following assemblies are built in debug mode:\n");
                foreach (var assembly in m_debuAssemblies) {
                    sb.AppendFormat("Assembly {0} in solution {1}/{2},\n",
                        assembly.AssemblyName, assembly.SolutionName, assembly.SolutionId);
    
                }
                return sb.ToString();
            }
            else {
                return "No assemblies built in debug mode could be detected.";
            }
        }
    }

    This property retrieves all assemblies from the local property and writes a nice message for the administrators.

    Result of a failed Health Check rule

    Build the farm feature and register the rule

    Once we're finished with the rule we need to deploy it to our farm and register the rule with the Health Analyzer. Add a feature to your project and set the scope to farm. By default all farm features are Activated on Default - I prefer to change it to not activate on default and instead manually enable the feature in Central Admin. Add a feature receiver to your newly added feature and copy the FeatureActivated and FeatureDeactivated code from the MSDN article.

    Deploy and activate

    All is now ready for compilation, packaging and deployment. Do it! Then browse to Central Administration > System Settings > Manage Farm features and activate your feature:

    Activate!

    Your rule(s) should then appear in Central Administration > Monitoring > Review Rule definitions and you can (if you can't wait for it to automatically run) click on the rule and choose Run Now. Failed checks will appear in Monitoring > Review Problems and Solutions.

    Note: To debug your rule you need to attach the debugger to the OWSTimer.exe process - which is the timer service.

    Download

    If you think this rule is something that could be useful (and you should do), then download it here.

    Summary

    You've now seen how easy it is to implement and deploy a custom Health Rule. You should implement Health Rules that complies with your governance plans to make it easier and faster for the administrators and the governance-police.

  • About Cumulative Updates and Service Packs

    Tags: SharePoint, SQL Server, SharePoint 2010

    Yesterday the SharePoint Team posted on their blog about a major issue with the latest Cumulative Update for SharePoint 2010 and recommending not to install it. If you have installed it you might experience major problems with User Profile services - contact Microsoft Support as soon as possible for help.

    So what about these Cumulative Updates?

    imageEveryone that has been in the business for some time working with products such as SharePoint and other products such as SQL Server knows that the CU's are coming every each month or quarter. These updates contains the latest hotfixes assembled into a one package to make it easier for you to patch your server product. One problem with these CU's (not the actual CU's though) is that a lot of people download them and install them as soon as they are released - Fail! This is not the intended purpose of Cumulative Updates, let me explain why:

    Hotfixes

    Since the CU's contains of hotfixes, critical on-demand fixes and security fixes; some might already be available for download and some can only be reached through the Microsoft Support Services. A hotfix is intended to fix one or more specific bugs. The aim is to release a high-quality fix in an acceptable time frame - which in some cases might be a real issue. Sometimes there is not enough time to thoroughly test each hotfix for the wide diversity of environment and use-cases. One problem with the CU thing is that Microsoft also try to release them on a predictable schedule - this also means that there is not enough time to test.

    If you need to install a hotfix or a CU you must (just as you do with custom code or similar) test the installation before applying it to the production servers. One problem I've seen here is the lack of a test/staging environment where you can apply these hotfixes - if you do not have these environments - do not install the fixes! Even if you have a staging environment the best tip is to wait for a Service Pack, more about these later, or take it easy and listen (read Twitter, blogs etc.) for any issues. Oh, and how about making sure that you have a backup plan!

    KB articles

    For each and every hotfix Microsoft releases a set of Knowledge Base articles describing (almost) exactly what the hotfix is intended to fix. Before applying even the smallest hotfix - make sure that you read and understand the KB articles and also that you are experiencing the problems mentioned. If you do not experience them - there is no reason to apply the fix!

    The KB articles might not be ready when the CU/hotfix is published (back to the time frame issue). So wait until it is published and then read it. But still - only apply fixes that fix a problem you are having or if the CSS tells you to install it.

    Service Packs

    Sooner or later Microsoft bundles all CU's, hotfixes and optionally some new features together into a Service Pack. These are treated differently since most often there are more time to plan and test these. Service Packs are not flawless though. Same goes for all patching, updating, upgrading etc. - TEST, TEST and TEST!

    Been there, done that...

    I know I shouldn't throw stones in a glass house - I've been too trigger happy sometimes finding that a CU fixes one of my problems, installed it without testing enough and finally finding out that it only caused me more trouble on another end. Nevertheless I've learned my lesson...

    You can read more about the CU's in this KB article: http://support.microsoft.com/kb/953878

  • Southeast Asia SharePoint Conference wrap-up

    Tags: SharePoint 2010, Presentations

    I just came home from a great trip to Singapore and the Southeast Asia SharePoint conference. It has been a great adventure travelling that far and meet so many SharePoint fans, Southeast Asia is really hot. The conference has been perfectly arranged by Debbie, Randy and Steve at a great location. Thank you! A new conference in the area was announced during the closing session, and if I'm allowed I'll gladly come back! Hopefully I can spend a few more days here in Singapore then. One thing that really stood out in this conference part from the actual SharePoint content, the speakers and the great people here was the great local food for dinner and tea breaks - love it! As always great to see the real person behind the tweets and the twitter images.

    I had two sessions for this conference; Playing in the Sandbox and SharePoint + Silverlight, new BFFs. Both sessions had a good number of attendees and I want to thank those who attended and came up with good questions. If you missed the sessions or just want to see the slides one more time you will find them below. I also have a download of the source code of the demos below.

    Images

    Here's a collection of a few images that I shot during the conference:

    image image
    Mike Fitzmaurice, the SharePoint High Priest, opening up the conference by showing some nostalgia box shots. They do build some really crazy buildings in Singapore. Just love this one. Who came up with the idea - "uhhh..let's put a ship on top of the buildings".
    image image
    During all breaks this great slideshow was on all screens presenting all speakers from all around the world. Me doing the Silverlight session - wonder why I look surprised - perhaps my demo worked!

    Presentations

    Here are the presentations on Slideshare:

    Demo downloads

    If you want to download the demos and code produced during the session here is a ZIP file with the most interesting parts: SPCSEA-Demos.zip.

  • New external SharePoint Search connectors

    Tags: SharePoint, Windows 7, SharePoint 2010

    Today Microsoft released a bunch of external Search connectors for their search products such as SharePoint Server, FAST and Search Server or for clients such as Windows 7. The external search connectors are based on the OpenSearch specification, so it's quite easy to integrate with whatever product you like.

    Downloads

    These are the new released connectors:

    Using the connectors in Windows 7

    To use the connectors in Windows 7 all you have to do is download the OSDX file and click on it. It will bring up a dialog as below - and after that you are good to go and search using Explorer.

    SNAGHTML1285037

    Adding connectors to SharePoint

    To add the connector to SharePoint Server or Search Server then download the FLD file (Federated Location Definition). After that go to Central Administration and select to manage the Search SNAGHTML1361e8dservice application. In the Search Service application choose Federated Locations in the menu on the left hand side. Then click on the Import Location button and use the Browse button to find the FLD file you downloaded. Once you're done click on the Done button unless you want to change the definition manually or enter any credentials.

    To see the results from the federated location you need to modify your Search Center. Just edit the results page and add the Federated Results Web Part (from the Search category). Then choose to Edit the Web Part properties through the Web Part menu. In the drop down choose the federated location that you would like to use.

    SNAGHTML1385f54

    Save the page and try it out. It just as simple as this.

    SNAGHTML1397390

  • SharePoint and Exchange Conference 2010 and User Group meeting wrap up

    Tags: SharePoint 2010, Presentations, Microsoft Visio

    This years SharePoint and Exchange Conference, the seventh in order, took place this week. For the second year I was there as a speaker and had just as great time as last year. It is currently the largest conference in Scandinavia focusing on SharePoint and Exchange technologies and its growing for each year.

    Göran Husman (MVP) and Beatrice from Humandata has done an excellent job in putting this conference together and finding such good speakers; both national and international. Thank you!

    The conference had some extra icing this year with presentations about three brand new Microsoft products; Internet Explorer 9, Windows Phone 7 and Xbox Kinect. All I can say is that I'm all in - amazing stuff!

    I presented two sessions; Playing in the SharePoint Sandbox and KPI for the People. Thanks to everyone attending and for the interesting questions. Funny thing is with us Swedes that the interesting questions always comes after the session, we're quite shy over here... As promised below are my presentation slides (all powered with Office Web Apps).

    User Group meeting

    A couple of weeks ago we had the Sweden SharePoint User Group meeting at the Microsoft HQ in Akalla. It was good to see such crowd even that far out of town. It was a really good to listen to Pontus Haglund introducing the new Microsoft Lync.

    I did a session about Visio and Visio Services and my presentation can be found below.

    SharePoint 2010 + Visio 2010

    KPI for the People

    Playing in the Sandbox

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

    Tags: LiveID, SharePoint 2010

    Here is the third part of my Visual guide to Windows Live ID authentication in SharePoint 2010. This part takes off just where we ended the last part. If you haven't read part 1 and part 2 then make sure to read them through before continuing.

    Submitting site for compliance

    In order to get your INT site into the PROD/production environment you need to make sure that your site follows the compliance rules. If you do not follow the rules then you will not be able to run your site using the "normal" Live ID accounts. The compliance criteria and verification cases can be found at the MSM site as Word or PDF format. Note that this document is dated way back in 2006 so some things are quite outdated. Here is a short but not complete summary of the compliance criteria:

    • Must work with Internet Explorer 6.0 or later (don't think this one is valid though, since I got my SharePoint 2010 site approved - aim for IE7+ support)
    • A link to your Privacy statement must exist on the first page and this privacy statement must include a link to the Windows Live ID privacy statement
    • All first-level pages must have a valid and functional Sign In text or valid Live ID Sign In button
    • There must be a Sign Out link (or image) when logged in
    • Windows Live ID must be correctly spelled and have the trademark symbol at first mention

    If you are going to use images for the Sign In and Sign Out links - you must use the official ones. And you must have them point to the original location.

     http://www.passportimages.com/signin.gif  http://www.passportimages.com/signout.gif

    Once you believe that you meet the criteria's it is time to submit it for approval. In the MSM site go to your site and select Submit for compliance.

    Submit for compliance

    This link takes you to a wizard where you have a link to the compliance criteria and verification cases documents. The wizard has two pages. On the first page choose Yes in the drop down (if you meet the compliance requirements). Then click Next

    Compliance wizard

    The second requires you to enter information about your site, test environment and anticipated launch date. You also have to option to write some notes to the tester. Once you have entered the information click Submit.

    Compliance properties

    When you're done you should see a message that the site is successfully submitted.

    Congratulations

    Now all you have to do is wait for a response from the tester. This can take anything between two days to two weeks. While you are waiting you can see the current status of your site in the MSM site. The image below shows that; (1) your site is pending, (2) you cannot longer submit it for compliance and (3) it is not yet submitted to production (this is the next step).

    Waiting...

    Compliance answer

    You will receive answer after some time and it can either be negative or positive. I've actually had some problems at first - the tester did not see the standard (OOTB) Sign In link in SharePoint 2010 (probably due to the 115% zoom bug in SP2010). But once it was approved I received an email like this:

    YES!!!

    Submitting for production

    When you are approved but before you can use the site in the PROD environment you need to go back to the MSM site and submit the site into production. This is done on the manage site page. The Site Details will look like this before submitting to production.

    Completed

    To submit the site to the PROD environment choose the Submit Site Properties to Production link in the Tasks below the Site Details:

    Submit again...

    Once you have clicked that link you will be asked to specify the production environment details. The most important thing is to change the DNS Name. As said in part 1 you must use a URN instead of a URL. If you have a URN like this urn:wictorslivesite:int then create a URN looking like this for production: urn:wictorslivesite:prod.

    DNS Name

    When you are done click Submit and on the next page verify that all your properties are valid. Once you are ready click the Yes button to finalize the submission to the PROD environment.

    Congratulations x2

    The Site Details should look like this when everything is set and done.

    In production

    Configuring the PROD site

    Enough of fiddling in the MSM site - let's take on SharePoint 2010 instead. These steps are pretty much the same as for when configuring the INT site - with the difference that we use another certificate, the new DNS Name, a new login URL and new accounts.

    First you need to get the PROD certificate. Go to https://nexus.passport.com/federationmetadata2/2007-06/federationmetadata.xml and extract the signing certificate. Copy the inner text of the X509Certificate element into an empty Notepad document and save it as LiveID.cer.

    Lot of characters...

    Start a new MMC session and add the Certificates snap in. Import this certificate into the same three locations as you did with the INT certificate; Trusted Root Certificates, Trusted People and SharePoint. Make sure to do this on ALL WFE and application servers in your SharePoint farm.

    MMC

    Note that you do not need to remove the INT certificate if you are using the same farm/servers for PROD and INT.

    Next is to fire up PowerShell and do basically the same procedure as for the INT site. The difference is highlighted in red below:

    1: asnp microsoft.sharepoint.powershell
    2: $realm = "urn:wictorslivesite:prod"
    3: $certfile = "C:\Temp\LiveID.cer"
    4: $rootcert = Get-PfxCertificate $certfile
    5: New-SPTrustedRootAuthority "Live ID 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"     -Description "LiveID" -Realm $realm -ImportTrustCertificate $certfile     -ClaimsMappings $emailclaim,$upnclaim -SignInUrl "https://login.live.com/login.srf"     -IdentifierClaim "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"

    On line 2 you must use the PROD DNS Name/URN. On line 3 you need to use the newly created Live ID certificate On line 5 use a different name of the trusted root authority, compared to the INT site On line 8 when creating the trusted identity provider specify a different name (than the INT provider) and use the PROD Sign In Url.

    Then go to Central Administration on your site and select the Web Application that will use the Live ID. Configure the authentication providers to use the new trusted identity provider. If it is the same web application uncheck the INT provider before checking the PROD provider and save your edits.

    We're close now...

    Only one thing more to do. The INT and PROD environments uses different Unique User Identifiers for the logins. If Live ID is your only authentication provider you need to configure a new site collection administrator for your site collections. You can find the Unique ID on the Live ID Account Overview page.

    Long ID's

    Use that ID and append @live.com and use that when configuring your site collection admins:

    Permissions

    That's it - you are now running your SharePoint 2010 site using Windows Live ID login! Use the same procedure as in part 2 to assign permissions to all users out there...

    Summary

    This also sums up this series on configuring SharePoint 2010 for usage with Windows Live ID. I hope that you enjoyed it and avoids falling into some of the traps that I did along the road. Possibly (but not guaranteed) I will have some follow-ups on this series with some more troubleshooting and interesting tidbits found on my journey!

    Keep on SharePointing!

    Oh, and if your in Singapore next week for the Southeast Asia SharePoint Conference just come by and say hello and I'll give you some great discount on my SharePoint book - SharePoint 2010 Web Parts in Action.

  • NullReferenceException when uploading multiple files in SharePoint 2010

    Tags: Microsoft Office, SharePoint 2010

    Recently came across a really interesting bug in SharePoint 2010. It's when you are trying to upload multiple files using the ActiveX control, where you can drag and drop files or select multiple files. I started receiving "Object reference not set to an instance of an object" exceptions from the STSUpld control. The usual Google, ahem, Bing check revealed nothing. Just that I was not alone having this problem (hence this post).

    SNAGHTMLe5d8a

    The strange thing is that this only appeared on some sites and on some computers. After some fiddling around I noticed that it actually only happened on sites where I used a custom master page. My initial thought was that this had something to do with invalid HTML or missing delegate controls - but everything was just fine (alright then, I actually found a missing end div tag, but that didn't solve it).

    So I pulled out the almighty Reflector tool and checked the STSUpld.UploadCtl.GetFormInformation method to see what could possibly go wrong there. By inspecting the code for possible situations where a NullReferenceException could be thrown I found a couple of places where this is not checked for (ouch!):

    • The control needs a hidden input element with the ID destination This one was there, I did not touch the upload.aspx file - and you should not either!
    • This destination field must have a value This is populated by the code behind
    • The control needs an input element of the type button with an AccessKey attribute set to "O" For the OK button (might be different in other languages than English)
    • The control needs an input element of the type button with an AccessKey attribute set to "C" For the Cancel button (might be different in other languages than English)
    • All input element of the type button must have the AccessKey value set to non empty The control iterates through all input elements looking for the AccessKey to find the OK and Cancel buttons. In my case this was the one playing games with me!

    The final point above was the thing that caused the NullReferenceException in the multiple upload control. In this case I had a few input elements with the type button without any AccessKey attributes in my master page (let's not go into why they are there...). Nevertheless once I added the AccessKey attribute with a non-empty value the upload worked like a charm. Note that setting AccessKey="" causes the same exception, you need to set a value for it for instance; AccessKey="_".

    What can we learn from this! You should always check for null! Can't be said too many times. Calling ToString() on objects without checking for null is the eight deadly sin.

    PS: I think this post is worthy of a KB article, Microsoft? At least as a patch in upcoming Office updates...

  • Dissecting the SharePoint 2010 Taxonomy fields

    Tags: SharePoint 2010

    An intense Twitter conversation initiated by Fabian about how Managed Metadata is updated in SharePoint 2010 gave me the idea to note down a few interesting bits about the Taxonomy Fields and how they work within a Site Collection. I hope/guess that Fabian will write a good post (as usual) about his findings as well.

    image

    Introduction

    The possibility to tag documents in SharePoint is one of my favorite features and one of the reasons that I think you should move to SharePoint 2010 as soon as possible. As every new function added to the huge SharePoint spectrum I have an urge to dive deep into these new additions to really know how to use them fully. I've spent some time with the Managed Metadata Service Application and the taxonomy fields used with it. I can't say it has been a smooth ride all the way - but digging into the actual bits and understanding how it all works made it a whole lot easier. And you know what - why keep everything a secret!

    Taxonomy Fields are Lookup columns!

    Yes, you heard it right! It is a smart and clever implementation from the SharePoint Team (some say the opposite though). In order to get performance from the taxonomy and managed metadata fields all used keywords and terms within that Site Collection is stored in a hidden list (in the top-level root site).

    If you've read my previous posts about how to create Taxonomy Site Columns you've probably seen that we use two different fields; one of the type TaxonomyFieldType and one hidden using the type Note. And when defining a field of the type TaxonomyFieldType we need to specify a reference to a list called TaxonomyHiddenList.

    Looking at the properties with SharePoint Designer This hidden list contains all used keywords and terms for the Site Collection and SharePoint uses this list for fast retrieval of the labels of the keyword and terms. You can find the list either by just browsing to /Lists/TaxonomyHiddenList, use SharePoint Designer to get the list id from the Site Properties (see image to the right) or use SharePoint Manager 2010.

    If we take a look at the columns in that list we will see that it contains a number of interesting things. The first interesting columns are the IdFor* (1-3). IdForTermStore (1) is the Guid of the term store used to store this term and IdForTerm (2) is the Guid for the term. Keywords doesn't belong to a term set so the IdForTermSet (3) is an empty Guid, while managed metadata terms have a Guid corresponding to the term set.

    Columns in the hidden list

    Also worth noticing here is that the hidden list also contains the localized labels. I have the French language pack installed, so I can see both the English (4) term and path as well as the French one (5).

    SharePoint uses this list as a lookup column so that it does not have to query the Managed Metadata Service all the time, but instead just looks it up in the local Site Collection.

    You need proof?

    Ok, let's make a really sample scenario. I have one document with Enterprise Keywords and a Managed Metadata column like this:

    A document with metadata

    Let's change the Term1033 column in the hidden taxonomy list to all uppercase letters and save the list item.

    Change the hidden list info

    When the list is reloaded you will immediately see that the column value has changed to the value we updated in the hidden list:

    Display info is changed!

    What happens if I delete one of the items in the hidden list?

    Removed a tag!

    As you probably guessed, it was removed from the file. Let's look at the document from another point of view - the edit properties view!

    Edit info is not changed

    What! As you can see: the term for which I changed the label is back to it's normal state, but the deleted one is still missing (and it is permanently). What's really happening here is that when in edit mode the taxonomy fields queries the Managed Metadata service directly - it does not use the local hidden list.

    So, how do I get it back to where it were? The short answer is you can't. But by default every hour a timer job is executed. It is called Taxonomy Update Scheduler, and it's job is to push down the term store changes to the hidden lists (very much like the sync between the site collection user list and the UPA). Unfortunately it only pushes down changed items, so no luck here. Instead you actually need to go change it in the Term Store Management tool before running the timer job.

    Warning: Under normal conditions you should never ever fiddle with the items in this hidden list. I'm just doing you this to show some stuff some of you never seen or even thought about.

    What about the Note field then?

    Let's take a look on what is stored in these two taxonomy fields. The TaxonomyField which is the lookup looks quite similar to a lookup column. It has the lookup id and the value:

    Taxonomy column in SharePoint Manager 2010

    The Note field (the hidden field) on the other hand contains just the term identifier and is the actual field used to store the connection to the term store. In case you copy, move or uploads a document to another Site Collection - then it will update the TaxonomyField with the correct lookup values.

    Hidden Note field in SharePoint Manager 2010

    I've seen the TaxCatchAll field, what's that!?

    If you use managed metadata there is a hidden column on all your list items or documents called TaxCatchAll. This field contains all ID's in the hidden lookup list of all used terms and keywords for the list item object and is used by SharePoint when adding and updating items.

    Who manages the hidden list?

    Good question, it isn't you! The hidden list is automagically managed by two internal event receivers (can be found in the Microsoft.SharePoint.Taxonomy assembly). These event receivers are responsible for adding items to the hidden list and clean up old and unused ones. There's also a feature stapled, called TaxonomyFieldAdded, on the site definitions which is responsible for creating the hidden list as well as adding the item receivers.

    Summary

    This was it - a quick introduction on how to very clever use the SharePoint feature-set to make the tagging functionality available in SharePoint. And essentially it is just a plain ol' lookup columns with some event receivers that does all the magic for us!

  • SharePoint 2010 and Visio 2010: Better together - Part 3

    Tags: SharePoint 2010, Microsoft Visio

    Welcome back to the SharePoint 2010 and Visio 2010 Better together series for this third part. In part 2 I showed you how to use Visio 2010 to convert your business requirements into workflows that later could be used in SharePoint 2010, using SharePoint Designer 2010 as the man in the middle. This time I'll show you how Visio comes into play even after you have deployed your workflows and running them in your organization.

    Workflows are a great feature in SharePoint 2010 that allows for instance your business rules to be performed in a consistent and repeatable manner. The SharePoint workflows are executed in the background of your web interface, they may pause for long durations and they may involve several users within your company. It can sometimes be hard to keep track of a long-running workflow and see what is happening right now, who is currently working on it etc. By default in SharePoint 2010 you have the Workflow History which is used to log events from the workflow. Events such as workflow status, errors and manual logging operations are seen there. This might be enough for a simple workflow. You can access the Workflow Information page, which contains the history, by clicking on the workflow status column in the list.

    Workflow History

    But for more complex workflows containing several branches and involving multiple users this history list can be long. To get a quick snapshot of the current workflow status it can be hard to interpret this list of log events. Wouldn't it be better to have a visual overview of the workflow? For earlier versions of SharePoint this was available through third party products, but now in SharePoint 2010 this is actually available out of the box.

    It is here Visio Services comes into play. Without digging into deep to the actual Visio Services Service Application, we'll have plenty of time for that, let's satisfy for the moment with that Visio Services is a server side Visio rendering engine. This feature is only available in SharePoint Server, since Visio Services is not available in SharePoint Foundation. If you have a successfully installed and configured the Visio Services Service Application in your SharePoint farm then all you have to do is open the workflow using SharePoint Designer 2010 and in the Settings section click the Show workflow visualization on status page checkbox. Don't forget to save and publish your workflow. If Visio Services is not correctly configured for your Web Application then the checkbox will be disabled.

    Workflow Settings

    Once you have done this you can fire up a new instance of your workflow and then head on over to the Workflow Status page. You will now be presented with Workflow Visualization section on the status page containing the current status of your workflow presented visually using Visio Services. Take a look at the screenshot below, which is taken from the workflow that we used in the previous post. First you can see exactly which steps have been completed using the check box icon (1) and even better you can also see who is actually the current owner of the approval task (2). The screenshot shows that the original task has been reassigned twice. This is a perfect solution to get a hint on the workflow status within seconds.

    Workflow Visualization

    This image is rendered by Visio Services using Microsoft Silverlight, which allows you to zoom and pan the workflow visualization. If you don't have Silverlight installed then Visio Services will render a plain image instead. Using Silverlight is preferred though due to performance and quality of the visualization.

    Worth noticing here is that the visualization does not to apply to already running instances of your Workflow, only new ones. When you publish the workflow from SharePoint Designer a new version of the workflow is created containing the visualization setting. Already running instances keep running the old version of the workflow.

    As you can see from the screenshot some of the workflow arrows intersect and the layout is not optimal, also the labels on the actions are not that descriptive. For instance what does Compare data source actually do? Fortunately there is a really easy solution to this. Notice in the upper left corner of the Visio drawing that there is a Open in Visio button. Click it! In the dialog asking you which mode to open it, choose Edit and click OK.

    The workflow will open in Visio 2010 and you can design the workflow as you like and even apply the corporate branding. You can basically do anything but edit the actual workflow. I do recommend you to edit the labels of the actions and arrange the workflow so that no lines intersect. While you're at it; do try the new auto-align features in Visio 2010 and the great container objects. When you are done all you have to do is save the drawing and then exit Visio.

    The screenshot below shows a modified visualization of the previous workflow, it also has one of the built-in themes applied. I think this is pretty neat and for complex workflows I think this is a necessity.

    Workflow Visualization Deluxe

    Note: You cannot enable visualization for the Workflows that you have created using Visual Studio 2010, only for those created by SharePoint Designer.

    That was it for this time. An introduction on how Visio Services can enhance your workflow experience even further. This really is a usability enhancement and your end-users will adore you for enabling it on your workflows. I will continue this excavation of SharePoint and Visio in the next part taking a closer look at the actual Visio Services Service Application.


    This post was originally posted on EndUserSharePoint.com at http://www.endusersharepoint.com/2010/09/15/sharepoint-2010-and-visio-2010-better-together-part-3/

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

    Tags: LiveID, SharePoint 2010

    UPDATE 2012-02-01: A new and better approach to this is detailed in a new Visual Guide - Visual guide to Azure Access Control Services authentication with SharePoint 2010.

    I'm back with the second part of the Visual guide to Windows Live ID authentication with SharePoint 2010 series. Part 1 was a huge success and has received a lot of feedback and hits - I hope many of you out there successfully configured your web sites and extranets. I'm currently working on getting the new Swedish SharePoint User Group website up using Live ID...

    This second part will continue where we left it last time, and this time also using a lot of images. Jeremy Thake (MVP), who currently working on a secret SharePoint project, blogged about some of the things I will detail in this post, so for some of you there are stuff repeated in this post.

    Give access to users

    One of the first things you need to do is to give all Windows Live ID users the possibility to log in to your application. It's not mandatory but it is really hard asking for the PUID of all users and manually adding them to your site(s). The PUID will be seen by the user by accessing the Live ID account services at https://accountservices.passport-int.net/ or by signing in so they see the access denied page.

    image

    Instead of manually adding users you should add all authenticated Live ID users to a Visitors group for instance and have some kind of application form with a workflow or similar which they must fill-in to become "real members" (sounds like an InfoPath and SharePoint Designer task...). To add all authenticated Windows Live ID users to the Visitors group; log in to your site and select Site Actions > Site Permissions. Then select the Visitors group or any other group of your choice. Clicking New > Add Users will open up the Grant Permissions dialog. If you write anything in the Users/Groups field and click Check Names you will see that you can actually type anything and it will be valid.

    SNAGHTML5a9d49

    The Live ID authentication provider accepts any string and it does not perform a lookup with Windows Live ID, so essentially you can use any string . But users will only be sent from Live ID to your site with a PUID (nnnn@live.com), so you can't give access to a user without the PUID. If you write All users instead this will perfectly resolve to two interesting groups; The All Users (windows) and All Users (LiveID INT) - all depending on what authentication providers you have, in this case the standard Windows login and Live ID (INT) is enabled for the web application. If you select the All Users (LiveID INT) and add it to the group, all authenticated Live ID users will be a member of it.

    SNAGHTML5cfca7

    You can also click the Browse icon and bring up the People Picker dialog, which has a new look when claims is enabled for the web application. To select the All Users group for Live ID select the All Users node in the tree on the left hand side and then select the All Users (LiveID INT).

    image

    Worth noticing here is you cannot "search" for a Live ID user - not by name, e-mail or anything. You always need the exact PUID or username when claims mode is enabled.

    Anonymous Access

    So, now you have allowed all Live ID users to log in to your site. Enabling anonymous access to users is no different than before. First you have to change the Authentication Provider of the Web Application (Central Administration > Manage Web Applications > Select Web Applications > Click Authentication Providers in the Ribbon > Select Authentication Provider). Just check the Enable anonymous access for the authentication provider and then click OK.

    SNAGHTML65b29d

    Next you have to enable anonymous access per Site Collection. Once again go to Site Actions > Site Permissions and click on the Anonymous Access button in the Ribbon menu.

    SNAGHTML67167e

    Then select what the anonymous users can access; Entire Site, Lists or Nothing.

    Once you have done this new users will not be required to log in to your site immediately. Instead they will see the "Sign In" link in the upper right corner.

    SNAGHTML68c9d5

    The display name of the user

    Once the user logs in to the site the user name still looks pretty ugly - it's just the PUID that is given to SharePoint from the Windows Live ID login service. Unfortunately Windows Live ID only returns one single claim and that is the UPN, which is in the form of a e-mail address. That e-mail address is not even a valid address. You can not expect to get the full name or e-mail of the user from Live ID - you have to implement something of your own OR use the built-in amazing stuff in SharePoint.

    SNAGHTML6a0c80

    What amazing things do we have in SharePoint then? First of all - if you are on SharePoint Foundation, it's not that amazing at all. You have to live with the PUID or build something of your own and keep all your Site Collections in sync.

    But if you are lucky to set up a SharePoint Server then you can take advantage of the User Profile Service Application. Configure the UPA according to all best practices - but do not configure the User Profile Synchronization (UPS), we do not need it and it does not synchronize with Windows Live ID anyways. Only configure the UPS if you are using both internal Active Directory users in combination with Live ID.

    Once you have configure the User Profile Service Application go to Central Administration > Manage Service Applications and select the User Profile Service Application. Then click on Manage User Properties. We will do that to configure what properties the users are allowed to change.

    SNAGHTML717eb2

    You can change a whole lot of User Properties here, but the most important ones are Name and E-mail. We need to make sure that the user can edit those. Browse down to the Name property and select to Edit it.

    SNAGHTML731b01

    To make the Name editable and usable there are a couple of things that we need to take care of:

    1. Make sure that the property can be edited
    2. Make sure that it is visible on the Edit Details page
    3. Choose if the property is publically visible on the profile page
    4. Choose if updates to the property should be visible in the newsfeed
    5. Make sure that the property will be replicated from the profile into the userinfo list in all Site Collections

    SNAGHTML747e93

    Once you have configured the Name and Email property (at least) you are ready for a test drive. Log in to your site and choose My Profile from the login (upper right) menu and click on Edit My Profile. As you can see you are now able to edit the name, by default it is the PUID. Update the settings and click Save and Close and go back to the your main site.

    SNAGHTML79b877

    Once you get back to the site you will probably see that the PUID is still there, hold on and don't start crying yet. It takes some time to synchronize between the user profiles and userinfo lists. You can speed up the process by running the "User Profile to SharePoint Full Synchronization" job - normally run once an hour.

    SNAGHTML7f5ea5

    After a successful sync you should see that the upper right menu shows the Name that you specified in the user profile.

    SNAGHTML81a23a

    HTTPS and HTTP

    There is one final thing that you should do before continuing with your site and submit it for the PROD environment and that is to allow users to browse your site without HTTPS. The login procedure must use and will still be using HTTPS. Fire up the IIS manager and select the web site that you have been using and select to edit its Bindings.

    SNAGHTML850fda

    Add a new Host Header binding or other binding of your choice using the HTTP protocol and then click Close.

    image

    Then open Central Administration and select Application Management, under Web Applications choose to Configure alternate access mappings (AAM). Choose to Edit Public URLs and then select your web application. In the Internet Zone add the URL of HTTP address, using the HTTP protocol and then click Save.

    SNAGHTML8cee18

    Once this is done you should be able to browse to your site using the HTTP protocol, and then if you click the Sign In link you will be taken to Windows Live ID and be authenticated. When you are successfully authenticated Windows Live ID will redirect you back to the HTTPS address (remember that you specified the Return URL in the MSM using the HTTPS protocol, in part 1). From now on you can move seamless between the HTTP and HTTPS zones.

    There are other options here as well, such as extending the web apps, but that is for someone else to write about...

    Summary

    That's it, you should now have a fully functional Windows Live ID enabled site. You can even edit the site using SharePoint Designer using the Live ID account. Next part will give you the details on how to move this site from the INT environment to production (PROD),

    Until next time...

  • Sweden SharePoint User Group (SSUG), Meeting in October

    Tags: SharePoint 2010

    Introduction

    After a long and well deserved vacation we’re now back with new strength! It’s time for our first SSUG meeting for the fall!

    Please do remember; This is a FREE event – we never have and never will charge anyone for loving SharePoint and sharing the awesomeness :-)

    Meeting details

    Let’s meet up at Microsoft HQ for our first SSUG meeting this fall! You will have the possibility to mingle around with SharePoint MVPs, folks from Microsoft and of course all our splendidly cool members!

    We will of course have snacks and beer/beverages at hand, just like we always do.

    Please see the following sections for details about the meeting!

    Location

    Microsoft AB, the Swedish Microsoft HQ.

    Microsoft AB Finlandsgatan 36 KISTA

    Find it: http://www.hitta.se/ViewDetailsPink.aspx?Vkiid=FRfzEz0DKh9ofdUqflCH4g%253d%253d&vad=Microsoft

    Time and Date

    October 5th, 2010.

    We’ll meet up at 17:30 at Microsoft HQ and sessions will start around 18.00 – so there’s plenty of time for making acquaintances before we begin.

    Session agenda

    • 17:30 – Doors open at Microsoft HQ
    • 18:00: Session 1;
      • Lync/OCS 14: Pontus Haglund from Microsoft AB
    • Break!
    • 19:00: Session 2;
      • Visio 2010 + SharePoint 2010: Wictor Wilén, Connecta AB

    Sign up for the meeting!

    As we still haven’t finalized the new membersite for the SSUG group (hold your breath, we’re soon to be finished); you can sign up for the meeting by e-mailing info@ssug.se with the subject “Oktobermöte”.

    If you know of anyone interested in attending, please feel free to forward this information!

    Summary

    A lot of questions have popped up in regards to what’s going on with the member-site, and we’ll shortly announce some news about that – but for now, let’s focus on making this meeting rock as always :-)

    Cheers!

  • Making every site in SharePoint 2010 into a BI Center

    Tags: Visual Studio, SharePoint 2010, PerformancePoint

    The other day I had an interesting and great workshop with a customer about the BI features in SharePoint 2010. SharePoint Insights is one thing that really gets me going - so much great stuff can be unleashed using Excel, Visio and PerformancePoint Services.

    One thing that annoys me with the default settings in SharePoint 2010 is the BI Center. A BI Center does not support the "BI for everyone" mantra - that center only turns numbers and KPI fans on. What you should do is enable BI features on all of your sites; your Intranet home page, your department sites or even on project sites etc. But it isn't as easy as you could imagine. So here's some tips for you all to BI-enable all your sites. Oh wait, don't say to your end-users that you BI-enabled their site - tell them that you have Insight enabled their site instead so you don't scare them off.

    Let's start this little excursion by enabling the PerformancePoint features and Dashboard Designer on an new Site Collection with a top-level site based on a plain ol' Team Site. Of course it is on a SharePoint 2010 Server with Enterprise features installed.

    Enabling basic Insight features

    First of all we need to make sure that the Enterprise features are enabled on your site. If not enable them on the Site Collection or enable them on all Site Collections from Central Administration under Upgrade and Migration.

    Enterprise Features

    Enabling BI-Center features

    So what is so special about the BI-Center. It contains some demo pages using Excel Services, indicators and PerformancePoint content. But most interestingly it contains the special libraries and lists used by PerformancePoint Services to store the PerformancePoint data; the Data Connections Library, the PerformancePoint Content list and the Dashboards library. These lists and libraries cannot be created directly in the web interface, the definitions for these are "hidden" inside the BI-Center site definition. This can easily be solved using PowerShell or by creating our custom Insight enabler feature. PowerShell is great; but building a custom feature allows us to either staple it onto other site definitions or allow the end-user to turn the features on or off.

    Let's create a new feature that adds the necessary lists and libraries. Open Visual Studio and create a new Empty SharePoint Project and to that project we need to add a new feature, scoped to Web. The first thing we need to do is to enable two PerformancePoint features. Since these are hidden ones, activation dependencies is out of question. Let's make it using a Feature Receiver. This feature receiver enables the PPSSiteMaster feature on the current web site and PPSSiteCollectionMaster feature on the Site Collection:

    public const Guid PPSSiteMaster = 
        new Guid("0b07a7f4-8bb8-4ec0-a31b-115732b9584d");
    public const Guid PPSSiteCollectionMaster = 
        new Guid("a1cb5b7f-e5e9-421b-915f-bf519b0760ef");
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        SPWeb web = properties.Feature.Parent as SPWeb;
        SPSite site = web.Site;
        if (site.Features[PPSSiteCollectionMaster] == null) {
            site.Features.Add(PPSSiteCollectionMaster);
        }
        if (web.Features[PPSSiteMaster] == null) {
            web.Features.Add(PPSSiteMaster);
        }
                
    }

    In the FeatureDeactivated method, these features are removed as well. Of course you can add or check for any other features here that you would like to add, such as the Enterprise Features.

    Insights Enabler

    Next up is to create the libraries and lists. Just add a new Empty Element SPI to the project and the lists as follows:

    <ListInstance Title="$Resources:ppsma,Onet_BICenter_Title"
                  Description="$Resources:ppsma,Onet_BICenter_Description"
                  TemplateType="450"
                  Url="Lists/PerformancePoint Content"
                  FeatureId="481333E1-A246-4d89-AFAB-D18C6FE344CE"
                  QuickLaunchUrl="$Resources:core,lists_Folder;/PerformancePoint Content/AllItems.aspx"
                  OnQuickLaunch="TRUE"/>
    <ListInstance Title="$Resources:ppsma,Onet_BIDataConnections_Title"
                  Description="$Resources:ppsma,Onet_BIDataConnections_Description"
                  TemplateType="470"
                  Url="Data Connections for PerformancePoint"
                  FeatureId="26676156-91A0-49F7-87AA-37B1D5F0C4D0"
                  OnQuickLaunch="TRUE"/>
    <ListInstance Title="$Resources:ppsma,Onet_BIDashboards_Title"
                  Description="$Resources:ppsma,Onet_BIDashboards_Description"
                  TemplateType="480"
                  Url="Dashboards"
                  FeatureId="F979E4DC-1852-4F26-AB92-D1B2A190AFC9"
                  OnQuickLaunch="TRUE"/>

    Insight list and librariesThis CAML is almost a copy of what is in the BI Center site definition, with only modifications so that the correct elements and attributes are used (ListInstance instead of List etc).

    Just hit F5 and watch it build and deploy beautifully. You can see the PerformancePoint lists and libraries in the Quick Launch. Also if you inspect the lists you can see that the correct content types are there.

    Adding the Dashboard Designer

    In order to utilize this fully we need to use the PerformancePoint Dashboard Designer. In the BI-Center template this application could be accessed through a button on one of the publishing pages that was added by default - not a nice solution.

    Instead we would like to have this one in the Site Actions menu, or any other suitable location. Site Actions is where I think it belongs. Let's add it there.

    Add a new Empty Element SPI and in that elements.xml add a CustomAction as follows:

    <CustomAction Id="LaunchPPSDD"
                  Location="Microsoft.SharePoint.StandardMenu"
                  GroupId="SiteActions"
                  Title="Dashboard Designer"
                  Description="Launch PerformancePoint Dashboard Designer"
                  ImageUrl="/_layouts/images/PPSSiteTemplateRun.png"
                  >
      <UrlAction Url="javascript:
    var a = _spPageContextInfo.siteServerRelativeUrl.toLowerCase();
    var b = _spPageContextInfo.webServerRelativeUrl.toLowerCase();
    var c = location.protocol + '//' + location.host + a;
    var d = b.replace(a,'');
    location.href = b + '/_layouts/ppswebparts/designerredirect.aspx' + '?SiteCollection=' + c + '&SiteLocation=' + d;"/>
    </CustomAction>

    The CustomAction uses the default Dashboard Designer image and contains a UrlAction with a JavaScript. This JavaScript launches the Dashboard Designer with the correct Site Collection and Site.

    Dashboard Designer CustomAction

    Deploy your solution once again and create your dashboards - without the BI-Center.

    Team BI Center

  • Join me for a chat with the SharePoint MVP Experts

    Tags: SharePoint, SharePoint 2010

    MVP_BlueOnlyNext Wednesday I will sit in the SharePoint MVP Experts panel for a Q&A session where you can ask your questions about SharePoint. The SharePoint MVP Experts Q&A chat is your opportunity to chat and get instant answers about any SharePoint related questions, including topics such as development, design, configuration and setup. There will be several SharePoint MVP's ready to answer your questions...

    When? The chat will take place the 29th of September at 9AM PDT. Sign up here and add it to your calendar. Also sign up here at the Facebook event page.

    Where? In the MSDN Chat Rooms

    How? You only need a web browser to ask your questions

    The chat transcript will be published at the MSDN site after the session.

    See ya there...

  • SharePoint 2010 and Visio 2010 - better together - part 2

    Tags: SharePoint 2010, Microsoft Visio

    This is the second post in the SharePoint 2010 and Visio 2010 - better together series. And it is time to really check out what this great combination have to offer, and the most obvious subject to start with is that we can now use Visio to design the workflows, which then are imported to SharePoint via SharePoint Designer 2010. So let's get started.

    If you ever built workflows for previous versions of SharePoint you either used SharePoint Designer 2007 or Visual Studio 2005/2008. SharePoint Designer 2007 had a very limited workflow designer (you can't actually call it a designer) that took quite some time to get used to and you were very limited in what to do. Visual Studio of course offered you the full set of workflow features. I'm not trying to get to deep into the actual workflow stuff here but it is important to understand how hard it was for the organizations to get their hand-drawn or Visio-drawn workflow into SharePoint. If you used SharePoint Designer to build the workflows then the most problematic situation was when you were supposed to move the workflow from you development environment to production - this was just impossible (yea, there was ways to work around it - but not for mere mortals).

    Visio is excellent in drawing flowcharts, workflows and business processes and some business analysts just love it. So very often you were presented with a Visio diagram of a workflow that you were supposed to implement in SharePoint. What did you do then? Yes, you had to translate the workflow into either a SharePoint Designer 2007 workflow, using the wizard or go for the full monty with Visual Studio. There was room for many mistakes in this process of you, the developer or SharePoint professional, interpreting the Visio diagram to a SharePoint workflow.

    Now, with SharePoint 2010, SharePoint Designer 2010 and Visio 2010 the story is quite different. You can let your business draw the actual SharePoint workflow using the SharePoint Workflow template in Visio. Then you take this Visio diagram, turn it into a SharePoint Designer acceptable file format and configure the last bits in SharePoint Designer. Once that is done all that is left is to hit the publish button. Once the workflow is in place you can let the original author of the Visio diagram verify the functionality. If it is not what he or she asked for you can export it once again to a Visio drawing and fine tune it. The workflow can go back and forth between Visio and SharePoint via SharePoint Designer until everything is set and done.

    Before going into some conclusions and experience from this new way of producing SharePoint workflows, let's take a look at how you do this.

    Assume that we have a list in SharePoint containing proposals that we would like to send to our clients. In this case we use a custom list, but it could be any kind of list or library. Each proposal has a Proposal Value. If the proposal Value is higher than $100.000 then our manager must approve the proposal before sending it to the client.

    image

    The financial controller of our organization decides that this must be implemented as a Workflow on a list and fires up Visio 2010. Of course he uses Visio 2010 Premium - which is the edition of Visio that contains the SharePoint Workflow template. Using this template the controller can draw the workflow using the default SharePoint Actions, Conditions and Terminators.

    By dragging a Start and End Terminator onto the drawing and then adding a condition (Compare Data Source) which should be used for comparing the proposal value to the limit he starts building the workflow, visually. If the condition is below a certain threshold it automatic set the content approval status and if it is above then it should send an e-mail to the manager and then start an approval process and so on. The actual values are not set here, just the actions and conditions in the workflow.

    image

    All this is done by dragging the Actions and Conditions onto the drawing surface and then using the connection tool to connect the items. Notice that the controller cannot set any properties, see Shape Data tool pane, on the actual Workflow Actions. The only thing that can be configured is which path to take for a condition. This is set by right-clicking the connection and then select Yes or No.

    The SharePoint Workflow template, as well as other templates in Visio can also be validated. This is done using the Check Diagram button in the Process Ribbon tab. This check makes sure that all actions are connected and that there are no loose ends. It also checks so that the workflow does not contain any loops, which is not allowed in SharePoint Designer workflows.

    SNAGHTML1e4722c

    Once the financial controller is satisfied with his workflow he saves it and sends it to the SharePoint professional, if he isn't one himself. Here, he can send it as a standard Visio drawing using the .VSD format or he can use the new Visio Workflow Interchange format with the .VWI extension. The downside with sending it as a .VSD file is that the SharePoint professional must open it in Visio and convert it to a VWI file - which is the format that SharePoint Designer 2010 supports. On the other hand, it might be easier to not teach the business about that and avoid confusions?!

    SNAGHTML1e92be9To create the VWI file you cannot choose File > Save As. You need to use the Process tab in the Ribbon once again and select the Export button. This pops up an Export Workflow dialog where you can specify path and file name. Also notice the Import button. You use this to import a VWI file created by Visio or exported from SharePoint Designer, if you need to go back and update any changes.

    Here it is important to notice that if you export it from SharePoint Designer and then import it into Visio to once again get it back to SharePoint Designer. When exporting an imported VWI file using the same file name you must select to Update workflow information in existing file in the dialog. This makes sure that you can import it to SharePoint Designer once again without losing any settings configured in SharePoint Designer and to allow you to update an existing workflow.

    Ok, now you have the VWI file and you have fired up SharePoint Designer on the site containing the Proposals list. Select the Workflows object in the left navigation of SharePoint Designer and choose Import from Visio in the Workflows Ribbon tab. Then choose the workflow interchange file that you just exported. When you have selected the file you will be presented with a dialog that asks you how to import this Workflow. In this case we want it to be a list workflow, so we select the Proposals list and also give it a good name, then click Finish.

    image

    SharePoint Designer will now open the workflow in the Workflow editor and you will see a workflow without any configuration - just the "flow" as designed in Visio in another, more logical, representation.

    image

    Now you have to discuss with the financial controller what exactly is supposed to be the conditions and values - or even better whish that you got some documentation with the Visio file or even annotations in the actual file. After configuring the workflow it should look like below:

    image

    We are almost there. All that is left is to verify the workflow by clicking on the Check for Errors button in the Ribbon menu and then configure the workflow to start whenever an item is added or changed. To edit the start options you use the bread crumb menu in SharePoint Designer and click on the name of the workflow. This takes you to the Workflow page and in the Start Options section check the Start workflow automatically when an item is created and the same for the changed option.

    The workflow is done, designed using Visio and configured using SharePoint Designer. Now we need to test it in SharePoint. But first you must publish the workflow. This is also done using the Ribbon menu, click on Publish and wait for the process to finish. SharePoint Designer will also check the workflow for any errors before publishing it. If you don't want to publish it right now you can select Save and go get a coffee and get back later and publish it.

    So now, head on over to the Proposals list and add a new proposal, this time with a proposal value of over $100.000. Notice how a new column is added to the list, with the workflow status, and that it automatically starts when you created an item.

    image

    Since this workflow had a Start approval process action a task item will be created in the Tasks list, assigned to the person configured in the workflow using SharePoint Designer. Once the task is done with an approve or reject status the workflow will continue and update the proposal with the outcome, as well as sending an e-mail back to the original person creating the proposal.

    image

    Quite easy, isn't it.

    I really like this approach, as a first version of the Visio, SharePoint Designer and SharePoint integration. There are a couple of things that I hope gets addressed in the future. First of all you can't really put the SharePoint Workflow template in the hands of a business analyst. They are so used to working with regular flow charts or BPMN diagrams. It can sometimes be hard for the to get a good understanding of the different actions in the SharePoint workflow directly related to lists. Secondly it is too bad that you can't configure more using Visio - as the matter of fact it will be hard having one person designing the workflow in Visio and another configuring it in SharePoint Designer. But we have a lot of things to look forward to in upcoming versions - and it's a fantastic start!

    Next time I will show you how to enhance the workflow experience using Visio Services so that your end-users always knows what is happening to their workflows. Which is one of the features I like most about the Visio and SharePoint marriage.


    This post was originally posted on EndUserSharePoint.com at http://www.endusersharepoint.com/2010/09/06/sharepoint-2010-and-visio-2010-better-together-part-2/

  • Sandboxed workflow activities in SharePoint 2010

    Tags: SharePoint 2010

    One of the really great features in SharePoint 2010 is the Sandbox, which allows the end-users to upload solutions using the web interface, instead of relying on administrators adding the solutions directly to the farm. One of the things that that can be deployed to the Sandbox is custom workflow activities. These activates can then be used by the end-users building workflows with SharePoint Designer. It is really powerful to add custom sandboxed activities and it is very easy as well! In this post I will show you how to really fast build a custom sandboxed activity that breaks the permission inheritance on the item which the workflow is executed on.

    Create the activity

    In order to build a sandboxed activity you need to use Visual Studio 2010 and create a new Empty SharePoint project and choose to deploy it as a Sandboxed Solution. Then add a new class to the project. It is this class that will contain the logic for the activity. First make sure that the class is marked as public. Then you need to add a method which is the activity logic itself. This method must have a first parameter as a SPUserCodeWorkflowContext object and it must return a Hashtable. In this case we will use the SPListItem.BreakRoleInheritance() method on the item and since that method takes a boolean parameter, we will add that parameter to our activity as well. This parameter is added as the second in-parameter, which leaves the method definition as follows:

    public Hashtable BreakRoleInheritance(
        SPUserCodeWorkflowContext context, 
        bool copyRoleAssignments);

    The code required to break the role inheritance is as follows:

    Hashtable ht = new Hashtable();
    try {
      using (SPSite site = new SPSite(context.SiteUrl)) {
        SPWeb web = site.OpenWeb(context.WebUrl);
        SPList list = web.Lists[context.ListId];
        SPListItem currentItem = list.GetItemById(context.ItemId);
        currentItem.BreakRoleInheritance(copyRoleAssignments);
        currentItem.Update();
        ht["Result"] = "Success";
      }
    }
    catch (Exception) {
      ht["Result"] = "Failure";
    }

    First of all the Hashtable to return is created. This hash table is used to store different return values, in this case only on: Result which can be either Success or Failure. Using the SPUserCodeWorkflowContext object the SPSite, SPWeb, SPList and finally SPListItem is retrieved. On the list item the BreakRoleInheritance method is called with the copyRoleAssignments parameter. If the update works fine then the Result return value is set to Success. All exceptions are caught and a Result value of Failure is set.

    Define the Activity for SharePoint Designer

    imageTo be able to use this activity in SharePoint Designer we need to deploy a WorkflowActions/Action element in an Empty Module. Add a new Empty Module SPI to the project. Before editing the elements.xml file modify the automatically added feature (called Feature1) to be scoped to Site so this activity can be used within the whole Site Collection.

    Then open up the elements.xml file and edit it as follows. Here is the full declarative code needed to hook up the activity to SharePoint Designer.

       1:  <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
       2:    <WorkflowActions>
       3:      <Action
       4:        Name="Break Role Inheritance"
       5:        Category="Permissions"
       6:        Assembly="$SharePoint.Project.AssemblyFullName$"
       7:        ClassName="$SharePoint.Type.0bc46b26-96ca-4201-8480-6fd7d8ea598e.FullName$"
       8:        FunctionName="BreakRoleInheritance"
       9:        AppliesTo="all"
      10:        UsesCurrentItem="true"
      11:        SandboxedFunction="true">
      12:        <RuleDesigner 
      13:          Sentence="Breaks role inheritance on the item (copy current roles: %1)">
      14:          <FieldBind 
      15:            Field="copyRoleAssignments" 
      16:            Text="Copy Roles" 
      17:            Id="1" 
      18:            DesignerType="Bool"/>
      19:        </RuleDesigner>
      20:        <Parameters>
      21:          <Parameter 
      22:            Name="__Context" 
      23:            Type="Microsoft.SharePoint.WorkflowActions.WorkflowContext,                        Microsoft.SharePoint.WorkflowActions" 
      24:            Direction="In" 
      25:            DesignerType="Hide" />
      26:          <Parameter 
      27:            Name="copyRoleAssignments" 
      28:            Type="System.Boolean, mscorlib" 
      29:            Direction="In" 
      30:            DesignerType="ParameterNames" 
      31:            Description="Copy roles" />
      32:          <Parameter 
      33:            Name="Result" 
      34:            Type="System.String, mscorlib" 
      35:            Direction="Out" 
      36:            DesignerType="ParameterNames" 
      37:            Description="Result of activity"/>
      38:        </Parameters>
      39:      </Action>
      40:    </WorkflowActions>
      41:  </Elements>

    Looking for the ActionFirst of all the WorkflowActions (2) and Action (3) elements are added. The Action element contains the Name (4) and Category (5) of the activity - these are visible in SharePoint Designer when browsing/searching for the Actions. The Assembly, ClassName and FunctionName is of course pointing to the actual assembly, class and method that we previously defined. Note that I'm using replaceable tokens here for the assembly and class name (read more about this in a previous post). The AppliesTo (9) indicates that this will apply to both document libraries and lists and with UseCurrentItem (10) set to true allows the action to modify the item in the list/library.

    The RuleDesigner (12) element tells SharePoint Designer how to render this action in the Workflow Designer. It will write the text in the Sentence attribute and the %1 token will be replaced with the field with the specific Id. In this case the field is the copyRoleAssignments (14-18). With this configuration editing the activity in SharePoint Designer will look like this:

    image

    The last pieces of XML that is required for this activity is the definition of the Parameters (20). The two input parameters (the context and copyRoleAssignments) and the output parameter (via the Hashtable) is defined in the Parameter elements. The XML is quite self explanatory.

    That was it, just deploy this to a Site Collection then open up SharePoint Designer 2010 and build your workflows. Remember that the activity runs in the Sandbox and therefore has its limitations.

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

    Tags: LiveID, SharePoint 2010

    UPDATE 2012-02-01: A new and better approach to this is detailed in a new Visual Guide - Visual guide to Azure Access Control Services authentication with SharePoint 2010.

    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

    Tags: SharePoint 2010, Microsoft Visio

    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

    Tags: Visual Studio, SharePoint 2010

    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)

    Tags: SharePoint 2010

    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

    Tags: Visual Studio, SharePoint 2010

    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

    Tags: Visual Studio, SharePoint 2010

    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

    Tags: SharePoint 2010, Presentations

    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

    Tags: SharePoint, SharePoint 2010

    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

    Tags: Visual Studio, Scripting, AJAX, SharePoint 2010

    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

    Tags: Visual Studio, Web Parts, SharePoint 2010

    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

    Tags: SharePoint 2010

    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

    Tags: SharePoint 2010

    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

    Tags: SharePoint 2010

    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

    Tags: SharePoint 2010

    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

    Tags: SharePoint 2010, SharePoint 2010 Web Parts in Action

    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...)

  • SharePoint 2010 Site Definition images must use the correct format

    Tags: SharePoint 2010

    When you create a Site Definition for SharePoint 2010 you should provide an image that illustrates the Site Definition. It allows the users to separate the Site Definitions from each other, find the correct one faster and it looks quite nice!

    In SharePoint 2010 Silverlight is used when selecting Site Actions > New Site. This gives you a nice and fast interface to search for the correct Site Definition. The image of the Site Definition is here very prominent. SharePoint 2007 used a different interface but also used images to represent each Site Definition, but in another way and in another size, so might consider updating them if you are updating your farms.

    Create a Site Definition in Visual Studio 2010

    The Site Definition image is declared in the webtemp_XXX.xml file in the Configuration element using the ImageUrl attribute. When you create a new Blank Site Definition in Visual Studio 2010 your Configuration element will look like this:

    <Configuration 
        ID="0" 
        Title="Default Site Def" 
        Hidden="FALSE" 
        ImageUrl="/_layouts/images/CPVW.gif" 
        Description="DefaultSiteDef" 
        DisplayCategory="SharePoint Customizations">
    </Configuration>

    Default Site Definition image Notice the ImageUrl property pointing to the default image. The problem here is that this little property actually has two problems:

    1. It uses a GIF image - which is not supported by the Create Site Silverlight app
    2. It uses an image of the wrong size

    The image, shown to the right, has the size of 307x291 pixels and this size does not fit into the Silverlight application. And the image is of GIF format and that is not supported by the Create Site Silverlight implementation.

    So what should I do?

    Only PNG and JPEG images can be used, so you should create your own image and deploy to the mapped Images folder. Also set the size should be 64x64 pixels to fit into the Silverlight UI. The image below shows how it looks like with four different site definitions; the default image, a GIF image, a JPEG image and a PNG image.

    Site Definitions

    As you can see the GIF images are using a default image instead of the actual GIF image.

    This is a small thing (compared to some other hefty stuff in SharePoint 2010) but for the end-user it really makes a difference and allows them to more easily select the appropriate template.

  • Enhancing the SharePoint 2010 Tag Profile Page with Bing news

    Tags: Web Parts, SharePoint 2010

    The Tag Profile Page in SharePoint 2010 is used by the Managed Metadata Service (MMS) as a landing page for a term or a keyword. It is used to describe the tag, its location in the taxonomy, synonyms etc. It also contains all the latest tagged items and a note board.

    Tag Profile Page

    The page is quite dull out of the box. Fortunately this page is a Web Part Page and can be customized as you like! Get Connected Web PartYou can add Web Parts and rearrange the page. There is not much you can do with the Tag Profile Web Part, but you can edit the Tagged Items Web Part and change how many days it should go back to look for tagged items (default 60 days). The Get Connected Web Part can be slightly configured with what links it will show, see image to the right. And the Noteboard Web Part also has some configuration options such as how many notes to show etc.

    You could add some more out of the box Web Parts if you like but none of them integrates with the current term, not even through Web Part connections.

    Wouldn't it be awesome to connect the tag to an outside service like...let's say Bing News, and see if there are any related news to the tag? Just like below? The image shows the standard RSS Web Part in SharePoint 2010 which is configured to query Bing News for the current term.

    Tag Profile connected to Bing News

    To achieve this I whipped together a small Provider Web Part that takes the term-id from the query string, looks up the value in the term store and then make that tag name available through an IWebPartField connection. This provider Web Part has one property which is used to set the name of the field. That field is then used by the RSS Web Part to create the query string to get the RSS feed. The provider Web Part is configured to be hidden on the page so that it is not seen by the users.

    The code for the Web Part looks like this:

       1:  namespace Wictor.SocialExtensions.SocialTagInfoWebPart {
       2:      [ToolboxItemAttribute(false)]
       3:      public class SocialTagInfoWebPart : WebPart, IWebPartField {
       4:          string socialTagName;
       5:          Guid termId;
       6:          
       7:   
       8:          protected override void OnLoad(EventArgs e) {
       9:              try {
      10:                  termId = new Guid(this.Page.Request["termid"]);
      11:                   
      12:              }
      13:              catch (FormatException) {
      14:                  termId = Guid.Empty;
      15:              }
      16:              // get the tag name
      17:              TaxonomySession taxonomySession = new TaxonomySession(SPContext.Current.Site); 
      18:   
      19:              Term term = taxonomySession.GetTerm(termId);   
      20:              socialTagName = term.Name;
      21:   
      22:              base.OnLoad(e);
      23:          }
      24:          protected override void RenderContents(HtmlTextWriter writer) {
      25:              writer.Write(string.Format("id:{0}, tag:{1}",termId,socialTagName));
      26:              base.RenderContents(writer);
      27:          }
      28:   
      29:          [WebBrowsable(true)]
      30:          [Personalizable(PersonalizationScope.Shared)]
      31:          [WebDisplayName("Filter name")]
      32:          public string FilterName {
      33:              get;
      34:              set;
      35:          }
      36:          public void GetFieldValue(FieldCallback callback) {
      37:              callback.Invoke(this.socialTagName);
      38:          }
      39:   
      40:          public string TagName {
      41:              get {
      42:                  return socialTagName;
      43:              }
      44:          }
      45:   
      46:          public PropertyDescriptor Schema {
      47:              get {
      48:                  return TypeDescriptor.CreateProperty(this.GetType(), this.FilterName, typeof(string));
      49:              }
      50:          }
      51:          [ConnectionProvider("Social Tag name")]
      52:          public IWebPartField GetConnectionFieldProvider() {
      53:              return this;
      54:          }
      55:      }
      56:  }

    This is a standard Web Part that exposes the IWebPartField interface (line 3) (which the RSS Web Part consumes). In the OnLoad (line 8) method the termid parameter is retrieved from the query string and this is used to lookup the name of the term using the TaxonomySession object (line 17) and stored in the local property socialTagName. The RenderContents (line 24) is used when in editing mode to display the status of the Web Part. The configurable property FilterName (line 32) is exposed so that the editor can change the name of the filter value that is sent to the consumer. For instance the Bing News RSS feed URL expects that the query parameter has the value "Query". The IWebPartField interface requires that the GetFieldValue and Schema methods are implemented. The GetFieldValue invokes the callback with the local property socialTagName and the Schema property returns a PropertyDescriptor of the type string and with the name equal to the FilterName property. Finally the provider connection end-point is configured.

    Configure Connect The TagWhen the Web Part is deployed and feature activated on the My Site Site Collection you can edit the Tag Profile page and add the SocialTagInfoWebPart to the page. Configure it so that it is hidden and set the Filter name property to Query.

    Then add the RSS Web Part to the page. Configure the Web Part, give it a meaningful name like Related on Bing and set the RSS Feed URL to "http://api.bing.com/rss.aspx?Source=News&Market=en-US&Version=2.0". This is the URL that will be used to query Bing News.

    To connect the provider Web Part with the RSS Web Part edit the hidden provider Web Part and select Connections > Send Social Tag name To > Related on Bing. In the dialog box select Get Feed Parameter From and click Finish. Then save your page. When the connection is established the RSS Web Part will append the filter name and social tag name to the RSS Feed URL, for instance http://api.bing.com/rss.aspx?Source=News&Market=en-US&Version=2.0&Query=SharePoint

    Connections

    That is all needed to enlighten the Tag Profile Page. A little bit of coding can always sharpen up your SharePoint.

    If you would like to connect it to other RSS sources, just edit the URL in the RSS Web Part and the Filter name in the provider Web Part.

    Note: there are for sure other ways to do this and I bet the SharePoint "no-code" specialists will seconds after this post is available show you how to do it with a little bit of jQuery magic :)

    Until next time...

  • Status of ChartPart for SharePoint 2010

    Tags: SharePoint, Web Parts, CodePlex, SharePoint 2010

    Chart Part

    I have recently been getting quite a few requests and comments about the status of ChartPart for SharePoint - a charting Web Part that I built about a year ago and shared on Codeplex. This latest version have had more than 6.000 downloads which I think is amazing, version 1 had close to 10.000 downloads.

    I temporarily put this project on hold a couple of months a go, due to two major reasons; the built-in Chart Web Part in SharePoint 2010 and that I'm currently writing a book (which essentially means that I have no time at all). Now we now that the out-of-the-box charting Web Part is SharePoint 2010 Server Enterprise only and I only have one and half chapters left on the book.

    So I aim to produce a new and improved ChartPart for SharePoint 2010 as soon as I return from my (well deserved IMHO) vacation.

    If you have any requests, ideas or rants about ChartPart for SharePoint then head on over to the Codeplex site and discuss or submit a feature request.

  • DevSum 2010 presentation about SharePoint 2010 BCS

    Tags: SharePoint 2010, Presentations

    DevSum 2010 is over two days packed with cool sessions. I had the last session of the day and conference but some brave SharePointers showed up and eagerly listened. I hope you enjoyed it and if you need some evening lecture you can download the presentation below, which was about SharePoint 2010 Composites and especially Business Component Services.

    DevSum 2010

    DevSum 2010 had some great content from local gurus and MVPs and the Microsoft Pattern & Practices group was here and shared some valuable knowledge! Thanks Cornerstone for arranging it!

  • SharePoint User Group Sweden May 2010 meeting recap

    Tags: SharePoint, Presentations

    This Wednesday the SharePoint User Group Sweden (#SSUG) had an awesome meeting sponsored  by Sogeti at Hotel Anglais in Stockholm. The event was sold out when announced in a few hours and we had to change conference room a few times at the hotel to fit everyone. More than 80 people showed up - our new record that we have to beat the next time.

    On the agenda for the day was first Christoffer von Sabsay (Sogeti) presenting about the Handelshögskolan SharePoint 2007 WCM case. A great presentation with a good deal of tips and tricks. MVP Göran Husman (Humandata) was up next presenting about the offline capabilities in SharePoint 2010 and Office 2010, also an interesting session with good insight how to combine Office, SharePoint Workspace and SharePoint for optimal flexibility. Last, but not least, I (Wictor Wilén, Connecta) did a session about SharePoint 2010 licensing and the related products. For me it was a good exercise to dig in to the gazillion options of SharePoint licensing.

    You can download the presentations here (all in Swedish):

    Thanks to all speakers, sponsors and to the attendees (especially those who shared a pint at the hotel bar :-)

    If you would like to speak, attend or host upcoming Swedish SharePoint User Group meetings - please contact me.

  • DIWUG SharePoint eMagazine 2nd edition

    Tags: SharePoint 2010

    SharePoint eMagazine The 2nd edition of the Dutch Information Worker User Group SharePoint eMagazine is out! It's a free SharePoint magazine, focusing on SharePoint 2010. The first edition released a couple of months ago was a fantastic opening issue with awesome content and It looks like this edition is keeping up the high standard. Looking forward to the series continuing...

    This issue contains some really interesting content ranging from an article about WCM in SharePoint 2010 from Waldek Mastykarz, CKS:DEV from Wes Hackett and feature/solution life-cycle/versioning by Anders Rask. And also an article about SharePoint 2010 Themes by yours truly.

    Happy reading!

  • SharePoint 2010 Sandboxed Web Parts does not support file uploading

    Tags: SharePoint 2010

    This is just a friendly reminder for you who tries to build a Sandboxed Web Part for SharePoint 2010 and trying to use the FileUpload or HtmlInputFile controls - it will not work. The uploaded files are not transferred to the sandboxed processes and cannot be used in the sandbox.

    The SharePoint 2010 sandbox runs in a separate process and all requests from the IIS to SharePoint are marshaled over to the User Code process. It is during this process the files that are uploaded during the request are lost - you will always see that HttpContext.Current.Request.Files.Count is equal to 0, or similar properties on the upload controls are set to null.

    For text or XML files it is quite easy to work around using other types of input fields (and optionally some JavaScript hacks).

    This is (probably) due to security issues - we do not want user code solutions to be able to upload malicious files to compromise the security.

    As always - this was learned the hard way...

  • Custom application pages in the SharePoint 2010 Sandbox

    Tags: Web Parts, SharePoint 2010

    The Sandbox in SharePoint 2010 allows Site Collection administrators to upload solutions in their Site Collections without access to the physical server. This is a great way to open up for creativity and for each Site Collection owner to expand the functionality of their Site Collection without adventuring the stability of the SharePoint farm. Sandbox Solutions do have some limitations, for instance we cannot add new Application Pages. Application pages are normally pages added to the _layouts folder, which are located in the {SharePoint Root}\TEMPLATE\LAYOUTS physical folder on each server.

    Application pages or similar are often used in different scenarios such as when you are building configuration or settings pages. I use them quite often and felt a bit limited with building Sandboxed solutions without them.

    Sandboxed solutions still allows us to upload Content Pages, that is pages that are located in a document library for instance. So one workaround is to build a Web Part containing the custom logic and a Content Page that contains this Web Part. Then deploy this to the Solution gallery in your Site Collection. And this is how to do it:

    Create a project

    Create a new Empty SharePoint 2010 project using Visual Studio 2010 and deploy it as a Sandboxed solution.

    Add a Web Part item

    Solution ExplorerThen add a new Web Part item to your project. Remove the Web Parts Control Description file (.webpart) and the Elements.xml file. We do not want to add the Web Part to the Web Part gallery, this Web Part will only be used by our Sandboxed Application Page.

    Then build your control logic in the Sandboxed Web Part.

    Add a Module item

    In the Web Part item add a new Module item. Rename the Sample.txt file to AdminPage.aspx or similar - just make sure the extension is .aspx. Your Solution Explorer should then look like the image to the right.

    Edit the URL and location in the elements.xml file if you want to deploy it in a document library or any other location. If you have named your items as shown above your page will end up at http://site/AdminPage/AdminPage.aspx.

    Edit the ASPX page

    Open up the the AdminPage.aspx and build a standard Web Part Page. You can copy the source from a basic Web Part Page using SharePoint Designer for instance. The source should look something like this when you cleaned it up:

    <%@ Page language="C#" 
      MasterPageFile="~masterurl/default.master"  
      Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c"%>
    <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" 
      Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    
    <asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
    Sandboxed Admin Page
    asp:Content>
    
    <asp:Content ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">
    Sandboxed Admin Page
    asp:Content>
    
    <asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
    <style type="text/css">
    body #s4-leftpanel {
        display:none;
    }
    .s4-ca {
        margin-left:0px;
    }
    style>
    asp:Content>
    
    <asp:Content ContentPlaceHolderId="PlaceHolderLeftNavBar" runat="server">asp:Content>
    
    <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
    
    asp:Content>

    In this Web Part Page I have removed all unnecessary page directives and only kept the Page directive with the master page reference and the import of the Microsoft.Sharepoint.WebPartPages namespace, which we will soon use. In the PlaceHolderAdditionalPageHead some CSS is added to remove the Quick Launch and I added a page title and heading.

    Of course you can use any kind of HTML in here. You cannot use code-behind or inline server-side code though.

    Add the Web Part

    In the PlaceHolderMain the Web Part will be added. This is done by using the SPUserCodeWebPart, which is a wrapper for Web Parts that lives in the Sandbox. In my case it will look like this:

    <WebPartPages:SPUserCodeWebPart 
        runat="server" 
        Description="Admin" 
        Title="Admin" 
        AssemblyFullName="$SharePoint.Project.AssemblyFullName$" 
        SolutionId="473f9e55-bf55-4283-a9ce-3de0b05650f7" 
        ID="adminwp"     TypeFullName="Wictor.SBAppPage.AdminWebPart.AdminWebPart" >
    WebPartPages:SPUserCodeWebPart>

    Here we need to edit two things. First the TypeFullName must be the full name of your Web Part, just check the .cs file of your Web Part if you don't know how to get it. Secondly we need to set the SolutionId attribute to the solution id value of our solution. You can get a hold of this id by opening up the Package Editor and select Manifest. Then check the Solution element for the SolutionId attribute and just copy it.

    SolutionId

    The AssemblyFullName attribute contains a Visual Studio replaceable parameter which inserts the full name of your assembly.

    Deploy and enjoy!

    That's it - just deploy your solution and navigate to your custom sandboxed application page.

    Ready for action!

  • Dissecting the Office Web Apps cache in SharePoint 2010

    Tags: Microsoft Office, SharePoint 2010

    The Office Web Apps, OWA, in SharePoint 2010 is a great way to enhance the SharePoint experience. It allows users without a decent OS or a locally installed Office client to view and edit Word, Excel, PowerPoint and OneNote documents.

    When you install and correctly configures Office Web Apps (yea, can be a bit of a hazzle if you like me avoid the Farm Configuration wizard) and then enable the required Site Collections feature a cache will be created. This cache is used by Word and PowerPoint Web Apps to store the renditions (XAML) of the documents to speed up the process. Office Web Apps will create one cache per Web Application and the cache is stored in one of the Content Databases attached to the Web Application.

    The cache is actually a Site Collection, based on the Team Site template, which contains a Document Library called cache which holds the cached content.

    Office Web Apps Cache site

    The content in this document library is ZIP compressed files with the XAML and images of the actual renditions.

    Cached documents

    By default the cache is set to contain 100GB of caching per cache (i.e. per Web Application). You can configure the cache size using the Set-SPOfficeWebAppsCache PowerShell cmdlet. So 100 GB of data will end up in your content database if you use OWA quite frequently and this will also be a part of your backups!

    The Cache Site Collection

    What you should do is to move this Site Collection to a separate database! This database could have a separate backup schedule and SLA, since this is just a cache. It is better to have it in its own database instead of reducing the cache size. Of course the cache size depends on the usage most read or read/write using OWA. For instance if you have most read ops then you could easily increase the cache size and increase the retention times for the cache.

    So how do I move the cache then. Well, since it is just a simple Site Collection - just as we do normally to when site collections grow...

    1. Create a new database, call it for instance OWA_Cache
    2. Move the cache Site Collection to the new database
    3. Update your SLAs

    To move the cache Site Collection we can use some PowerShell love like this:

    $db = Get-SPContentDatabase | ?{$_.Name -eq "OWA_Cache"}
    $webapp = Get-SPWebApplication | ?{$_.Url -eq "http://sp2010/"}
    Get-SPOfficeWebAppsCache -WebApplication $webapp
        | Move-SPSite -DestinationDatabase $db

    Don't forget an IISRESET - the ultimate SharePoint command!

    Cache moved to separate Content DB

    Notice that I also specified maximum of 1 Site Collection to this content db. We do not want real Site Collections ending up there...

    Hmm...I'm turning this blog into an IT-pro blog....

  • SharePoint 2010 user profile properties temporarily disabled

    Tags: SharePoint 2010

    I am currently setting up SharePoint 2010 farms back and forth testing out the most optimal ways using least privileges and different configurations. The by far most complex part in the configuration is the User Profile Service Application and the User Profile Sync. Spencer Harbar have fortunately documented how to do it properly in his Rational Guide to implementing SharePoint Server 2010 User Profile Synchronization article. Following that you will likely not fail...

    Today I configured a new farm to thoroughly document all the involved steps from a clean OS to an optimal farm I followed Spencers instructions and after the mandatory boot (I always need the boot to get the FIM working) the UPS was up and running. I headed on over to the My Site to check that all properties was correctly imported and found this:

    Updating values in this field is disabled temporarily.

    Some of the user profile properties had this error. "There was a problem retrieving data for this field. Updating values in this field is disabled temporarily. You can still update values in other fields". I actually saw this error earlier today at a colleagues new farm.

    I was first tracing backwards what did I do wrong this time and found no errors so I headed on over to check how that property was defined in the service app. And now things really made me believe that I needed to start all over again.

    Office Location property!!! 

    This property really is misconfigured! I checked the miisclient.exe for mappings, examined logs inside out etc. I started up another farm I built the other day and in that farm the property looked fine and had no strange mapping. It's Friday and I don't have time for this - so I turned to the SharePoint Jedi Spence and without doubt he had the answer in his sleeve. The error is due to the fact that the Managed Metadata Service is not setup or configured.

    Since the UPS is the service I usually start with I had no other service apps running. I added the Managed Metadata Service and tada - the properties was working as they should. So if you stumble upon this you now know what to do and can leave Spence doing what he really should be doing Friday evenings...

    Thank you Spence!

  • Timer job changes and additions in SharePoint 2010

    Tags: SharePoint 2010

    Timer JobsTimer jobs is a great feature of SharePoint to use when you need to perform background execution at regular or specific times or when you need to execute code on all or selected servers in the farm. A timer job is a persistable object deriving from the SPJobDefinition class.

    SharePoint 2010 has updated this class in many ways, to the better. Not only can the timer jobs be configured and monitored better through Central Administration they can also be invoked on demand.

    SPJobDefinition changes

    The SPJobDefinition class in SharePoint 2010 has received some major updates. First of all the class now inherits from IBackupRestore which is an interface that tells that the timer job can be backed up. The IBackupRestore interface contains methods that you can override and implement to perform actions before and after restores and backups of the timer job. You need to override the EnableBackup property and return true if you would like to make a backup of the job.

    Another great addition is that all timer jobs now have a Progress value (ranging from 0 to 100) which you can set by calling the UpdateProgress(int) method. Awesome for long running timer jobs and the progress is shown in Central Administration.

    Long running job

    The new timer job method RunNow() creates a one-time-schedule and schedules it immediatley, if it is not disabled.

    There are lot of new timer job classes that all inherits from the SPJobDefinition. They are specifically made to target different types of artifacts of SharePoint. Some of the most interesting and valuable are:

    Pausable Timer Jobs

    You can now create pausable timer jobs. This is done by inheriting from the SPPausableJobDefinition and overriding Execute(SPJobState) instead of Execute(Guid). You can then use the current job state (SPJobState) to store values which are retrieved when the job is resumed.

    Running jobs on all content databases

    Another new timer job derivative type is the SPContentDatabaseJobDefinition.This is a timer job specifically made to perform actions on content databases. The timer job is distributed on the WFE servers and each content database is only processed by one job. Override the Execute(SPContentDatabase, SPJobState) to add your own processing. The job supports pausing.

    Running jobs on all Site Collections

    A really interesting new timer job type is the SPAllSitesJobDefinition. This one is derived from the SPContentDatabaseJobDefinition and has a method called ProcessSite(SPSite, SPJobState) which you override to process the SPSite object. This could be very useful to build site inventories/directories.

    Running job on a specific server

    The SPServerJobDefinition is a pausable timer job that is designed to be targeted to a specific server (SPServer).

    Running jobs for specific services

    The SPServiceJobDefinition is another pausable timer job that runs a job on all servers where a specific SPService has been provisioned. A very similar job is the SPFirstAvailableServiceJobDefinition which runs the job on the first available server which has a specific SPService installed. If you would like to run a job an all servers you can easily use SPServiceJobDefinition. Then use the timer job service (which is installed on all servers, except dedicated database servers) and pass SPFarm.Local.TimerService as the SPService parameter in the constructor.

    All of the new specific timer jobs are essentially smart derivatives of the SPJobDefinition but using these new abstract classes will certainly save you some time when you need to target your timer jobs.

  • Tips for doing SharePoint demos on virtual machines

    Tags: SharePoint, Windows 7, SharePoint 2010, Windows Server 2008, VMWare, Windows Server 2008 R2

    It's Friday and thought that I should share some small tips on how to make your SharePoint demonstration experience better. I assume that you have a quite powerful laptop with virtual machines running SharePoint.

    I used to do my demos directly in the virtual machine, in full screen mode. This requires that I have all the necessary client components installed such as Office, SharePoint Designer, the Windows Server Desktop Experience feature enabled etc. All this of course take resources such as memory and CPU from the virtual machine. Also Internet Explorer consumes CPU cycles and if you're using Firefox in the demo you get another memory hog in your virtual machine.

    A better approach is to use you local workstation as the client, In my case I have Windows 7 and VMWare running (yea, I like to promote them...) the virtual machines. This allows me to show a more realistic case when doing demos.

    The Network

    Networks The first tip here is how to configure the network for the virtual machines. I normally have one AD server and one SharePoint server which are connected using a separate network, so that I can use static IP addresses. Then I have a secondary network on the SharePoint VM which is host-only with known IPs, that is I can access the VM from the client using a browser or an Office application. I also have a third network on the VM which is connected to the Internet. I only enable this third NIC if I need to access web services and such from my VM.

    Then I add entries to the hosts (...\system32\drivers\etc\hosts) file with the IP numbers from the host-guest network so that I can use domain names instead of IP-numbers.

    Authentication

    I never have the host and clients on the same domain. My laptop is connected to my company's domain and the VMs all use their own directories. To get rid of annoying authentication prompts I use the Windows Vista/Windows 7 feature to store credentials - the Credential Manager.

    Credential Manager

    The Credential Manager allows you to save Windows credentials for a specific Internet or network address. Just add the name of the server, which you added to the hosts file, and then your default user username and password. Voila! You can now directly from your client/host browse to your virtual server using a good looking URL and without any authentication prompts.

    Firefox, Safari and other obscure browser does not use this credential manager and I use them to log in as other users.

    If you don't do this and log on to your server from the web browser you will be asked for the credentials every time you open an Office document from the server or when you open the site using SharePoint Designer.

    If you use these small tips you will have a much better experience when doing demos, developing or configuring your SharePoint virtual machines.

    Have a nice weekend!

  • SharePoint 2010 Central Administration Service Application Shortcut Web Part

    Tags: SharePoint 2010

    While fiddling, developing and configuring SharePoint 2010 I use the Service Application management a lot. This requires that you go to Central Administration, click on Manage service applications and then click on the service application that you need to configure or manage. I believe that managing the service applications are one of the most common tasks for people like me (I know some of you readers gets more fired up about the monitoring and upgrade parts of CA though).

    Previously I have use a links Web Part and added all links to the Service Applications to get a shortcut to them. But when you are adding new ones and removing old ones they get new application ids and also new management URLs. This makes me have to update the links Web Part once in a while.

    Introducing Manage Service Applications Web Part

    Therefore I whipped up a small feature that contains a Web Part with links to the management pages for all manageable Service Applications. You can place it anywhere you like in Central Administration, preferable on the CA start page.

    This is how the Web Part looks like. It provides you with a link to the SA management page and also shows the current status of the service application.

    CA Service Application Shortcut Web Part

    Installation

    To install the feature, just download the Wictor.ServiceAppLinks.wsp WSP file and add this to the solution store and then deploy it to the central administration web application/site collection. Go to the Site Collection Features in Central Administration and activate the Manage Service Application Shortcuts. One the feature is activated the Web Part is automatically added to the default page of Central Administration.

    Manage Service Application Shortcuts feature

    When it is deactivated it is also removed from the default page. If you prefer to have it in any other location it can be found in the Web Part gallery, just like any Web Parts.

    Web Part Gallery

  • Plan your SharePoint 2010 Content Type Hub carefully

    Tags: SharePoint 2010

    Currently setting up a new environment on SharePoint 2010 (which was made available for download yesterday if anyone missed that :-). One of the new features of SharePoint 2010 is to set up a Content Type Hub (which is a part of the Metadata Service Application), which is a hub for all Content Types that other Site Collections can subscribe to. That is you only need to manage your content types in one location.

    Setting up the Content Type Hub is not that difficult but you must make it very careful to avoid a lot of work and troubleshooting. Here is a short tutorial with a few tips and tricks to make it easy for you to get started.

    Determine location of Content Type Hub

    First of all you need to decide in which Site Collection to place your Content Type Hub; in the root site collection or a specific one. I think using a specific Site Collection that only acts as a Content Type Hub is the best way, there are no best practice as of now. So I create a new Site Collection, at for instance http://server/sites/CTH/. The top-level site of this site collection should be for instance a Team Site. You cannot use Blank Site by default, which would have been the best option IMHO, since that site does not have the Taxonomy feature stapled upon it (check the TaxonomyFeatureStapler feature for which site templates that can be used).

    Configure Managed Metadata Service Application

    Next you need to create your Managed Metadata Service Application or configure the existing one, Central Administration > Application Management > Manage Service Applications. Select the Managed Metadata service application and click Properties if you already have created it.

    Managed Metadata Service

    In the bottom of the dialog window when you are creating the service application or when you are editing the properties is a section to fill in the Content Type Hub. In this text box fill in the URL of the Content Type Hub. It is essential that you have decided where your Content Type Hub will reside, since once this is set you cannot change it. The only way to change it is to rebuild the whole managed metadata service application! Also make sure that you enter the URL correctly. I did copy and paste the URL once and got the /default.aspx in the URL which funked the whole service up. Make sure that you only use the URL to the Site Collection of the hub.

    Service Application properties

    Now you have to set up so that other Site Collections can consume the content types from the hub. This is done by selecting the connection for the managed metadata service application and clicking properties.

    Service Connection

    A new dialog window opens and there you need to click the Consumes content types from the Content Type Gallery at nnnn.

    Serivce Connections gallery

    Now you are free to syndicate your Content Types from the Hub.

    Publish Content Types

    To publish a Content Type from the hub you need to go to Site Settings > Content Types and select the content type that you would like to publish. Then select Manage publishing for this content type. This takes you to a page from where you can Publish, Unpublish or Republish the content type.

    Publish it!

    Once the content type is published it can take up to an hour for the subscribing Site Collections to get it. This is controlled by the Content Type Subscriber job that is scheduled to run once an hour. To speed up your publishing just go to Central Administration > Monitoring > Review Job Definitions > Content Type Subscriber and click Run now and you content type is very soon available for use.

    Published Content Type status

    You can check the status of the content type publishing in your destination site collections by selecting Site Settings > Content Type Publishing. From here you can force a refresh of all subscribed content types, see which ones that are subscribed and finally check the publishing error log. This error log is very useful for detecting errors during the publishing. For instance if you use any features such as ratings, metadata, document ids in your content type hub and your destination site collection does not have those features available this will be reported here.

    Have a nice weekend...I know what I will be doing...

  • Create SharePoint 2010 Managed Metadata with Excel 2010

    Tags: Microsoft Office, SharePoint 2010

    Building the metadata structure in the Term Store Manager in SharePoint 2010 is not the most convenient way. I prefer working with the metadata structure and terms in an Excel document so that I can discuss the structure with colleagues and clients before implementing it.

    The Term Store Manager allows you to import a comma separated text file containing a Term Set. By default the Excel 2010 Save as CSV does not save in the correct format and for that I have made a Excel 2010 macro enabled template which produces the correct format.

    The Excel document allows you to build a Term Set per sheet, see figure below. It contains a number of columns:

    • Term Set Name - name of term set. Only needed on first row
    • Term Set Description - description of term set. Only needed on first row
    • LCID - the locale identifier. Can be left blank for default LCID
    • Available for tagging - TRUE if the term should be available for tagging otherwise FALSE
    • Term Description - description of the term
    • Level N Term - the name of the term. See figure below on how to build the structure

    Term Set in Excel 2010

    When the term set is ready you click on the new Ribbon tab added by the Excel document called SharePoint 2010 and then select Create Term Store File. Excel will then ask you for a file name and produce an import file for the Term Store from the active sheet.

    Term Store Ribbon tab in Excel 2010

    If you click on Create New Term Store Sheet an new workbook sheet will be added to the workbook in which you can add another term set.

    To import the term set into your Managed Metadata store, create a new Group and select Import Term Set, as in the figure below.

    Import Term Set

    SharePoint will then parse your file and import the term set. And it will look something like this:

    image

    Download the Excel 2010 document

    You can download the macro-enabled Excel 2010 document here. Unzip the file and open the document (TermStoreCreator.xltm) to create a new workbook.

  • A whole lot of SharePoint 2010 guidance available - weekend reading

    Tags: SharePoint 2010

    Documents...SharePoint 2010 is just around the corner and Microsoft is starting to release guidance and planning documents for the new and shiny version. Up until now there has been little guidance on hardware and software limits/boundaries/recommendations of SharePoint 2010 and comparisons with SharePoint 2007. But now when the release is imminent is essential to get up to speed on this. Here is a compilation of some of them that I find really interesting and will take for weekend reading.

    SharePoint Server 2010 capacity management: software boundaries and limits: A huge document with all details of boundaries, supported limits and thresholds of lists, sites, databases, network etc that you need to know about SharePoint 2010.

    SharePoint Server 2010 performance and capacity technical case studies: Two different studies on performance and capacity. One for a publishing intranet and on a collaboration environment. These are actual used implementations of SharePoint at Microsoft.

    SharePoint Server 2010 performance and capacity test results and recommendations: Nine different documents focusing on different scenarios and services with test results and performance characteristics.

    Databases That Support SharePoint 2010 Products: A great Visio diagram describing all the databases in the SharePoint family. Something to decorate your living room with.

    Have a nice weekend everyone. And I hope that the ash cloud disappears so that everyone attending the Evolutions conference will have a good time next week.

  • Create custom Rating icons for SharePoint 2010 Server

    Tags: SharePoint 2010

    SharePoint 2010 contains functionality for rating documents and items using a classic five-star rating approach. But those starts looks a little bit like the Google stars, right?

    Wouldn't it be cool to brand the rating and use custom icons like this:

    The solution is quite easy actually. You need to create a set of images and then set a few properties on the SPWeb object of the top-level site in the Site Collection.

    Images

    First you need four images. Two images used for CSS-sprites and two images used when hovering/selecting the rating. I used the following images:

    This image is used for standard left-to-right rendering of the ratings.

    This image is used for right-to-left rendering of the ratings.

    |

    And these final two images are used when selecting the new rating.

    Deploy it as a feature

    You should deploy everything as a feature, you should know this by now. Create an empty SharePoint 2010 project and add a new Site Collection scoped feature. Then add an Images mapped folder in which you add the four images.

    Visual Studio 2010 solution

    To set the properties of the TLS site in the Site Collection add a new Event Receiver to the feature. Edit the FeatureActivated method and add code like this:

    SPSite site = properties.Feature.Parent as SPSite;
    SPWeb web = site.RootWeb;
    web.AllProperties["ratings_imagestripurl_old"] = web.AllProperties["ratings_imagestripurl"];
    web.AllProperties["ratings_imagestripurl"] = "/_layouts/Images/Wictor.CustomRatings/AlienRatings.png";
    web.AllProperties["ratings_imagestriprtlurl_old"] = web.AllProperties["ratings_imagestriprtlurl"];
    web.AllProperties["ratings_imagestriprtlurl"] = "/_layouts/Images/Wictor.CustomRatings/AlienRatingsRtl.png";
    web.AllProperties["ratings_newratingiconurl_old"] = web.AllProperties["ratings_newratingiconurl"];
    web.AllProperties["ratings_newratingiconurl"] = "/_layouts/Images/Wictor.CustomRatings/AlienRatingsNew.png";
    web.AllProperties["ratings_emptyiconurl_old"] = web.AllProperties["ratings_emptyiconurl"];
    web.AllProperties["ratings_emptyiconurl"] = "/_layouts/Images/Wictor.CustomRatings/AlienRatingsEmpty.png";
    web.Update();

    This will update the properties of the site and also save the original values so that we can restore them in the FeatureDeactivating method, like this:

    SPSite site = properties.Feature.Parent as SPSite;
    SPWeb web = site.RootWeb;
    web.AllProperties["ratings_imagestripurl"] = web.AllProperties["ratings_imagestripurl_old"];
    web.AllProperties.Remove("ratings_imagestripurl_old");
    web.AllProperties["ratings_imagestriprtlurl"] = web.AllProperties["ratings_imagestriprtlurl_old"];
    web.AllProperties.Remove("ratings_imagestriprtlurl_old");
    web.AllProperties["ratings_newratingiconurl"] = web.AllProperties["ratings_newratingiconurl_old"];
    web.AllProperties.Remove("ratings_newratingiconurl_old");
    web.AllProperties["ratings_emptyiconurl"] = web.AllProperties["ratings_emptyiconurl_old"];
    web.AllProperties.Remove("ratings_emptyiconurl_old");
    web.Update();

    All you then have to do is to deploy and activate the feature. Unfortunately you need to recycle the application pool to get the hovering functions to work.

  • SharePoint 2010 - The Developer Tour in Sweden

    Tags: SharePoint 2010

    SharePoint 2010 The release SharePoint 2010 and Office 2010 is imminent and I can already smell them! Microsoft Sweden with André Henriksson will take a tour around our beautiful country and show all the good stuff that is coming for us developers called SharePoint 2010 - The Developer Tour.

    Me and my awesome MVP mate Tobias Zimmergren will help out during some stops of the tour. It's a half day full with developer goodies that you can't miss out on! The tour will stop in Umeå, Göteborg, Sundsvall, Malmö and Stockholm. I will be doing the last stop and that one is after RTM and general availability of SharePoint 2010 so be sure that I will show you the latest and coolest bits of the fantastic SharePoint platform!

    Update: Umeå has been changed to 19th of May and Göteborg has been changed to the 25th of May

    And if you can't get enough of all the great stuff that is crawling out of Redmond there is a full afternoon with web-development by Johan Lindfors (Microsoft).

    See you there!

  • Upcoming engagements of spring 2010

    Tags: Personal, SharePoint 2010, Presentations

    Wictor presenting SharePoint 2010 in Stockholm I'd like to take the opportunity to tell you about some of my upcoming engagements this spring.

    SharePoint 2010 - the Developer Tour - May 17th, Stockholm

    A half day introduction to SharePoint 2010 development arranged by Microsoft in Stockholm. If you are new to SharePoint development or a skilled SharePoint 2007 developer you should not miss this out. Together with Microsoft we will dive into the wonderful world of the new Visual Studio 2010 SharePoint Developer Tools and SharePoint Designer 2010.

    Introduction to SharePoint 2010 - May 20th, Göteborg

    A half day introduction to all the new and awesome features of SharePoint 2010. This is a repeat of the seminar held twice in Stockholm with full venues, arranged by AddSkills with speakers from Microsoft, FAST and Connecta.

    Developer Summit 2010 - June 1st-3rd, Stockholm

    Developer Summit is a two day conference + one day workshop arranged by Cornerstone. I will talk about SharePoint 2010 Composites and take a look at the Business Connectivity Services, SharePoint Designer 2010 and the SharePoint tools for Visual Studio 2010.

    Unfortunately I will not attend any of the big conferences, there are just no time at the moment with the book writing and all but I trust in the Twitterverse and my colleagues to give me the latest news.

    Laters...

  • I am a SharePoint Server MVP

    Tags: Personal, SharePoint

    While commuting home this beautiful afternoon I received an e-mail from Microsoft containing the following:

    Congratulations! We are pleased to present you with the 2010 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in SharePoint Server technical communities during the past year.

    I am very, very proud of receiving this award and it gives me a real boost to continue exploring the SharePoint world...

    MVP

    Thanks to all current and former SharePoint MVP's out there - without this SharePoint community I would not have as fun as I'm currently having!

    Time to celebrate...with some book writing this weekend, but first get my daughters bicycles ready for this season!

  • SharePoint 2010 Developer Dashboard configuration feature

    Tags: Downloads, SharePoint 2010

    The Developer Dashboard in SharePoint 2010 can be configured using STSADM commands, PowerShell or some coding. To easy turn the Developer Dashboard on and off I have created a Farm scoped feature that allows you to configure the Developer Dashboard from Central Administration > General Application Settings > Development Settings.

    Developer Dashboard configuration in Central Administration

    The Developer Dashboard contains more configuration options than just to turn it on or off. With this feature you can configure all of the options available for the dashboard:

    • Display mode (On, Off, On Demand)
    • Auto Launch of Developer Dashboard when critical events is tracked
    • Enable the ASP.NET tracing output
    • Configure the maximum amount of SQL queries traced
    • Configure the maximum amount of critical events traced
    • The required permission to view the Developer Dashboard (Full, None or Custom)

    Configuration of the Developer Dashboard

    If you think this is something you need, and of course you do then you can download the feature here. Extract the ZIP file and install the WSP into your SharePoint 2010 farm!

  • Working with SharePoint 2010 Correlation ID in PowerShell and code

    Tags: SharePoint 2010, SharePoint 2010 Web Parts in Action

    SharePoint 2010 the logging has been extended with a new Correlation ID which is unique for each request or operation. The Correlation ID makes it very easy to track down any unexpected errors since you can search for the id in the trace logs. This unique ID is also maintained between servers for instance when making a call to a service application.

    SharePoint 2010 error message The SharePoint 2010 error page also shows this Correlation ID so that any end-users seeing the message can contact support and give the the Correlation ID. Using the ID the support team can then track down the cause of the error.

    To Search for the Correlation ID in the Trace Logs the Windows Suisse Knife called Notepad can be used but a far better, faster and more 2010:ish approach is to use the Get-SPLogEvent cmdlet.

    Get-SPLogEvent

    The Get-SPLogEvent cmdlet is used to search the local Trace logs or merged (Merge-SPLogFile) logs. To search for a Correlation ID the following PowerShell command line can be used.

    Get-SPLogEvent |
    ?{$_.Correlation -eq "2872bd2d-a0a5-4cac-b218-f504a7d2a4c5"} |
    ft Category, Message -Autosize

    This will search the Trace Logs for the Correlation ID and output the category and message of any records in the log related to the id.

    Correlation ID in code

    If you have error handling in your code and perhaps logging information manually to the Trace Logs you can get the current Correlation ID by using a native method called EventActivityIdControl() found in advapi32.dll. You have to import the method like this:

    [DllImport("advapi32.dll")]
    public static extern uint EventActivityIdControl(uint controlCode, ref Guid activityId);
    public const uint EVENT_ACTIVITY_CTRL_GET_ID = 1;

    And then use it in code like below, perhaps in a catch statement

    Guid g = Guid.Empty;
    EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref g);
    this.Controls.Add(new Label { 
        Text = string.Format("An error occurred with correlation id {0}", g)
    });

    Pretty neat! If you like it you can find even more information on the topic in my upcoming book SharePoint 2010 Web Parts in Action.

  • Deployment and security options of custom code in SharePoint 2010

    Tags: SharePoint 2010

    In SharePoint 2010 there are more ways to deploy custom code than in its predecessors, the reason is the introduction of the Sandboxed solutions. There are basically now three different ways to deploy custom assemblies:

    • Full trust solutions, aka Farm solutions - The assemblies are registered in the GAC and runs under full trust
    • Partial trust solutions, aka Web Application solutions - The assemblies are deployed to the bin folder of a specific Web Application
    • Sandboxed solutions, aka User code solutions - The assemblies (solutions) are deployed to the Site Collection gallery

    These are the basic variants of how to deploy custom assemblies. There are actually a few variants of them, but more about them later. So which one should I use and when? Let's go through them all and look at the pros and cons.

    SharePoint 2010 is still in beta (RC for some) and there are no best practices of this. It's hard to create a best practice before the product is released and actually tested in all situations. I guess we have to wait a few months until we have general best practice. Meanwhile consider this...

    Sandboxed Solutions

    The Sandboxed Solutions runs inside the a special service, called Microsoft SharePoint Foundation Sandboxed Code Service, which is a completely and separate application domain than the SharePoint application pools. The Sandboxed solutions are monitored and if they consume to much resources or fails to many times SharePoint automatically shuts the solution down. The code running in a Sandboxed assembly does not have access to the full SharePoint API, basically it's just the classes from Site Collection level and below. The sandbox is also protected with a very minimal CAS policy which for example prohibits the user code solutions from calling web services, making database calls or accessing the file system.

    Sandboxed solutions are deployed into the Solution gallery of a Site Collection and only access that Site Collection. They can be deployed without having any downtime of the farm or web application. Anyone within the Site Collection Administrators group can upload solutions to the gallery and activate them. Farm administrators controls how much resources each Sandbox can use and can also block specific solutions from running at all.

    Pros Cons
    Can easily be deployed by Site Collection Administrators Very limited CAS policy
    Resource usage is monitored * Current uncertainty about the monitoring stability
    Secure Hard to deploy in a farm
    Great support in Visual Studio 2010  
    Only crashes the Sandbox if it blows  

    * There are currently many discussions in the blogosphere and on Twitter about how good the monitoring actually is. There is a timer job running that calculates the resource usage every 15 minutes, by default, and during 15 minutes a lot of things can happen.

    I must admit that I was very skeptical at first to the Sandbox but the more I have tested and experimented with it the more satisfied I am. Also looking at my current day-job assignment I so much would like to have the Sandbox right now!

    Farm Solutions

    The Farm solutions or full trust solutions adds the assembly to the Global Assembly Cache, GAC, which means that they can run without any CAS policies, i.e. under full trust. The assemblies can be accessed from any application in the farm. Full-trust solutions are (was?) the most common way to install solutions since it is easy and requires no knowledge of for instance CAS policies. The code running in a full trust solution has the same access as the application pool account to the local server and can do almost what it want with the server. Deploying Farm solutions should only be done with code that you really trust.

    Only farm administrators can upload new farm solutions to the configuration database and most often an application pool recycle is needed, especially when updating solutions.

    Pros Cons
    Easy to implement Only Farm Administrators can add new solutions (can be a pro also :-)
    Great support in Visual Studio 2010 Downtime when updating
    Runs in full trust Have to much privileges
      Can crash the whole server

    Web Application Solutions

    Solutions deployed to the web application bin directory was the way to go in SharePoint 2007 when you wanted/needed to secure you application using CAS. This partial trust option is still valid in SharePoint 2010. Web application deployed solutions by default only have a very minimal CAS policy applied. Using custom CAS policies it is easy ("CAS is easy!" - Todd Bleeker) to give more privileges to assembly. Installing these solutions also requires a Farm Administrator but they are only applied to specific Web Applications. Updating the assembly does not require an application pool recycle.

    Visual Studio 2010 have support for Web Application deployment but not for custom CAS policies. If you need custom CAS policies you need to hack some XML and you cannot use the F5-debugging experience in Visual Studio. Instead you have to install the solution using PowerShell or create your own Visual Studio SharePoint Deployment Steps.

    Pros Cons
    Security policies can be configured and kept minimal Only Farm Administrators can add new solutions (can be a pro also :-)
    Minimal downtime when upgrading No support OOB for custom CAS policies in Visual Studio 2010
    Only crashes the web application  

    Sandboxed Solutions with User Code Proxies

    There is actually a fourth option of deployment. And that is to use Sandboxed Solutions in combination with a full-trust User Code Proxy. A User Code Proxy is a special assembly and class that is registered in the GAC and running under full trust. This class exposes an operation that can be called by the Sandboxed code. Since it runs under full trust we can easily create a Proxy Operation that calls a web service or access other protected (from the Sandbox) sources. The proxy has to be registered by a farm administrator and is accessible to the whole farm, which means that all developers who knows about the assembly, class and operation can use the operation.

    Since the User Code Proxy runs under full trust you need to be careful about that one. But if you design your application carefully the proxy operations should be kept to a minimum and quite small. This allows you to make the thorough code review on only a fraction of the whole application.

    Tip: Make the User Code Proxies as Farm solutions which are registered using Feature activation and unregistered using deactivation of the Feature. Then your farm administrators can enable and disable them easy!

    My Recommendation

    Which one to choose is up to you, your client and the SLAs. Based on my experience with SharePoint 2010 so far is that I do recommend that you always start with building your solutions as Sandboxed Solutions. If that is not enough then try to add one or more User Code Proxies. Only use full-trust solutions when you have no other option. And pleas do still consider Web Application deployment - even though Visual Studio doesn't have that good support (right now, let's see what the CKS:DEV team have up their sleeves)

    What do you think?

  • Confusing names of commands in SharePoint 2010

    Tags: SharePoint 2010

    If you have been developing with SharePoint for the last few years you probably are very aware of the SPWeb and SPSite naming is a bit confusing. SPWeb is actually a site and SPSite is a site collection. It's always fun explaining this to new SharePoint developers...

    In SharePoint 2010 this naming convention confusion continues and now expands to the administration of SharePoint.

    Let's for example take the example when you are activating or deactivating features. In the web interface of SharePoint 2010 and SharePoint 2007 it is called Activate and Deactivate.

    Feature activation in SharePoint 2010

    The same term is used in STSADM with the activatefeature and deactivatefeature operations when scripting feature activations and deactivations. But STSADM is old-school in SharePoint 2010 right? So we use PowerShell to deploy the solutions, and guess what, there are no cmdlets using the verb activate or deactivate. Instead activate is called enable and deactivate is called disable. This gives us the PowerShell cmdlets Enable-SPFeature to activate a feature and Disable-SPFeature for deactivation.

    And it doesn't stop there if we look at the PowerShell commands. Deploying a solution is called Deploy in Central Administration and deploysolution using STSADM. In PowerShell it is called Install (Install-SPSolution). And it gets better Retracting a solution is called Remove in Central Administration, retractsolution in STSADM and Uninstall (Uninstall-SPSolution) in PowerShell.

    I never said the SharePoint world is easy...and that's why I'm all into it...

  • SharePoint 2010 Web Parts in Action - book site is live

    Tags: SharePoint 2010, SharePoint 2010 Web Parts in Action

    As some of you know I'm writing a book on SharePoint 2010 Web Parts development to be published by Manning Publications. I have set up a site dedicated to this book project where you can follow the progress of it.

    You can find the site at http://www.sharepointwebpartsinaction.com/

    image

    I am currently half way through the writing and we are closing in on the Manning MEAP program. So if you are interested in the latest news on the book head on over to the site...

    By the way: I set up the site using the really promising Orchard CMS system. It's fun once in a while and try something else than SharePoint...

  • What is new with the CssRegistration control in SharePoint 2010

    Tags: Web Parts, SharePoint 2010

    The CssRegistration class (in Microsoft.SharePoint.WebControls namespace) is one of the most useful controls in SharePoint 2010. It existed in SharePoint 2007 but was fairly limited then. I thought I should guide you through why it is so useful in SharePoint 2010 and why and when you should use it. I briefly mentioned the CssRegistration control in my previous post on SharePoint 2010 themable CSS files. But first some background.

    Why the CssRegistration control?

    There are plenty of times when you need to add custom CSS definitions to your SharePoint projects, for instance in pages and Web Parts. There are several methods of adding CSSes to your projects. You could use inline CSS styles - which results in a lot of markup which may slow your page/site down. Another approach is creating a CSS file and include it in your master page - better but the CSS is always loaded.

    The third option is to add a link tag and reference your CSS in your Web Part so it's only loaded when needed. But if you have several of these Web Parts on your page you will reference it several times. A common method is to override the RenderContents method or similar and add the CSS link tag there. Not a good option either and can result in multiple CSS registrations.

    This is the reason for the CssRegistration. This control registers the CSS files with SharePoint and once it is time to render the page it only renders one link tag for each, even though you might have registered the same CSS file multiple times. It is the CssLink control that is responsible for the actual rendering and this control is normally placed in your master page.

    The CssRegistration control existed in SharePoint 2007 and it was somewhat useful in removing duplicate CSS links. The problem is that the CSS files and rules are processed in the order that the links appear and the SharePoint 2007 implementation always rendered the CSS files in alphabetically order.

    CssRegistration in SharePoint 2010

    The new implementation of the CssRegistration have a number of new features. First of all you can specify the order using the After property. The After property contains the name of the CSS that you want to place the CSS after.

    Registering two CSS files like this:

    CssRegistration

    would yield the following output CSS order on a Team site:

    1. myCss.css
    2. myCss2.css
    3. wiki.css
    4. corev4.css

    Adding the After property to the controls like this, so that out myCss2 is rendered after corev4 and myCss after myCss2.

    CssRegistration and After

    would yield this order:

    1. wiki.css
    2. corev4.css
    3. myCss2.css
    4. myCss.css

    Pretty smooth!

    Another useful new feature of the CssRegistration is that you can add Conditional-CSS expressions so that you can target the CSS files to different browsers.

    CssRegistration and ConditionalExpression

    By adding the ConditionalExpression parameter to the control we tell the CssLink to render the Conditional-CSS code as well as the CSS link. The result of the registration above is:

     Conditional Expression

    If you are targeting a non Internet Explorer browser you should also set the RevealToNonIE  parameter to true.  The reason is that the syntax is not valid XHTML syntax and the extra parameter will add some extra HTML comments to make it valid XHTML. Read all the details on Wikipedia.

    The CssRegistration control also has a parameter called EnableCssTheming that allows your CSS to be themed, which I showed in the previous post.

    I hope this little CssRegistration tutorial was useful - I think it's one of the great improvements in SharePoint 2010!

  • Creating custom themable CSS files for SharePoint 2010

    Tags: Web Parts, SharePoint 2010

    SharePoint 2010 has a completely rebuilt theme engine. Instead of having to modify .inf files, create folders and copy and pasting CSS files and images in the SharePoint root we can now create a theme in PowerPoint and upload it to the server. The default SharePoint CSS files are tagged with comments that tells SharePoint to substitute colors and images with the values from the theme. When you switch theme SharePoint generates a new set of CSS files and images with the result of this substation.

    What if you have the need to create a custom CSS for you solution or Web Part? How can you use this theme? It's actually quite easy!

    Let's take a look at a sample Visual Web Part that is going to have a custom CSS file.

    Create the Visual Web Part

    First of all we need to start the new awesome/fantastic/productive new Visual Studio 2010 and create a Visual Web Part Project. Add a simple button to the user control and attach a custom CSS class to it.

    Button with custom CSS

    Add the CSS

    Once we have this button with the CSS class we need to create the CSS file and define the class. This is done by adding the SharePoint "Layouts" Mapped Folder to the Project. This will also add a folder with your project name under the Layouts folder - remove that one. Then add a folder structure like this 1033/Styles/Themable to the Layouts folder.

    To the Styles folder you then need to add the CSS file with your class. It should look something like this:

    .MyCustomClass {
    /* [ReplaceColor(themeColor:"Light2-Lightest")] */ border:solid 1px #d9dde1;
    /* [ReplaceColor(themeColor:"Light2")] */ background-color:#f5f6f7;
    }

    The ReplaceColor tag in the CSS comment will replace the colors in the CSS styles using the named color of the theme. For full reference check out corev4.css in the SharePointRoot.

    Then copy this file so it has a duplicate in the Themable CSS folder, your solution should look like this:

    The solution!

    SharePoint will use the CustomStyle.css in the Styles folder, when no theme is activated, so this is your default CSS. When you activate a theme it will take the CustomStyle.css from the Themable folder and substitute the colors as you wrote in the CSS file. Note that if you already have a theme enabled you have to re-enable it or if you make changes to the CSS you also need to re-enable the theme.

    Register the CSS

    We have one more thing to do to get this thing going - and that is to tell the Visual Web Part to use this CSS. This is done using the CssRegistration control which we add to the Visual Web Part user control like this:

    CssRegistration control

    You need to specify the Name attribute, which is the name of your CSS file. The EnableCssTheming attribute is not necessary since the default value is true. If it's set to false the CSS in the Styles folder will always be used. If you leave it out or set it to true and provide no CSS in the Themable folder then your CSS will not be loaded.

    Try it out!

    Now deploy your Visual Web Part and then add it to a page. Then go to Site Settings and change between themes. Isn't it beautiful!

    No theme Bittersweet theme Vantage theme

    To get some more details - make sure to get my book once it hits the streets!

  • Local SharePoint 2010 development on Windows 7 - awesome experience

    Tags: Visual Studio, SQL Server, Windows Vista, Windows 7, SharePoint 2010

    I thought I should share my experience on working with SharePoint 2010 development on Windows 7. My previous posts on installing SharePoint 2007 on Vista and Windows 7 are posts that are quite popular. The downside with the “old” SharePoint version is that it was not officially supported to install it on a client machine, but SharePoint 2010 is supported for installation on Windows 7 and Windows Vista SP1 for development purposes.

    There are many opinions on having SharePoint 2010 installed on your client OS. Some thinks it is despicable, but I think it is great and I’ve used local installations for years now. It’s perfect for rapid development, testing and demos. In seconds you can spin up a site and show some basic stuff for a client. Of course I use virtualization when testing my final bits etc.

    Benefits and drawbacks

    Having a local installation have several benefits:

    • You are running on the metal – i.e. no virtualization layer
    • Speed!
    • If you don’t have more than 4GB RAM then virtualization will be really slow
    • Visual Studio 2010 heavily uses WPF which requires a lot of your GPU. The virtualization layer will degrade the WPF performance
    • You don’t need to spin up and shut down VMs
    • Saves you a lot of disk space – one VM requires at least 20GB

    Of course there are drawbacks. I would never go from developing on a local installation to production. Always test your code on a server OS!

    SharePoint Foundation 2010 on Windows 7

    I have installed SharePoint Foundation 2010 on my Windows 7 machine. I did not go for a full SharePoint Server installation. Most of the development can be done towards SPF and it makes a minimal impact on my client OS. But perhaps I go for a full SPS 2010 install once we have the final bits of it in June.

    MSDN contains instructions on how to install SharePoint 2010 on a client OS, you need to extract the setup files and make some changes to the setup configuration file. With SQL Server Development Edition installed on my machine I installed a Server Farm, i.e. not the Standalone configuration. I also used domain accounts when I installed it, which required me to be connected to the domain during installation.

    After the installation I’ve changed all SharePoint Services and SQL Services to be manually started to save some boot time. Emmanuel Bergerat has a great post on how to create Stop and Go scripts with PowerShell so that you quickly can start and stop all services. Starting these services and warming up my sites takes about 2-3 seconds on my machine equipped with an SSD (best gadget buy of 2010!)

    Visual Studio 2010 RC and Team Foundation 2010 Basic

    I use Visual Studio 2010 in combination with a Team Foundation Server 2010 Basic installation on my local machine. Using a local install of TFS is something I really recommend – never loose any of your local projects or files.

    Visual Studio uses the GPU a lot so you will certainly have a better experience running without a virtualization layer. F5 debugging is no pain, it just takes a second to compile, package, deploy and start Internet Explorer.

    Summary

    If you have not tried to install SharePoint Foundation 2010 on your Windows 7 then stop reading right now and do it! It will increase your productivity immediately. The experience is awesome and together with RC of Visual Studio 2010 it’s just amazing.

  • SharePoint 2010 Wiki Pages displays the wrong content when passing Query String parameters

    Tags: Web Parts, SharePoint 2010

    While I was testing building some mashups using SharePoint 2010, Web Parts and SharePoint Designer I found an interesting bug.

    Initial problem

    Here’s what I did; I set up a Wiki Content Page (the new kind of Web Part Pages) in SharePoint 2010 that was supposed to be called with Query String parameter named ID which should be used by a Web Part. Another page contained items linking to this page using different integer values for the ID query string parameter like this:

    http://server/SitePages/Item.aspx?ID=nn

    My wiki pages was located in the Site Pages library within a Team site and when I clicked on one of the items I did not end up on my landing page ( Item.aspx in the sample above). Instead I ended up on random other pages in the library or received an SPException that the item did not exist. It took me a minute before I realized what really happened.

    I was redirected to the item (page) in the library that had the Id of passed query string parameter. Strange! I did the same test but used a standard Web Part Page and then it worked as intended.

    Actual problem

    So I did a new test by creating a new Team Site. On the home page of the site /SitePages/Home.aspx I added a Web Part displaying just the Shared Documents library. This page has the Id=1. A second page is automatically created when you create the site, the How to use this library page, with an Id=2.

    If I pass this request /SitePages/Home.aspx?ID=2 then I get the content of page 2 and vice versa. The strange is though if I call /SitePages/How%20To%20Use%20This%20Library.aspx?ID=1 I expected to see the contents of Home.aspx including the Web Part I added, which I did except for that the Web Part on that page was not present.

    Developer Dashboard I opened up the Developer Dashboard which verified what I saw. When I called the /SitePages/Home.aspx?ID=2 I saw the contents of page #2 but It loaded the Web Parts from page #1. The image to the right proves that it added the Web Part to the page.

    When passing the ID as a query string the Wiki Pages uses the Wiki content from the page with that ID provided in the Query String but uses the Web Parts from the page in the URL.

    This certainly must be a bug…

  • SharePoint 2010 tools in Visual Studio 2010 violates basic naming conventions

    Tags: Visual Studio, Web Parts, SharePoint 2010

    The SharePoint 2010 Development Tools for Visual Studio 2010 is great and I really like the way that the project is built using the different artifacts. One thing really annoys me though and that is the way that the code is generated and named when you add items. For example if you create a project and then add a Web Part item to that project then Visual Studio will create a Web Part class with a namespace and class name like this:

    namespace Wictor.CodeAnalysis.WebPart1 {
        public class WebPart1 : WebPart {
            // ---
    }

    As you can see the namespace and the name of the Web Part has the same name. This is a violation of one of the basic naming guideline rules (CA1724 if you run the code analysis in Visual Studio 2010). Although it works it will make your generated assembly having many different namespaces which makes it quite hard to work with. For each new item you will get a sub-namespace.

    With tools like WSPBuilder I normally placed Web Parts within one namespace, controls in one and event receivers in another. This made the experience when working with the assembly easy.

    If you now decide to change the namespace to something mode naming-convention-compliant such as below, then you need to update your Web Parts Control Description file (.webpart) and the SafeControl entry in the Package manifest.

    namespace Wictor.CodeAnalysis.WebParts {
        public class WebPart1 : WebPart {
            // ---
    }

    Making all these manual corrections will likely make your project break at some time. So I guess we have to put up with this…but it is not good looking (so if you guys there in Redmond have a few nights over until VS2010 RTM, please fix this).

  • A request to the Microsoft SharePoint Product Team

    Tags: Web Parts, SharePoint 2010

    SharePoint is an amazing product and there are some fantastic opportunities to make awesome applications. It also has a great API which has had improved further in the upcoming SharePoint 2010 release. But there are several features available in the platform/API that just isn’t available to all of us, unless we sit in Redmond and are building the actual product.

    There are so many classes or methods that are marked internal or sealed, that I really would like to use. I’m not going to nag about the search Web Parts this time, but instead focus on some classes that I really would like to be changed from internal to public.

    When working with Web Parts and especially Editor Parts, where you can create your own interface for fiddling with the Web Part properties and its configuration. I really would like to be able, without writing numerous lines of styling code, to create neat looking Editor Parts that align with the rest of the Web Part tool pane. In particular I’m thinking about the BuilderButton class which is used to create the little ellipsis button, which you get a popup to edit the text in. Why on earth is that class sealed?

    Dear SharePoint Product Team, you still have a few months until RTM of SharePoint 2010. Please make the BuilderButton public. And while you are there please go through the PropertySheetRow and Utlity classes and expose some of the methods or put them in a Tool Pane Utility class. Pure and simple…

    Meanwhile I continue to use Reflector…

  • I am now an approved SharePoint 2010 Ignite instructor

    Tags: SharePoint 2010

    SharePoint 2010 A couple of weeks ago I participated in the SharePoint 2010 Ignite training and after a great, but quite hard, interview and discussion I have been approved as a SharePoint 2010 Ignite Developer trainer. I really look forward getting out there and teaching developers about all the awesome features and improvements in SharePoint 2010.

    If you are interested in training don’t hesitate in contacting me. Together with AddSkills I have planned for a couple of SharePoint 2010 upgrade classes this spring.

    Take care and see you out there…

  • SharePoint Bad Practices are still around!

    Tags: SharePoint

    It is 2010 now and SharePoint 2007 have been out forever, it feels like it anyways. The last two years has been about best practices in SharePoint both for developers and IT-pros and especially the Disposing of SharePoint objects has been discussed in absurdum. So I guess we should have to talk about it - but guess what - we certainly do!

    The reason I bring this up today is that I was about to join a new WFE to a farm and it failed once it started to provision the web applications. Using the logs I found the source of the failure, it was some kind of component that threw an unhandled exception when it was created. See logs below (I have cropped it a bit)

    01/19/2010 14:58:58  8  INF                            Openning configdb so that I can join it at server 01/19/2010 15:18:16  8  ERR                            Task configdb has failed with an unknown exception 
    01/19/2010 15:18:16  8  ERR                            Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: The Web application at http://SERVERXXX could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
       at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
       at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
       at XXX.YYY.MyTimerJob.GetWeb()
       at XXX.YYY.MyTimerJob..ctor()
       --- End of inner exception stack trace ---
       at System.RuntimeMethodHandle._InvokeConstructor(Object[] args, SignatureStruct& signature, IntPtr declaringType)
    ...
       at Microsoft.SharePoint.Administration.SPWebApplication.Provision()
       at Microsoft.SharePoint.Administration.SPWebServiceInstance.Provision()
       at Microsoft.SharePoint.Administration.SPFarm.Join()
       at Microsoft.SharePoint.PostSetupConfiguration.ConfigurationDatabaseTask.CreateOrConnectConfigDb()
       at Microsoft.SharePoint.PostSetupConfiguration.ConfigurationDatabaseTask.Run()
       at Microsoft.SharePoint.PostSetupConfiguration.TaskThread.ExecuteTask()
     

    I opened up the source code to take a look what was going on in there. Fortunately this was no component that we have produced! This is what I found:

    public class MyTimerJob: SPJobDefinition {
        static SPSite site = null;
        static SPWeb web = GetWeb();
        public static SPWeb GetWeb() {
            site = new SPSite("http://" + Environment.MachineName);   
            return site.RootWeb;
        }
    ...
    }

    So what is wring with this? Pretty obvious huh?

    Not disposing objects!

    This is a really bad example of not disposing objects. Both the SPSite and SPWeb are static members and are not getting disposed correctly and will hold the resources for as long as the object lives, in this case until the process terminates. You will likely not notice any degradation in performance if you have one of these objects but if you continue to build objects like this you will eventually trash the server.

    SharePoint 2007 and SharePoint 2010, yup we are stuck with the same obstacles, have objects that are non-managed and uses connections to the database. These unmanaged are used by managed objects such as SPSite and SPWeb. The idea behind unmanaged code is that you should not have to care about object lifetime, destruction and garbage collecting but when we use unmanaged code we have to release these objects once we are finished with them and we should not use them any longer than we need to. Please do read through the Best Practices on MSDN before doing anything else!

    Not testing the code!

    This code had obviously not been tested thoroughly. The reason I got the exception was that during the web application provisioning objects like the timer jobs are being deserialized and that involves creating the object. Since the static objects are created the first time an object of that type is created and in this case it tries to attach to the web application that we are provisioning and not yet done with. So it will not find any web application and we get that exception.

    Using the machine name!

    The code tries to attach to the web application that has the address equal to the server name - that may be true on some occasions, but more often you have another address for your web application or use host headers etc.

    What can we learn from all of this? I guess that we should all make sure that you and your colleagues know what to dispose and when to dispose it. If you are a trainer - please add an extra 10-15 minutes for this. Then test your code, not just on a single machine, but in a live environment resembling your production environment.

    And by the way, since I had no control over the code causing the exception all I had to do was to deactivate the feature, install SharePoint and then activate it again.

    For more bad practices head on over to Natalyas post.

  • Creating a SharePoint 2010 Ribbon extension - part 2

    Tags: Web Parts, SharePoint 2010

    This is the second post in my mini series on how to extend the SharePoint 2010 Ribbon. First post can be found here.

    The goal with this excersice is to extend the Editing Tools Insert tab with a smaller Insert Web Part drop-down, so we don’t have to expand the whole Web Part Gallery to insert a Web Part.

    In the last post we created a Visual Studio 2010 solution and added the drop-down to the correct tab in the Ribbon using the CustomAction element and some new SharePoint 2010 XML syntax.

    Quick Add Web Part

    Readers with good memory/eyes see that I made some more enhancements to the drop-down…

    Step 3: Create the JavaScript Page Component for the Ribbon control

    To make our new drop-down to be contextual, load the correct content and to react to clicks and actions we need to create a JavaScript Page Component object. This is not currently documented in any way that I have found on MSDN, so this might not be the correct way to do it once we get to RTM. But it works!

    First of all we need to add a JavaScript file to our solution, this JavaScript file should be deployed in the _LAYOUTS folder. Right click the project and select Add->SharePoint “Layouts” mapped folder. Then add a JavaScript file to that folder so that the project looks like this:

    JavaScript file added.

    I recommend that you use a naming standard as I’ve done, have your file end i UI.js, since this is how the UI JavaScript files are named in SharePoint 2010. It doesn’t really matter but it’s easier for other developers to understand your code then.

    Now it’s time for some heavy weight JavaScript hacking. Add the following code to your JavaScript file:

       1:  Type.registerNamespace('QuickAddWebPart.UI');
       2:  QuickAddWebPart.UI.QuickAddWebPartPageComponent = function () {
       3:      QuickAddWebPart.UI.QuickAddWebPartPageComponent.initializeBase(this);
       4:  }
       5:  QuickAddWebPart.UI.QuickAddWebPartPageComponent.initialize = function () {
       6:      var ribbonPageManager = SP.Ribbon.PageManager.get_instance();
       7:      if (null !== ribbonPageManager) {
       8:          ribbonPageManager.addPageComponent(this.instance);
       9:          ribbonPageManager.get_focusManager().requestFocusForComponent(this.instance);
      10:      }
      11:  }
      12:  QuickAddWebPart.UI.QuickAddWebPartPageComponent.refreshRibbonStatus = function () {
      13:      SP.Ribbon.PageManager.get_instance().get_commandDispatcher().           executeCommand(Commands.CommandIds.ApplicationStateChanged, null);
      14:  }
      15:  QuickAddWebPart.UI.QuickAddWebPartPageComponent.prototype = {
      16:      init: function () {
      17:      },
      18:      getId: function () {
      19:          return 'QuickAddWebPartComponent';
      20:      },
      21:      getFocusedCommands: function () {
      22:          return [];
      23:      },
      24:      getGlobalCommands: function () {
      25:          return ['QuickAdd_Button', 'QuickAdd_Populate', 'QuickAdd_Query', 'QuickAdd_Add'];
      26:      },
      27:      isFocusable: function () {
      28:          return true;
      29:      },
      30:      receiveFocus: function () {
      31:          return true;
      32:      },
      33:      yieldFocus: function () {
      34:          return true;
      35:      },
      36:      canHandleCommand: function (commandId) {      
      37:          return true;
      38:      },
      39:      handleCommand: function (commandId, properties, sequence) {
      40:           return true;
      41:      }
      42:  }
      43:  QuickAddWebPart.UI.QuickAddWebPartPageComponent.         registerClass('QuickAddWebPart.UI.QuickAddWebPartPageComponent', CUI.Page.PageComponent);
      44:  QuickAddWebPart.UI.QuickAddWebPartPageComponent.instance =          new QuickAddWebPart.UI.QuickAddWebPartPageComponent();
      45:  QuickAddWebPart.UI.QuickAddWebPartPageComponent.initialize();

    This piece of JavaScript creates a new JavaScript object called QuickAddWebPartPageComponent (line 2) and is registered in the QuickAddWebPart.UI namespace (line 43). The object has a set of methods that is used by the Ribbon to query the component for which actions it supports and the object also has methods such as handling the actions and focus of the control. This is exactly how the native SharePoint 2010 UI objects behave.

    There are a few important things to notice here:

    1. getGlobalCommands (line 24) returns an array of all our commands that we defined in the custom action in the previous post (QueryCommand, Command etc)
    2. There will be a lot of functionality added to canHandleCommand (line 36) and handleCommand (line 39) and other methods in the upcoming posts
    3. To create your own just replace QuickAddWebPart with your own string.

    If we deploy this just as it is now, we won’t load the JavaScript file so we have to create a load control for this.

    Step 4: Load the JavaScript

    The easiest way to load our JavaScript is to create a delegate control and add that control to AdditionalPageHead.

    First of all I add some more XML to the elements.xml file, just after our CustomAction:

    Delegate Control...

    This XML tells SharePoint to load the control and place it in the AdditionalPageHead. Note how I’m using the new Visual Studio 2010 tokens to replace the namespace and assembly name so I don’t have to write them and figure out the strong name. My control is called ScriptLoader and that control is added to the project as a new Class.

    To load the control, see the code below, I use the ScriptLink.RegisterScriptAfterUI method, which is a part of the Microsoft.SharePoint.dll. I also make sure that I add some other necessary JavaScripts, that the page component and my code is dependant on.

       1:  namespace Wictor.QuickAddWebPart {    
       2:      public class ScriptLoader : WebControl {
       3:          protected override void OnPreRender(EventArgs e) {
       4:              SPRibbon currentRibbon = SPRibbon.GetCurrent(this.Page);    
       5:              if (currentRibbon != null && currentRibbon.IsTabAvailable("Ribbon.EditingTools.CPInsert")) {
       6:                  ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Core.js", false, true);
       7:                  ScriptLink.RegisterScriptAfterUI(this.Page, "CUI.js", false, true);
       8:                  ScriptLink.RegisterScriptAfterUI(this.Page, "core.js", true, false);
       9:                  ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Ribbon.js", false, true);
      10:                  ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Runtime.js", false, true);
      11:                  ScriptLink.RegisterScriptAfterUI(this.Page, "SP.js", false, true);
      12:                  ScriptLink.RegisterScriptAfterUI(this.Page, "Wictor.QuickAddWebPart/QuickAddWebPart.ui.js", false, true);
      13:              }
      14:              base.OnPreRender(e);
      15:          }
      16:      }
      17:  }

    To avoid that the scripts are loaded unnecessary I get the current Ribbon instance (line 4) and checks if the page has a Ribbon and if the Editing Tools->Insert tab is available (line 5). If you compile your project now it will fail, since the IsTabAvailable method is defined in the Ribbon class (not the SPRibbon class) which exists in the Web.Command.UI.dll assembly, so we need to add a reference to that DLL.

    References

    We also need to add this control to the Safe Controls. This is done by looking at the properties of the item that contains the elements.xml and selecting Safe Control Entries and then add our control to this collection.

     Properties

    Fill in as below, note that I’m using the replaceable tokens here also.

    Safe Control entry

    Now we can build and deploy our solution. It still looks the same, there are no items in the drop-down yet. Until next part you can fiddle with the different methods in the Page Component and insert some JavaScript alerts to see when the methods are invoked (that’s how I figured out how it works…)

    Until next time.

  • Creating a SharePoint 2010 Ribbon extension - part 1

    Tags: Web Parts, SharePoint 2010

    SharePoint 2010 contains numerous of improvements in the user interface and it has been built to be able to be extended. I guess that all of you have seen the Ribbon in SharePoint 2010 by now and probably even tried to add a button and fire away a Hello World JavaScript alert (it’s one of the HOLs available also). That’s quite an easy task. But doing some more advanced contextual and dynamic customizations to the Ribbon really makes you sweat!

    For a couple of days I have wandered into the undocumented land of the SharePoint 2010 Ribbon and the JavaScript API’s and I thought I should share my experiences with you. It will be a couple of blog posts, so be sure to check back often – I’ll try to write them as fast as I can between writing the book.

    As most of you now I’m quite fond of Web Parts and I don’t really like the new Web Part Gallery that pops out when you add a Web Part to a page in SharePoint 2010. It occupies so much of the screen. So why not building my own!

    SharePoint 2010 Quick Add Web Part extension

    This series will focus on creating a drop-down that lists all Web Parts in the site collection and then adds them to the page, just as you would do with the standard Web Part Gallery option. The idea here is to in the end be able to add some nifty extensions that helps the user adding correct Web Parts. This list might filter out a specific Web Part category or similar. I grabbed a short introduction video to what we are trying to achieve. Take a look:

    As you can see it works really smooth – I still have to work on some improvements. But this simple extensions contains a declarative Ribbon, a JavaScript Ribbon component object, some SharePoint 2010 native JavaScript APIs and a delegate control all wrapped up as a feature. So let’s get started with the first part

    Step 1: Creating the solution

    To create this extension we use Visual Studio 2010 and create a new empty SharePoint project. It should be deployed as a fully trusted solution since custom actions is not supported in sandboxed mode. A declarative Ribbon extension is a CustomAction, just like you added custom actions in SharePoint 2007 – but with a whole new schema.

    TIP: Check out the out-of-the-box Ribbon definition in the [SharePointRoot]\TEMPLATE\GLOBAL\XML\CMDUI.xml file

    Step 2: Adding the Drop-down to the Ribbon

    Empty elementNow it’s time to add the custom action, this is done by adding an an Empty Element item to the solution, called QuickAddRibbon. When you add this item to the solution a feature will automatically be added to your package called Feature1, rename it to something easier, let’s call it QuickAddWebPart. Then give it a meaningful name and description. Your solution should now look like this:

    The solution

    Now it’s time to add the actual Ribbon Custom Action, and this is the step that took me the longest time to get right. Intellisense helps you a lot and if you are like me, you like to take an iterative approach and try stuff as you hack along. This does not work in this case! You have to get your XML correct before deploying it, (almost) any  changes after that first deployment will not change if you redeploy it. It doesn’t appear even if you IISRESET and almost goes ballistic on the metal. If you need to change it then this is how to do it (read: they way it worked for me). First retract the solution, then remove the feature from your project, then add a new feature back and add the elements file back to the feature. Now you can once again deploy it to see your changes. I for sure hope that this changes in the future!

    Ok, enough chatter, let’s see the code:

    Ribbon Custom Action

    As you can see I’m adding a custom action with the Location=”CommandUI.Ribbon”, this is what you would like to use if you would like to add extensions to the Ribbon. Then next thing to pay attention to is the Location of my extension (blue rectangle); I’m adding it to the Ribbon.EditingTools.CPInsert tab and the WebParts Group – all of these ids can be found in CMDUI.xml (see above). Then I append Controls, which means that I want all the controls in that group and finally _children to indicate that this is a new child element.

    Note that this will only work for Wiki pages, standard Web Part pages has another id.

    By now you can deploy this and see an empty drop down in the Insert tab when editing a Wiki page.

    Wow, we got a drop-down!

    In the next part we’re going to fill this drop-down with some cool JavaScripts and a server control.

    Until next time.

  • I'm writing a SharePoint 2010 book

    Tags: Personal, Web Parts, SharePoint 2010, SharePoint 2010 Web Parts in Action

    A Book This is the first post for the year of 2010 and what could be better to start with than announcing that I’m writing a SharePoint 2010 book. More specifically I’m writing a book about SharePoint 2010 Web Parts development with the working title SharePoint 2010 Web Parts in Action.

    This is a dream come true to me and I have been thinking about writing a book on and off for quite some time. I want to take my writing/blogging even further, it’s through writing that I educate and evolve myself. It makes me think twice and really make sure that I’m writing the correct stuff (who wants to be haunted down by all the readers and pros out there :-). So a book will be perfect to learn more about the SharePoint 2010 platform and dig down even further in Web Parts development.

    Web Parts has been one of my favorite topics in SharePoint – I really like the concept of making self-contained applications that can be configured by the end-users and optionally connected to create mashups. I written a bunch of posts on the topic and published two Codeplex projects; ChartPart and Tweetpart. Web Parts is one of the subjects that almost all SharePoint developers have been working with and it has its difficulties and pains. I hope I can get down all my experience, ideas and troubleshooting into this book and that it gets great feedback and usage.

    The book is going to be published by Manning Publications and I really want to thank them for making this possible! Manning got a really interesting concept with their MEAP program (Manning Early Access Program), which allows you to buy the book at a discounted price even before it’s complete and published. Then those buyers have an opportunity to comment on the book so far and possibly influence the author. This book will during the spring become a part of the MEAP program – so watch out for further announcements. Manning have a nice line-up of books coming this year including SharePoint Workflows in Action by Phil Wicklund, SharePoint 2010 Site Owners’ manual by Yvonne Harryman and SharePoint Server 2007 Survival Guide by Penelope Coventry et al.

    I have already started writing and I’m really satisfied so far. If you have any particular questions or things that you would like to have answered then don’t hesitate to contact me!

    Happy new year!

About Wictor...

Wictor Wilén is the Nordic Digital Workplace Lead working at Avanade. Wictor has achieved the Microsoft Certified Architect (MCA) - SharePoint 2010, Microsoft Certified Solutions Master (MCSM) - SharePoint  and Microsoft Certified Master (MCM) - SharePoint 2010 certifications. He has also been awarded Microsoft Most Valuable Professional (MVP) for seven consecutive years.

And a word from our sponsors...