PostRank Topblogs 2009 - #20 in Sharepoint

Windows Live Alerts web tracker
Chat with me if I'm online!
search blog
most popular
MCP MCTS MCT MVP

SP 2010: Uploading files using the Client OM in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will guide your through the process of uploading a document to any chosen document library in SharePoint 2010 through the Client Object Model.

This application has a very simple usage scenario:

  1. Type in the URL to your site where you want to upload your file
  2. Choose one of the available Document Libraries
  3. Click Upload a Document and you'll get a browse-dialog to choose the file

Example:

1) Enter a servername and click Fetch Libraries
2) Select the Document library you want to upload your file to
image

3) Browse for a local file on your filesystem
image

4) Click the magic button (Upload) and you'll see your document shoot straight into SharePoint from your client machine(s)
image

How to utilize the Client Object Model in SharePoint 2010 to upload files

The most important thing to learn about when it comes to uploading files with the Client OM is to master the FileCreationInformation class that comes with the Client OM.

Take a look at this complete snippet to see how you can upload a file:

private void btnUploadDocument_Click(object sender, EventArgs e)
{
    string library = listBox1.SelectedItem.ToString();
 
    OpenFileDialog openDialog = new OpenFileDialog();
    openDialog.Multiselect = false;
 
    if(openDialog.ShowDialog() == DialogResult.OK)
    {
        SP.ClientContext ctx = new SP.ClientContext(tbSite.Text);
 
        var web = ctx.Web;
 
        var fciNewFileFromComputer = new SP.FileCreationInformation();
        fciNewFileFromComputer.Content = File.ReadAllBytes(openDialog.FileName);
        fciNewFileFromComputer.Url = Path.GetFileName(openDialog.FileName);
 
        SP.List docs = web.Lists.GetByTitle(library);
        SP.File uploadedFile = docs.RootFolder.Files.Add(fciNewFileFromComputer);
 
        ctx.Load(uploadedFile);
        ctx.ExecuteQuery();
 
        // Tell your user that the file is uploaded. Awesomeness has been done!
        MessageBox.Show(openDialog.FileName + " uploaded to " + library);
    }
}

Things to note here is that I'm currently not changing the authentication for this application. That means it'll be using your Windows/Domain Credentials.

Learn more about the authentication options here:
http://www.zimmergren.net/archive/2009/11/30/sp-2010-getting-started-with-the-client-object-model-in-sharepoint-2010.aspx

Summary, References & Download

With this sample application you can easily upload any file to any of your SharePoint 2010 document libraries by first entering the URL to the site, then selecting your library and finally browsing for a file and click OK.

Easily enough, you can change or extend this project the way you want it to work if you've got specific requirements to upload files using the Client OM.

References

  1. Getting Started with the Client Object Model
  2. FileCreationInformation

Download project

You can download this sample project here.

Enjoy this piece of awesomeness :-)

 


Published: Jun-10-10 | 21 Comments | 0 Links to this post

SP 2010: How to create a PowerShell Snapin Cmdlet - Part 2

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In my previous article (How to create a PowerShell Snapin - Part 1) I talked about the general approach to create a custom PowerShell Cmdlet. However, in Part 1 I did not talk about how you create SharePoint 2010 specific Cmdlets. That's what this article is all about.

So without further ado, I will quickly brief you on how you can create a custom PowerShell Cmdlet for SharePoint 2010 using the SPCmdlet base class.

In my example I will create a very simple Cmdlet you can use to automatically create demo-sites for use in demo-purposes or development scenarios so you don't have to go about creating all the different sites by hand, and without a need to create scripts to do the same.

Creating a custom PowerShell Cmdlet that talks with SharePoint 2010

I will add some functionality to my previous project (found in my previous article) and extend that project with some custom SharePoint 2010 specific Cmdlets to get your started with writing PowerShell cmdlets for SP 2010.

In order to do this, we should derive from a subclass of the type SPCmdletBase. The following base classes deriving from SPCmdletBase are available:

