Tuesday, 23 July 2013

Attach workflow to all webs

So I've made my own custom approval state machine workflow and now I need to attach it to everyone of my subsites. how do I accomplish this? Well any time you're face with a cumbersome amount of pointing and clicking you have two alternatives:

  • Feature event receiver 
  • PowerShell

Now as I learned the hard way you're event receiver has a 2 minute time out, so in my case where I'm attaching a workflow to three libraries on every subsite and creating a custom task list it really didn't pan out. Instead I ended up moving my logic out of my visual studio project and into a powershell script. I'm going to break this script down into Five sections.

Section One (Start up)

#get the site url to deploy workflow to
param($siteUrl=$(read-host "Please provide web app url of the list to be delete (EG:'http://Wingtip'):"))

#ensure that user provided site url parameter
if($siteUrl -eq $null -or $siteUrl -eq '')
{
    throw "You must specify your server name. Value provided was null/empty."
}

#function to load SharePoint Powershell snap in
function LoadSharePointPowerShellEnviroment
{
 #clear the screen of pevious output
 Clear-Host
 write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
 Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
 Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}

#call sharepoint plugin function

LoadSharePointPowerShellEnviroment

Section Two(Declare Constants)

#get site using parameter
$site = Get-SPSite($siteUrl)

#get the rootweb of the site
$rootWeb = $site.RootWeb

#ensure that approval workflow has unique name
$workFlowName = "Approval_" +  [System.DateTime]::Now.ToString()

#specify the approval task list name
$TASKLISTNAME = "Approval Tasks"

#specify the task list description
$listDescription = "Task list for ccw custom approval tasks"

#reference approval task list definition, deployed through VS project
$TaskListTemplate= $rootWeb.ListTemplates["Page Approval Task List Definition"]

#specify OOTB workflow history list, every site has one
$HISTORYLISTNAME = "Workflow History"

#approval workflow ID, specified in elements file of workflow
$APPROVALWORKFLOWID = [GUID]"64f076cb-a5f8-4ee7-9ef4-54820d291886"

#reference workflow using workflow ID

$wfTemplate = $rootWeb.WorkflowTemplates[$APPROVALWORKFLOWID]

Section Three(Create list function)

#Create List Instance function
function createListInstance($web, $listName, $listDescription)
{
      #make sure list doesn't already exist
      if($web.Lists.TryGetList($listName) -eq $null)
      {
            #create list with no spaces
            $listGuid = $web.Lists.Add($listname.Replace(" ",""), $listDescription, $TaskListTemplate)
           
            #grab the list, change the name to the original parameter passed to the function
            $list = $web.Lists[$ListGuid]
            $list.title = $listName
            $list.Update()
      }
      else
      {
            Write-Host $listName + "was not created on web" + $web.Url -ForegroundColor Red;
      }
      $web.Dispose()

}

Section Four(Attach workflow function)

#attach workflow to web
function addApprovalWorkflow($web, $listname)
{
      #get the library you want to attach the workflow to
    $library = $web.Lists.TryGetList($listname)
   
      #ensure library exists
    if($library -ne $null)
    {
            #reference tasklist, and histrory list on web
        $taskList = $web.Lists[$TASKLISTNAME]
        $historyList = $web.Lists[$HISTORYLISTNAME]
       
            #create a workflow association refer to
        $workflowAssociation = [Microsoft.SharePoint.Workflow.SPWorkflowAssociation]::CreateListAssociation($wfTemplate, $workflowName, $taskList, $historyList);
       
            #set the properties of the workflow assocation
        $workflowAssociation.Name = $workFlowName
        $workflowAssociation.AllowManual = $true
        $workflowAssociation.AutoStartChange = $true
        $workflowAssociation.AutoStartCreate = $true
       
            #attach the workflow association to the Library
        $temp = $library.WorkflowAssociations.Add($workflowAssociation);
        $workflowAssociation.Enabled = $true;
            $web.Dispose()
    }

}

Section Five(Main)

#itterate through all subsites
$webs = $site.AllWebs
foreach ($web in $webs)
{
      #ignore the search site
      if($web.Title -eq "Search")
      {
            continue
      }
     
      Write-Host $web.Url
      #create the task list
      createListInstance $web $TASKLISTNAME $listDescription
     
      #Attach the approval wf to libraries
      addApprovalWorkflow  $web "Pages"
      addApprovalWorkflow  $web "Images"
    addApprovalWorkflow  $web "Documents"
    $web.Dispose()
}
$rootWeb.Dispose()
$site.Dispose()


write-host "Complete" -ForegroundColor Blue

Monday, 22 July 2013

Asynchronous calls

public class Program
{
    private static void heavyMethod(int pauseTime)
    {
        Thread.Sleep(pauseTime);
        int threadID = Thread.CurrentThread.ManagedThreadId;
        Console.WriteLine(string.Format("My runtime was {0} miliseconds, my id was {1}", 
                          pauseTime.ToString(), threadID));
    }
 
    private delegate void myDelegate(int iCallTime);
    private static myDelegate dlgt = new myDelegate(heavyMethod);
 
