"An unexpected error ocurred" CRM2015 OnPremise Plugins - plugins

For 2 weeks we have been experiencing a small totally random issue with plugins in CRM 2015 OnPremise. When we make an upload, randomly and without much sense (at least according to analyze all code does not) plugins are throwing us the following exception:
The Web Service plug-in failed in OrganizationId:
fb2630bc-8dc1-e411-80be-bae05bad392c; SdkMessageProcessingStepId:
d2713f4e-51b7-e411-80b8-527d00dcf108; EntityName: new_serviciobase;
Stage: 30; MessageName: Create; AssemblyName:
Microsoft.Crm.Extensibility.InternalOperationPlugin,
Microsoft.Crm.ObjectModel, Version=7.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35; ClassName:
Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception:
Unhandled Exception: System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object
obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object
target, Object[] values)
at
Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider
serviceProvider)
at
Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext
context)
at
Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext
context)
Inner Exception: System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
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.Activator.CreateInstance(Type type)
at
Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.InitializePlugin[T](IOrganizationContext
context, StepDescription stepDescription, SecureConfigurationCache
stepSecureConfigurationCache, Type type)
at Microsoft.Crm.Extensibility.V5PluginProxyStep..ctor(Guid stepId,
SecureConfigurationCache stepSecureConfigurationCache, CrmEventLog
eventLog, IOrganizationContext context)
at Microsoft.Crm.Extensibility.PluginStep..ctor(Guid stepId,
SecureConfigurationCache stepSecureConfigurationCache, CrmEventLog
eventLog, IOrganizationContext context)
at
Microsoft.Crm.Extensibility.PipelineStepFactory.CreateInstance(Guid
stepId, IOrganizationContext context)
at Microsoft.Crm.Caching.PipelineStepCacheLoader.LoadCacheData(Guid
key, ExecutionContext context)
at
Microsoft.Crm.Caching.ObjectModelCacheLoader`2.LoadCacheData(TKey key,
IOrganizationContext context)
at
Microsoft.Crm.Caching.CrmMultiOrgCacheBase`2.CreateEntry(TKey key,
IOrganizationContext context)
at Microsoft.Crm.Caching.CrmSharedMultiOrgCache`2.LookupEntry(TKey
key, IOrganizationContext context)
at
Microsoft.Crm.Caching.MessageProcessorCacheLoader.GetCustomizationLevel(MessageProcessor
mp, ExecutionContext context)
at
Microsoft.Crm.Caching.MessageProcessorCacheLoader.LoadCacheData(MessageProcessorKey
key, ExecutionContext context) at
Microsoft.Crm.Caching.ObjectModelCacheLoader`2.LoadCacheData(TKey key,
IOrganizationContext context)
at Microsoft.Crm.Caching.CrmSharedMultiOrgCache`2.LookupEntry(TKey
key, IOrganizationContext context)
at
Microsoft.Crm.Extensibility.InternalMessageDispatcher.TryGetMessageProcessor(MessageProcessorKey
key, ExecutionContext context)
at
Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.IsPipelineDefined(MessageProcessorKey
key, ExecutionContext context)
at
Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.CreateWithInvocationSource(BusinessEntity
entity, Int32 invocationSource, ExecutionContext context)
at
Microsoft.Crm.BusinessEntities.BusinessProcessObject.Create(IBusinessEntity
entity, ExecutionContext context)
Inner Exception: System.IO.FileLoadException: Could not load file or
assembly ‘SCM.CRM.Core, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=369abd01f82b8d9d’ or one of its dependencies. Access is
denied.
at SCM.CRM.Plugins.Plugin..ctor(Type childClassName)
at SCM.CRM.Plugins.PLGServicioBase..ctor()
It brings a little headache because we don't understand what happened, just that sometimes fails and sometimes not ... we have a custom library registered plugins (disk) "SCM.Core.dll" to which says itself unable to access ... Any ideas?

As #Sxntk said, you need to make sure you merge any plugins with ilmerge if you are using Sandbox mode isolation mode when registering the plugin assembly.
If you have an isolation mode of 'none', make sure the assembly is in the GAC or placed in the bin\assembly folder in the CRM installation directory on the server.
Hopefully this helps.

I'm a coleague of Alexis, and now we have more details thanks to crmdiagtool:
System.IO.FileLoadException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #ED0C936C: System.IO.FileLoadException: Could not load file or assembly 'SCM.CRM.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=369abd01f82b8d9d' or one of its dependencies. Access is denied.
File name: 'SCM.CRM.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=369abd01f82b8d9d'

You can do the following thing:
make sure all your referenced assemblies have "Copy Local" set to "True"
unload the project from visual studio
right click on the unloaded project and edit the csproj file
add the following lines in the csproj file right before the "Project" end tag (before last line in the document):
<Target Name="AfterResolveReferences">
<ItemGroup>
<EmbeddedResource Include="#(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
<LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
</Target>
add this method to the plugin class:
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(args.Name);
string path = assemblyName.Name + ".dll";
if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false)
{
path = String.Format(#"{0}\{1}", assemblyName.CultureInfo, path);
}
using (Stream stream = executingAssembly.GetManifestResourceStream(path))
{
if (stream == null)
return null;
byte[] assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
add the following constructor to the plugin class:
static [Constructor name]()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
}
rebuild and register your plugin
Doing this, all the referenced assemblies that are copied locally to your bin folder are packed into the main dll. The drawback is that you could end up having such a huge dll that you can not register it as a plugin.
Hope this helps,
Cheers

Related

After update to .NET 7, I get an error : System.ArgumentException: An item with the same key has already been added

I created a project with ASP.NET Core 6 and developed it over time.
Now I updated this project to .NET 7.
So far there have been no problems. I had no errors at runtime. The program works correctly.
After the update, when I run the add--migration command, I encounter an error whose origin is unknown.
I updated all nuget packages of the program.
Add-Migration -name test2 Build started... Build succeeded.
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.AddSeedData(IEntityType entityType, Dictionary`2 identityMaps, EntityState initialState)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.TrackData(IRelationalModel source, IRelationalModel target, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDataOperations(IRelationalModel source, IRelationalModel target, DiffContext diffContext)+MoveNext()
at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IRelationalModel source, IRelationalModel target)
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An item with the same key has already been added. Key: Description
I used nlog to debug and I got this error.
Microsoft.Extensions.Hosting.HostAbortedException: The host was aborted. at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.ThrowHostAborted() at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value) at System.Diagnostics.DiagnosticListener.Write(String name, Object value) at Microsoft.Extensions.Hosting.HostBuilder.ResolveHost(IServiceProvider serviceProvider, DiagnosticListener diagnosticListener) at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build() at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build() at Program.<Main>$(String[] args) in H:\Project\Rafa\erp\WebUI\Program.cs:line 61
I changed nullable values with ?
And I also put nullables context in the disable mode in the build propetries
I also used Debugger.Launch, but i got an error on
var app = builder.Build();
I encountered an exception
Microsoft.Extensions.Hosting.HostAbortedException
HResult=0x80131500
Message=The host was aborted.
Source=Microsoft.EntityFrameworkCore.Design
StackTrace:
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.ThrowHostAborted()
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
at Microsoft.Extensions.Hosting.HostBuilder.ResolveHost(IServiceProvider serviceProvider, DiagnosticListener diagnosticListener)
at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
at Program.<Main>$(String[] args) in H:\Project\Rafa\erp\WebUI\Program.cs:line 61
This exception was originally thrown at this call stack:
[External Code]
Program.<Main>$(string[]) in Program.cs

