Wednesday, December 12, 2012

Nintex + InfoPath 2010 Conditional Formatting Issue

The InfoPath 2010 web enabled task forms are served by nintex under /_layouts/NintexWorkflow/WrkTaskIP.aspx. The nomal infopath form is served via /_layouts/WrkTaskIP.aspx the /layouts folder is a directory shared by all web applications locaed under the 14 Hive at c:\program files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\. This page inherits from Nintex.Workflow.ApplicationPages.WrkTaskIPPage which is not part of SharePoint. The re-interpretation by the Nintex of InfoPath forms has consequently caused formatting rules to become an unsupported feature. Should I create normal SharePoint workflows with standard InfoPath forms the same form and rules will be functional (tested).

If you require Nintex Workflow and conditional formatting support you may wish to consider upgrading to the November 2012 release of Nintex forms which "supports" conditional formatting in the future, albiet this support has arrived somewhat late for those of us implementing Nintex workflows prior to November 2012.

Thursday, December 6, 2012

Nintex Update Multiple Items Null Reference Exception

A brief post to capture the fact that you may get ambigous exception using the update multiple item activity.

Setting fields to current list item fields which have no value. Or setting no value on the field will effectively throw a null reference exception. I wanted to create a single activity to set all the fields to the parent item fields but this failed as the step continues to throw null reference exceptions. If the user inputs no value into the field this can also trigger the exception, even if the field is an optional field.

The trick is to only set fields you have recieved data for.

Wednesday, November 21, 2012

Windbg SOS CheatSheets