    private static void Main(string[] args)
    {
        Console.WriteLine("Start demo");
 
        //simple async call, go do your stuff and i don't care when you finish
        dlgt.BeginInvoke(10000, null, null);
 
        //Async call with call back function, when compelte call fourSecond_callback method
        dlgt.BeginInvoke(4000, new AsyncCallback(fourSecond_CallBack), null);
 
        //async call with result, waits for end invoke
        Console.WriteLine("Waiting for 7s");
        IAsyncResult ar1 = dlgt.BeginInvoke(7000, null, null);
        dlgt.EndInvoke(ar1);
 
        //asyn call with wait
        IAsyncResult ar = dlgt.BeginInvoke(3000, null, null);
        Console.WriteLine("Doing some stuff here");
        ar.AsyncWaitHandle.WaitOne();
 
 
        //async with polling
        Console.WriteLine("5s counter start");
        IAsyncResult ar2 = dlgt.BeginInvoke(5000, null, null);
 
        int count = 0; 
        while (!ar2.IsCompleted)
        {
            Console.WriteLine(count++);
            Thread.Sleep(1000);
        }
 
        Console.WriteLine("Finished, press any key");
        Console.ReadKey();
    }
 
    public static void fourSecond_CallBack(IAsyncResult ar)
    {
        Console.WriteLine("4s is up");
    }
}

Tuesday, 16 July 2013

Deploy a form library via WSP

So you've created an InfoPath form, and now you want to deploy it to a library, but your SharePoint admin will light you on fire should you dare connect to production through InfoPath. So the question is; how do we deploy our InfoPath form declaratively via visual studio? Well let’s start by making a simple InfoPath form. 
With your simple form ready, make sure to set the permission on the form to domain, and  promote the properties through the advanced form option.  Once your form is configured publish it to a network location, when that’s complete open up visual studio and create a content type that inherits from the form base type. It should look something like:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Form (0x010101) -->
  <ContentType ID="0x010101004663c851f85b42f59d84e3bf2359a33f"
               Name="SimpleForm_CT"
               Group="Custom Content Types"
               Description="My Content Type"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
    </FieldRefs>
  </ContentType>
</Elements>

That’s what the Declarative xml for the content type should look like, now what we are going to do is bring our published form into our content type and deploy it using a module. 

Now with your published form added select the properties and ensure that:
  • The Deployment type is set to element file
  • The Deployment path is set to the root of the content type.


Notice how the deployment type property is set to ElementFile and that the deployment location path is cleared out. If you forget to do this your form will not be visible in the Mange form templates page in central admin.


Now with your info path form brought into your content type and the properties set correctly we have to add a module to deploy the InfoPath form, you can either do this in your Content type, or add a completely separate module file. In my opinion since it’s tightly coupled with the content type, I’d keep them together, but what do I know.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Form (0x010101) -->
  <ContentType ID="0x010101004663c851f85b42f59d84e3bf2359a33f"
               Name="SimpleForm_CT"
               Group="Custom Content Types"
               Description="My Content Type"
               Inherits="TRUE"
               Version="0"
               RequireClientRenderingOnNew="FALSE">
    <DocumentTemplate TargetName="/FormServerTemplates/SimpleForm.xsn"/>
    <FieldRefs>
    </FieldRefs>
  </ContentType>
  <Module Name="SimpleFormModule" Url="FormServerTemplates" RootWebOnly ="TRUE">
    <File Path="SimpleForm.xsn" Url="SimpleForm.xsn" Type="GhostableInLibrary"/>
  </Module>
</Elements>


Now you've got one more land mine to avoid, open up the feature template that you’re going to use to deploy your InfoPath form.


This is what you’ll see

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/">
</Feature>

Replace it with
<?xml version="1.0" encoding="utf-8" ?>
<Feature ReceiverClass="Microsoft.Office.InfoPath.Server.Administration.XsnFeatureReceiver"
    ReceiverAssembly="Microsoft.Office.InfoPath.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    xmlns="http://schemas.microsoft.com/sharepoint/">
  <ActivationDependencies>
  <ActivationDependency FeatureId="C88C4FF1-DBF5-4649-AD9F-C6C426EBCBF5" />
  </ActivationDependencies>
</Feature>
If you want a more in depth explanation then just do it.

http://msdn.microsoft.com/en-us/library/microsoft.office.infopath.server.administration.xsnfeaturereceiver.aspx

Now all that’s left to do is create a list definition and instance using your content type


Then enable the management of content types through the advanced library settings.

Thursday, 11 July 2013

Packaging a Helper Class with your Project

So you’ve created a helper class library for your SharePoint project, and you’ve gotten the lovely error:
Error occurred in deployment step 'Activate Features': Could not load file or assembly 'AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=Token' or one of its dependencies. The system cannot find the file specified.
What you need to do is package the helper assemble (the project) with your SharePoint Project, to do this you need two things:
  • A SharePoint Project
  • A Class Library project


Your Solution Explorer should look something like this:

Expand your SharePoint Project and double click on the package

Scroll down to the very bottom and click the advanced button.

This will open up the additional assemblies screen. Single click the Add button and Select the “Add Assembly from Project Output” option to bring up the associated window

Select your project from the source Project: drop down

Hit ok, and you’re done.