locked
Random System.Xaml.XamlObjectWriterException: Failed to create a 'PointCollection' RRS feed

  • Question

  • I have a Windows Service running several WorkflowServiceHost instances as well as a System.Threading.Timer on a 30 second interval running a workflow using WorkflowApplication.  This morning we came in, and saw this exception every 30 seconds since last night in the event log: 

    System.Xaml.XamlObjectWriterException: Failed to create a 'PointCollection' from the text '300,77.5 300,107.5 300,129'. ---> System.ComponentModel.Win32Exception: The operation completed successfully
       at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
       at System.Windows.Threading.Dispatcher..ctor()
       at System.Windows.DependencyObject..ctor()
       at System.Windows.Media.PointCollection.Parse(String source)
       at System.Windows.Media.PointCollectionConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
       at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateObjectWithTypeConverter(ServiceProviderContext serviceContext, XamlValueConverter`1 ts, Object value)
       at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName, IAddLineInfo lineInfo)
       --- End of inner exception stack trace ---
       at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName, IAddLineInfo lineInfo)
       at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName)
       at System.Xaml.XamlObjectWriter.Logic_CreateFromInitializationValue(ObjectWriterContext ctx)
       at System.Xaml.XamlObjectWriter.WriteEndMember()
       at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter, Boolean closeWriter)
       at System.Activities.XamlIntegration.FuncDeferringLoader.FuncFactory`1.Evaluate()
       at System.Activities.Activity.OnInternalCacheMetadata(Boolean createEmptyBindings)
       at System.Activities.Activity.InternalCacheMetadata(Boolean createEmptyBindings, IList`1& validationErrors)
       at System.Activities.ActivityUtilities.ProcessActivity(ChildActivity childActivity, ChildActivity& nextActivity, Stack`1& activitiesRemaining, ActivityCallStack parentChain, IList`1& validationErrors, ProcessActivityTreeOptions options, ProcessActivityCallback callback)
       at System.Activities.ActivityUtilities.ProcessActivityTreeCore(ChildActivity currentActivity, ActivityCallStack parentChain, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors)
       at System.Activities.ActivityUtilities.CacheRootMetadata(Activity activity, LocationReferenceEnvironment hostEnvironment, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors)
       at System.Activities.Hosting.WorkflowInstance.ValidateWorkflow(WorkflowInstanceExtensionManager extensionsManager)
       at System.Activities.WorkflowApplication.EnsureInitialized()
       at System.Activities.WorkflowApplication.Enqueue(InstanceOperation operation, Boolean push)
       at System.Activities.WorkflowApplication.WaitForTurn(InstanceOperation operation, TimeSpan timeout)
       at System.Activities.WorkflowApplication.Run(TimeSpan timeout)


    I have bolded the line that bothers me the most.  We restarted the service, and now it is working with no problems.  We did not make any file changes.  Why would this happen?  What are some steps to avoid this?
    Wednesday, December 16, 2009 5:51 PM

All replies

  • Hi Ryan,

    Thanks for the bug report, this looks like the bolded line is probably due to an interop bug in HwndWrapper, if so we can file on the appropriate team.

    My best understanding however is that even if they fix that bug, they would still have been throwing an exception in your scenario, it would have just been one with a more error-sounding error message than 'The operation was successful'.

    I.e. there probably was an actual root cause for the exception, but I have no idea what - maybe an out of resources issue on the server machine, or other 'temporary' condition that would be fixed by restarting the service.

    Tim
    Wednesday, December 16, 2009 10:19 PM
  • Tim, 

    I doubt there is any temporary condition affecting this.  Especially because in my Windows Service, when a workflow service fails we automatically reload it, and I have 6 days of Event Log entries (over the holiday break) with this error for our workflow services.  If I restart the whole Windows Service, it all loads fine.  How do I prevent this from happening?

    -Ryan
    Monday, December 28, 2009 4:40 PM
  • Hi Ryan,

    I'm happy to investigate this further. Can I ask a couple backgrounders:

    - do you need PointCollection or some other types from PresentationCore assembly available to your service (probably the only reason they are getting loaded is because of workflow designer ViewState saved in the XAML, but I want to check)?
    - do you know roughly how long the service uptime was before the problem occurred?
    - are these WorkflowServices that you reload after failure still in the same process, or would a reloaded instance be in a new process?
    - what OS was the service running on when it failed?

    You can also email me at microsoft com.

    Tim (tilovell @ ...)
    Tuesday, December 29, 2009 12:40 AM
  • I have the same exception on a WCF service hosted in IIS that run a WF activity.

    It hapend only on server core 2008 r2 (sp1 and .net4.0 instaled), in other OS(windows7, windows server 2008) it work fine.

    It is a incompatibility beteween server core and WF 4.0?

    Wednesday, August 31, 2011 8:06 AM
  • @Mstanculescu

    Interesting, I wonder if it is the exact same issue.

    Does it also seem like a stress/reliability issue in your scenario, i.e. only after the service has been running for a long time period? Or does it happen instantly as soon as you call the service?

    I'm insta-researching this, but it appears that a Server Core installation would not contain WPF, which probably means System.Windows.Presentation, plus various of its dependencies, like Presentation.Core, Presentation.Framework

    Anyhow, a couple of other questions:

    -Do you have the mc:Ignorable directive in your XAML file? e.g. mc:Ignorable="sap"
    -Is it actually a .xamlx file, with <Service> as root?

    -How did you generate the Workflow XAML, was it using the designer? Did you do any processing on it afterwards?

    Tim


    Thursday, September 1, 2011 4:32 AM
  • Hi,

    We're currently investigating a similar issue. I'm pasting the description sent to MS support:

     

    Issue Definition: The issue is with a Windows Service which hosts WCF and runs Windows Workflow Foundation.

    The service runs without any issues for some weeks but will over time end up in a state fault state where it is not possible to de-serialize any workflow instances at all and sometimes it is not even possible to create a new work workflow instance.

    Error message: Exception message: It was not possible to create a PointCollection from the text 390, 157.5 390, 179.

    The methods sofar seen to have given the error is WorkflowApplication.Load and WorkflowApplication.Run. The errors occurs when the server is in the fault state.

    The error occurs on all environments we have run the service on so far: Windows 2008 R2 and Windows 2003 R2.
    We use .Net Framework 4.0

    We read the theory that this is caused by a shortage-of-resource-condition but when investigating we have not found any major leaks in threads, memory or anything that we have been able to find. However, when the issue occurs the service starts to leak memory until it eventually stops to answer any calls.


    A restart of the service temporarily resolves the issue.

     

    Exception stack trace:

    Exception message: Failed to create a 'PointCollection' from the text '390,157.5 390,179'.
    Stack trace: at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName, IAddLineInfo lineInfo)
    at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName)
    at System.Xaml.XamlObjectWriter.Logic_CreateFromInitializationValue(ObjectWriterContext ctx)
    at System.Xaml.XamlObjectWriter.WriteEndMember()
    at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter, Boolean closeWriter)
    at System.Activities.XamlIntegration.FuncDeferringLoader.FuncFactory`1.Evaluate()
    at System.Activities.Activity.OnInternalCacheMetadata(Boolean createEmptyBindings)
    at System.Activities.Activity.InternalCacheMetadata(Boolean createEmptyBindings, IList`1& validationErrors)
    at System.Activities.ActivityUtilities.ProcessActivity(ChildActivity childActivity, ChildActivity& nextActivity, Stack`1& activitiesRemaining, ActivityCallStack parentChain, IList`1& validationErrors, ProcessActivityTreeOptions options, ProcessActivityCallback callback)
    at System.Activities.ActivityUtilities.ProcessActivityTreeCore(ChildActivity currentActivity, ActivityCallStack parentChain, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors)
    at System.Activities.ActivityUtilities.CacheRootMetadata(Activity activity, LocationReferenceEnvironment hostEnvironment, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors)
    at System.Activities.WorkflowInspectionServices.<GetActivities>d__0.MoveNext()

    ...

    Friday, September 2, 2011 8:03 AM
  • @Mstanculescu

    Interesting, I wonder if it is the exact same issue.

    Does it also seem like a stress/reliability issue in your scenario, i.e. only after the service has been running for a long time period? Or does it happen instantly as soon as you call the service?

    I'm insta-researching this, but it appears that a Server Core installation would not contain WPF, which probably means System.Windows.Presentation, plus various of its dependencies, like Presentation.Core, Presentation.Framework

    Anyhow, a couple of other questions:

    -Do you have the mc:Ignorable directive in your XAML file? e.g. mc:Ignorable="sap"
    -Is it actually a .xamlx file, with <Service> as root?

    -How did you generate the Workflow XAML, was it using the designer? Did you do any processing on it afterwards?

    Tim


    Not directed at me, but I'll answer these as well:

    >>Does it also seem like a stress/reliability issue in your scenario, i.e. only after the service has been running for a long time period? Or does it happen instantly as soon as you call the service?

    We've seen there go weeks between issues, but also as short as 2 days. There is not a lot of stress on the systems. We've been running automated testing for a few days with a much larger load than the production environments, but have not been able to reproduce the it in the test environment. I'd say there's no conclusive evidence that it's stress related. 

    -Do you have the mc:Ignorable directive in your XAML file? e.g. mc:Ignorable="sap"

    Yes.

    -Is it actually a .xamlx file, with <Service> as root?

    No, the document starts with: <Activity mc:Ignorable="sap" x:Class= ...

    -How did you generate the Workflow XAML, was it using the designer? Did you do any processing on it afterwards?

    Yes, with the designer. No, no processing afterwards.

    BR

    Mikael

     

    Friday, September 2, 2011 11:14 AM
  • Hi Mikael,
    The information you've added to this thread is great!

    Thoughts so far
    - It seems like it may not matter much about OS version, although I do notice so far only Server SKUs are coming up in examples.
    - It seems like it might be important that you are running as a Windows Service.

    More questions related to this thought:
    Q* Through services.msc, which account does the Service run as?
    Q* Is the service allowed to interact with the desktop? Does enabling it to interact with the desktop make a difference?
    Q* When you notice the issue starts occuring, and the service is still running, run "tasklist /svc". Can you see that the service is co-hosted with other services in a single process, or does it have its own process?

    -The call stack + error message itself is pretty interesting, there should be some underlying reason a HWndWrapper can't be created.

    More questions related to this thought:
    Q* We have ruled out some sorts of resource leaks, one resource we should probably be extra interested in related to the call stack though is Window Handles - do you have data on Handle counts?
    Q* If you just try do to new Threading.Dispatcher() from a VB expression in a custom Workflow which you run under the exact same conditions (Windows Service) do you hit the same error?

    -Also the fact it only happens after a period of time is still interesting to me. I wonder what can account for this if not a stress issue. The mc:ignorable tag is interesting because it should allow sap: attribute to be ignored under some situations, whereas normally it will invoke creating an object. Does the PointCollection object creation itself only happen later for some reason? What could be a possible reason?

    More questions related to this thought:
    Q* Are you able to attach a debugger to the process while it is in the good state (but having run some workflows), and then also later, while it is in the bad state? (Will probably need to 'show processes from all users/all sessions)
    Q* Is System.Activities.Presentation loaded at each point in time? (If no difference, any difference in PresentationFramework, PresentationCore, or WindowsBase?)
    Q* Does your service have any UI? 

    Thanks in advance to whoever can provide more data!
    Tim

     


    Sunday, September 4, 2011 3:26 AM
  • Hi,

     

    - It seems like it may not matter much about OS version, although I do notice so far only Server SKUs are coming up in examples.
    - It seems like it might be important that you are running as a Windows Service.

    Possibly. We have not tested on other platforms or installation forms.

     

    Q* Through services.msc, which account does the Service run as?

    As NT AUTHORITY\NetworkService


    Q* Is the service allowed to interact with the desktop? Does enabling it to interact with the desktop make a difference?

    Not available for the NetworkService user. Do you feel that would be a worthwhile test? It'd take quite a while before we can say with any certainty that the issue is not happening (weeks) but it's doable.


    Q* When you notice the issue starts occuring, and the service is still running, run "tasklist /svc". Can you see that the service is co-hosted with other services in a single process, or does it have its own process?

    That command gives me "ERROR: Server execution failed" on the test server where the faulty service now is running. No idea if it's related, but I can run the command on other servers fine (and the service is hosted in a single process there, so I suppose it'd be odd if it weren't in the faulty system too). I don't want to restart the faulty service to see if that changes anything since we can't reliably reproduce it.

    Q* We have ruled out some sorts of resource leaks, one resource we should probably be extra interested in related to the call stack though is Window Handles - do you have data on Handle counts?

    No, we'll investigate that asap. The behavior does seem consistent with running out of some semi-invisible resource.


    Q* If you just try do to new Threading.Dispatcher() from a VB expression in a custom Workflow which you run under the exact same conditions (Windows Service) do you hit the same error?

    Will need some more info here. Do you mean we should reproduce the error and then try the Dispatch(), or attempt to reproduce it by repeatedly doing Dispatch() in the service?

    - Does the PointCollection object creation itself only happen later for some reason? What could be a possible reason?

    We have not been able to link the first occurence of the fault to any special activity or state in our service, i.e. I don't think we do anything earlier or later in our handling of the workflow that triggers the fault, compared to the hundred ones before it. If that's not what you're asking for I'll need some more details.

    Q* Are you able to attach a debugger to the process while it is in the good state (but having run some workflows), and then also later, while it is in the bad state? (Will probably need to 'show processes from all users/all sessions)

    That should be possible. Anything in particular we should look for that we don't already know from the stack trace?

    Q* Is System.Activities.Presentation loaded at each point in time? (If no difference, any difference in PresentationFramework, PresentationCore, or WindowsBase?)

    I'll have to get back to you on this. I'm not entirely clear on what would cause loads/unloads of the above. I'm pretty sure we don't have any explicit logic for it, unless fairly straight-forward processing of workflows count, but I'll double-check.

    Q* Does your service have any UI?

    No.

     

    BR Mikael


    • Edited by Mikael I Sunday, September 4, 2011 9:55 AM typo
    Sunday, September 4, 2011 9:52 AM
  • This is not a solution to the issue at question, but I do think it is an effective "side step".  The underlying issue seems to be that mc:Ignorable is not being ignored and over time a memory/resource leak related to that is causing runtime exceptions in long running services.   Also it appears, based on the fact that the sap namespace is included, that these resource leaks are related to running loose xaml rather than compiled xaml.

    The proposed side step is to..compile the xaml into a dll and then run the workflows from that dll.  This would require an extra step either in the deployment phase or in the service to compile the xaml before use (perhaps use a file watcher/WMI to monitor source files for changes, and you would have to host your runtime engine in a separate AppDomain to allow for updating of the dlls,  In my case I allow both versions to run side by side I simply disable event generation in the old version once it's running instance table is empty it can be unloaded). 

    This sounds complicated, but the actual compiling of the xmal is actually quite easy if you use msbuild which has been included in every version of .net since 2.0.  As an example here is the complete code for my main builder class. I have another class BuildManager that uses this, but it would be meaningless to show since it is tied to this applications architecture.

    First the completely uninteresting BuildItem Class

     

     public class BuildItem
        {
            public string FileName { get; set; }
            public Stream Content { get; set; }
        }
    

     

    and now the more interesting BuilderClass

     

        /// <summary>
        /// Creates a build file for a single dll target
        /// </summary>
        public class Builder
        {
            /// <summary>
            /// Creates a dll from source streams
            /// </summary>
            /// <param name="targetname">The name of the target dll</param>
            /// <param name="items">A list of BuildItems to include</param>
            /// <param name="references">A list of references (ie: "System.dll","System.Xaml.dll")  if you include
            /// your own dll's they will either have to be GAC'd or the full path ("C:\mypath\....\my.dll") specified</param>
            /// <param name="buildlocation">The location to put the build files</param>
            /// <returns></returns>
            public List<string> Build(string targetname,List<BuildItem> items,List<string> references,string buildlocation=null)
            {
                #region get build location
                var path = buildlocation;
                //Get a temp directory to act as build location(if none specified)
                if(string.IsNullOrEmpty(path))
                    path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                if(!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                #endregion
    
                var olddir = Directory.GetCurrentDirectory();
                Directory.SetCurrentDirectory(path);
                var logger = new ErrorLogger();
                try
                {
                    #region Deserialziation
                    //Deserialize our build sources
                    foreach (var item in items)
                    {
                        var fullpath = Path.Combine(path, item.FileName);
                        var fs = new FileStream(fullpath, FileMode.Create, FileAccess.Write);
                        CopyStream(item.Content, fs);
                        fs.Close();
                    }
                    #endregion
    
                    var pcoll = new ProjectCollection {DefaultToolsVersion = "4.0"};
                    var project = new Project(pcoll);
                    #region Add default properties
                    var pgroup = project.Xml.CreatePropertyGroupElement();
                    project.Xml.InsertAfterChild(pgroup, project.Xml.LastChild);
                    pgroup.AddProperty("DefaultTarget", "Build");
                    pgroup.AddProperty("SchemaVersion", "2.0");
                    pgroup.AddProperty("AssemblyName", targetname);
                    pgroup.AddProperty("TargetFrameworkVersion", "4.0.1");
                    pgroup.AddProperty("OutputType", "Library");
                    pgroup.AddProperty("IntermediateOutputPath", "obj");
                    pgroup.AddProperty("DebugType", "none");
                    pgroup.AddProperty("Optimize", "true");
                    pgroup.AddProperty("OutputPath", "bin");
                    pgroup.AddProperty("WarningLevel", "4");
                    #endregion
    
                    #region Add Imports
                    var refgroup = project.Xml.CreateItemGroupElement();
                    project.Xml.InsertAfterChild(refgroup, project.Xml.LastChild);
                    foreach (var reference in references)
                        refgroup.AddItem("Reference", reference);
                    #endregion
    
                    #region Add Build Items
                    var buildgroup = project.Xml.CreateItemGroupElement();
                    project.Xml.InsertAfterChild(buildgroup, project.Xml.LastChild);
                    var properties = new Dictionary<string, string>();
                    foreach (var item in items)
                    {
                        properties.Clear();
                        var noext = Path.GetFileNameWithoutExtension(item.FileName);
                        var parent = (from p in items where p.FileName == noext select p.FileName).FirstOrDefault();
                        if (parent != null)
                            properties.Add("DependentUpon", parent);
    
                        var ext = Path.GetExtension(item.FileName);
                        switch (ext)
                        {
                            case ".xamlapp":
                                properties.Add("Generator", "MSBuild:Compile");
                                properties.Add("SubType", "Designer");
                                buildgroup.AddItem("XamlAppDef", item.FileName, properties);
                                break;
                            case ".cs":
                                properties.Add("SubType", "Code");
                                buildgroup.AddItem("Compile", item.FileName, properties);
                                break;
                            case ".xaml":
                                properties.Add("Generator", "MSBuild:Compile");
                                properties.Add("SubType", "Designer");
                                buildgroup.AddItem("Page", item.FileName, properties);
                                break;
                            case ".bmp":
                            case ".jpg":
                            case ".png":
                                buildgroup.AddItem("EmbeddedResource", item.FileName, properties);
                                break;
                            default:
                                throw new ArgumentException("BuildItems contains invalid filetype, currently only (*.cs,*.xaml,*.bmp,*.jpg,*.png,*.xamlapp) are supported");
                        }
                    }
                    #endregion
    
                    project.Xml.AddImport(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");
                    project.Save(Path.Combine(path,"BuildIt.prj"));
                    project.Build(logger);
    
                }
                catch (Exception)
                {
    
                    return logger.Errors;
                }
                finally
                {
                    Directory.SetCurrentDirectory(olddir);
                }
                return logger.Errors;
            }
            private static void CopyStream(Stream source, Stream target)
            {
                var buffer = new byte[1024];
                const int size = 1024;
                var count = source.Read(buffer, 0, size);
                while (count > 0)
                {
                    target.Write(buffer, 0, count);
                    count = source.Read(buffer, 0, size);
                }
                target.Flush();
            }
    
        }
    
    

     


    If you have waded through this post this far the question is what does this buy you.  Well it buys you a dll with an embedded xaml  that has no sap namespace:

     

    <local:DownloadRequests mva1:VisualBasic.Settings="Assembly references and imported namespaces serialized as XML namespaces"xmlns ="http://schemas.microsoft.com/netfx/2009/xaml/activities"xmlns:local ="clr-namespace:;assembly=Resources"xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:mv ="clr-namespace:Microsoft.VisualBasic;assembly=System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:mv1 ="clr-namespace:Microsoft.VisualBasic;assembly=System"xmlns:mva ="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"xmlns:mva1 ="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities"xmlns:nc ="clr-namespace:Nexus.Centrics;assembly=Resources, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"xmlns:nc1 ="clr-namespace:Nexus.Centrics;assembly=Resources"xmlns:nca ="clr-namespace:Nexus.Centrics.Activities;assembly=Resources, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"xmlns:nca1 ="clr-namespace:Nexus.Centrics.Activities;assembly=Resources"xmlns:ng ="clr-namespace:Nexus.GMEE;assembly=Resources, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"xmlns:ng1 ="clr-namespace:Nexus.GMEE;assembly=Resources"xmlns:p ="clr-namespace:XamlStaticHelperNamespace;assembly=Resources"xmlns:s ="clr-namespace:System;assembly=System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:s1 ="clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:s10 ="clr-namespace:System;assembly=System.Numerics"xmlns:s11 ="clr-namespace:System;assembly=System.DirectoryServices.Protocols"xmlns:s12 ="clr-namespace:System;assembly=System.DirectoryServices"xmlns:s13 ="clr-namespace:System;assembly=System.Drawing"xmlns:s14 ="clr-namespace:System;assembly=System.Web"xmlns:s2 ="clr-namespace:System;assembly=System.Web.Services"xmlns:s3 ="clr-namespace:System;assembly=System.Xml"xmlns:s4 ="clr-namespace:System;assembly=System.Configuration"xmlns:s5 ="clr-namespace:System;assembly=System.DirectoryServices.AccountManagement"xmlns:s6 ="clr-namespace:System;assembly=System.Windows.Forms"xmlns:s7 ="clr-namespace:System;assembly=System"xmlns:s8 ="clr-namespace:System;assembly=System.Core"xmlns:s9 ="clr-namespace:System;assembly=mscorlib"xmlns:sa ="clr-namespace:System.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"xmlns:sa1 ="clr-namespace:System.Activities;assembly=System.Activities"xmlns:sae ="clr-namespace:System.Activities.Expressions;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"xmlns:sae1 ="clr-namespace:System.Activities.Expressions;assembly=System.Activities"xmlns:sap ="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation"xmlns:sas ="clr-namespace:System.Activities.Statements;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"xmlns:sas1 ="clr-namespace:System.Activities.Statements;assembly=System.Activities"xmlns:sav ="clr-namespace:System.Activities.Validation;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"xmlns:sav1 ="clr-namespace:System.Activities.Validation;assembly=System.Activities"xmlns:sax ="clr-namespace:System.Activities.XamlIntegration;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"xmlns:sax1 ="clr-namespace:System.Activities.XamlIntegration;assembly=System.Activities"xmlns:scg ="clr-namespace:System.Collections.Generic;assembly=System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:scg1 ="clr-namespace:System.Collections.Generic;assembly=mscorlib"xmlns:scg2 ="clr-namespace:System.Collections.Generic;assembly=System"xmlns:sd ="clr-namespace:System.Data;assembly=System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:sd1 ="clr-namespace:System.Data;assembly=System.Data"xmlns:si ="clr-namespace:System.IO;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:si1 ="clr-namespace:System.IO;assembly=mscorlib"xmlns:sl ="clr-namespace:System.Linq;assembly=System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"xmlns:sl1 ="clr-namespace:System.Linq;assembly=System.Core"xmlns:td ="clr-namespace:TSDynamicResource.Data;assembly=TSDynamicResource, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"xmlns:td1 ="clr-namespace:TSDynamicResource.Data;assembly=TSDynamicResource"xmlns:tm ="clr-namespace:TSDynamicResource.MSSQL;assembly=TSDynamicResource, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"xmlns:tm1 ="clr-namespace:TSDynamicResource.MSSQL;assembly=TSDynamicResource"xmlns:tp ="clr-namespace:TSActivities.Primitives;assembly=TSActivities"xmlns:tws ="clr-namespace:TSDynamicResource.Web.SOAP;assembly=TSDynamicResource, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"xmlns:tws1 ="clr-namespace:TSDynamicResource.Web.SOAP;assembly=TSDynamicResource"xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml">
      <local:DownloadRequests.Implementation >
        <Sequence mva1:VisualBasic.Settings="Assembly references and imported namespaces serialized as XML namespaces">
          <Sequence.Variables >
            <Variable x:TypeArguments="nc1:Credentials"Default ="[new credentials()]"Name ="cred" />
            <Variable x:TypeArguments="nc1:ProductionRequestType[]"Name ="requests" />
          </Sequence.Variables>
          <tp:Map >
            <tp:Map.Setters >
              <tp:SetField Condition="{x:Null}">
                <tp:SetField.To >
                  <OutArgument x:TypeArguments="x:Object">
                    [cred.]</OutArgument>
                </tp:SetField.To>
                <tp:SetField.Value >
                  <InArgument x:TypeArguments="x:String">
                    Horizon</InArgument>
                </tp:SetField.Value>
              </tp:SetField>
              <tp:SetField Condition="{x:Null}">
                <tp:SetField.To >
                  <OutArgument x:TypeArguments="x:String">
                    [cred.password]</OutArgument>
                </tp:SetField.To>
                <tp:SetField.Value >
                  <InArgument x:TypeArguments="x:String">
                    H0r1z0n!</InArgument>
                </tp:SetField.Value>
              </tp:SetField>
            </tp:Map.Setters>
          </tp:Map>
          <TryCatch >
            <TryCatch.Try >
              <nca1:GetNewProductionRequests Result="[requests]"WebServiceCredentials ="[cred]" />
            </TryCatch.Try>
            <TryCatch.Catches >
              <Catch x:TypeArguments="s9:Exception">
                <ActivityAction x:TypeArguments="s9:Exception">
                  <ActivityAction.Argument >
                    <DelegateInArgument x:TypeArguments="s9:Exception"Name ="exception" />
                  </ActivityAction.Argument>
                  <Sequence >
                    <WriteLine Text="["Could not download new requests, reason: " & exception.Message]" />
                    <TerminateWorkflow Reason="Failed to download new requests" />
                  </Sequence>
                </ActivityAction>
              </Catch>
            </TryCatch.Catches>
          </TryCatch>
        </Sequence>
      </local:DownloadRequests.Implementation>
    </local:DownloadRequests>
    
     
    
    

     


    And an activity dervied class to use it:

     

    [ComVisible(false)]
    public class DownloadRequests : Activity, ISupportInitialize
    {
        // Fields
        private bool _contentLoaded;
    
        // Methods
        public DownloadRequests()
        {
            this.InitializeComponent();
        }
    
        private string FindResource()
        {
            foreach (string str in typeof(DownloadRequests).Assembly.GetManifestResourceNames())
            {
                if (str.Contains(".DownloadRequests.g.xaml") || str.Equals("DownloadRequests.g.xaml"))
                {
                    return str;
                }
            }
            throw new InvalidOperationException("Resource not found.");
        }
    
        [DebuggerNonUserCode]
        public void InitializeComponent()
        {
            if (!this._contentLoaded)
            {
                this._contentLoaded = true;
                string name = this.FindResource();
                Stream manifestResourceStream = typeof(DownloadRequests).Assembly.GetManifestResourceStream(name);
                XmlReader xmlReader = null;
                XamlReader xamlReader = null;
                XamlObjectWriter xamlWriter = null;
                try
                {
                    XamlSchemaContext schemaContext = _XamlStaticHelper.SchemaContext;
                    xmlReader = XmlReader.Create(manifestResourceStream);
                    XamlXmlReaderSettings settings = new XamlXmlReaderSettings {
                        LocalAssembly = Assembly.GetExecutingAssembly(),
                        AllowProtectedMembersOnRoot = true
                    };
                    xamlReader = new XamlXmlReader(xmlReader, schemaContext, settings);
                    XamlObjectWriterSettings settings2 = new XamlObjectWriterSettings {
                        RootObjectInstance = this,
                        AccessLevel = XamlAccessLevel.PrivateAccessTo(typeof(DownloadRequests))
                    };
                    xamlWriter = new XamlObjectWriter(schemaContext, settings2);
                    XamlServices.Transform(xamlReader, xamlWriter);
                }
                finally
                {
                    if (xmlReader != null)
                    {
                        xmlReader.Dispose();
                    }
                    if (xamlReader != null)
                    {
                        ((IDisposable) xamlReader).Dispose();
                    }
                    if (xamlWriter != null)
                    {
                        ((IDisposable) xamlWriter).Dispose();
                    }
                }
            }
        }
    
        void ISupportInitialize.BeginInit()
        {
        }
    
        void ISupportInitialize.EndInit()
        {
            this.InitializeComponent();
        }
    }
    
     
    Collapse Methods
     
    
    

     


    As if that isn't enough you get for free one more little tidbit:  A static class autogenerated for you that will verify the runtime enivornment (all required dll's are present).  Admittedly you will have to generate code to call it, but that's not hard to do.

    internal class _XamlStaticHelper
    {
        // Fields
        private static IList<Assembly> assemblyListField;
        private static WeakReference schemaContextField;

        // Methods
        private static Assembly Load(string assemblyNameVal)
        {
            AssemblyName name = new AssemblyName(assemblyNameVal);
            byte[] publicKeyToken = name.GetPublicKeyToken();
            try
            {
                return Assembly.Load(name.FullName);
            }
            catch (Exception)
            {
                AssemblyName assemblyRef = new AssemblyName(name.Name);
                if (publicKeyToken != null)
                {
                    assemblyRef.SetPublicKeyToken(publicKeyToken);
                }
                return Assembly.Load(assemblyRef);
            }
        }

        private static IList<Assembly> LoadAssemblies()
        {
            return new List<Assembly> { Load("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), Load("System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"), Load("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), Load("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), Load("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), Load("System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), Load("System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), Load("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), Load("TSActivities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"), Load("TSDynamicResource, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"), Load("TSExtras, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"), Assembly.GetExecutingAssembly() };
        }

        // Properties
        internal static IList<Assembly> AssemblyList
        {
            get
            {
                if (assemblyListField == null)
                {
                    assemblyListField = LoadAssemblies();
                }
                return assemblyListField;
            }
        }

        internal static XamlSchemaContext SchemaContext
        {
            get
            {
                XamlSchemaContext target = null;
                if (schemaContextField != null)
                {
                    target = (XamlSchemaContext) schemaContextField.Target;
                    if (target != null)
                    {
                        return target;
                    }
                }
                if (AssemblyList.Count > 0)
                {
                    target = new XamlSchemaContext(AssemblyList);
                }
                else
                {
                    target = new XamlSchemaContext();
                }
                schemaContextField = new WeakReference(target);
                return target;
            }
        }
    }

     
    Collapse Methods
     

    In summary, while it will take effort to switch from loose Xaml to demand compiled Xaml the resulting stability (assuming I am correct and the issue revolves around resource leakage from mc:Ignorable not being fully respected) would be worth the time investment.

     

     


    Sunday, September 4, 2011 12:40 PM
  • Thanks Frank, that might prove to be useful down the line.

     

    Tim, about handles:

    Faulty service has in 9 hours increased its handle count from ~16200 to ~20000. It has also increased RAM usage from 558MB to 755 MB. Both figures are from Task Manager.

    However, if there is an increase in handle count on the non-faulty service it is too small to be seen in the same 9 hours. At both times the handle count was fluctuating between 400-500. The load is much smaller on that system so it's possible that there is an increase, but it's not noticeable. I'd wager a guess though that there actually is no leakage on either memory or handles until the fault is triggered.

    Either way, if I understand correctly, the amount of handles available to the system are several million so it seems unlikelt that that is a resource limit that is relevant.

    BR
    Mikael

    Sunday, September 4, 2011 8:03 PM
  • Hi Mikael,
    The amount of handles overall available to the system may be several million (I don't know anything to the contrary), but the amount of handles of specific types, such as window handles, or e.g. gdi objects, may be less than that - e.g. 65,536 - which is still higher than the number you are seeing, I know.

    The VB Expression creating a new Dispatcher one is a very interesting thing to try because it may be that creating a new Dispatcher (which is something on the call stack) will fail the very first time that you try it - due to e.g. insufficient permissions to interact with the desktop when running as a service.

    If you just evaluate 'new Threading.Dispatcher()' in a VB expression in the workflow, that's ultimately the same as what's happened at the top of the call stack, just triggered in a more deterministic way, so easier to investigate, and it failing the first time suggests that it's not the out of resources issue.

    Running the process with a debugger attached would let you
    -view the set of loaded modules 
    -using public symbols, set breakpoints on the functions in the stack you posted to see e.g. whether they are failing the first time you hit them or instead the many'th time

    If it looks like it is failing with a permissions issue, try running the service with UI permission (as a different user than NetworkService if necessary), to see if that makes a difference.
    Tim


    P.S. - update. Found this article "Pushing the Limits of Windows - User and GDI objects

    http://blogs.technet.com/b/markrussinovich/archive/2010/02/24/3315174.aspx

    I think it might imply the max handle limit is much lower, e.g. 10,000 or 20,000 (depending on types of handles involved). Which (unfortunately?) gives some more legs to the out-of-resources theory... am still keen to hear from customers in the field on the above suggestions of course.
    Tim

    Tuesday, September 6, 2011 4:22 AM
  • Hi all,

    I experience the same error. I have a windows service that leaves errors after some time (serveral weeks), resources dont seem to be the problem. 'Any updates?

    This is my stack trace

    Does anyone have any ideas on how to trouble shoot this? Debugging is a bit tricky since it happens only now and then.

    Regards

    Florian

    - <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    - <SOAP-ENV:Body>
    - <a1:XamlObjectWriterException id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/System.Xaml/System.Xaml%2C%20Version%3D4.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Db77a5c561934e089">
     <Line>0</Line>
     <Offset>0</Offset>
     <ClassName id="ref-4">System.Xaml.XamlObjectWriterException</ClassName>
     <Message id="ref-5">Failed to create a 'PointCollection' from the text '310,77.5 310,107.5 310,109'.</Message>
     <Data xsi:null="1" />
     <InnerException href="#ref-6" />
     <HelpURL xsi:null="1" />
     <StackTraceString id="ref-7">at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName, IAddLineInfo lineInfo) at System.Xaml.XamlObjectWriter.Logic_CreateFromInitializationValue(ObjectWriterContext ctx) at System.Xaml.XamlObjectWriter.WriteEndMember() at System.Xaml.XamlWriter.WriteNode(XamlReader reader) at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter, Boolean closeWriter) at System.Activities.XamlIntegration.FuncDeferringLoader.FuncFactory`1.Evaluate() at System.Activities.Activity.OnInternalCacheMetadata(Boolean createEmptyBindings) at System.Activities.Activity.InternalCacheMetadata(Boolean createEmptyBindings, IList`1& validationErrors) at System.Activities.ActivityUtilities.ProcessActivity(ChildActivity childActivity, ChildActivity& nextActivity, Stack`1& activitiesRemaining, ActivityCallStack parentChain, IList`1& validationErrors, ProcessActivityTreeOptions options, ProcessActivityCallback callback) at System.Activities.ActivityUtilities.ProcessActivityTreeCore(ChildActivity currentActivity, ActivityCallStack parentChain, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors) at System.Activities.ActivityUtilities.CacheRootMetadata(Activity activity, LocationReferenceEnvironment hostEnvironment, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors) at System.Activities.Hosting.WorkflowInstance.ValidateWorkflow(WorkflowInstanceExtensionManager extensionManager) at System.Activities.Hosting.WorkflowInstance.RegisterExtensionManager(WorkflowInstanceExtensionManager extensionManager) at System.Activities.WorkflowApplication.EnsureInitialized() at System.Activities.WorkflowApplication.RunInstance(WorkflowApplication instance) at System.Activities.WorkflowApplication.Invoke(Activity activity, IDictionary`2 inputs, WorkflowInstanceExtensionManager extensions, TimeSpan timeout) at System.Activities.WorkflowInvoker.Invoke(Activity workflow, IDictionary`2 inputs, TimeSpan timeout, WorkflowInstanceExtensionManager extensions) at System.Activities.WorkflowInvoker.Invoke(IDictionary`2 inputs) at Loodswezen.Accorderen.BackgroundService.AccorderenController.Run(Boolean alleLoodsen) in C:\Projects\heusfl\Loodswezen.Accorderen\Loodswezen.Accorderen\Loodswezen.Accorderen.BackgroundService\AccorderenController.cs:line 123</StackTraceString>
     <RemoteStackTraceString xsi:null="1" />
     <RemoteStackIndex>0</RemoteStackIndex>
     <ExceptionMethod id="ref-8">8 Logic_CreateFromValue System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Xaml.XamlObjectWriter System.Object Logic_CreateFromValue(MS.Internal.Xaml.Context.ObjectWriterContext, System.Xaml.Schema.XamlValueConverter`1[System.ComponentModel.TypeConverter], System.Object, System.Xaml.XamlMember, System.String, MS.Internal.Xaml.Runtime.IAddLineInfo)</ExceptionMethod>
     <HResult>-2146233088</HResult>
     <Source id="ref-9">System.Xaml</Source>
     <WatsonBuckets xsi:null="1" />
     </a1:XamlObjectWriterException>
    - <a3:Win32Exception id="ref-6" xmlns:a3="http://schemas.microsoft.com/clr/nsassem/System.ComponentModel/System%2C%20Version%3D4.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Db77a5c561934e089">
     <NativeErrorCode>2</NativeErrorCode>
     <ClassName id="ref-10">System.ComponentModel.Win32Exception</ClassName>
     <Message id="ref-11">The system cannot find the file specified</Message>
     <Data xsi:null="1" />
     <InnerException xsi:null="1" />
     <HelpURL xsi:null="1" />
     <StackTraceString id="ref-12">at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D wc_d) at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks) at System.Windows.Threading.Dispatcher..ctor() at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at System.Windows.DependencyObject..ctor() at System.Windows.Media.PointCollection.Parse(String source) at System.Windows.Media.PointCollectionConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateObjectWithTypeConverter(ServiceProviderContext serviceContext, XamlValueConverter`1 ts, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateFromValue(ServiceProviderContext serviceContext, XamlValueConverter`1 ts, Object value, XamlMember property) at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(ObjectWriterContext ctx, XamlValueConverter`1 typeConverter, Object value, XamlMember property, String targetName, IAddLineInfo lineInfo)</StackTraceString>
     <RemoteStackTraceString xsi:null="1" />
     <RemoteStackIndex>0</RemoteStackIndex>
     <ExceptionMethod id="ref-13">8 RegisterClassEx WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 MS.Win32.UnsafeNativeMethods UInt16 RegisterClassEx(WNDCLASSEX_D)</ExceptionMethod>
     <HResult>-2147467259</HResult>
     <Source id="ref-14">WindowsBase</Source>
     <WatsonBuckets xsi:null="1" />
     </a3:Win32Exception>
     </SOAP-ENV:Body>
     </SOAP-ENV:Envelope>

    
    
    
    
    
    
    
    
    
    Wednesday, April 18, 2012 2:10 PM
  • I assume that most people are hitting this issue by hosting their service as a declarative service Xamlx, in IIS or WorkflowServiceHost. I have a non-fully tested workaround here based on shutting down the dispatcher to release resources after each call to the service. Please give this a try.

    1) web.config needs to have the withDispatcherShutdownBehavior added.

      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
              <serviceMetadata httpGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
              <withDispatcherShutdownBehavior />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <extensions>
          <behaviorExtensions>
            <add
              name="withDispatcherShutdownBehavior"
              type="DeclarativeServiceLibrary1.WithDispatcherShutdownBehavior, DeclarativeServiceLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
            />
          </behaviorExtensions>
        </extensions>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      </system.serviceModel>

    2) the behavior definition

    using System;
    using System.Linq;
    using System.ServiceModel.Configuration;
    using System.ServiceModel.Description;
    
    namespace DeclarativeServiceLibrary1
    {
        public class WithDispatcherShutdownBehavior : BehaviorExtensionElement, IServiceBehavior, IOperationBehavior
        {
            public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {
                return;
            }
    
            public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
            {
                var operationDescriptions =
                    serviceDescription.Endpoints
                        .Select((endpoint) => endpoint.Contract)
                        .SelectMany((contract) => contract.Operations);
    
                foreach (OperationDescription od in operationDescriptions)
                {
                    od.Behaviors.Add(this);
                }
            }
    
            public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
            {
                return;
            }
    
            public override Type BehaviorType
            {
                get { return typeof(WithDispatcherShutdownBehavior); }
            }
    
            protected override object CreateBehavior()
            {
                return new WithDispatcherShutdownBehavior();
            }
    
            public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {
                return;
            }
    
            public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
            {
                return;
            }
    
            public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
            {
                dispatchOperation.Invoker = new WithDispatcherShutdownInvoker(dispatchOperation.Invoker);
            }
    
            public void Validate(OperationDescription operationDescription)
            {
                return;
            }
        }
    }

    3) the invoker extension code

    using System;
    using System.ServiceModel.Dispatcher;
    
    namespace DeclarativeServiceLibrary1
    {
        public class WithDispatcherShutdownInvoker : IOperationInvoker
        {
            private IOperationInvoker innerInvoker;
    
            public WithDispatcherShutdownInvoker(IOperationInvoker innerInvoker)
            {
                this.innerInvoker = innerInvoker;
            }
    
            public object[] AllocateInputs()
            {
                return innerInvoker.AllocateInputs();
            }
    
            public object Invoke(object instance, object[] inputs, out object[] outputs)
            {
                var ret = innerInvoker.Invoke(instance, inputs, out outputs);
                System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
                return ret;
            }
    
            public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
            {
                return innerInvoker.InvokeBegin(instance, inputs, callback, state);
            }
    
            public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
            {
                var ret = innerInvoker.InvokeEnd(instance, out outputs, result);
                System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
                return ret;
            }
    
            public bool IsSynchronous
            {
                get { return innerInvoker.IsSynchronous; }
            }
        }
    }
    

    Tuesday, May 1, 2012 9:33 PM
  • Hi Tim, 
    I found the Dispatcher.CurrentDispatcher.InvokeShutdown(); works fine, but I was interested to apply your fix, can you please advice me how to wire it in WPF desktop application, I've tried to use it but I couldn't wire it up with my reshosted workflow in WPF desktop applicaiton. 

    Friday, February 24, 2017 11:24 AM
  • The problem can be avoided by removing the view state information from the Workflow Xaml Definition and by excluding the SAP / SAP2010 libraries from the AppDomain when instancing the Workflow, since they are not needed at runtime for the execution: https://andreioros.com/blog/failed-to-create-pointcollection-exception-windows-workflow-foundation/
    Tuesday, March 6, 2018 4:47 PM