1. Create a new Cmdlet (SPNewCmdletBase)

  • Create a new Class and name it something of your own preference (I chose this silly name: SPAwesomeness.cs)
  • Add a reference to the following two namespaces:
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.PowerShell;

  • Add the following base code to your class:
    using System;
    using System.Management.Automation;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.PowerShell;
     
    namespace Zimmergren.SP2010.PowerShell
    {
        [Cmdlet(VerbsCommon.New, "SPCreateDemoSites")]
        public class SPAwesomeness : SPNewCmdletBase<SPWeb>
        {
            protected override SPWeb CreateDataObject()
            {
                throw new NotImplementedException();
            }
        }
    }
     

As you can see in the code above I've got a class called SPAwesomeness which derives from the SPNewCmdletBase class which in turn derives from the SPCmdletBase. SPNewCmdletBase should be derived from when you create a Cmdlet that should create and save data to SharePoint.

Also note that we're using the Attribute [Cmdlet] to set a name for our command, in this case SPCreateDemoSites.

When deriving from this class, you need to implement at least one method override, in this case CreateDataObject. This is where our magic will take place!

2. Add some logic to your custom SharePoint Cmdlet

Now that we've got the basic code up and out of the way, we need to add some logic to actually make something happen.

I've added some very simplistic code to create some Demo-sites based on the available templates in your installation. It looks like this:

using System;
using System.Management.Automation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.PowerShell;
 
namespace Zimmergren.SP2010.PowerShell
{
    [Cmdlet(VerbsCommon.New, "SPCreateDemoSites")]
    public class SPAwesomeness : SPNewCmdletBase<SPWeb>
    {
        // Let's add a mandatory parameter that indicates that you need
        // to specify a value for this property through the PS console 
        [Parameter(Mandatory = true, 
            ValueFromPipeline = true, 
            Position = 0, 
            HelpMessage = "Specify an existing site to extend with demo sites")]
        public string SiteUrl { get; set; }
 
        protected override SPWeb CreateDataObject()
        {
            var site = new SPSite(SiteUrl);
 
            try
            {
                // SharePoint Server Publishing Infrastructure feature 
                site.Features.Add(new Guid("f6924d36-2fa8-4f0b-b16d-06b7250180fa"));
            }catch(Exception ex)
            { /* Empty catch block is not recommended :-) */}
 
            SPWeb demoWeb = CreateBaseDemoSite(site);
 
            // When we're done, you'll get this object returned to the PS console
            return demoWeb; 
        }
 
        private static SPWeb CreateBaseDemoSite(SPSite site)
        {
            // Creates a Blank Site which will host all the Demo-sites
            SPWeb web = site.AllWebs.Add(
                "DemoSite", 
                "Demo Sites", 
                "Demo Sites", 
                1033, 
                "STS#1", 
                false, 
                false);
 
            web.QuickLaunchEnabled = true;
            CreateDemoSites(web);
 
            return web;
        }
 
        private static void CreateSite(SPWeb parentWeb, string url, string template)
        {
            string desc = " created by Tobias Zimmergren's custom cmdlets";
            parentWeb.Webs.Add(url, 
                url + " demo", 
                url + desc, 
                1033, 
                template, 
                false, 
                false);
        }
 
        private static void CreateDemoSites(SPWeb web)
        {
            SPWebTemplateCollection webTemplates = 
                web.GetAvailableWebTemplates((uint)web.Locale.LCID, true);
            foreach (SPWebTemplate template in webTemplates)
            {
                try
                {
                    CreateSite(web, 
                        template.Title.Replace(" ", ""), 
                        template.Name);
                }
                catch (Exception ex) 
                { /* Empty catch block is not recommended :-) */ }
 
            }
        }
    }
}
 

3. Test your custom SharePoint 2010 cmdlet

In order to test it, follow along with the steps I mentioned in my previous article (here) to deploy it - then call the new command you've created called New-SPCreateDemoSites like this:

image

It will ask you to supply the mandatory property (SiteUrl), so type in an existing url to an existing site collection and execute like this:

image

Now you'll need to wait for a few minutes. What's happening now is that your Cmdlet is creating a site called "Demo Sites" and will add a whole bunch of sub-sites to that new site.

Navigate to your new site called "Demo Sites" and you should see something like the following sub-sites created:

image

Summary & Download

Quite easily you've created your first SharePoint 2010 Cmdlet extension to operate with the SPCmdletBase classes. In this case we've created a new site called Demo Sites and added a bunch of sites to that new site, as per the available templates on your server.

Download project

You can download my sample project here

Enjoy this awesomeness!


Published: Jun-08-10 | 8 Comments | 0 Links to this post

SP 2010: How to create a PowerShell Snapin - Part 1

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will talk about how you can get started with creating custom PowerShell commands for SharePoint 2010 that you can use.

You will see how easy it actually is to build a custom class library that in turn is an extension to the PowerShell console and will add a couple of extra commands according to your preference.

The reasons for wanting to do this is an endless list, but as an example if you've got repeated tasks you'll need to perform that are not available out of the box, you can create them yourself and then use normal PowerShell scripts to execute your code. That way you can easily build your own custom commands (CmdLet) for PowerShell which basically extends the functionality to support whatever scenario you've got.

You might remember that in SharePoint 2007 you could extend the STSADM.EXE command with something called STSADM Extensions. The approach I'm talking about in this article is pretty much the same concept - extending the build-in commands of your PowerShell console by adding custom code.

How to create a PowerShell Snapin

Download the Windows SDK in order to get the
System.Management.Automation.dll file for PowerShell easily accessible.

1. Create a new Class Library project

Start out by creating a new Visual Studio 2010 Class Library project and give it a proper name.
I've named mine Zimmergren.SP2010.PowerShell.

Add assembly references

  1. Add a reference to System.Management.Automation
    1. This DLL is located  in:
      C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\
      (if you installed the Windows SDK as I told you earlier on in this article)
  2. Add a reference to System.Configuration.Installation

You should now have the following reference added: 
image

2. Create a PowerShell Installer class

In order for our PowerShell Cmdlet to work, we need to create an installer-class. This class is called when you install the SnapIn/Cmdlet and will provide the system with some information like where it comes from and what it's supposed to do.

Start out by creating a new class in your project, I named mine PowerShellInstallerClass.cs. Next, add the following code to that class:

using System.ComponentModel;
using System.Management.Automation;
 
namespace Zimmergren.SP2010.PowerShell
{
    [RunInstaller(true)]
    public class PowerShellInstallerClass : PSSnapIn
    {
        public override string Name
        {
            get
            {
                return "Zimmergren.SP2010.PowerShell";
            }
        }
 
        public override string Vendor
        {
            get
            {
                return "Tobias Zimmergren";
            }
        }
 
        public override string Description
        {
            get
            {
                return "Tobias Zimmergren's awesome PowerShell Cmdlets";
            }
        }
    }
}

This essentially provides some information to the system upon installation of your SnapIn.

3. Create a PowerShell Cmdlet class

Now you need to continue this venture by creating a new class in your project. I named mine TestCmdlet1.cs.

Use the [Cmdlet()] attribute on your class to tell the system that it's going to be a Cmdlet for PowerShell like this:

using System.Management.Automation;
 
namespace Zimmergren.SP2010.PowerShell
{
    [Cmdlet(VerbsCommon.Get, "TestCmdlet1")]
    public class TestCmdlet1 : PSCmdlet
    {
    }
}

Next, you should override the methods you want to execute your code and add some dummy-code. There's a couple of different methods to use here:

  • BeginProcessing()
  • EndProcessing()
  • ProcessRecord()
  • StopProcessing()

You should make sure your class looks like this so we can test the first part out:

using System.Management.Automation;
 
namespace Zimmergren.SP2010.PowerShell
{
    [Cmdlet(VerbsCommon.Get, "TestCmdlet1")]
    public class TestCmdlet1 : PSCmdlet
    {
        protected override void BeginProcessing()
        {
            WriteObject("BeginProcessing() method - Execution has begun");
        }
 
