Showing posts with label Sandbox Solutions. Show all posts
Showing posts with label Sandbox Solutions. Show all posts

Wednesday, January 18, 2012

Custom Web Templates and Activating Features

Introduction
Lately I was messing around with Custom Site and Web Templates with Office 365 and made a few discoveries that I figure I share. Some of it is old, some of it I had to piece together.

Background
I am building a solution in Office 365 using SharePoint Online. I have a site collection with publishing turned on. I created a custom site template and I need to make sure that site (web level) publishing feature is turned on.

Publishing Feature Disables Creating Site Templates
For some reason, when you turn on the publishing feature on a site, the “Save site as a template” is removed from Site Settings. Now I have found some blog posting where people go down into the SharePoint install files and make some changes to fix that. First, probably not the best course of action if you want to make sure you have supportable upgrades (and someone actually documents the change <g>). Second, since I am working with Office 365 that is not even an option, so I need to find a solution that does it the right way.

Another thing I saw people suggest is go to the Save as Template page by typing in “_layouts/savetmpl.aspx”. Do not waste your time with that approach either, it will not work correctly.

My only option is to create my custom site initially without the publishing feature turned on. Then build some solutions to turn on publishing for the site automatically and ensure that the masterpages are set appropriately. The solutions I looked into are:

1. Feature Stapling
2. Modifying the Web Template
3. WebProvisioned Event Handler

Custom Web Template Feature Stapling
The first solution that I investigated was the most obvious; create a Feature Stapler that would activate the site publishing feature.

The first thing I ran into was finding the actual name of the template. Traditionally the name of the site template is usually something like STS#0. However since this is a custom site template where would I get the site template name from? I found some scripts that would help me get the template name. Since I was doing the development on my local machine it was easy for me to run some PowerShell on my development box to test this all out (I did find similar code to run API code against Office 365).

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <FeatureSiteTemplateAssociation Id="94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb" TemplateName="{04FB0801-1DFA-41ED-9B87-06D0FF088F01}#MyCommunityTemplate" />
</Elements>

I create a Feature Stapling feature that looked like this. As you can see there is a GUID#template name format.

Let me save you some though – this is not supported and did not work. Feature Stapling can only be used against the site templates that are OOB the box or deployed down into the hive. You cannot apply do Feature Stapling to a site template created off SharePoint web site.
Modifying the Web Template

The next thing I tried, which is a recommended approach, is to modify the web template. This is a really easy thing to do now with Visual Studio 2010.
In Office 365 I created a web template the way I needed but without publishing turned on. I then went into site settings and created web template like usual. I then went to the Site Collection Solution Gallery, downloaded the WSP, and opened it in Visual Studio 2010 (using an Import SharePoint Solution Package project).
In the project, there will be a module called “Web templates” and you will find a file called “ONet.xml”. Open this file and you will see <SiteFeatures> and <WebFeatures>.
<SiteFeatures> correspond to the site collection and the following features should already be in the web template because you will have publishing turned on at the site collection level.

<!--PublishingPrerequisites Feature-->
<Feature ID="{a392da98-270b-4e85-9769-04c0fde267aa}" Name="FeatureDefinition/a392da98-270b-4e85-9769-04c0fde267aa" />
<!--PublishingResources Feature-->
<Feature ID="{aebc918d-b20f-4a11-a1db-9ed84d79c87e}" Name="FeatureDefinition/aebc918d-b20f-4a11-a1db-9ed84d79c87e" />
<!--PublishingLayouts Feature-->
<Feature ID="{d3f51be2-38a8-4e44-ba84-940d35be1566}" Name="FeatureDefinition/d3f51be2-38a8-4e44-ba84-940d35be1566" />
<!--PublishingSite Feature-->
<Feature ID="{f6924d36-2fa8-4f0b-b16d-06b7250180fa}" Name="FeatureDefinition/f6924d36-2fa8-4f0b-b16d-06b7250180fa" />

Why are there four when you only turn on one publishing feature for the site collection through the SharePoint UI? The one with f6924d36-2fa8-4f0b-b16d-06b7250180fa is actually the main one, but the other three are supporting, hidden ones. There is not action for you, just brought this up because I thought is it interesting.

Now this is what you do need to do. Go to the <WebFeatures> and add the following two features.

Add the Publishing Web after the MetaDataNav:
<!--MetaDataNav Feature-->
<Feature ID="{7201d6a4-a5d3-49a1-8c19-19c4bac6e668}" Name="FeatureDefinition/7201d6a4-a5d3-49a1-8c19-19c4bac6e668" SourceVersion="14.0.0.0" />
<!--PublishingWeb Feature-->
<Feature ID="{94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb}" Name="FeatureDefinition/94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb" SourceVersion="14.0.0.0" />

Add the Publishing Feature after the GridList:
<!--GridList Feature-->
<Feature ID="{00bfea71-3a1d-41d3-a0ee-651d11570120}" Name="FeatureDefinition/00bfea71-3a1d-41d3-a0ee-651d11570120" SourceVersion="1.0.0.0" />
<!--Publishing Feature-->
<Feature ID="{22a9ef51-737b-4ff2-9346-694633fe4416}" Name="FeatureDefinition/22a9ef51-737b-4ff2-9346-694633fe4416" SourceVersion="14.0.0.0" />

This worked great and was really clean.

The next thing I needed do was make sure the master pages are set appropriately. Even though I turned on publishing, it does not mean that the mast pages will be set correctly. The solution is again very simple.

I created a new Feature in Visual Studio 2010 to the web template solution I already had open and set the scope for Web. I then added an event handler to the new Feature. Then in the FeatureActivated event handler I added the following code:
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{              
    web.MasterUrl = web.ParentWeb.MasterUrl;
    web.AllProperties["__InheritsMasterUrl"] = "True";
    web.CustomMasterUrl = web.ParentWeb.CustomMasterUrl;
    web.AllProperties["__InheritsCustomMasterUrl"] = "True";
               
    web.Update();
}

Then I selected the new Feature, clicked on the manifest and copied the GUID for the Feature ID. I then subsequently added that Feature ID into the bottom of the <WebFeatures> section in the ONet.xml file.
Now when this custom web template is provisioned, this code will be executed to set the master page appropriately.
Web Provisioned Event
Another totally different option to consider is use the new SharePoint 2010 WebProvisioned Event Handler. This event handler is available in the SharePoint Sandbox and can run in Office 365. This solution is very simple:
  • Create a new SharePoint 2010 solution in Visual Studio.  
  • Add an Event Handler. 
  • Then add the following code.
