Friday, February 11, 2011

Talking about timmer job on sharepoint 2010

Timer 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 theSPPausableJobDefinition 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 theExecute(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 theSPFirstAvailableServiceJobDefinition 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.

Wednesday, February 2, 2011

Activating and Deactivating Features with PowerShell in SharePoint 2010


Activating and Deactivating Features with PowerShell in SharePoint 2010

I was looking at the analytics of the site the other day and I noticed that my post, Adding and Deploying Solutions with PowerShell, currently has the most traffic on the site.  I had always intended to write a follow up post on this, so here it is.  Today I’m going to talk about how to enable and disable features using PowerShell.  It’s great that you know how to deploy solutions now with PowerShell, but now you want to activate your features.
In SharePoint 2007 to activate a feature from the command line you might have used a statement like the one below.  I’ll use the Reporting feature on my server named sp2010 as an example.  The value specified in the name parameter refers to the actual folder name of the feature that is in your SharePoint Root folder (14 hive).
stsadm.exe –o activatefeature –name Reporting –url http://sp2010
To get started with PowerShell, run the SharePoint 2010 Management Console located in your Microsoft SharePoint 2010 Products folder on your start menu.  This automatically loads the Microsoft.SharePoint.PowerShell snapin so that we can execute SharePoint commands.    You might have noticed earlier that I said we will talk about enabling and disabling features.  The words enable and disable are key here because PowerShell uses those verbs to activate and deactivate features.  To issue the same command above but with PowerShell, we use the Enable-SPFeature command.  The rest of the syntax is pretty similar as you can see below.  Just use –Identity to specify the name of the feature.  You can even pass the –Force command like you could with stsadm.exe.
Enable-SPFeature –Identity Reporting –url http://sp2010
If your command worked successfully, you will see nothing and just get a blank prompt back.
PowerShellEnableSPFeatureNoOutput
If you would like to get some feedback from the command, you can have it return the SPFeature object back to you by specifying the –PassThru parameter.
PowerShellEnableSPFeaturePassThru
We can confirm that the feature did in fact activate successfully using the SharePoint UI.
PowerShellReportingFeatureEnabledUI
Can we confirm that the feature is enabled with PowerShell?  Yes, we can by using Get-SPFeature.  Now this cmdlet behaves differently depending upon the parameters passed through it.  For example, if you type the following, it lists every feature on the SharePoint farm along with its Id and Scope.
Get-SPFeature
However, if you want to know which features are enabled, you can pass it a URL for a given scope (i.e.: –Web, –Site, –WebApplication, and –Farm).  So to get a list of all Site Collection scoped features, we would use the –Site parameter.
Get-SPFeature –Site http://sp2010
PowerShellGetSPFeatureSite
You can still specify a specific feature or even use Where-Object to query the list as well.
Get-SPFeature –Identity Reporting –Site http://sp2010
PowerShellGetSPFeatureSiteSpecific
If you get something like you see in the screenshot above, you know the feature has been activated.  When the feature hasn’t been activated, you will get a lovely red error message.
PowerShellGetSPFeatureSiteSpecificNotEnabled
The Enable-SPFeature command can also take a Pipe Bind from Get-SPFeature.  This means that you could even activate multiple features at once this way.  I’ll include an example of this in the future.
At some point, you will want to disable that feature you activated.  As you probably guessed, the cmdlet you want is Disable-SPFeature.  You use the same parameters that you use with Enable-SPFeature.  When you execute the command, it prompts for confirmation as you can see in the screenshot.
Disable-SPFeature –Identity Reporting –url http://sp2010
PowerShellDisableSPFeatureWithConfirmation
If you want to disable confirmation, you can pass the –confirm:$false parameter.
Disable-SPFeature –Identity Reporting –url http://sp2010 –Confirm:$false
PowerShellDisableSPFeatureNoConfirmation
Setting the confirm parameter eliminates the confirmation prompt and you can use it with other PowerShell cmdlets as well.  That is all that is involved in activating and deactivating features with PowerShell.  It’s pretty easy.   Hopefully, you can incorporate these commands in your deployment scripts.

Adding and Deploying Solutions with PowerShell in SharePoint 2010


Visual Studio 2010 makes it really easy to add and deploy solutions when you are developing, but you may eventually want to deploy those solution packages elsewhere right?  We can still use stsadm, but that is effectively considered deprecated now in favor of PowerShell.  In the past to add a solution, we used an stsadm command like the one below.  In today’s example, we’ll be working with a package called SharePointProject2.wsp on my server named sp2010.

stsadm –o addsolution –name SharePointProject2.wsp
To get started with PowerShell, run the SharePoint 2010 Management Console located in your Microsoft SharePoint 2010 Products folder on your start menu.  This automatically loads the Microsoft.SharePoint.PowerShell snappin so that we can execute SharePoint commands.  To install a solution we use the Add-SPSolution command.  If you are using a Sandboxed solution you would use Add-SPUserSolution instead.  It takes just one parameter, –literalpath, which is the path to the solution file.  One thing that is different is that you must specify the full path to the file for some reason.  I haven’t been able to get it to take a path to the solution in the current folder even if I make use of .\ before the filename.  Here is an example.
Add-SPSolution c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp
In this case you don’t actually have to type –literalpath before the parameter.  This is what it looks like when executed.  You can see that it displays the id of the solution along with its deployment status.
PowerShellAddSolution
Now we need to deploy the solution.  In the past, we used an stsadm command like the following.
stsadm –o deploysolution –name SharePointProject2.wsp –url http://moss-server –allowCasPolicies –immediate
We would also follow this up with a call to stsadm with the execadmsvcjobs operation.  To do the same operation in PowerShell, we use the Install-SPSolution command (again use Install-SPUserSolution for Sandboxed solutions).  You can use the Get-Help command (i.e.: Get-Help Install-SPSolution) to get more information on a command but it’s not always obvious what it is expecting as you can see below.  That is why I am writing the post today.
PowerShellGetHelpInstallSolution
The first parameter you need is the –Identity parameter.  This is the name of the solution package (i.e.: MySolution.wsp).  Depending on if you are using the GAC or Code Access Security, you will specify either –GACDeployment or –CASPolicies.  You then need to specify a specific web application using the –WebApplication parameter or –AllWebApplications to deploy it to all web applications (assuming the manifest allows it).  If you need to force the deployment, you can still use the –Force command.  Here is what an install command might look like.
Install-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010 -GACDeployment
I’ll point out that executing this command actually does do the deployment operation.  You don’t have to fire off something to execute a job later like you did with stsadm.
You might want to update your solution, so we’ll talk about how to do that as well.  Here is what your stsadm command might have looked like in WSS3.  Which would also be followed up with an execadmsvcjobs operation.
stsadm –o upgradesolution –name SharePointProject2.wsp –filename SharePointProject2.wsp –immediate –allowCasPolicies
The upgrade solution syntax is similar to the others.  We just have to specify an identity and a literalpath with the Update-SPSolution command.  The identity is the name of the package on the server to upgrade and the literalpath is the full path to the new solution package on the file system.  Here is what that might look like.
Update-SPSolution –Identity SharePointProject2.wsp –LiteralPath c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp –GACDeployment
We’ve talked about everything else, so we’ll finish it up by talking about retraction and removal.  To retract a solution we use the Uninstall-SPSolution command.  By now you are probably noticing a pattern in the way things are named.  Install –> Deploys, Uninstall –> Retracts.  It also just uses the -Identity parameter and the –WebApplication parameter.  You can also use the –AllWebApplications parameter to retract it from all web applications. Many of these commands may prompt you with an “Are you sure?” type prompt.  You can skip this prompt by adding a –confirm parameter.  Here is what it looks like.
Uninstall-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010
Lastly, to remove the package from the solution store, we use the Remove-SPSolution command.  It just takes the name of the package.
Remove-SPSolution –Identity SharePointProject2.wsp
I hope this helps.  If you’re like me, it’s one thing to see the docs on something, but I like to see real examples.  There aren’t any examples in the Get-Help command yet.  This should cover all of the common commands that you probably used to used with stsadm in regards to solution deployment.  The nice thing is that you can script these things together very easily and create highly flexible PowerShell scripts.  Expect a few more posts soon on the basics of working with PowerShell and SharePoint 2010.

Tuesday, January 25, 2011

Metadata Services: “The required feature is not enabled for this column type.”

If you are trying to enable metadata and you receive the following error:


“The required feature is not enabled for this column type.”




you should enable the following features via console:

Stsadm -o activatefeature -id 7201d6a4-a5d3-49a1-8c19-19c4bac6e668 -url http://tuwebapp/ –force


Stsadm -o activatefeature -id 73EF14B1-13A9-416b-A9B5-ECECA2B0604C -url http://tuwebapp/ –force

This should solve your problems.

Regards,

Tuesday, January 11, 2011

Persisting state in Sharepoint timer job definitions


Using class member variables will not work if you want to persist state between invocations. This seems to be due to the way sharepoint manages timer jobs. A solution is to use the Properties *property* which is exposed to all SPJobDefinition subtypes. This is a hashtable which accepts a key value pair. Usage:

public class SampleTimerJob : SPJobDefinition
{
    public SampleTimerJob(string jobName, SPWebApplication webApplication, string url, string email)
        : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
    {
        ContainerSite = url;
        Email = email;

        this.Title = "sample timer";
    }

    public string ContainerSite
    {
        get { return Properties["site"].ToString(); }
        set { Properties["site"] = value; }
    }

    public string Email
    {
        get { return Properties["email"].ToString(); }
        set { Properties["email"] = value; }
    }

    public override void Execute(Guid targetInstanceId)
    {
        SPSite site = new SPSite(ContainerSite);

        using (SPWeb web = site.OpenWeb())
        {

            SPUtility.SendEmail(web, false, false, Email,
                                "title",
                                "content");
        }
    }
}

Friday, January 7, 2011

Using a Config File for Windows SharePoint Services Timer Jobs

One of the biggest problems I've had with timer jobs is that you cannot access the membership provider or role providers with them because they do not have a configuration value.  Then if you want to read from a configuration file, you have to point it to one of the web.configs of the site.
 
Not any more.  I was looking around for a way to add an app.config to the timer service and stumbled upon Jason Huh's blog post about using the Microsoft Enterprise Library with Timer Jobs.  I figured I would be able to use the same configuration for my projects.
 
All you need to do is create a config file for OWSTimer.  You can do this one of two ways, you can deploy this using a solution or you can do it manually. 
 
To do it manually, navigate to the hive (Program Files\Common Files\Microsoft Shared\web server extensions\12) and then open up the BIN folder.  Now create a new file named OwsTimer.exe.config.  In this file, you can place your config settings, this works just like an app.config or a web.config file that you would add in visual studio.
 
I've placed an example config file, but the Membership Provider and Role Provider nodes are not filled all of the way out, you can replace this with your own information or just remove the membership and role manager nodes completely.
 
xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="ConnectionStringGoesHere" />
connectionStrings>
<system.web>
<membership defaultProvider="MembershipProvider">
<providers>
<add name="MembershipProvider" />
providers>
membership>
<roleManager enabled="true" defaultProvider="RoleProvider">
<providers>
<add name="RoleProvider" />
providers>
roleManager>
system.web>
<appSettings>
<add key="SiteUrl" value="http://sharepointsite"/>
<add key="ProviderPrefix" value="RoleProvider"/>
appSettings>
configuration>
 
Using this, you will be able to finally use a configuration file with your timer services without having to hard code the site that you are going to read the config settings from.

Tuesday, January 4, 2011

Talking about owstimer.exe.config

When a new timer job is created for Sharepoint, it has to be programatically installed in a SPWebApplication.JobDefinitions of type SPJobDefinitionCollection. If the timer job have to receive some settings during run time, one option would be to use the .Net application configuration feature.
First you might think to copy the configuration section from the app.config of the dll where the timer job resides into the web.config of the web application where the timer job is registered. The first catch: the timer job is loaded by the timer service, which is the 'Windows SharePoint Services Timer' Windows service on the web front end servers and runs the "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN\OWSTIMER.EXE" executable, so we have to configure this service.
This can be done by creating the OWSTIMER.EXE.config file near the exe file, and put there the timer job configuration section.
Don't forget to restart the timer service :-).