        protected override void ProcessRecord()
        {
            WriteObject("ProcessRecord() method - Executing the main code");
        }
 
        protected override void EndProcessing()
        {
            WriteObject("EndProcessing() method - Finalizing the execution");
        }
    }
}

4. Deploy the new PowerShell Snap-ins

Since this is a generic Class Library-project, we need to create some kind of deployment script to make sure that our Cmdlet gets deployed when we build our project.

There are two requirements for deploying and installing our PowerShell Cmdlet:

  1. Deployed to the server (Using GACUTIL)
  2. Installed on the server (using INSTALLUTIL)

In this sample project I'm simply adding two lined in the Post-Build actions like this::

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe" -if "$(TargetPath)" "C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe" "$(TargetPath)"

You'll find the post-build events if you click project properties and go to this box:

image

5. Project overview

Your project should look something like this:

image

6. Test your PowerShell Snapin

In order to test our project, we now just need to build the Visual Studio project and the post build scripts will automatically hook up our assembly in the GAC and use INSTALLUTIL to install the Cmdlet.

To try the commands out, you need to launch a powershell console and type in the following command:

Add-PSSnapin Zimmergren.SP2010.PowerShell

Now you should be able to just call your command (in my case, it's called TestCmdlet1) like this:

TestCmdlet1

This should bring your the following output in your PowerShell console window:

image

Great, our very first PowerShell cmdlet is created - and we have validated that it works!

Summary & Download

In this article we talked about how you create a general PowerShell Cmdlet in order to extend the capabilities in your PowerShell consoles. There's no business logic incorporated in this sample, that's up to you to implement in your projects. You've got the starting point to get sailing on the great PowerShell seas right here!

In my next article (Part 2) I will talk about the SharePoint 2010 specific details for creating a custom Cmdlet for your SharePoint installations. It will cover how you create custom Cmdlets to interact with the SharePoint 2010 object model in a nice way.

Download

Download this project here

Enjoy!


Published: Jun-07-10 | 5 Comments | 0 Links to this post

Access denied by Business Data Connectivity - Solution

Auhtor: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Lately I've been rolling around parts of Sweden and doing training, seminars and workshops on SharePoint 2010 with a bunch of companies and people.

One thing that I've been showing off, which I'm totally in love with by the way, is the BCS (Business Connectivity Services) functionality.

I've been getting a few questions from people who have been trying this out, but stumbled onto some problems with it in terms of permissions when they tried it out themselves.

Problem - Access Denied by Business Data Connectivity

When you've created your external list and try to access it (even as the same user, Administrator, that created it) you might get the following error:

image
Access denied by Business Data Connectivity

If you bump into this, please don't freak out - just keep reading..

Solution - Permissions on the BCS Entity

To resolve this so called problem, follow along here:

Go to Central Administration -> Application Management -> Manage Service Applications -> Business Data Connectivity Service* -> [Your Entity] -> Set Permissions

* or whatever name you've chosen for your BCS Service application

image

Configure the actual permissions

In my case below, I've just told SharePoint that my Farm Administrator should be able to do all actions (Edit, Execute, Selectable in Clients and Set Permissions)

image

Please note: You might want to use different permissions in your environments - the permissions set in this blog post is just to demonstrate how you effectively change/add permissions for your BCS Entities to get up and running.

Check your external list

You should now be able to access the external list and see the desired result.

image

Keep rocking folks!

Cheers


Published: May-08-10 | 19 Comments | 0 Links to this post

SP 2010: SharePoint Server 2010 - Creating a custom Document ID provider

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will talk about how you can create your custom Document ID provider for your SharePoint Server 2010 installation. Sometimes I've been getting the question weather or not it's possible to change the behavior or change the way the Document ID's are generated, and some people have a tendency to say no to that question, just because there's no interface or out of the box functionality to do so.

I'll give you a quick walkthrough of how you can extend your Site Collection by adding a custom Document ID provider, that will automatically generate custom ID's based  on your own algorithms entirely!

Recommended reading about Document ID's before proceeding: 
http://msdn.microsoft.com/en-us/library/ee559302(office.14).aspx

Document ID overview

This section will give you a very brief conceptual overview of Document ID's in SharePoint Server 2010.

What is Document ID's?

Document ID's in SharePoint Server 2010 provide you with the ability to tag documents with a unique identification number. Something a lot of my clients have done manually or by implementing custom solutions to take care of in SharePoint 2007. With this new feature, you get all the required functionality to tag documents with unique identification numbers based on a specific pre-set formula with a custom prefix.

See this sample screenshot for an example:
image

Where do I enable Document ID's for my Site Collection?

In order to enable Document ID's in your Site Collection, you'll need to activate the Site Collection Feature called Document ID Service.

See this screenshot for an example:
image

How do I change the way my Document ID's are generated?

If you want to alter the way the Document ID's are generated for your documents in your Site Collection, you can do that by navigating to:

Site Actions - Site Settings - Document ID Settings, like so:
image

From this new settings page, you'll get the possibility to tell SharePoint how it should generate your unique ID's. You can specify a prefix for all the generated ID's:
image

I want to take it one step further!

If you're not quite satisfied with the way SharePoint 2010 generates your Document ID's for you, then you should most definitely follow along with the rest of this article as I will guide you through the steps to create your very own Document ID provider to generate exactly the kind of ID's you want - based on your very own code/algorithms!

Bring it on!

Learning about a SharePoint 2010 Custom Document ID provider

This section will give you an overview of what you will need in order to create a custom Document ID provider for SharePoint Server 2010!

Note: As of this writing MSDN isn't fully updated on these new SharePoint Server namespaces. Some details may or may not change when SharePoint Server 2010 is released into the wild (RTM)

Microsoft.Office.DocumentManagement

The namespace Microsoft.Office.DocumentManagement contains a class called DocumentIdProvider, which will be the base for our upcoming project!

Microsoft.Office.DocumentManagement.DocumentIdProvider

This is the class we will derive from when creating our custom provider. It contains three (3) abstract methods and one (1) abstract method that we need to implement:

A description of each of these methods and the property will be made inline in my code in the samples!

Creating a SharePoint Server 2010 Custom Document ID provider

Let's code this little piece of functionality, shall we. The final project (very basic) will look something like this:
image

So, let's get coding.

1. Create a class and derive from DocumentIdProvider

public class CustomDocumentIdProvider :
Microsoft.Office.DocumentManagement.DocumentIdProvider
    {
        // Method to generate the actual document ID. Awesomeness lives here!
        public override string GenerateDocumentId(SPListItem listItem)
        {
            // In this method we will tell SharePoint how it should generate
            // the unique ID we want.
            // In my case, I've just created a dummy-generator. 
            // Normally you would perhaps want to fetch this from another system or
            // generate it properly instead of like this.. 

            // Points to a method I've created that generates foo-ID's
            return FooSampleIDGenerator.GetFooUniqueID();
        } 

        public override bool DoCustomSearchBeforeDefaultSearch
        {
            // If set to true: It will call the GetDocumentUrlsById method before search
            // If set to false: It will use SharePoint Search before custom methods
            get { return false; }
        } 

        public override string[] GetDocumentUrlsById(SPSite site, string documentId)
        {
            // Returns an array of URLs pointing to 
            // documents with a specified DocumentId
            // An empty string array 

            // This is where you will implement your logic to find
            // documents based on a documentId if you don't want to use
            // the search-approach.
            return new string[] { };
        } 

        public override string GetSampleDocumentIdText(SPSite site)
        {
            // Returns the default Document ID value that will be initially
            // displayed in the Document ID search web part as a help when searching
            // for documents based on ID's.
            // This should correspond with the way you've designed your ID pattern
            return "AWESOME-12345-67890-SharePointRules";
        }
    }

2. Create a Feature Receiver to hook up your custom provider with your Site Collection

public class ProvisionCustomDocIdProviderEventReceiver : SPFeatureReceiver
{
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        DocumentId.SetProvider(properties.Feature.Parent as SPSite,
                                                                 new CustomDocumentIdProvider());
    }
    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        DocumentId.SetDefaultProvider(properties.Feature.Parent as SPSite);
    }
}