SqlPackage Object reference not set to an instance of an object

When I attempt to deploy DACPACs via SqlPackage.exe,
I encounter the error below :
An unexpected failure occurred: Object reference not set to an instance of an object..
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.Sql90TableBaseColumnPopulator`1.InsertElementIntoParent(SqlColumn element, TElement parent, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.CreateChildElement(TParent parent, EventArgs e, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.PopulateAllChildrenFromCache(IDictionary`2 cache, SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.TopLevelElementPopulator`1.Populate(SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulators(ReliableSqlConnection conn, IList`1 populators, Int32 totalPopulatorsCount, Int32 startIndex, Boolean progressAlreadyUpdated, ReverseEngineerOption option, SqlReverseEngineerRequest request)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulatorsInPass(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, SqlReverseEngineerRequest request, Int32 totalCount, Tuple`2[] populatorsArray)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.PopulateBatch(SqlReverseEngineerConnectionContext context, SqlSchemaModel model, ReverseEngineerOption option, ErrorManager errorManager, SqlReverseEngineerRequest request, SqlImportScope importScope)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineer.PopulateAll(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, ErrorManager errorManager, Boolean filterManagementScopedElements, SqlImportScope importScope, Boolean optimizeForQuery, ModelStorageType modelType)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.ImportDatabase(SqlReverseEngineerConstructor constructor, DeploymentEngineContext context, ErrorManager errorManager)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.OnLoad(ErrorManager errors, DeploymentEngineContext context)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.PrepareModels()
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.InitializePlanGeneratator()
at Microsoft.SqlServer.Dac.DacServices.<>c__DisplayClass21.<CreateDeploymentArtifactGenerationOperation>b__1f(Object operation, CancellationToken token)
at Microsoft.SqlServer.Dac.Operation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.ReportMessageOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.Execute(IOperation operation, DacLoggingContext loggingContext, CancellationToken cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(DacPackage package, String targetDatabaseName, DacDeployOptions options, Nullable`1 cancellationToken)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.<>c__DisplayClasse.<DoDeployAction>b__4(DacServices service)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.ExecuteDeployOperation(String connectionString, String filePath, MessageWrapper messageWrapper, Boolean sourceIsPackage, Boolean targetIsPackage, Func`1 generateScriptFromPackage, Func`2 generateScriptFromDatabase)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.DoDeployAction(DeployArguments parsedArgs, Action`1 writeError, Action`2 writeMessage, Action`1 writeWarning)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.DoDeployActions(CommandLineArguments parsedArgs)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Run(String[] args)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Main(String[] args)
Below is the command I run:
SET vardeploy2=/Action:Script
set varBlockOnDriftParameter=/p:BlockWhenDriftDetected=False
"SSDTBinaries\SqlPackage.exe" %vardeploy2% %varBlockOnDriftParameter% /SourceFile:"dacpacs\DBName.dacpac" /Profile:"Profiles\%1.DBName.Publish.xml" >> Log.txt 2>>&1
I deploy to a SQL Server 2008 R2. The SqlPackage.exe version is 11.0.2820.0.
The issue is intermittent, which suggests it's not related to the DACPAC being deployed or the destination database's schema. My best guess is that something about the state of the database is causing the problem.
Still, I haven't been able to identify anything unusual at the time of the failures.
When recreating the issue locally, using schema locks results in a different error message.
Has anyone know of a solution?
Upgrade to a more resent SQL Server Data Tools.

Inserting Spatial\Geometry in EF5 with dotConnect 6.7 for PostgreSQL

I installed the latest dotConnect for PostgreSQL. Im trying to insert a record in the Postgres DB. I have a geometry column what gives me errors. Here is the code:
using (var context = new WKP_DBEntities())
{
var Location = DbGeometry.PointFromText(string.Format("POINT({0} {1})", 157873, 364282), 28992);
var record = new monitoring_object()
{
geometry = Location,
last_changed_by = "ssg",
};
context.monitoring_object.Add(record);
context.SaveChanges();
}
Here is the error message:
System.Data.Entity.Infrastructure.DbUpdateException was unhandled
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at ConsoleApplicationGEOdata.Program.Main(String[] args) in c:\Users\Stefan\Documents\Visual Studio 2012\Projects\ConsoleApplicationGEOdata\ConsoleApplicationGEOdata\Program.cs:line 38
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.ArgumentException
HResult=-2147024809
Message=Cannot convert value
Source=Devart.Data.PostgreSql
StackTrace:
at Devart.Data.PostgreSql.af.a(Object A_0, Type A_1, Encoding A_2)
at Devart.Data.PostgreSql.af.a(String A_0, Encoding A_1, PgSqlType A_2, Object A_3, Int32 A_4, Boolean A_5)
at Devart.Data.PostgreSql.PgSqlCommand.a(String A_0, Encoding A_1, ArrayList A_2, Boolean A_3)
at Devart.Data.PostgreSql.PgSqlCommand.InternalExecute(CommandBehavior behavior, IDisposable stmt, Int32 startRecord, Int32 maxRecords)
at Devart.Common.DbCommandBase.InternalExecute(CommandBehavior behavior, IDisposable stmt, Int32 startRecord, Int32 maxRecords, Boolean nonQuery)
at Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior behavior, Boolean nonQuery)
at Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at Devart.Data.PostgreSql.Entity.y.a(CommandBehavior A_0)
at Devart.Common.Entity.i.b(CommandBehavior A_0)
at Devart.Data.PostgreSql.Entity.y.b(CommandBehavior A_0)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException:
What am I doing wrong?
Your code works in our environment:
a) dotConnect for PostgreSQL v 6.7.287
b) SharpMap v1 RC3
c) Postgis 2.0
d) DDL:
CREATE TABLE monitoring_object
(
id serial NOT NULL,
geometry geometry,
last_changed_by character varying
);
Please give us the following information:
1) the version of your SharpMap. Be aware that current release of dotConnect for PostgreSQL supports SharpMap 1.0 RC3 ( http://sharpmap.codeplex.com/releases/view/106717 ). The 1.0 Final version will be supported soon
2) the version of your Postgis. It should be of the 2.0 (or higher) version. You can check it by executing "select postgis_version()" in the database
3) the DDL script of your monitoring_object table
4) if possible send us a small test project
The corresponding Devart documentation is available at http://blogs.devart.com/dotconnect/enhanced-entity-framework-spatials-support-for-oracle-mysql-and-postgresql.html .

Ef 4.x dbcontext generator fails when executed

I have vs2010, installed Entity framework 4.3.1 from nuget, installed the EF 4.x DbContext Generator from microsoft. I create a project then try to add a new EF 4.x DbContext Generator item but the following error. Does anyone know how to resolve this?
Error 1 Running transformation:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.IO.FileNotFoundException:
Unable to locate file at
Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.ResolvePath(String
path) at
Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.ResolvePath(String
path) --- End of inner exception stack trace --- at
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo
method, Object target, Object[] arguments, SignatureStruct& sig,
MethodAttributes methodAttributes, RuntimeType typeOwner) at
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method,
Object target, Object[] arguments, Signature sig, MethodAttributes
methodAttributes, RuntimeType typeOwner) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture,
Boolean skipVisibilityChecks) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.DynamicHost.ResolvePath(String
path) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.MetadataLoader.TryCreateEdmItemCollection(String
sourcePath, String[] referenceSchemas, EdmItemCollection&
edmItemCollection) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.MetadataLoader.CreateEdmItemCollection(String
sourcePath, String[] referenceSchemas) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.MetadataLoader.TryLoadAllMetadata(String
inputFile, MetadataWorkspace& metadataWorkspace) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.TransformText()
at
Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession
session, String source, ITextTemplatingEngineHost host, String&
result) 1 1
Clearly its a case of PEBKAC. I hadn't created my edmx file. Once I had done this all I needed to do was right click on the model. Select "Add Code Generation item".

Receiving a PersistenceException when persisting Workflow

Here is the stack trace of the exception I get when the workflow is persisted:
System.Workflow.Runtime.Hosting.PersistenceException: Type 'System.Xml.XmlElement' in Assembly 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable. ---> System.Runtime.Serialization.SerializationException: Type 'System.Xml.XmlElement' in Assembly 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)
at System.Workflow.ComponentModel.Activity.Save(Stream stream, IFormatter formatter)
at System.Workflow.ComponentModel.Activity.Save(Stream stream)
at System.Workflow.Runtime.Hosting.WorkflowPersistenceService.GetDefaultSerializedForm(Activity activity)
at System.Workflow.Runtime.Hosting.SqlWorkflowPersistenceService.SaveWorkflowInstanceState(Activity rootActivity, Boolean unlock)
at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation)
--- End of inner exception stack trace ---
at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation)
at System.Workflow.Runtime.WorkflowExecutor.ProtectedPersist(Boolean unlock)
How and where can I debug this exception?
The error message tells you right at the top:
'System.Xml.XmlElement' in Assembly
'System.Xml, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089' is
not marked as serializable.
When a workflow is persisted the WorkflowPersistenceService uses the binary serializer to dump all the data in the workflow. So everything in there must be either marked as non serializable or must be binary serializble. An XmlElement isn't so you must either store the data in some other way or not save it at all.