System.ServiceModel.ServiceActivationException: The service ‘/SecurityTokenServiceApplication/securitytoken.svc’ cannot be activated due to an exception during compilation.

Re-post from here

Problem
I had performed an in-place upgrade of a Team Foundation Server from Windows Server 2012 to Windows Server 2012 R2. Overall, no issues detected until a couple of weeks later when all the Developers came back to work (after XMas break) and informed me that Documents were not available via the Visual Studio 2012 application. The following error was occurring in Visual Studio; Please contact your administrator. There was an error contacting the server.Technical information (for administrator): HTTP code 200: OK
So off to the TFS Server it was….

Research
First stop was the Event Viewer and there were two errors that I believe were related and occurring.

Error 1 – Event ID 3 System.ServiceModel 4.0.0.0 WebHost failed to process a request. 

Sender Information:System.ServiceModel.ServiceHostingEnvironment+HostingManager/4032828
Exception: System.ServiceModel.ServiceActivationException: The service ‘/SecurityTokenServiceApplication/securitytoken.svc’ cannot be activated
due to an exception during compilation. 

The exception message is: Exception has been thrown by the target of an invocation.. —> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.ArgumentNullException: Value cannot be null. Parameter name: certificate at System.IdentityModel.Tokens.X509SecurityToken..ctor(X509Certificate2 certificate, String id, Boolean clone, Boolean disposable) at System.IdentityModel.Tokens.X509SecurityToken..ctor(X509Certificate2 certificate) at Microsoft.SharePoint.Administration.Claims.SPSecurityTokenServiceManager.ConfigureTokenHandlerCollection(SPSecurityTokenServiceManager manager, SecurityTokenHandlerCollectionManager collectionManager, String key, SecurityTokenHandlerCollection& tokenHandlerCollection) at Microsoft.SharePoint.IdentityModel.SPSecurityTokenServiceConfiguration.ConfigureTokenHandlerCollectionForLocalIssuer(SPSecurityTokenServiceManager manager, SecurityTokenHandlerCollectionManager collectionManager, String key) at Microsoft.SharePoint.IdentityModel.SPSecurityTokenServiceConfiguration..ctor() — End of inner exception stack trace — at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean&bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory.CreateSecurityTokenServiceConfiguration(String constructorString) at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) at Microsoft.SharePoint.IdentityModel.SPSecurityTokenServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) — End of inner exception stack trace — at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath, EventTraceActivity eventTraceActivity) Process Name: w3wp Process ID: 5664

Error 2 – Error ID 8306 SharePoint Foundation

An exception occurred when trying to issue security token:
The requested service, ‘http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc’ could not be activated.
See the server’s diagnostic trace logs for more information.. 

Error 3 – Error ID 6398

The Execute method of job definition Microsoft.Office.Server.UserProfiles.LMTRepopulationJob (ID 1b0c4725-fbcf-476d-af60-3aeabbdbd35c) threw an
exception. More information is included below. System.ServiceModel.ServiceActivationException 

The common problem here appeared to me to be with relation to the SecurityTokenServiceApplication, which can be sussed out within IIS… First I check that the Application Pool was configured with correct TFS Account and started…check Next went to browse the SecurityTokenServiceApplication web page itself (IIS Manager –> Sites –> SharePoint WebServices –> SecurityTokenServiceApplication, click on ‘Content View’ down at the bottom, right click on Securitytoken.svc and click Browse)…ERROR Basically you get a ‘Server Error in ‘/..’ Application + Error 1 above, or Internet Explorer cannot display the webpage etc.
From here I knew that the only way to fix this was to focus on the SecurityTokenServiceApplication web service but I wasn’t really sure where to start except that I knew this would be easy with PowerShell. 🙂

Thanks to gurus such as Syed and Abhishek Saigal, this is what fixed my issue.

Resolution
The below PowerShell commands re-provisions all the SharePoint Web Services.
Don’t worry about losing any data/applications on SharePoint, all will remain intact.
Run the following commands one by one on SharePoint PowerShell:

$h = Get-SPServiceHostconfig
$h.Provision()
$services = Get-SPServiceApplication
foreach ($service in $services) { $service.provision(); write-host $service.name} 

The output will take a little time and display each service one after another, patiently wait until it finishes.
Perform an IIS Reset and give another shot to browsing ‘http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc’ This page then displayed correctly, e.g. no error messages and Documents then worked within Visual Studio.