Actually, you're all done with the code for now.

3. Go to Document ID Settings page and see this message appear

image

This basically means that your custom provider has been successfully enabled (as per our Feature Receiver).

4. See that the Document ID's on your documents now is using your custom provider

(Please allow for some time to pass so the Timer Jobs can do their magic, or manually go into Central Admin and run the timer jobs instantaneously)

Behold, awesome custom Document ID provider in action:
image 

Summary and Download

What did we just do?

What we just did was to create a custom Document ID provider that generates our very own custom Document ID's based on whatever algorithm or pattern we want. There's no need to follow the built-in format for your generated IDs - which some people have presented in their seminars and blogs. So there you go, step by step!

This could be especially awesome if you've got an external system generating Document ID's already, and you want SharePoint to use those ID's alongside whatever other system is running. Use your own imagination as to what can be done. The code is in your hands, Obi Wan Coder!

Download project

You can download my sample project here

Enjoy, and please don't be afraid to leave comments!


Published: Apr-13-10 | 36 Comments | 0 Links to this post

SP 2010: Site Collection Keep-Alive Job now available by AC

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Normally I don't make link-posts like this one, but it is too good to miss out on. My main man and friend Andrew Connell (AC) have created a new utility for SharePoint 2010 which is essentially a "warmup" job for your Site Collecions.