A Couple of Cheatsheets (reference: http://geekswithblogs.net/.NETonMyMind/archive/2006/03/14/72262.aspx and http://blogs.msdn.com/b/alejacma/archive/2009/06/30/sos-cheat-sheet-net-2-0-3-0-3-5.aspx):

Cheatsheet #1

Starting, Attaching, Executing and Exiting

Start -> All Programs -> Debugging Tools for Windows -> WinDbg
F6
attach to process
Ctrl-Break
interrupt debugee
.detach
detach from a process
g
continue debugee execution
q
exit WinDbg


Getting Help
?
help on commands that affect the debugee
.help
help on commands that affect the debugger
.hh command
view the on line help file
!help
help on the extension dll at the top of the chain (e. g., SOS)


Issuing Commands
up arrow, down arrow, enter
scroll through command history
Right mouse button
paste into command window


Examining the Unmanaged Environment
lmf
list loaded modules with full path
lmt
list loaded modules with last modified timestamp
~
list unmanaged threads
~thread s
select a thread for thread specific commands
!token -n
view thread permissions
k
view the unmanaged call stack
!runaway
view thread CPU consumption
bp
set a breakpoint
.dump path
dump small memory image
.dump /ma path
dump complete memory image


Working with Extension DLLs (e. g., SOS)
.chain
list extensions dlls
.load clr10\sos
load SOS for debugging framework 1.0 / 1.1
.unload clr10\sos
unload SOS
.loadby sos mscorwks
load SOS for debugging framework 2.0


SOS Commands
!threads
view managed threads
!clrstack
view the managed call stack
!dumpstack
view combined unmanaged & managed call stack
!clrstack -p
view function call arguments
!clrstack –l
view stack (local) variables
!name2ee module class
view addresses associated with a class or method
!dumpmt –md address
view the method table & methods for a class
!dumpmd address
view detailed information about a method
!do address
view information about an object
!dumpheap –stat
view memory consumption by type
!dumpheap –min size
view memory consumption by object when at least size
!dumpheap –type type
view memory consumption for all objects of type type
!gcroot address
view which object are holding a reference to address
!syncblk
view information about managed locks


SOS 2.0 Commands
!bpmd module method
set breakpoint
!DumpArray address
view contents of an array
!PrintException
view information about most recent exception



Cheatsheet #2
========================================================================
HELP
========================================================================

.hh
  -> Open Debugger.chm.
!SOS.help
  -> See all commands in an extension.
!SOS.help !command
  -> Get help for one command in an extension.

========================================================================
PREPARE THE ENVIRONMENT
========================================================================

---------------
SET SYMBOL PATH
---------------

.sympath
    -> Shows current symbol path.
.sympath srv*c:\symbols*\\symbols\symbols
    -> Sets symbol path.
.sympath+ srv*c:\symbolspub*http://msdl.microsoft.com/downloads/symbols
    -> Adds path to symbol path.
 
--------------------
SET SOURCE CODE PATH
--------------------

.srcpath
    -> Shows current source path.
.srcpath \\dubitgfila04\DevDivServicing\whidbey\50727.42\sources
    -> Sets source path.
.srcpath+ C:\path
    -> Adds path to source path.
 
----------------
LOAD EXTENSIONS
----------------

.chain
    -> Shows loaded extensions. 
!EEVersion
    -> Shows .NET version and SOS version.
.load SOS
    -> Loads extension.
sxe ld mscorwks.dll; g; .loadby SOS mscorwks
sxe -c "" clrn; g; .loadby SOS mscorwks
sxe -c ".loadby sos mscorwks; g" ld mscorwks.dll
    -> Loads the right version of SOS when mscorwks.dll gets loaded.
.unload SOS
    -> Unloads extension

========================================================================
SET A BREAKPOINT
========================================================================

-----------
FIND METHOD
-----------

!DumpDomain
    -> Shows all app domains and their assemblies/modules.
!DumpAssembly <Assembly>
    -> Shows assembly info: name, modules...
!DumpModule -mt <Module>
    -> Shows Method Tables (types) defined and referenced by a module.
!DumpMT -md <Method Table>
    -> Shows Method Descriptors of a Method Table.
!DumpMD <Method Descriptor>
    -> Shows Method Descriptor info. We can see Code Address if method
       is jitted.
!Name2EE <Module> <NameSpace.Class.Method>
!Name2EE <Module>!<NameSpace.Class.Method>
    -> Shows Method Descriptor and jitted Code Address of a method.
!Name2EE * <NameSpace.Class.Method>
!Name2EE *!<NameSpace.Class.Method>
    -> Shows Module, Method Descriptor and jitted Code Address of a
       method.

--------------
SET BREAKPOINT
--------------

!BPMD -md <Method Descriptor>
    -> Sets breakpoint on method by Method Descriptor.
bp <Code Address>
    -> Sets breakpoint on method by jitted Code Address.
!BPMD <Module> <NameSpace.Class.Method>
    -> Sets breakpoint on method by module and name.
bl
    -> Lists breakpoints.
bd 0
bd *
    -> Disables breakpoints.
be 1
    -> Enables breakpoint.
bc 0
    -> Removes breakpoints.

-----------------
STEP THROUGH CODE
-----------------

l+t
    -> Enables source code mode. With private symbols and source code,
       Windbg will open source code files automatically.
l-t
    -> Enables assembly mode.
p
    -> Steps over (F10).
t
    -> Steps into (F11 or F8).

========================================================================
CALL STACKS
========================================================================

--------------------------
INSPECT CURRENT CALL STACK
--------------------------

k
    -> Shows unmanaged + managed call stack.
kp
    -> Shows unmanaged + managed call stack with unmanaged parameters.
!DumpStack
    -> Shows raw call stack with unmanaged + managed calls and managed
       Method Descriptors.
!CLRStack
    -> Shows managed call stack.
!DumpStack -EE
    -> Shows managed call stack with Method Descriptors.
!CLRStack -p
    -> Shows managed call stack with parameters.
!CLRStack -l
    -> Shows managed call stack with locals (we will only see memory
       addresses in the stack).
!CLRStack -a
    -> Shows managed call stack with parameters and locals.
   
---------------
INSPECT OBJECTS
---------------

!DumpObj <Object>
!do <Object>
    -> Shows object info: Method Table, EEClass, size, fields...
!DumpArray <Array>
!da <Array>
    -> Shows array info: # of elements, elements, their type... 

-------------------
INSPECT SOURCE CODE
-------------------

kn
    -> Shows unmanaged + managed call stack with frame numbers.
.frame <Frame Number>
    -> Changes the local context to a specific method frame. With Source
       Code Mode enabled, private symbols and source code, Windbg will
       open the source code file automatically.

------------
INSPECT MSIL
------------

!IP2MD <Instruction Pointer>
!CLRStack; !IP2MD <Instruction Pointer>
!DumpStack -EE
!IP2MD @eip
    -> Gets a Method Descriptor that we can use with !DumpIL.
!DumpIL <Method Descriptor>
    -> Shows IL of a method. ILDASM.exe and Reflector.exe show the same
       IL, but also locals.

-------------------
INSPECT SOURCE CODE
-------------------
lm; !SaveModule <Dll start> c:\sample.dll
    -> Writes a loaded dll to disk.
   
----------------
INSPECT ASSEMBLY
----------------

k
!DumpMD <Method Descriptor>
!DumpStack -EE; !DumpMD <Method Descriptor>
    -> Gets Code Address of an unmanaged or managed jitted method.
u <Code Address>
    -> Shows several lines of assembly code at a given Code Address, and
       source code lines if we have private symbols.
uf <Code Address>
    -> Shows all the assembly code of the managed or unmanaged function
       containing the Code Address, and source code lines if we have
       private symbols.
!u <Code Address>
    -> Shows all the assembly code of the managed method containing the
       Code Address, and marks that address with ">>>".
       If address is in unmanaged method and we have private symbols and
       source code, it shows all the assembly in that method along with
       the source code itself!
      
-----------------
INSPECT REGISTERS
-----------------

r ecx   
    -> When hitting a breakpoint on a managed function, it shows its
       first parameter (_fastcall calling convention). First parameter
       is usually the 'this' pointer.
r edx
    -> When hitting a breakpoint on a managed function, it shows its
       second parameter (_fastcall calling convention).
r esi
    -> Typically used to hold the 'this' pointer as copied from ecx.

========================================================================
THREADS
========================================================================

-------------------
INSPECT ALL THREADS
-------------------

~
    -> Shows all threads (managed and unmanaged).
!runaway
    -> Shows time consumed by each thread.
~0s
    -> Switches to thread 0.
~#s
    -> Switches to the thread where the debugger broke.
~*k100
    -> Shows all unmanaged + managed call stacks in all threads.
!Threads
    -> Shows all managed threads.
~*e !CLRStack
    -> Shows managed calls in all threads.
!Threads -special
    -> Shows all .NET related threads (managed and unmanaged).
!ThreadPool
    -> Shows ThreadPool info: number of work requests in the queue,
       timers and completion port threads.
      
========================================================================
THREAD STACKS
========================================================================

----------------------------
INSPECT OBJECTS IN THE STACK
----------------------------

!DumpStackObjects
!dso
    -> Shows a list of references to objects that are still on the
       thread’s stack.
      
---------------
INSPECT OBJECTS
---------------

!do <Object>
    -> Shows object info: Method Table, EEClass, size, fields...
!do -nofields <Object>
    -> Shows object info but not fields. Good to see i.e. Strings.
!da <Array>
    -> Shows array info: # of elements, elements, their type... 
!DumpVC <Method Table> <Value Type Address>
    -> Shows value type structs ('VT = 1' in '!do').
!DumpClass <EEClass>
    -> Shows the static fields of an object/class ('Attr = static' in
       '!do'). These fields are part of the EEClass, a representation of
       a class created before any method invocations are made on it.
!DumpClass <EEClass>      
!Name2EE <Module> <NameSpace.Class>; !DumpClass <EEClass>
    -> Shows the static fields of a class.
   
========================================================================
MANAGED HEAP
========================================================================

------------
INSPECT HEAP
------------

!EEVersion
    -> Shows version of GC heap (server/workstation) and how many GC
       heaps we have in server mode.
!EEHeap -gc
    -> Shows how many GC heaps there are and how much memory is taken by
       them.
!Threads
    -> Shows if Preemptive GC is enabled on a thread.
   
---------------------------
INSPECT OBJECTS IN THE HEAP
---------------------------

!DumpHeap
    -> Shows all objects in the heap.
!DumpHeap -stat
    -> Shows statistics of all objects in the heap: # of objects of
       a given type/Method Table, etc.
!DumpHeap -mt <Method Table>      
!Name2EE * <NameSpace.Class.Method>; !DumpHeap -mt <Method Table>
    -> Shows all objects in the heap of a given type/Method Table.
!DumpHeap -type <Partial Class Name>
    -> Shows all objects in the heap which class name contains a text.
!DumpHeap -min 85000
!EEHeap -GC; !DumpHeap <LOH begin> <LOH allocated>
    -> Shows all objects in Large Object Heap (LOH/Gen 3).
!FinalizeQueue
    -> Shows which objects are ready for finalization and in general
       which objects in the heap have a Finalize method.
!FinalizeQueue; dd <generation 0 begin> <generation 0 end>-4
    -> Shows all finalizable objects in Gen 0.
!FinalizeQueue; !DumpHeap -mt <Method Table>
    -> Shows all finalizable objects of a given Method Table/type.
!DumpMT -md <Method Table>
    -> Useful to check if an object/class has Finalize and Dispose
       methods.
!FinalizeQueue -detail
    -> Shows SyncBlocks and RuntimeCallableWrappers (RCW) registered
       for finalization.
!GCRoot <Object>
    -> Shows references to an object.
!ObjSize <Object>
    -> Shows the size of an object including its child objects.

------------------------
TROUBLESHOOT HEAP ISSUES
------------------------

!TraverseHeap c:\memory.log
    -> Generates a log file which can be analyzed with CLR Profiler.
!VerifyHeap
    -> Checks the heap for signs of corruption.

---------------------------
TROUBLESHOOT GCHANDLE LEAKS
---------------------------

!GCHandles
    -> Shows statistics of GCHandles.
!GCHandleLeaks
    -> Tracks down GCHandle leaks.
!GCHandleLeaks; !DumpObj poi(<GCHandle>)
    -> Shows the object a GCHandle references.
   
-------------------------------
TROUBLESHOOT LOADER HEAP ISSUES
-------------------------------

!DumpHeap -stat -type Assembly
    -> Shows the number of assemblies in the heap.
!DumpDomain
    -> Shows all assemblies.   
!DumpDomain; !DumpModule <Module>; dc <MetaData start> <MetaData start>+<Metadata size>
    -> Shows metadata of a module in an assembly.   
!EEHeap -loader
    -> Shows Loader Heap size and modules.

========================================================================   
BREAK ON AN EXCEPTION
========================================================================   

-----------------------
BREAK ON CLR EXCEPTIONS
-----------------------

sxe clr
sxe 0xe0434f4d
    -> Break on all CLR exceptions.
!StopOnException -create <Exception Type> 1
!soe -create <Exception Type> 1
    -> Break on a specific CLR exception type.
!soe -derived -create <Base Exception Type> 1
    -> Break on all exceptions which derive from a certain type.
sxn clr
    -> Stops breaking on CLR exceptions. If we used '!soe' before, we
       can still see the exception types of the CLR exceptions that we
       hit, but the debugger won't break on them.
sxr
    -> Resets to defaults.
   
----------------------
INSPECT CLR EXCEPTIONS
----------------------

kp; !do <Object from mscorwks!RaiseTheExceptionInternalOnly>
    -> Shows exception object info.
!PrintException <Object>
!pe <Object>
    -> Shows exception info.
!pe
    -> Shows exception info of last exception thrown in current thread.
!dso; !pe <Object>
    -> Shows exception info of an exception in the stack of current
       thread.
!DumpHeap -type Exception; !DumpHeap -mt <Method Table>; !pe <Object>
    -> Shows exception info of an exception in the heap.
.foreach(ex {!DumpHeap -type <Partial Class Name> -short}){!pe ex;.echo}
    -> Shows exception info of all exceptions of a given type in the
       heap.

-----------------------------------------
INSPECT METHOD WHERE WE GOT THE EXCEPTION
-----------------------------------------

!pe <Object>; !u <Instruction Pointer>; u <Memory Address>
    -> Shows the line of code where the exception happened.
   
========================================================================   
LOCKS
======================================================================== 

---------------------
INSPECT MANAGED LOCKS
---------------------

!SyncBlk
    -> Shows the Index of the syncblock in the syncblock table, the
       address of the syncblock, the thread holding it & the object
       which syncblock we are waiting for. MonitorHeld = 1 for each
       owner and 2 for each waiter. Used with i.e.
       System.Threading.Monitor.
~*kp; ~*e !CLRStack -p; ~*e !dso; !SyncBlk
    -> Helps to find out which threads are waiting on the syncblock of
       which object.

-----------------------
INSPECT UNMANAGED LOCKS
-----------------------

!locks
!critsec
!SIEExt.critlist
    -> Shows info of a critical sections (unmanaged). Use with i.e.      
       System.Threading.Mutex (not based on syncblocks).

SPSolutionExport Exception SecurityTokenService.Issue()

In trying to save a site using the Site Settings -> Save as Template, I received the following error:

11/15/2012 15:57:26.84  w3wp.exe (0x1A64)                        0x1944 SharePoint Foundation          General                        c42u Monitorable SPSolutionExporter: System.InvalidOperationException: The Writer is closed or in error state.     at System.Xml.XmlWellFormedWriter.AdvanceState(Token token)     at System.Xml.XmlWellFormedWriter.WriteEndElement()     at Microsoft.SharePoint.ScopedXmlWriterElement.Closer(XmlWriter writer, ScopedObjectUsage`1 wrapper)     at Microsoft.SharePoint.ScopedObjectUsage`1.Dispose(Boolean isDisposing)     at Microsoft.SharePoint.ScopedObjectUsage`1.Dispose()     at Microsoft.SharePoint.SPSolutionExporter.ExportContentTypes(SPContentTypeCollection contentTypes, String partitionName)     at Microsoft.SharePoint.SPSolutionExporter.ExportLists()     at Microsoft.SharePoint.SPSolutionExporter.GenerateSolutionFiles()     at Microsoft.SharePoint.SPSolutionExporter.ExportWebAsSolution() 2cf55a43-6bc9-47cb-82a2-27fbd38d452b
11/15/2012 15:57:26.86  w3wp.exe (0x1A64)                        0x1944 SharePoint Foundation          Runtime                        tkau Unexpected System.InvalidOperationException: Error generating solution files in temporary directory.    at Microsoft.SharePoint.SPSolutionExporter.ExportWebAsSolution()     at Microsoft.SharePoint.SPSolutionExporter.ExportWebToGallery(SPWeb web, String solutionFileName, String title, String description, ExportMode exportMode, Boolean includeContent, String workflowTemplateName, String destinationListUrl)     at Microsoft.SharePoint.SPSolutionExporter.ExportWebToGallery(SPWeb web, String solutionFileName, String title, String description, ExportMode exportMode, Boolean includeContent)     at Microsoft.SharePoint.ApplicationPages.SaveAsTemplatePage.BtnSaveAsTemplate_Click(Object sender, EventArgs e)     at System.Web.UI.WebControls.Button.OnClick(EventArgs e)     at System.Web.UI.WebControls.Button.Rai... 2cf55a43-6bc9-47cb-82a2-27fbd38d452b
11/15/2012 15:57:26.86* w3wp.exe (0x1A64)                        0x1944 SharePoint Foundation          Runtime                        tkau Unexpected ...sePostBackEvent(String eventArgument)     at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 2cf55a43-6bc9-47cb-82a2-27fbd38d452b
11/15/2012 15:57:26.87  w3wp.exe (0x1A64)                        0x1944 SharePoint Foundation          Monitoring                     b4ly High     Leaving Monitored Scope (Request (POST:https://workflow-int.curtin.edu.au:443/sites/test/_layouts/savetmpl.aspx)). Execution Time=5500.39376512937 2cf55a43-6bc9-47cb-82a2-27fbd38d452b
In addition it appeared that the SecurityTokenService was also throwing exceptions issueing tokens.

When visiting the service directly I recieved the following message:
The service encountered an error.
An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a policy export extension.
Extension: System.ServiceModel.Channels.TransportSecurityBindingElement
Error: Security policy export failed. The binding contains a TransportSecurityBindingElement but no transport binding element that implements ITransportTokenAssertionProvider. Policy export for such a binding is not supported. Make sure the transport binding element in the binding implements the ITransportTokenAssertionProvider interface. ----> System.InvalidOperationException: Security policy export failed. The binding contains a TransportSecurityBindingElement but no transport binding element that implements ITransportTokenAssertionProvider. Policy export for such a binding is not supported. Make sure the transport binding element in the binding implements the ITransportTokenAssertionProvider interface.
   at System.ServiceModel.Channels.TransportSecurityBindingElement.System.ServiceModel.Description.IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext policyContext)
   at System.ServiceModel.Description.MetadataExporter.ExportPolicy(ServiceEndpoint endpoint)
   --- End of inner ExceptionDetail stack trace ---

3 Steps were needed to resolve the issue:

Step 1. Ensure that SecurityTokenService is responding to requests on all SharePoint farm servers, then go to IIS manager and edit the SecurityTokenService web.config by replacing it with the content below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <!-- Behavior List: -->
    <behaviors>
      <serviceBehaviors>
        <behavior name="SecurityTokenServiceBehavior">
          <!-- The serviceMetadata behavior allows one to enable metadata (endpoints, bindings, services) publishing.
               This configuration enables publishing of such data over HTTP GET.
               This does not include metadata about the STS itself such as Claim Types, Keys and other elements to establish a trust.
          -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- Default WCF throttling limits are too low -->
          <serviceThrottling maxConcurrentCalls="65536" maxConcurrentSessions="65536" maxConcurrentInstances="65536" />
  <serviceDebug includeExceptionDetailInFaults="True" httpHelpPageEnabled="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- Service List: -->
    <services>
      <service name="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract" behaviorConfiguration="SecurityTokenServiceBehavior">
        <!-- This is the HTTP endpoint that supports clients requesing tokens. This endpoint uses the default
             standard ws2007HttpBinding which requires that clients authenticate using their Windows credentials. -->
        <endpoint address="" binding="customBinding" bindingConfiguration="spStsBinding" contract="Microsoft.IdentityModel.Protocols.WSTrust.IWSTrust13SyncContract" />
        <!-- This is the HTTP endpoint that supports clients requesting service tokens. -->
        <endpoint name="ActAs" address="actas" binding="customBinding" bindingConfiguration="spStsActAsBinding" contract="Microsoft.IdentityModel.Protocols.WSTrust.IWSTrust13SyncContract" />
        <!-- This is the HTTP endpoint that supports IMetadataExchange. -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
      <service name="Microsoft.SharePoint.Administration.Claims.SPWindowsTokenCacheService">
        <endpoint address="" binding="customBinding" bindingConfiguration="SPWindowsTokenCacheServiceHttpsBinding" contract="Microsoft.SharePoint.Administration.Claims.ISPWindowsTokenCacheServiceContract" />
      </service>
    </services>
    <!-- Binding List: -->
    <bindings>
      <customBinding>
        <binding name="spStsBinding">
          <binaryMessageEncoding>
            <readerQuotas maxStringContentLength="1048576" maxArrayLength="2097152" />
          </binaryMessageEncoding>
          <httpTransport maxReceivedMessageSize="2162688" authenticationScheme="Negotiate" useDefaultWebProxy="false" />
        </binding>
        <binding name="spStsActAsBinding">
          <security authenticationMode="SspiNegotiatedOverTransport" allowInsecureTransport="true" defaultAlgorithmSuite="Basic256Sha256" messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12" />
          <binaryMessageEncoding>
            <readerQuotas maxStringContentLength="1048576" maxArrayLength="2097152" />
          </binaryMessageEncoding>
          <httpTransport maxReceivedMessageSize="2162688" authenticationScheme="Negotiate" useDefaultWebProxy="false" />
        </binding>
        <binding name="SPWindowsTokenCacheServiceHttpsBinding">
          <security authenticationMode="IssuedTokenOverTransport" />
          <textMessageEncoding>
            <readerQuotas maxStringContentLength="1048576" maxArrayLength="2097152" />
          </textMessageEncoding>
          <httpsTransport maxReceivedMessageSize="2162688" authenticationScheme="Anonymous" useDefaultWebProxy="false" />
        </binding>
      </customBinding>
    </bindings>
  </system.serviceModel>
  <system.webServer>
    <security>
      <authentication>
        <anonymousAuthentication enabled="true" />
        <windowsAuthentication enabled="true">
          <providers>
            <clear />
            <add value="Negotiate" />
            <add value="NTLM" />
          </providers>
        </windowsAuthentication>
      </authentication>
    </security>
    <modules>
      <add name="WindowsAuthenticationModule" />
    </modules>
  </system.webServer>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="10000" />
    </connectionManagement>
  </system.net>
    <system.web>
        <identity impersonate="false" />
    </system.web>
</configuration>

Once the changes are complete


Step 2:

On all IIS servers ensure that under Web Services root => IIS - Authentication => only Windows and Anonymous authentication are "Enabled". Then progress down to the SecureTokenService virtual directory and ensure the same. This had forms authentication enabled on only one of my farm servers.

Step 3:

Delete and reprovision the UserProfileService. You may notice when you delete it, you can already access the sites again. This is because the user profile service was failing to communicate with the SecureTokenService on the app server.

Step 4:

Test this by building a new web application and site collection. Ensuring that no existing content is responsible for the failure to save template.

Note: In my situation I found the content type hub was also responsible publishing broken content types for which the "Save as Template" command could not save.