public override void WebProvisioned(SPWebEventProperties properties)
{
    base.WebProvisioned(properties);

    using (SPWeb web = (SPWeb)properties.Web)
    {
        Guid sitePublishing = new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb");

        web.AllowUnsafeUpdates = true;

        web.Features.Add(sitePublishing, true);
               
        web.MasterUrl = web.ParentWeb.MasterUrl;
        web.AllProperties["__InheritsMasterUrl"] = "True";
        web.CustomMasterUrl = web.ParentWeb.CustomMasterUrl;
        web.AllProperties["__InheritsCustomMasterUrl"] = "True";
               
        web.Update();
    }

}

There are some advantages to this solution. First it is really simple. Second this code will be executed for ANY site that is provisioned. So if you need to always make sure that publishing is turned on for any site that is provisioned and that the master pages are always the same, this may actually be a better solution. Otherwise you will have to do what I previously described for every web template.

Conclusions

This was a really interesting little exercise that I went through and though it would be interesting to share. Hopefully you will see that there are options based on the business requirements you want to support. This is by no means the only options you have available either.

References

Things that I found along the way:

Wednesday, January 4, 2012

Architecture Considerations for Moving SharePoint to Office 365 and SharePoint Online

Introduction
Why are customers looking to come to the Office 365 cloud? Customers want an environment that can scale on-demand. Customers do not want to be in the business of managing and patching software . Customers want a solution that give better business continuity and service level agreements to their users. Customers want solutions that are better governed and that will force them to do better governance. Customers want to be in the business of building solutions (i.e. an airplane company should focus on building planes; not writing enterprise applications from the ground up).
When I talk with customers about SharePoint Online, this is where they want to move to.
In this blog I am going to talk about how an organization should be looking at moving to SharePoint Online.
  1. In first half we are going to analyze SharePoint Architecture and Governance and review what potential blockers people see when moving to the cloud.
  2. In the second half I am going to have a more detailed discussion around how to architecturally plan to move to SharePoint Online.
Why the decision is not always straight forward?
Coming to SharePoint Online in Office 365 may not sometimes be the most straight forward decision for organizations that have made a large investment in SharePoint. Going to SharePoint Online is really easy for organizations that are in it for document management, intranets, OOB features, SharePoint Designer, etc. It gets harder for organizations that have had poor governance of their on-premise environments, made signification investments with custom code, utilize features not available in cloud, have a heavy reliance on third party solutions, etc.
There is a solution to these issues but it requires an organization to take a step back and look at what they have.
Poor governance is probably one of the largest changes organizations have faced with SharePoint. These challenges could have been avoided thought with good forethought and planning. There is not always a one size fit all solution either; SharePoint is powerful platform that can be used to be used to implement a very broad set of business requirements.
SharePoint Architecture Foundations
The following a Venn diagram that I always draw on whiteboard with customers.
image
I typically say that that:
  • Information Architecture – Is content types, taxonomy, topology, site collections, sites, libraries, lists, and solutions that drive the management of this content. The information architecture should be driven by business requirements.
  • Logical Architecture – Is the architecture of SharePoint services, web apps, databases, etc. to support the information architecture.
  • Physical Architecture – Is the configuration, deployment, farms, etc. that actually host the SharePoint logical architecture.
I admit this is open to interpretation but let’s use this as a foundation for discussion.
Here are some of the biggest problems organizations that have come up when I discuss the diagram above:
  • Started with Physical Architecture – This is the first mistake that many seem to make. Smart IT are concerned about how many servers to buy and configure they forget to actually create an environment needed to support their business requirements. What usually happens is the environment is not scaled or organized to support the actual utilization; this is where the trouble starts. This pretty much goes away if you go to the cloud.
  • No business requirements and software design best practices – One of the biggest, consistent challenges I see many organizations have with SharePoint is no business requirements. I typically just see organizations create very light documents (a bullet list) of requirements and just start building. I very rarely see organizations actually do software design best practices. There are no use cases, data models, ERDs, UI wireframes, data dictionaries, architecture documents discussing what SharePoint elements they plan to use, etc. Why; because SharePoint is such an easy platform to start building with. I personally believe SharePoint is one of the best solution platforms on the market but sometimes organizations need architect a solution fist. This does not go away with SharePoint Online.
  • No Governance – Organizations usually forget to put Governance plans to manage content and solutions running in SharePoint. A solution can be anything from a group of team sites or a complex .NET application in SharePoint. I have even seen organizations create Governance plans but then not manage nor adhere to them. An analogy would be a organizing a ton of boxes in their basement really well (with labels too). However as time goes on, they just keep on stuffing and stuffing the room with more boxes so that entry to the room is blocked. A good SharePoint environment needs care and feeding. The information, logical and physical architectures need to have policies and procedures to manage it. Policies, procedures, service level agreements, etc. must be put into place. With SharePoint Online several of these Governance woes are removed because the Office 365 cloud manages the environment. Still Governance needs to be but in place to manage content and solutions deployed in Office 365.
  • Over Regulation – I have also seen the term “SharePoint Governance” used as a crutch. I have seen organizations lock down SharePoint too much. My response to that is was there a requirement to lock it down? If so, the right thing was done like a publishing intranet or Internet site – no user should have rights to do what they want. There should be a locked controlled publishing and branding process. However it is perfectly acceptable to have areas of SharePoint that are pure collaboration. Your information architecture and governance plans will drive business users to put content and solutions in the appropriate areas.
There are more things to think about but I am getting a little preachy J
A Not So Unusual Situation
Here is a very common scenario that backs up what I just described. It is very common for an organization to start a SharePoint environment like the following. As you can see they start with a top level SharePoint site. They create some department level sites and some sub sites for their intranet. All in all this is a pretty good start; right?
image
However within a few months (after some very heavy business and user adoption) we have the following.
image
We see such things as:
  • Team sites starting to sprawl underneath some of the sub-sites within a department. The challenge is being able to support collaboration in what was meant to initially be a publishing site.
  • Navigation, presentation, branding and user experience is not consistent.
  • We see custom applications either built from scratch or third party solutions purchased and embedded in sub-sites of a department. The challenge is should these custom solutions be hooked directly here?
  • Department level project sites are created. The challenge is that as project sites grow and take on new responsibilities for the business, they need to be elevated and made accessible like other sites.