This job is easy to configure and will keep your demos, presentations and dev-machines fresh all the time by making repeated HTTP requests on the sites.

Awesomeness, AC. Good work!

Get the info, get the goods - SharePoint Site Collection Keep Alive Job

Head on over to http://www.andrewconnell.com/blog/archive/2010/03/27/introducing-the-sharepoint-site-collection-keep-alive-job.aspx to get the latest details and download this fantastic keep-alive job.

Enjoy this piece of awesomeness from AC.

Cheers


Published: Mar-29-10 | 11 Comments | 0 Links to this post

SP 2010: Certification exam details for SharePoint 2010 published

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Microsoft has published the two developer-oriented certifications for SharePoint 2010 on Microsoft Learning.

Personally, I think there is a huge improvement now as we're not only getting the MCTS-credit but can now also become an MCPD (Microsoft Certified Professional Developer) on the SharePoint platform. Something I've been waiting for a long time ;-)

SharePoint 2010 exams

For us developers/solution architects there are two certifications of interest (of course you should do the IT-pro tracks as well, but let's start here with the developer ones):

  1. 70-573: TS: Microsoft SharePoint 2010, Application Development
  2. 70-576: PRO: Designing and Developing Microsoft SharePoint 2010 Applications

SharePoint 2007 Exams

Way back in 2007 I wrote about passing all 4 certifications for SharePoint 2007 (link here). For SharePoint 2007 there is four certifications for the 2007 product-line:

  1. 70-541 - TS: Microsoft Windows SharePoint Services 3.0 - Application Development
  2. 70-542 - TS: Microsoft Office SharePoint Server 2007 - Application Development
  3. 70-630 - TS: Microsoft Office SharePoint Server 2007, Configuring
  4. 70-631 - TS: Microsoft Windows SharePoint Services 3.0, Configuring

Summary

So, keep an eye out on those two new certifications and be well prepared when they arrive - should be a fun ride :-)


Published: Mar-28-10 | 8 Comments | 0 Links to this post

SP 2010: Validate Sandboxed Solutions using SPSolutionValidator

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

If you've been playing around with SharePoint 2010 lately, you've most likely noticed a new concept introduced as "Sandbox Solutions".

