While upgrading some timer job solutions from SharePoint 2010 to SharePoint 2013 I ran into a frustrating problem. For some reason some of my fairly basic code just wouldn’t run. Instead I was getting the following error:
System.TypeInitializationException: The type initializer for 'System.Management.Automation.SessionStateScope' threw an exception. ---> System.InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain.
This wasn’t really the most helpful error, but I traced it down to where my Timer Job was actually calling a couple PowerShell CmdLets.
After doing some research I was able to isolate the issue down to .Net Legacy CAS support being enabled. By default in SharePoint 2013, all the web applications as well as the SharePoint Timer Service have .Net legacy CAS (Code Access Security) support enabled. I assume this is required so that SharePoint 2013 can fully support sites and solution running in SharePoint 2010 mode.
The easiest solution is to go into the configuration file for the SharePoint Timer Service and to disable the legacy CAS support for the service. Note that you’d have to do this on every server in the farm that is running the Timer Service.
To change the settings:
- Navigate and open for edit the configuration file located in the SharePoint hive:
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\BIN\OWSTIMER.EXE.CONFIG
- Disable the support for Legacy CAS - change to the following
<NetFx40_LegacySecurityPolicy enabled="false" />
- Save the file and recycle the SharePoint Timer Service
That should now allow your Timer Jobs to execute PowerShell without any issues.
Some notes on this though:
From my research I’ve seen that disabling legacy CAS support is supported, but not recommended
By disabling the legacy CAS support, it might break your farm’s ability to run sites fully in SharePoint 2010 mode as any SharePoint 2010 solutions deployed to the farm that contain Timer Jobs will probably not run anymore due to CAS issues
If you are sure that your SharePoint 2013 farm won’t need to support sites or solutions in SharePoint 2010 mode that this should work for you. As for me, breaking SharePoint 2010 mode support wasn’t an option so I had to come up with a better alternative that I’ll discuss in Part 2.