There tons more. And I have had customers tell me this is not an issue with “SharePoint”. They currently have these same exact challenges with their legacy intranet, portals, etc. So why do organizations keep on having these challenges? I usually point to a lack of attention to Governance and Information Architecture.
So How Should You Be Thinking About This?
What if content and solutions that are to be deployed are delivered within a framework? Not a “novel” idea either. Hopefully we can make it as simple as we can. Instead of just adding more and more sites and applications; have rules that drive where we put things.
image
For example:
  • The Intranet site should remain a dedicated publishing site collection. This would be geared towards business users having read-only access with only a small set of content owners. Content is delivered in a consistent and clean fashion so that every site is the same giving the user a unified user experience.
  • Create a separate site collection for team sites with appropriate service level agreements. In the team site collection, sites should be can be dynamic generated from pre-define site templates. Users are given the ability to do pure collaboration, standing up lists, libraries, etc. They should be able to share information to complete everyday business tasks. There would also be an expectation that this area is not uniform and that users can do what they want with these sites. Retention polices can be put in place to discard these sites if they have not been used for a pre-defined period of time.
  • Create another site collection for business project sites. These have different support SLAs and Governance. These sites are a little bit more formal in nature with only a subset of people that would have access to manage them. Maybe there are designers from the IT department who have responsibility for building and supporting them. There could be policies and automated procedures to move content out of them to other site collections. Retention policies on these sites would be completely different than team sites and these sites may only be deleted when the project is over (or never deleted).
  • For custom applications, instead of embedding the application into a sub-site, place them into their dedicated site collections. Navigation links can be made to the application from other site collections. This would give significantly more flexibility to move it or provide it more resources.
  • Instead of creating one massive site collection where all scanned documents or records create multiple site collections and then route content to them based on business rules.