With sandboxed solutions (read more about them here: http://msdn.microsoft.com/en-us/library/ee536577(office.14).aspx) comes the possibility to scope your solutions to Site Collection (into the new Solution gallery).

A question I often get is how you can validate those solutions automatically, and therefore I'll lay out the basic principles of creating a Sandbox Solution Validator which now is part of the SharePoint object model.

What will happen?

If you have a custom Solution Validator hooked up with your farm, a custom error page will be displayed, and the solution will not be activated.

If you try to activate the solution:
image

Our custom Solution Validator kicks in and in this case disallows the solution and displays the following custom error page:
image

So, let's get down to business!

Building a Solution Validator

What we need:

  1. A Solution Validator
  2. A feature to install/uninstall the validator in our Farm

1. Let's begin by creating our custom Solution Validator class

Essentially this is just a simple class, inheriting from SPSolutionValidator which gives us some methods we can override. Check this example out:

using System.Runtime.InteropServices;
using Microsoft.SharePoint.UserCode;
using Microsoft.SharePoint.Administration; namespace

Zimmergren._2010.SolutionValidation
{
    [Guid("29e3702d-5d8c-45ad-b1aa-a2087b9e8585")]
    public class ZimmergrenSolutionValidator : SPSolutionValidator
    {
        private const string myAwesomeValidator = "ZimmergrenSolutionValidator";
       
        // Not used, but needed for deployment and compilation
        public ZimmergrenSolutionValidator(){}  

        public ZimmergrenSolutionValidator(SPUserCodeService sandboxService) :
                   base(myAwesomeValidator, sandboxService)
        {
            // Use this to define a unique identification number
            // You may need this when updating/modifying the validator
            Signature = 666;
        } 

        public override void ValidateSolution(SPSolutionValidationProperties properties)
        {
            base.ValidateSolution(properties); 

            // Set to false if you want invalidate the solution
            // Set to true (default) if you want to validate
            properties.Valid = false; // Being evil and invalidates all solutions for test!

            // Then specify an errorpage to display
            // Tip: Create a nice application page for this..
            properties.ValidationErrorUrl =
                      "/_layouts/Zimmergren.2010.SolutionValidation/InvalidSolution.aspx";
        }
    }
}

In my sample I used an override of the ValidateSolution method and invalidated the solution to show you that it actually works.

The two most suitable methods for overriding are:

  1. ValidateSolution
  2. ValidateAssembly

2. We need to make easy installable (Read: Feature)

In order for our awesome solution validator (which in this case is very slim and don't really do any real validation, rather invalidates all solutions) - we need to let the SPUserCode service (Sandboxed Solution Service in layman terms) know that we want to hook it up.

This can easily be done using a Farm feature, using PowerShell or just plain'ol Object Model code in any application.

My approach is of course to make it as easy as possible for the end-user and administrator, so I'll create a Farm Feature with the following snippets of code:

[Guid("d0d086ec-2bef-45e8-be8b-a67895c1bd3b")]
public class ZimmergrenSolutionValidatorEventReceiver : SPFeatureReceiver
{
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        SPUserCodeService sandboxService = SPUserCodeService.Local;
        SPSolutionValidator zimmerValidator =
                new ZimmergrenSolutionValidator(sandboxService);
        sandboxService.SolutionValidators.Add(zimmerValidator);
    }

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        SPUserCodeService sandboxService = SPUserCodeService.Local;
        Guid zimmerValidatorId =
                sandboxService.SolutionValidators["ZimmergrenSolutionValidator"].Id;
        sandboxService.SolutionValidators.Remove(zimmerValidatorId);
    }
}

Summary and reflections

If you want to create some kind of check to automatically validate solution that are uploaded by end-users in their Solution Galleries, this is the way to do it.

Solution validators are very easy to write, and they can be installed using a few different approaches. My take is to create a farm feature, while you could still do it using powershell or in any way you want through the object model.

Good resources on Sandboxed Solutions:

  1. Deploying a Sandboxed Solution
  2. Sandboxed Solution Considerations
  3. Sandboxed Solution Architecture

Enjoy!


Published: Mar-20-10 | 16 Comments | 0 Links to this post

SP 2010: Dynamically displaying messages to your users with the Notification and Status bar areas in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren 

Introduction

With the new version of SharePoint comes a full set of new and awesome features that you'll have to indulge and learn. One of the small things that makes my day much more fun is to display messages to your users in the Status- and Notification areas.

Example of a message in the Status bar area:
image

Example of a message in the Notification area:
image

How do we make this magic happen?

In order to display these messages, you really (really) don't need a lot of code. I'll lay out the simple code I used to display the messages you saw in my screenshots.

It's all JavaScript based, so get ready to dig out those old JS skills you know you've got lying around somewhere ;-)

Oh wait, you don't need skills to do this, it's just that easy!

Show me a Status bar!

JavaScript:

function ShowStatusBarMessage(title, message)
{
    var statusId = SP.UI.Status.addStatus(title, message, true);
    SP.UI.Status.setStatusPriColor(statusId, 'yellow'); /* Set a status-color */
}

HTML, call the JS method:

<a onclick="ShowStatusBarMessage('Title'!','Awesome message!')">
    Display Status Bar message!
</a>

Show me a Notification popup!

JavaScript:

function ShowNotificationMessage(tooltip, message, sticky)
{
    SP.UI.Notify.addNotification(message, sticky, tooltip, null);
}

HTML, call the JS method:

<a onclick="ShowNotificationMessage('I am cool!','This is a cool message',false)">
   Display Notification!
</a>

Summary

Actually, there's no need for a summary. It's way too easy.

Enjoy!


Published: Mar-17-10 | 54 Comments | 0 Links to this post

This is my current development rig

Author: Tobias Zimmergren
http://www.zimmergren.net | www.tozit.com | @zimmergren

Introduction

A lot of my clients, students and SharePoint friends have been asking me about details on my latest development rig - so here you go, a full disclosure of the machine and it's peripherals that I'm currently using for my primary SP 2010 development.

Notes: I've been running with HP for my laptops the last couple of years - and all I can say is that they're amazingly stable and versatile and my next laptop will probably be HP as well!

Hardware configuration

In this section I'll talk about the hardware configuration of my development rig, along with the peripherals I use on a daily basis to make my SharePoint and .NET world rock!

Laptop details

Learn more about the actual laptop models:

HP Compaq EliteBook 8530w (Mobile Workstation, EliteBook)

Accessories

I use this docking station on a daily basis to enable quick docking of my laptop at home and at the office. Definitely worth the cash!

HP 2008 120W Docking Station

CPU

Intel(R) Core(TM)2 Duo CPU, T9400 @ 2.53GHz

RAM memory

8 GB 800 MHz DDR2 SDRAM

Disks

For my internal disks (that is, not external) I'm using two of these:

Corsair 128 GB Performance Series Internal Solid State Drive (SSD)

For my external disks, I'm using the following:

+ 500GB eSATA 7200rpm disks connectable to the eSATA port on the laptop, for storage

Software configuration

This is my current software configuration (related to my daily-basis work):

  • Windows 7 Ultimate
    • VMWare Workstation 7
    • Office 2010 (Beta)

Summary

To sum it up really quick - I'm using a normal EliteBook laptop.

I've simply replaced the optical (DVD/CD) drive with a second SSD disk. This makes for a super-fast experience in your computer no matter if you're doing things virtually in VMWare or if you're doing it on the host operating system, as I'm placing my VM's on the secondary drive.

It's definitely worth spending a few extra bucks on those SSD drives, I would do it without a blink of an eye.

Since there isn't any alternative for running a client-based virtualization engine in 64-bit from Microsoft, I'll stick with VMWare Workstation for now - which has done the job very (very!) well!

Sidenote: I'm looking at the HP Envy for an upgrade to a newer model later. Support for +16GB RAM is going to have a huge impact on my decision for my next laptop.


Published: Mar-15-10 | 7 Comments | 0 Links to this post
 Next >>