This list I provided is not meant to be an all-encompassing list of possibilities and/or solutions. Hopefully you will see that you need to start vertically and horizontally partitioning solutions and data based on such simple things as business rules, security access, data characteristics, etc. Knowing this will help you identify the types of site collections, sites, features, content types, managed metadata, site templates, permission levels, etc. that you need to configure SharePoint with.
The net result is you would take the previous diagram and start creating management boundaries based on the characteristics of the solutions and data managed in SharePoint. This is why Information Architecture is so critical for Enterprise Content Management system like SharePoint.
Putting everything into a single site collection really puts an organization into a tough spot to scale with the business. Microsoft has been publishing great technical diagrams for SharePoint 2010 (http://technet.microsoft.com/en-us/library/cc263199.aspx) and SharePoint 2007 (http://technet.microsoft.com/en-us/library/cc263199(office.12).aspx). Please review and get to know these diagrams well because they accurately tell everything I am talking about here.
Now some people counter this whole thing with why does SharePoint not give this to me? Why does SharePoint not auto-govern itself? SharePoint absolutely comes with a ton of features and capabilities that support a good governance model like Features, site templates, sandbox, managed metadata service, permission levels, and the list goes on. All of the configuration settings are there and organizations just need to set them as appropriate for their business.
I promise; we are coming back to the SharePoint Online cloud but we need to finish setting the stage.
How You Should Change Your Thinking
The following is a diagram a colleague (http://blogs.msdn.com/b/edhild/) and I commonly discuss with customers. I am shamelessly using it because this simple diagram really helps customers with a basic understanding of Information Architecture with SharePoint. Plus it supports everything that I just discussed. This is what we call the “Arch of SharePoint Data”. This is not all encompassing list, however there are different extremes.
image
There is publishing which are sites that are managed by a small group of users and read by a large community of read-only users. While on the other side is something like MySites which is my personal area to manage information and data. In between these two extremes are tons of different types of sites. Department sites, project sites, organization sites, custom application sites, team sites, etc. There are too many to even try to draw. Each one of these types of sites has different security, retention, data usage, transaction management, business rules, automation, etc.
I tell customers is that is perfectly ok to have a team sites area that are for pure collaboration where business users can spin-up a site, do some work on it for two months and then move on. Some people call this the “wild wild west” and that is ok. Just do not allow pure collaboration in you publishing area which is probably one of the most common mistakes J.
Coming full circle, you can see this is all about solution and data management. An Information Architecture is going to tell you the data characteristics. This will drive you to put content in one area versus another.
This is the beauty of SharePoint. It allows you to create and manage business workloads based on your specific business and mission. Once you have the Information Architecture nailed down, you can determine the Logical Architecture (services) you need and then the Physical Architecture needed to support this. By doing this, you know that both your Logical and Physical Architectures will be driven off real business requirements.
Where Does this All Fit with SharePoint Online?
Once you build an Information Architecture you will see that many of these partitions can be moved to the cloud. Intranets, team sites, project sites, my sites, light weight custom solutions, etc. can all be moved to the cloud. If you look at the “Arch of SharePoint Data” diagram, depending on your scenarios, there is a good chance that 80% to 90% of your solutions can be moved to the SharePoint Online cloud. For some organizations, they will be able to move everything up to the cloud. For some organizations they will have a hybrid.
Regardless the re-architecture should be a primary task in your SharePoint 2007 migrations to SharePoint 2010 anyways. Going through this exercise will put you in a position to move pieces to the cloud and with time, more and more.
So what are the Gaps with SharePoint Online?
If you want to know the exact answer it is clearly spelled out and completely available for you. Read either the Multi-tenant SharePoint Online Service Description (http://www.microsoft.com/download/en/details.aspx?id=13602) or the Dedicated SharePoint Service Description (http://www.microsoft.com/download/en/details.aspx?id=18128).
However really understanding these gaps depends on the perspective and approach you are taking with SharePoint. As I say a lot, “SharePoint means a lot of different things to different people”. I have seen customers extremely happy with using SharePoint with out of the box features and SharePoint Designer. While I have seen other customers use SharePoint as a full application development platform writing thousands lines of code. Knowing what SharePoint means to you will dictate your approach to the SharePoint Online cloud. The approach that I outlined in the first part of this bog will really help you with that decision process for moving to the cloud.
When you read the SharePoint Online service descriptions for both the multitenant and dedicated you will see that the gaps are really small. However there are some ones you must be aware of as they will affect your decisions on how to move to the cloud. The big ones that most people bring up are full trust code, business intelligence, FAST search, PowerShell, and Central Administration. This list will quickly change and become outdated because more and more features will be released with time. However let me address each one as it stands today:
  • Full trust code is usually the first one the first challenges. Right now, the only way to deploy custom code to the SharePoint Online Multitenant cloud is using a Sandbox solution. For the SharePoint Online Dedicated cloud, full trust code is supported but it must adhere to a strict set of rules (which are publically available) and the code will only be deployed within set windows. Why such restrictions and strong governance? Well, for all the obvious reasons that would come up if you were tasked with having to run an extremely large SharePoint environment on-premise. What has been one of the biggest issues with SharePoint 2007 Governance? It was developers writing complex code on SharePoint and disregarding the fact that an error they write may take down other sites in the farm (like the content query web part that retrieved too much data on the home page of the intranet <g>). We need to ensure that there is strong security and good performing code and that there is no possibility the Company A can take down Company B. The only way to achieve that service level agreement is to have an environment for running governed code. The net effect is that there will be limitations but you will have that guaranteed uptime. My golden rule is that all SharePoint development (on-premise and cloud) should begin with Sandbox solutions and only when the customizations cannot run in the Sandbox then build as full trust solutions. Doing this will ensure you have agility to move to the SharePoint Online cloud when you are ready. If you really need to do complex operations and manage data structures consider using services Windows Azure integrated through Business Connectivity Services (BCS), Silverlight, etc. But still that may not always suffice and that is why SharePoint Hybrid implementations will be commonplace for organizations with mature SharePoint deployments. I will cover this in more detail shortly.
  • Business Intelligence today in Office 365 is Excel and Visio Services. Other SharePoint business intelligence services like PerformancePoint, SSRS, PowerPivot and Chart Parts are not available right now. Another limitation today is Excel and Visio services only utilize data that is within the SharePoint Online context; it is not able to reach outside (i.e. to back-end databases). More and more capability will be released through the Office 365 cloud; just for the time being Silverlight and Windows Azure can be used to satisfy these requirements.
  • FAST Search is not available in the SharePoint Online cloud right now. It is possible to integrate a local FAST farm with SharePoint Online Dedicated; but not Multitenant. Still take comfort in the fact that SharePoint 2010 search made significant jumps forward from the SharePoint 2007 offering and provides a very strong search experience. With time more and more advanced search capabilities will be released in the cloud.
  • PowerShell currently is not fully available with SharePoint Online. There are a lot of PowerShell commands available for Exchange Online and user subscription management; however the full set of SharePoint PowerShell commands is not available today.
  • Central Administration Site is not available and this should be expected by anyone who understands what cloud architecture. There are administration screens available to some operation that you would normally perform in Central Admin however it is limited and does not give you the granular control. Why? Well this is the cloud. Customers want to come to the environment so they do not need to be in the business of managing every little configuration of SharePoint.
And the reality is with more and more releases of SharePoint Online this gap is going to continue to close. Still, even if it were to completely close, there will be perfectly valid reasons why some SharePoint may remain on-premise thus, creating a SharePoint Hybrid environment.
What is the SharePoint Hybrid Architecture?
SharePoint Hybrid is as simple as it sounds; it is some SharePoint delivered through the cloud and some SharePoint delivered through on-premise. What will drive you to have SharePoint on-premise? All of that has pretty much been covered to this point. Anything from a specific feature to a business policy may keep some SharePoint on-premise. However using the approach I laid out, you will be able to significantly reduce your footprint of SharePoint on-premise and gain the advantages of the cloud.
The great thing about using SharePoint on-premise is that it is the same software being run in the cloud. This means it is very easy to deliver a consistent user experience between on-premise and the cloud. Branding, navigation, security groups and single sign-on can be configured in such a way that the user can go between these two environments and not know it.
What Type of Cloud is SharePoint Online?
One other thing I want to discuss is what type of cloud is SharePoint Online. I really like this picture it really spells it out for people whom are not fully aware of the multiple delivery models for cloud computing.
image
Starting on the left side, you see on-premises and this is how most organizations run SharePoint. You must own the entire solution; all the way up the computing stack. Next is Infrastructure as a Service (IaaS) which is the cloud environment that is managed all the way up to the virtualization layer. The company is responsible for everything else; including the management of the operating systems. From a SharePoint perspective that means all the software installation, configuration, management, patching, adding new servers to meet demand, load balancing, etc. needs to be managed by the you. IaaS gets you of the business of hosting virtual SharePoint servers.
Platform as a Service (PaaS) is running the environment all the way up to the application and data tiers. Windows Azure is a PaaS cloud. In this cloud you build custom applications, data models and run them through a highly available environment.
Software as a Service (SaaS) is the entire stack delivered in the cloud and this is the delivery model for SharePoint Online. You do not have to install software, manage patches, availability, etc. This environment gets you out of the business of managing software and into the business of building solutions. SaaS does not provide the granular level of control of the SharePoint environment (which we have discussed).
The reality is that organizations and companies need to save costs and SaaS is the cloud delivery framework they want for the long-run. IaaS can run SharePoint 2010 and can be leveraged as a replacement for on-premise complex SharePoint computing. Still it is well recognized by industry that companies want more SaaS solutions.
Supplement with SharePoint Online with Windows Azure
Windows Azure (PaaS) and SharePoint Online (SaaS) can be used together to deliver end-to-end cloud solutions. Companies that have mature SharePoint deployments commonly have:
  • Code that runs in full-trust
  • Are managing complex data
  • Require the ability to do back-end systems integration.
One thing I have been talking with customers about is offloading that code out of SharePoint and into to the Windows Azure (PaaS) cloud. The Windows Azure cloud allows you to develop and deliver custom code, services, complex data (SQL Azure) and connected back-end integration (AppFabric). These complex operations can be connected through Business Connectivity Services (BCS) in SharePoint Online.
This makes a lot of sense too when you take a step back. I have already said that you should develop SharePoint code to the Sandbox first and when there is good reason to deliver outside the Sandbox. Here is a similar question. At what point do you know you should be developing in SharePoint? I fully recognize there is a gray area here.
I say good software development patterns and practices should drive that decision. This is why Windows Azure is so interesting with Office 365 because we can move complex code that cannot run in the SharePoint Sandbox to the Windows Azure cloud. I recognize this is not a perfect rule because some code needs to run in SharePoint as full trust. However this should be part of your design analysis to reduce to your SharePoint on-premise footprint.
There are lots of different ways Windows Azure can be utilized with SharePoint Online. There may be situations where you need:
  • To work with data in SharePoint but you have complex relationships in the data model that are not right for SharePoint lists. Use SQL Azure to manage that data and build services and connect via BCS or Silverlight.
  • To integrate with line of business applications on premise use custom services deployed in Windows Azure or AppFrabic. Again BCS or Silverlight can connect Windows Azure which is conduit to line of business applications.
  • To use custom web services to perform complex computations and logic. Again offload that to Windows Azure.
  • As well, reverse the direction. There may be solutions and applications delivered in Windows Azure can utilize SharePoint Online services. There are SharePoint web services, REST services for data, SharePoint Client API, Javascript APIs and Silverlight APIs that can be used as integration points. A simple scenario could be a web page deployed in Windows Azure that needs to manage documents. Instead of building that up from scratch in Windows Azure just connect through SharePoint Online APIs and deliver SharePoint Online services through that custom web page.
At the end of the day both SharePoint Online and Windows Azure can be used to complement each other in the delivery enterprise business solutions through the cloud.
image
Conclusions
Why did I go through all of this? The answer is simple; to give SharePoint Architects ideas on how to move forward with SharePoint Online. There really should be no blockers as long as you take a realist look at your Information Architecture and assess how you use SharePoint. There will be lots of stuff which can clearly be moved to the cloud, there will be some stuff where it is not appropriate (hybrid) and then there is that gray area. However I really hope that approach I put forth will help you with your thinking into how to significantly reduce, if not completely remove, your SharePoint on-premise footprint.
Thanks
Special thanks to Chris Geier and Stephen Cawood for providing me feedback and advice as I wrote this.

Saturday, July 30, 2011

Part 2 – Custom Action for Workflow Initiation

· Part 1 - Pattern for Building Stateful Workflows with SharePoint Designer 2010
· Part 2 - Custom Action for Workflow Initiation
· Part 3 - Delays for Workflow Initiation Action
· Part 4 - Using Business Connectivity Services (BCS) with SharePoint 2010 Workflow
· Part 5 - Custom Visio Services Reports with SharePoint 2010 Workflow

Part 2

Building the Custom Action

In the previous part of this blog I explained my approach and in this part I am going to show you how I created two custom actions that is needed to support my approach. I am first going to show you the code solution I created and then dive a bit into why I made the solution as is.

I can tell you honestly that I really wanted this solution to be a SharePoint 2010 Sandbox solution however I ran into a few challenges that prevented me from doing that. This forced me to build a full trust solution with Visual Studio 2010. There are basically two actions I needed to create. The first one is an action that can initiate another workflow. The second action I needed checks to see if 1 to N workflows are running on a list item, and if so, stop the running of that workflow.

It is pretty well documented on how to create a custom action, deploy it and then use that action in SharePoint Designer. The following are some good references:

· http://blog.voltje.be/?p=144

· http://msmvps.com/blogs/sundar_narasiman/archive/2010/12/26/develop-custom-workflow-activity-for-sharepoint-2010-workflow.aspx

Workflow Helper Class

First thing I did was create a simple helper class where I stored logic to initiate the workflow and to check to see if there are any existing workflows running. The ItemHasActiveWorkflows method is really straight forward as it is searching workflows that are running for the specific item. If it finds a workflow is running, it will return false. Why is this important? Well because a document or list item can only have one of a particular type running at a time. But since we broke the larger business process up into five smaller ones, we need to check to see if any of the five are running on the item. If any one of them is running, we need to block any new workflows from being started. This method will take a comma delimited list of workflow names that must be checked.

The second method is StartWorkflow which will initiate a workflow on a specified item. This code is very straight forward.

public class WorkflowHelper
{

private string siteCollectionUrl;
private string webUrl;
private string listName;
private int itemID;
private string workflowName;

public WorkflowHelper(string siteCollectionUrl, string webUrl, string listName, int itemID)
{
this.siteCollectionUrl = siteCollectionUrl;
this.webUrl = webUrl;
this.listName = listName;
this.itemID = itemID;
}

public WorkflowHelper(string siteCollectionUrl, string webUrl, string listName, int itemID, string workflowName) : this(siteCollectionUrl, webUrl, listName, itemID)
{
this.workflowName = workflowName;
}

public bool ItemHasActiveWorkflows(string workflowNames)
{
string[] seperator = new string[] {","};
string[] workflowNamesSplit = workflowNames.Split(seperator, StringSplitOptions.RemoveEmptyEntries);

//Get the site collection
using (SPSite site = new SPSite(siteCollectionUrl))
{
//Get the web
using (SPWeb web = site.OpenWeb(webUrl))
{
SPList list = web.Lists[listName];
SPListItem workflowItem = list.GetItemById(itemID);

//Loop over the workflows to look for
foreach (string workflowName in workflowNamesSplit)
{
//Loop over the workflows on the item
foreach (SPWorkflow workflow in workflowItem.Workflows)
{
//Check the state of the workflows to see if any are running
if (workflow.InternalState == SPWorkflowState.Running ||
workflow.InternalState == SPWorkflowState.Expiring ||
workflow.InternalState == SPWorkflowState.Faulting)
{
if (list.WorkflowAssociations[workflow.AssociationId].Name.ToLower() == workflowName.Trim().ToLower())
{
return true;
}
}
}
}
}
}

return false;
}

public void StartWorkflow()
{
//Open the site collection. Cannot go across site collections in
//sandbox so easier to just pull of workflow context
using (SPSite site = new SPSite(siteCollectionUrl))
{
//Just open web because we cannot go across site collections
//with a sandbox solution.
using (SPWeb web = site.OpenWeb(webUrl))
{
//Get the manager that will initiate the workflow
SPWorkflowManager workflowMgr = site.WorkflowManager;

//Get the available workflows on the list
SPWorkflowAssociationCollection workflowAssocs = web.Lists[listName].WorkflowAssociations;

//Get the list item that the workflow will be initiated on
SPListItem workflowItem = web.Lists[listName].GetItemById(itemID);

//Get the workflow that has been associated
SPWorkflowAssociation workflowAssoc = workflowAssocs.GetAssociationByName(workflowName, System.Threading.Thread.CurrentThread.CurrentCulture);

//Start the workflow
workflowMgr.StartWorkflow(workflowItem, workflowAssoc, workflowAssoc.AssociationData, true);
}
}
}
}


Start Workflow Action



Next I created an action that would start a second workflow. I created the following code.




public class InitWorkflowAction : Activity
{

#region Properties

public static DependencyProperty SiteCollectionUrlProperty = DependencyProperty.Register("SiteCollectionUrl", typeof(string), typeof(InitWorkflowAction));

[Description("Site Collection URL")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string SiteCollectionUrl
{
get
{
return ((string)(base.GetValue(InitWorkflowAction.SiteCollectionUrlProperty)));
}
set
{
base.SetValue(InitWorkflowAction.SiteCollectionUrlProperty, value);
}
}

public static DependencyProperty WebUrlProperty = DependencyProperty.Register("WebUrl", typeof(string), typeof(InitWorkflowAction));

[Description("Web Url")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string WebUrl
{
get
{
return ((string)(base.GetValue(InitWorkflowAction.WebUrlProperty)));
}
set
{
base.SetValue(InitWorkflowAction.WebUrlProperty, value);
}
}

public static DependencyProperty ListNameProperty = DependencyProperty.Register("ListName", typeof(string), typeof(InitWorkflowAction));

[Description("List Name")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string ListName
{
get
{
return ((string)(base.GetValue(InitWorkflowAction.ListNameProperty)));
}
set
{
base.SetValue(InitWorkflowAction.ListNameProperty, value);
}
}

public static DependencyProperty WorkflowNameProperty = DependencyProperty.Register("WorkflowName", typeof(string), typeof(InitWorkflowAction));

[Description("Workflow Name")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string WorkflowName
{
get
{
return ((string)(base.GetValue(InitWorkflowAction.WorkflowNameProperty)));
}
set
{
base.SetValue(InitWorkflowAction.WorkflowNameProperty, value);
}
}

public static DependencyProperty ItemIDProperty = DependencyProperty.Register("ItemID", typeof(int), typeof(InitWorkflowAction));

[Description("Item ID")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public int ItemID
{
get
{
return ((int)(base.GetValue(InitWorkflowAction.ItemIDProperty)));
}
set
{
base.SetValue(InitWorkflowAction.ItemIDProperty, value);
}
}


#endregion

#region Methods

protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
//WorkflowHelper workflowHelper = new WorkflowHelper(this.SiteCollectionUrl, this.WebUrl, this.ListName, this.ItemID, this.WorkflowName);
//workflowHelper.StartWorkflow();

WorkflowHelper workflowHelper = new WorkflowHelper(this.SiteCollectionUrl, this.WebUrl, this.ListName, this.ItemID, this.WorkflowName);
Thread thread = new Thread(new ThreadStart(workflowHelper.StartWorkflow));
thread.Start();

return ActivityExecutionStatus.Closed;
}

#endregion

}


With the StartWorkflow method you see the code is straight forward but there some threading. You may be wondering why I have implemented threading? Well I was getting the below error message in the SharePoint logs when the workflow was initiated on the same thread. I did not find any information on why this was occurring but on a hunch I thought the workflow service was competing for the same resources. My solution was to move the call to StartWorkflow into a different thread and the problem was resolved.



w3wp.exe (0x2BC4) 0x0A2C SharePoint Foundation Workflow Infrastructure xmfh Medium Workflow Compile Failed: Invalid token for impersonation - it cannot be duplicated.



w3wp.exe (0x2BC4) 0x0A2C SharePoint Foundation Workflow Infrastructure 72fs Unexpected RunWorkflow: Microsoft.SharePoint.SPException: Invalid token for impersonation - it cannot be duplicated. at Microsoft.SharePoint.Workflow.SPNoCodeXomlCompiler.SubCompiler.DoCompile(WorkflowCompilerParameters parameters, String xomlSource, String assemblyName, CompilationPacket& packet, DirectoryInfo& tempDir) at Microsoft.SharePoint.Workflow.SPNoCodeXomlCompiler.CompileBytes(Byte[] xomlBytes, Byte[] rulesBytes, Boolean doTestCompilation, String assemblyName, SPWeb web, Boolean forceNewAppDomain) at Microsoft.SharePoint.Workflow.SPNoCodeXomlCompiler.LoadXomlAssembly(SPWorkflowAssociation association, SPWeb web) at Microsoft.SharePoint.Workflow.SPWinOeHostServices.LoadDeclarativeAssembly(SPWorkflowAssociation association) at Microsoft.SharePoint.Workflow.SPWinOeHostServi...



w3wp.exe (0x2BC4) 0x0A2C SharePoint Foundation Workflow Infrastructure 72fs Unexpected ...ces.CreateInstance(SPWorkflow workflow) at Microsoft.SharePoint.Workflow.SPWinOeEngine.RunWorkflow(SPWorkflowHostService host, SPWorkflow workflow, Collection`1 events, TimeSpan timeOut) at Microsoft.SharePoint.Workflow.SPWorkflowManager.RunWorkflowElev(SPWorkflow workflow, Collection`1 events, SPWorkflowRunOptionsInternal runOptions)



0x0A2C SharePoint Foundation Workflow Infrastructure 98d8 Unexpected Microsoft.SharePoint.SPException: Invalid token for impersonation - it cannot be duplicated. at Microsoft.SharePoint.Workflow.SPNoCodeXomlCompiler.SubCompiler.DoCompile(WorkflowCompilerParameters parameters, String xomlSource, String assemblyName, CompilationPacket& packet, DirectoryInfo& tempDir) at Microsoft.SharePoint.Workflow.SPNoCodeXomlCompiler.CompileBytes(Byte[] xomlBytes, Byte[] rulesBytes, Boolean doTestCompilation, String assemblyName, SPWeb web, Boolean forceNewAppDomain) at Microsoft.SharePoint.Workflow.SPNoCodeXomlCompiler.LoadXomlAssembly(SPWorkflowAssociation association, SPWeb web) at Microsoft.SharePoint.Workflow.SPWinOeHostServices.LoadDeclarativeAssembly(SPWorkflowAssociation association) at Microsoft.SharePoint.Workflow.SPWinOeHostServices.CreateIns...



w3wp.exe (0x2BC4) 0x0A2C SharePoint Foundation Workflow Infrastructure 98d8 Unexpected ...tance(SPWorkflow workflow) at Microsoft.SharePoint.Workflow.SPWinOeEngine.RunWorkflow(SPWorkflowHostService host, SPWorkflow workflow, Collection`1 events, TimeSpan timeOut) at Microsoft.SharePoint.Workflow.SPWorkflowManager.RunWorkflowElev(SPWorkflow workflow, Collection`1 events, SPWorkflowRunOptionsInternal runOptions)



Check Active Workflows Action



Below is the code that will check to see if there is an action running on a workflow item. The code is straight forward and calls my helper class that I created earlier.




public class CheckActiveWorkflowsAction : Activity
{

#region Properties

public static DependencyProperty SiteCollectionUrlProperty = DependencyProperty.Register("SiteCollectionUrl", typeof(string), typeof(CheckActiveWorkflowsAction));

[Description("Site Collection URL")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string SiteCollectionUrl
{
get
{
return ((string)(base.GetValue(CheckActiveWorkflowsAction.SiteCollectionUrlProperty)));
}
set
{
base.SetValue(CheckActiveWorkflowsAction.SiteCollectionUrlProperty, value);
}
}

public static DependencyProperty WebUrlProperty = DependencyProperty.Register("WebUrl", typeof(string), typeof(CheckActiveWorkflowsAction));

[Description("Web Url")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string WebUrl
{
get
{
return ((string)(base.GetValue(CheckActiveWorkflowsAction.WebUrlProperty)));
}
set
{
base.SetValue(CheckActiveWorkflowsAction.WebUrlProperty, value);
}
}

public static DependencyProperty ListNameProperty = DependencyProperty.Register("ListName", typeof(string), typeof(CheckActiveWorkflowsAction));

[Description("List Name")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string ListName
{
get
{
return ((string)(base.GetValue(CheckActiveWorkflowsAction.ListNameProperty)));
}
set
{
base.SetValue(CheckActiveWorkflowsAction.ListNameProperty, value);
}
}

public static DependencyProperty ItemIDProperty = DependencyProperty.Register("ItemID", typeof(int), typeof(CheckActiveWorkflowsAction));

[Description("Item ID")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public int ItemID
{
get
{
return ((int)(base.GetValue(CheckActiveWorkflowsAction.ItemIDProperty)));
}
set
{
base.SetValue(CheckActiveWorkflowsAction.ItemIDProperty, value);
}
}

public static DependencyProperty HasActiveProperty = DependencyProperty.Register("HasActive", typeof(bool), typeof(CheckActiveWorkflowsAction));

[Description("Has Active")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool HasActive
{
get
{
return ((bool)(base.GetValue(CheckActiveWorkflowsAction.HasActiveProperty)));
}
set
{
base.SetValue(CheckActiveWorkflowsAction.HasActiveProperty, value);
}
}

public static DependencyProperty WorkflowNamesProperty = DependencyProperty.Register("WorkflowNames", typeof(string), typeof(CheckActiveWorkflowsAction));

[Description("Workfow Names")]
[Category("Custom Workflow")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string WorkflowNames
{
get
{
return ((string)(base.GetValue(CheckActiveWorkflowsAction.WorkflowNamesProperty)));
}
set
{
base.SetValue(CheckActiveWorkflowsAction.WorkflowNamesProperty, value);
}
}

#endregion

#region Methods

protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
WorkflowHelper workflowHelper = new WorkflowHelper(this.SiteCollectionUrl, this.WebUrl, this.ListName, this.ItemID);
this.HasActive = workflowHelper.ItemHasActiveWorkflows(this.WorkflowNames);

return ActivityExecutionStatus.Closed;
}

#endregion
}


Deployment



The deployment of this solution was pretty easy with Visual Studio 2010.



· I created an empty SharePoint 2010 project.



· Added the above code.



· Added a Site Collection level Feature.



· Added a SharePoint mapped folder called “Workflow”



· Create a new file called InitWorkflowAction.actions in the Workflow folder.



The InitWorkflowAction.actions file describes my custom actions and makes them available to design tools such as SharePoint Designer 2010 to create a declarative workflow. Information below is very straight forward. It defines the sentence users will fill in and what type of data will be consumed or returned from the methods I created earlier.




<WorkflowInfo>
<Actions Sequential="then" Parallel="and">
<Action Name="Start Workflow"
Assembly="My.Activities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7cb64b163bd9c1db"
ClassName="My.Activities.InitWorkflowAction"
AppliesTo="all"
Category="Custom Workflow">
<RuleDesigner Sentence="Initiate workflow %4 on item %5 in list %3 in Web %2 in Site Collection %1">
<FieldBind Field="SiteCollectionUrl"
Text="Site Collection Url"
Id="1"
DesignerType="TextBox" />
<FieldBind Field="WebUrl"
Text="Web Url"
Id="2"
DesignerType="TextBox" />
<FieldBind Field="ListName"
Text="List Name"
Id="3"
DesignerType="TextBox" />
<FieldBind Field="WorkflowName"
Text="Workflow Name"
Id="4"
DesignerType="TextBox" />
<FieldBind Field="ItemID"
Text="Item ID"
Id="5"
DesignerType="Integer" />
</RuleDesigner>
<Parameters>
<Parameter Name="SiteCollectionUrl"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="Site Collection Url"/>
<Parameter Name="WebUrl"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="Web Url"/>
<Parameter Name="ListName"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="List Name"/>
<Parameter Name="WorkflowName"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="Workflow Name"/>
<Parameter Name="ItemID"
Type="System.Int32, mscorlib"
Direction="In"
DesignerType="Integer"
Description="Item ID"/>
</Parameters>
</Action>
<Action Name="Check Active Workflow"
Assembly="My.Activities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7cb64b163bd9c1db"
ClassName="My.Activities.CheckActiveWorkflowsAction"
AppliesTo="all"
Category="Custom Workflow">
<RuleDesigner Sentence="Check if workflows %6 on item item %4 in list %3 in Web %2 in Site Collection %1 has a running workflow (Output to %5)">
<FieldBind Field="SiteCollectionUrl"
Text="Site Collection Url"
Id="1"
DesignerType="TextBox" />
<FieldBind Field="WebUrl"
Text="Web Url"
Id="2"
DesignerType="TextBox" />
<FieldBind Field="ListName"
Text="List Name"
Id="3"
DesignerType="TextBox" />
<FieldBind Field="ItemID"
Text="Item ID"
Id="4"
DesignerType="Integer" />
<FieldBind Field="HasActive"
Text="Has Active"
Id="5"
DesignerType="ParameterNames" />
<FieldBind Field="WorkflowNames"
Text="Comma delimited list of workflow names"
Id="6"
DesignerType="TextBox" />
</RuleDesigner>
<Parameters>
<Parameter Name="SiteCollectionUrl"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="Site Collection Url"/>
<Parameter Name="WebUrl"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="Web Url"/>
<Parameter Name="ListName"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="List Name"/>
<Parameter Name="ItemID"
Type="System.Int32, mscorlib"
Direction="In"
DesignerType="Integer"
Description="Item ID"/>
<Parameter Name="HasActive"
Type="System.Boolean, mscorlib"
Direction="In"
DesignerType="ParameterNames"
Description="Has Active"/>
<Parameter Name="WorkflowNames"
Type="System.String, mscorlib"
Direction="In"
DesignerType="TextBox"
Description="Comma delimited list of workflow names"/>
</Parameters>
</Action>
</Actions>
</WorkflowInfo>


Using Custom Actions in SharePoint Designer 2010



Now I am going to show you how I used the custom actions in my workflow. Earlier in this series you saw that I had created five different SharePoint Visio 2010 workflow diagrams. I am going to skip documenting the steps on how to bring the Visio diagrams into SharePoint Designer as that is a pretty straight forward process.



Below is a screenshot of the Initiate Process workflow. The first Action is my custom action that checks to see if there is already a workflow running for the custom list item. You will notice that the sentence displayed here corresponds with the sentence in the InitWorkflowAction.actions file. Also note the first parameter is a comma delimited list of all the other workflows (Review,Manager Review,Resubmit Request,Complete Request).



Next I take the value returned from my custom action and check to see if it Yes or No. If it is No, that means there are no running workflows and that I should initiate the Review Workflow. The third sentence in the diagram below captures this. I will initiate the Review workflow on the current item and send a notification email. Otherwise the workflow will not be started and the user will be notified.



image



Note that for the configuration of this workflow, it is the only one that supports allowing the workflow to be started manually. All of the other workflows I have created have no checkboxes checked for the Start Options section. This reduces the potential for user errors when starting the workflow for the item. The reason why is that we always want users to start with the Initiate Process workflow and let the other workflows be started based on business rules.



clip_image002



Next I have another workflow called Review that corresponds to the Visio diagram in the previous part of this series. Notice again I simply wire into the custom action StartWorkflow to start Manager Review, Complete Review or Resubmit Request.



clip_image004



Below is the Manager Review workflow. As you can see if the Manager approves the Complete Request workflow will be called otherwise the Resubmit Request workflow will be called.



clip_image006



Next is the Resubmit Request workflow. The workflow checks to see if the user cancels the workflow. If they do, the item will be updated and an email will be sent. Otherwise, the item will go back to the Review workflow (for re-review).



clip_image008



Finally the Complete Request workflow is below. I have not done much with it at this time but more can be added.



clip_image010



So now once I validate and deploy my workflow I can initiate it on an item. Below is a screenshot of a user initiate the process for an item. Notice only the Initiate Process workflow is available.



clip_image012



Once I have started the workflow I come back to the workflow status screen. Here you see the Review workflow is In Progress. Notice that the Initiate Process workflow is still available. Since the workflow is in progress I want to make sure that I cannot initiate the entire workflow again while it is current running.



clip_image014



Below is a screenshot of the completed workflow.



clip_image016



Now you can see I was able to chain together several workflows that as a whole make up a larger business process. Pretty neat.



Sandbox Solutions



I alluded earlier that I really wanted to make this a sandbox solution. Why? Because I believe that you should always develop for the Sandbox first because it quick to deploy solutions, it is secure, ensures good performance and works well with Office365.



Here are some good resources on how to deploy actions into the SharePoint 2010 Sandbox:



· http://msdn.microsoft.com/en-us/library/ff798499.aspx



· http://msdn.microsoft.com/en-us/library/ff630175.aspx



· http://msdn.microsoft.com/en-us/library/ff798389.aspx



· http://www.wictorwilen.se/Post/Sandboxed-workflow-activities-in-SharePoint-2010.aspx



The process is a little different and the code above would change a tiny bit so that it is scoped to a Site Collection only. However fundamentally there is not much difference.



When I deployed the custom actions and created the workflows I would get errors initiating the workflows. I went into the logs and found the following.



SPUCWorkerProcessProxy.exe (0x1E70) 0x1EC0 SharePoint Foundation Workflow Infrastructure 72er Medium System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.SharePoint.Library.SPRequest.ClearAllVars(String bstrUrl) at Microsoft.SharePoint.SPListItem.PrepareItemForUpdate(SPWeb web, Boolean bMigration, Boolean& bAdd, Boolean& bPublish, Object& objAttachmentNames, Object& objAttachmentContents, Int32& parentFolderId) at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents, String filename) at Microsoft.SharePoint.SPListItem.Update() at Microsoft.SharePoint.Workflow.SPWinOEWSSService.CommitUpdateListItem(Transaction txn, Object[] transData)



SPUCWorkerProcessProxy.exe (0x1E70) 0x1EC0 SharePoint Foundation Workflow Infrastructure 72fe High Error in commiting pending workflow batch items: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.SharePoint.Library.SPRequest.ClearAllVars(String bstrUrl) at Microsoft.SharePoint.SPListItem.PrepareItemForUpdate(SPWeb web, Boolean bMigration, Boolean& bAdd, Boolean& bPublish, Object& objAttachmentNames, Object& objAttachmentContents, Int32& parentFolderId) at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents, String filename) at Microsoft.SharePoint.SPListItem.Update() at Microsoft.SharePoint.Workflow.SPWinOEWSSService.CommitUpdateListItem...



SPUCWorkerProcessProxy.exe (0x1E70) 0x1EC0 SharePoint Foundation Workflow Infrastructure 72fe High ...(Transaction txn, Object[] transData) at Microsoft.SharePoint.Workflow.SPPendingWorkBatch.Commit(Transaction transaction, ICollection items)



SPUCWorkerProcessProxy.exe (0x1E70) 0x1EC0 SharePoint Foundation Workflow Infrastructure 88xr Unexpected WinWF Internal Error, terminating workflow Id# 8d547a01-bdb8-44ac-b066-586c12367dc0



The information that was provided was not very good. Here are some observations I made.



· Note that the error is in SPUCWorkerProcessProxy.exe and not w3wp.exe. This basically means the entire workflow is running inside the Sandbox service because it has a reference to an action that is deployed there.



· I would only get this error the very first time the workflow run. From then on, it worked every time flawlessly. However if I stopped and restarted the Sandbox service manually, I would get the error again.



· I would also not get the error if Workflow A started a very simple Workflow B. For instance if Workflow B was sending an email, no issues. However if Workflow B had an approval process there would be an error.



After doing some research I came to the conclusion that this error occurs based on a combination of a few things.



1. When you build a workflow in SharePoint Designer 2010 it is a declarative workflow, not a complied workflow. The workflow will be compiled the first time the workflow is initiated. This is why it always takes a long time to start a workflow the very first time.



2. Sandbox solutions have a threshold of 20 seconds before it is determined the process too intensive and will stop the execution.



This combination would push me over the 20 seconds rule the very first time running the workflow. The solution would be to write some sort of script that could manually go through each workflow and initiating them so they would be compiled and ready to go when the user comes to manually start the workflow. I did not find that to be an acceptable solution because the Sandbox cache will be remove items from memory if they are not used often. This is why I did a full trust solution.



Next Part



Hopefully this gave you a pretty good idea of how simple it is to achieve this vision I have. Now in the next part of this series I am going to extend the solution a little bit to support my reporting requirements using Visio Services.