I'm working on a WP8 app that uses a ScheduledTaskAgent to update a Live Tile. It's a pretty simple app, really. Problem is that while I've directly copied the code from the WP7 project to the WP8 project, it won't launch the ScheduledTask. Not only that, but I get an error if I'm debugging and I try to launch the scheduled task for testing.
'System.InvalidOperationException' occurred in System.Windows.ni.dll
Not only that, but it doesn't give me any stack to look through, and says that the source is not available, that I can look at the disassembly in the disassembly window, which means nothing to me. So, not a very helpful error, IMO.
I tried putting a break point in the constructor of the scheduled task, and it never makes it there. If I comment out the launch for test, no error. But of course, putting the app in my phone, it never launched, leaving it overnight.
Here's my code:
var taskName = "TileUpdater";
var oldTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (oldTask != null)
{
ScheduledActionService.Remove(taskName);
}
if (useLiveTile)
{
//GenerateTileInfo();
PeriodicTask task = new PeriodicTask(taskName);
task.Description = AppResources.BackgroundTaskDescription;
oldTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (oldTask == null)
{
ScheduledActionService.Add(task);
}
#if DEBUG
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(10));
#endif
}
The code works fine in the WP7 version. :/
This is in my WMAppManifest.xml file:
<ExtendedTask Name="BackgroundTask">
<BackgroundServiceAgent Specifier="ScheduledTaskAgent"
Name="xxxScheduledTask"
Source="xxxScheduledTask"
Type="xxxScheduledTask.SecheduledAgent" />
</ExtendedTask>
In my scheduled task, the only thing I'm doing is calling a procedure that generates the tile info, updating the tile, and for the moment, I'm re-running the launch for test, so I can watch to see if it updates again, though I've had this commented out - I uncommented it to paste here, but that was commented out. Here is my OnInvoke method:
GenerateTileInfo();
#if DEBUG
ScheduledActionService.LaunchForTest(task.ToString(), TimeSpan.FromSeconds(60));
#endif
NotifyComplete();
The GenerateInfo method doesn't do anything that would cause a problem, but of course, it's never getting there anyway. I did test my generating of the tile info, and implementing it, by placing that code in the MainPage.xaml.cs and calling it for now, to see if it worked, and the code I'm calling works fine. So if I open the app, the tile gets updated. Now I need to get the Background Task to work.
Any help that anyone can offer is greatly appreciated. One other clue is that last night I was getting an error that involved not being able to locate a pdb file - I think it was Microsoft.Phone.pdb, but whatever it was, it also referred to the System.Windows.ni.dll file, but now I'm not getting that pdb issue, just this InvalidOperationException. Last night the Debugging Symbols (I don't know what that means) were not loading. Today they are. I don't know what I did to fix it. Could have been a restart, for all I know.
Also, I tried creating a new project and copying my code to a new project, thinking I may have a corrupted project file, but the error I'm getting now is the same as I was getting earlier today that prompted me to create the new project.
Again, any help is appreciated. Thanks.
(Edit - New comments added below this point 12/29 at 11:34 am EST)
=================================================================================
I tried another expriment. I created a new project, and copy/pasted code from http://www.jeffblankenburg.com/2011/11/25/31-days-of-mango-day-25-background-agents/ to see if I could debug the app. I did have to make a few minor changes to the code that Jeff Blankenburg wrote, because he states that when you add the scheduled task project, it will automatically add to the WMAppManifest.xml file the following code, which it didn't. I did that manually.
I also changed the StandardTileData type to FlipTileData (since that is what was default in the WP8 project) in the code that is pasted to the ScheduledAgent.cs.
Other than that, the only thing I did that Jeff doesn't mention in his article is to add the necessary using directives.
Given the results of this experiment, I think I might be looking at somehow my Visual Studio install being corrupted. Would you concur? I'm thinking that doing an uninstall/reinstall of VS2012 and the phone sdk are what's in order here, but since it takes so long, I wanted to get another opinion. Thanks.
Update (1/4/2012)
===============================================================
Uninstalled VS, went through the registry, then reinstalled VS2012, and phone SDK. Here's what I get now - at least now it will show me the stack trace:
[Native to Managed Transition]
System.Windows.ni.dll!MS.Internal.JoltHelper.OnUnhandledException(object sender, System.UnhandledExceptionEventArgs args)
[Managed to Native Transition]
mscorlib.ni.dll!System.Reflection.RuntimeAssembly.nLoad(System.Reflection.AssemblyName fileName, string codeBase, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly locationHint, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks)
mscorlib.ni.dll!System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly reqAssembly, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks)
mscorlib.ni.dll!System.Reflection.RuntimeAssembly.InternalLoad(string assemblyString, System.Security.Policy.Evidence assemblySecurity, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool forIntrospection)
mscorlib.ni.dll!System.Reflection.RuntimeAssembly.InternalLoad(string assemblyString, System.Security.Policy.Evidence assemblySecurity, ref System.Threading.StackCrawlMark stackMark, bool forIntrospection)
mscorlib.ni.dll!System.Reflection.Assembly.Load(string assemblyString)
Microsoft.Phone.ni.dll!Microsoft.Phone.BackgroundAgentActivator.LoadEntryPointAssembly(string assemblyName)
Microsoft.Phone.ni.dll!Microsoft.Phone.BackgroundAgentActivator.LoadAgent(string assemblyName, string typeName)
Microsoft.Phone.ni.dll!Microsoft.Phone.BackgroundAgentActivator.Microsoft.Phone.IBackgroundAgentActivator.CreateBackgroundAgent(string assembly, string typeinfo)
Microsoft.Phone.ni.dll!Microsoft.Phone.BackgroundAgentDispatcher.AgentRequest.Invoke()
Microsoft.Phone.ni.dll!Microsoft.Phone.BackgroundAgentDispatcher.InvocationThread()
mscorlib.ni.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)
mscorlib.ni.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.ni.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.ni.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state)
mscorlib.ni.dll!System.Threading.ThreadHelper.ThreadStart()
[Native to Managed Transition]
Also considered that I was using the low memory emulator and had forgotten that background agents are not allowed in low mem devices, but which emulator (or device) I use makes no difference.
After all this time of fighting with it, I've got the problem resolved. In copying the code from one project to another, I forgot to add a reference to the ScheduledTask project in the main project.
I also learned a couple other things in the process of working on sample code to try to get it to work outside my project. First, when you add a ScheduledTask project it doesn't seem to add the necessary metadata to the WMAppManifest.xml file, so you need to add that manually. The other thing is that when dealing with background agents, the error messages can be pretty cryptic, and may not say a thing about what the problem really is.
From now on, when I see an error like I've seen here (I've seen several pretty cryptic errors, all seeming the same, but not quite) when working on Scheduled Tasks, that will be a prompt to be sure I've got a reference to the second project, and be sure the necessary info is in WMAppManifext.xml (including spelling - if you misspell it, it won't be underlined).
Yeah, there's no way this code snippet runs on WP7.5 SDK. task.ToString() will be the type name ("Microsoft.Phone.Scheduler.PeriodicTask") and as such not the right value.
Change:
ScheduledActionService.LaunchForTest(task.ToString(), TimeSpan.FromSeconds(60));
To:
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
And it works fine.
To answer your question: *.ni.dlls are NGENed .net dlls. The framework gets NGENed and deployed to the phone so most exceptions you'll see will come from *.ni frameworks dlls. I'm guessing you just saw a generic exception.
How are you getting on with this? I have a very similar issue ('System.InvalidOperationException' occurred in System.Windows.ni.dll" when I go into the Background agent code... it was working fine in WP7... the app is still WP7 except that now I am running under VS2012 and have installed the WP8 SDK.
Funny thing is that I have another app that works just fine - exactly the same scenario and environment.
Have you got your issue sorted yet? It's been very frustrating.
The ".ni." stands for Native Images, surrounding .NET specifically.
I found this when a BackgroundDownload.exe started running and I started tracking. This came out of one of its logs.
1,"fusion","GAC",0
1,"WinRT","NotApp",1
3,"System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System\556b21e2d636701016ad76fe3776a505\System.ni.dll",0
3,"System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Core\f8a689485cf213780df744fde2c54190\System.Core.ni.dll",0
3,"System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Configuration\d577fd286e51f472414996f5144aaaa9\System.Configuration.ni.dll",0
3,"System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Xml\b7630f847e13fc7dd88ab8a8862c2b7a\System.Xml.ni.dll",0
3,"System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Security\68e68081542c0d5baa15a846cf2ca458\System.Security.ni.dll",0
3,"System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Drawing\74f4937603f11ad21e91b4aed570fd4f\System.Drawing.ni.dll",0
3,"System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Windows.Forms\56eb2160cb5e0e733dd0c2366d3de3d2\System.Windows.Forms.ni.dll",0
3,"System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Runtime\89b3e92a43e17d474b9cbc6747c76fa0\System.Runtime.ni.dll",0
3,"System.Reflection, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Reflection\aaf8c507950277bf496287476935feeb\System.Reflection.ni.dll",0
3,"System.Numerics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Numerics\efa65924471acfbcd2b23cceae87e730\System.Numerics.ni.dll",0
3,"System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Runteb92aa12#\ddf4d9ca9e105b351ad6a99442e5edd9\System.Runtime.Serialization.ni.dll",0
3,"System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Data\7331e242363acc7a26bec36a4a703e6c\System.Data.ni.dll",0
3,"System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Xml.Linq\2ca98da3b8de00d4eaf9599d6316c284\System.Xml.Linq.ni.dll",0
3,"SMDiagnostics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\SMDiagnostics\614b71bb8864202da9d3e6dcbc0be4a3\SMDiagnostics.ni.dll",0
3,"C:\WINDOWS\system32\WinMetadata\Windows.Networking.winmd","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\Windows.Networking\c98b01a13bd7a97270a1775b1cd0cf4f\Windows.Networking.ni.dll",1
3,"System.Runtime.InteropServices.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Runtbff93e24#\16fa2326f490f06c2d7a427861e635b6\System.Runtime.InteropServices.WindowsRuntime.ni.dll",0
Related
I have a Xamarin.iOS project and recently upgraded that plus my PCL project to have Windows Azure Mobile Services SDK 1.3.1.
However I now get an error when it tries to create a new MobileServiceClient.
{System.NullReferenceException: Object reference not set to an instance an object
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient.GetUserAgentHeader () [0x0002e] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\Http\MobileServiceHttpClient.cs:683
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient..ctor (IEnumerable`1 handlers, System.Uri applicationUri, System.String installationId, System.String applicationKey) [0x0004e] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\Http\MobileServiceHttpClient.cs:138
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor (System.Uri applicationUri, System.String applicationKey, System.Net.Http.HttpMessageHandler[] handlers) [0x00040] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\MobileServiceClient.cs:199
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor (System.Uri applicationUri, System.String applicationKey) [0x00000] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\MobileServiceClient.cs:150
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor (System.String applicationUrl, System.String applicationKey) [0x00000] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\MobileServiceClient.cs:135
at MyApp.App..ctor () [0x00009] in c:\Users\adam\Documents\Visual Studio 2013\Projects\MyApp\App.cs:30 }
Looking at the source code of the MobileServiceClient here is the function it is failing on
private string GetUserAgentHeader()
678 {
679 AssemblyFileVersionAttribute fileVersionAttribute = typeof(MobileServiceClient).GetTypeInfo().Assembly
680 .GetCustomAttributes(typeof(AssemblyFileVersionAttribute))
681 .Cast<AssemblyFileVersionAttribute>()
682 .FirstOrDefault();
683 string fileVersion = fileVersionAttribute.Version;
684 string sdkVersion = string.Join(".", fileVersion.Split('.').Take(2)); // Get just the major and minor versions
685
686 IPlatformInformation platformInformation = Platform.Instance.PlatformInformation;
687 return string.Format(
688 CultureInfo.InvariantCulture,
689 "ZUMO/{0} (lang={1}; os={2}; os_version={3}; arch={4}; version={5})",
690 sdkVersion,
691 "Managed",
692 platformInformation.OperatingSystemName,
693 platformInformation.OperatingSystemVersion,
694 platformInformation.OperatingSystemArchitecture,
695 fileVersion);
696 }
I have no idea on what is specifically causing the error. Any help appreciated.
Update
If I run the following code, just in my app before I try to initialize the MobileServiceClient
AssemblyFileVersionAttribute fileVersionAttribute = typeof(MobileServiceClient).GetTypeInfo().Assembly
.GetCustomAttributes(typeof(AssemblyFileVersionAttribute))
.Cast<AssemblyFileVersionAttribute>()
.FirstOrDefault();
string fileVersion = fileVersionAttribute.Version;
With Don't Link it works perfectly. If I run it with Link SDK or Link All then assembly is equal to null.
Where to go from here I am not sure yet.
The intent of linking is to reduce overall app size by excluding unused namespaces, classes, and members. Linking most apps will require a manual iterative process of:
Enable full linking for whatever build config you're concerned with.
Clean and build the app.
Run the app, and observe what runtime exceptions occur as a result of missing types and methods (including constructors).
Add rules either to your mtouch command arguments or the link description XML file in order to skip linking on the namespaces, types, and classes that you find are throwing exceptions.
In order to link an app that uses the Azure Mobile Services Client PCL, you follow the same iterative process I just stated.
I prefer the XML-based config file strategy of linking preservation:
https://developer.xamarin.com/guides/cross-platform/advanced/custom_linking/
The XML file is commonly known as a link definition file. It allows you to control the linker in a declarative fashion, without adding [Preserve] attributes everywhere in your code; and for third-party libraries, without muddying up the mtouch arguments of Xamarin.iOS projects or the csproj file of Xamarin.Android projects. It can be named whatever you want, as long as you properly tell your platform project about it.
An appropriate configuration could look like this:
<?xml version="1.0" encoding="UTF-8" ?>
<linker>
<assembly fullname="Microsoft.WindowsAzure.Mobile">
<type fullname="Microsoft*" />
</assembly>
<assembly fullname="Microsoft.WindowsAzure.Mobile.Ext">
<type fullname="Microsoft*" />
</assembly>
</linker>
In each assembly node, you describe the types or members you want to preserve. For the sake of simplicity here, I've used a wildcard to include all types that begin with "Microsoft". That's matched by fully qualified name, including namespace.
However, as stated, you will encounter a runtime problem with the GetUserAgentHeader() method in the MobileServiceHttpClient class:
Fortunately, the source code is available. So, I pulled down the source and referenced it in my project. The exception occurs on line 699, where the the Version property of the fileVersionAttribute var is attempted to be retrieved. But fileVersionAttribute is null!...when linked. The LINQ statement that begins on line 695 returns null when linking is enabled. It does return a valid value when not linked; a value of "1.0.0.0".
WHY? I'm not quite sure yet. But that's the root cause of the exception.
Anyway, for now I'll have to include the Azure Mobile Service source in my project, and artificially set that value to "1.0.0.0"...which is dirty, and I'm not happy about it.
string fileVersion = fileVersionAttribute?.Version ?? "1.0.0.0";
EDIT:
Issue raised on github: https://github.com/Azure/azure-mobile-services/issues/855
I have finally discovered a way to prevent the linking of the Azure Mobile Services library, without disabling linking for everything else.
You can add
--linkskip=Microsoft.WindowsAzure.Mobile --linkskip=Microsoft.WindowsAzure.Mobile.Ext
to Additional mtouch arguments in the iOS build options under project settings for the iOS project.
This will skip the linker for the azure assemblies, but not the rest. More on the linker can be found at http://developer.xamarin.com/guides/ios/advanced_topics/linker/#Skipping_Assemblies
I needed to add
CurrentPlatform.Init();
in the AppDelegate in FinishedLaunching
Secondly in the iOS project I needed to go to
Properties > iOS Build > Linker Behavior and set it to "Don't link"
I still don't consider this the answer, its just a poor work around at the moment.
I am using Simple Data (1.0.0-rc0) like Simple.DataDatabase.Default.Licenses.All().ToList<License>() to get a list of licenses. It works fine and all in my productions environment (VS2010, IIS7.5) but once deployed to live server it throws :
`System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.Assembly.GetTypes()
at System.ComponentModel.Composition.Hosting.AssemblyCatalog.get_InnerCatalog()
at System.ComponentModel.Composition.Hosting.AssemblyCatalog.GetExports(ImportDefinition definition)
at System.ComponentModel.Composition.Hosting.AggregateCatalog.GetExports(ImportDefinition definition)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.AggregateExportProvider.GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.TryGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition, IEnumerable1& exports)
at System.ComponentModel.Composition.Hosting.CompositionContainer.GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExportsCore[T](String contractName)
at Simple.Data.MefHelper.Compose[T](String contractName)
at Simple.Data.AdapterFactory.DoCreate(String adapterName, IEnumerable1 settings)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Simple.Data.CachingAdapterFactory.Create(String adapterName, IEnumerable1 settings)
at Simple.Data.DatabaseOpener.OpenDefaultMethod()
at Simple.Data.DatabaseOpener.OpenDefault()`
`System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.Shell, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.VisualStudio.Shell, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'`
The server is running a freshly installed Windows Server 2008 R2.I have been going at this for the last two days without any progress at all. Did I perhaps miss something crucial during server setup?
This is an issue with MEF. One of the assemblies in your bin folder has a reference to Microsoft.VisualStudio.Shell, and when MEF tries to do its thing and it can't follow all the references, it throws that error.
This has been the cause of several bug reports recently, and the next release will have a change to the MEF code which will stop it from happening.
As a workaround in the meantime, you can either track down the assembly with the reference and remove it, or put that assembly in the bin folder. I'd recommend the former, since adding that assembly might be the start of a whole chain of adding more and more.
I am getting following error in sharepoint Logs for my SharePoint Visual Studio Sequential workflow having a custom activity.
The custom activity is created through Component Class.
I am not sure why this error is coming? Please help!!!
System.Workflow.Runtime.Hosting.PersistenceException: Type 'System.ComponentModel.Container' in Assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable. ---> System.Runtime.Serialization.SerializationException: Type 'System.ComponentModel.Container' in Assembly 'System, 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.WriteObjectInf... 3d93366f-a701-476c-91c9-d2153911486b
03/22/2012 12:38:36.31* w3wp.exe (0x049C) 0x1620 SharePoint Foundation Workflow Infrastructure 98d4 Unexpected ...o.InitSerialize(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.Runtime.Hosting.WorkflowPersistenceService.GetDefaultSerializedForm(Ac... 3d93366f-a701-476c-91c9-d2153911486b
03/22/2012 12:38:36.31* w3wp.exe (0x049C) 0x1620 SharePoint Foundation Workflow Infrastructure 98d4 Unexpected ...tivity activity) at Microsoft.SharePoint.Workflow.SPWinOePersistenceService.SaveWorkflowInstanceState(Activity instanceState, 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) 3d93366f-a701-476c-91c9-d2153911486b
Thanks!
The Issue was because when i changed the Component class to Sequential Activity I had Activity properties e.g. 'A' & 'B'. Then i added this activity to VS toolbox. At this stage it was working fine.
Now when I changed the activity code to change its property to 'A' & 'C' and i also removed a Constructor having parameter as 'Container' object.
When i re-compiled this Activity and refresh its DLL. In workflow designer the Activity was not getting refreshed i.e. its toolbox was still pointing to old dll.
To Resolve for this i closes and opened the VS again, VOILA the designer is now getting updated Activity with new properties.
This was i think was limitation of VS toolbox that it is not getting refreshed in-spite of dll for that activity is updated.
Thanks!
Can you access the source XAML for the workflow? See if a "Container" object is being included, and if it's necessary to have it there. If you can remove it and still have the workflow run properly, this may fix the issue.
I get the following exception loading any Xaml in my project:
'/Microsoft.VisualStudio.Xaml;Component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.Constants.xaml' value cannot be assigned to property 'Source' of object 'System.Windows.ResourceDictionary'. Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The system cannot find the file specified. Error at object 'ResourceDictionary_2' in markup file 'Microsoft.VisualStudio.Xaml;component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.xaml'.
at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)
at System.Windows.Markup.BamlRecordReader.ReadPropertyRecordBase(String attribValue, Int16 attributeId, Int16 converterTypeId)
at System.Windows.Markup.BamlRecordReader.ReadPropertyConverterRecord(BamlPropertyWithConverterRecord bamlPropertyRecord)
at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)
at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()
at System.Windows.Markup.TreeBuilder.Parse()
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.LoadComponent(Uri resourceLocator)
at MS.Internal.Designer.PropertyEditing.Resources.PropertyInspectorResources.GetResources()
at MS.Internal.Designer.PropertyEditing.PropertyInspectorHost.get_Host()
at MS.Internal.Designer.VSDesigner.VSDesignerClientImpl.get_PropertyWindow()
at MS.Internal.Designer.VSDesignerClient.get_PropertyWindow()
at MS.Internal.Designer.DesignerPane.LoadDesignerView()
This occurs even when I generate a new SilverLight project inside my solution, but not in a brand new solution. I've found that I am not the only person with this issue, and was wondering if you had any ideas for me.
Here is a post of someone with the same error, from Google Cache.
The stack trace is indicating you don't have a reference to the specified log4net assembly in your project. The solution would be to add a reference to it, although unless you get a log4net assembly that has been compiled against the Silverlight agCLR runtime you won't be able to.
The alternative if you are not trying to use log4net in your Silverlight app is to remove the sections of code attempting to use it. Again from the stack trace it looks like you are setting up some kind of resource that initialises log4net. Try opening your Windox.xaml and take a look in the reources section. If you see any signs of log4net there remove them and see if it helps.
I also am getting this error. I have gone through the application and made sure I am referencing the correct version. There is no use of log4net in the silverlight application, only in the web project containing a wcf service that the app uses. It looks like log4net has to be replaced with something safer. The log4net dll is also causing mstest projects to stop working.
'/Microsoft.VisualStudio.Xaml;Component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.Constants.xaml' value cannot be assigned to property 'Source' of object 'System.Windows.ResourceDictionary'. Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The system cannot find the file specified. Error at object 'ResourceDictionary_2' in markup file 'Microsoft.VisualStudio.Xaml;component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.xaml'.
I have no idea what the couse of the problem is. If anyone knows I would be interested find out!
I have a workaround though which solved it for me:
Remove the reference from the Silverlight project to whatever is using log4net
Remove that project using log4net from the solution.
Reload the XAML-pages and save the solution.
Finally add the project using log4net and the reference again.
Henrik
This question is a bit specific (MOSS2007) and I don't high hopes for getting an answer, but maybe luck will smile upon me.
I have a web part that works except the very first time it's being added to a page. It throws an exception inside a constructor when I'm trying to open a connection to a SQL server. The demand for the SqlClientPermission permission fails. When I say it works, I mean it is properly registered in any regard and works in every other case, including subsequent calls.
Someone said there is no way out. I'd like to know why. Is it by design?
I went so far as to give a full trust to everything I could (changed every .config file I could find on my server), but it did not help.
It appears that SharePoint is doing some kind of remoting the first time it adds a web part, which appears to run with minimal trust the first time it's constructed (same as defined in web_minimaltrust.config for ASP.Net). Attempts to grant permissions for everything in everything did not yield any fruitful results.
My solution was to move the data access code to the OnInit method, but that is irritating. Does anyone have any insight?
Thank you.
Some extra info from the debugger.
The only permitted permissions were:
<PermissionSet class="System.Security.PermissionSet" version="1">
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Execution"/>
<IPermission class="System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Level="Minimal"/>
</PermissionSet>
The inner exception stack:
hresult = -2146233078
mscorlib
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.PermissionSet.Demand()
at System.Data.Common.DbConnectionOptions.DemandPermission()
at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at IManageDocumentsPart.ClientSideDocumentsWebPart.GetOfficeCode(Int32 employeeId)
at IManageDocumentsPart.ClientSideDocumentsWebPart..ctor()
The full stack:
IManageDocumentsPart.DLL!IManageDocumentsPart.ClientSideDocumentsWebPart.ClientSideDocumentsWebPart() Line 98 C#
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.RuntimeType.CreateInstanceSlow(bool publicOnly, bool fillCache = true) + 0x68 bytes
mscorlib.dll!System.Activator.CreateInstance(System.Type type, bool nonPublic) + 0x43 bytes
System.Web.dll!System.Web.HttpRuntime.FastCreatePublicInstance(System.Type type) + 0x56 bytes
System.Web.dll!System.Web.UI.WebControls.WebParts.WebPartManagerInternals.CreateObjectFromType(System.Type type) + 0x7 bytes
System.Web.dll!System.Web.UI.WebControls.WebParts.WebPartManager.ImportWebPart(System.Xml.XmlReader reader = {EndElement, Name="metaData"}, out string errorMessage = null) + 0x35d bytes
Microsoft.SharePoint.dll!Microsoft.SharePoint.WebPartPages.SPWebPartManager.ImportWebPartBase(System.Xml.XmlReader reader = {EndElement, Name="metaData"}, string importErrorMessage = "Cannot import this Web Part.", out string errorMessage = null) + 0x25 bytes
Microsoft.SharePoint.dll!Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(bool clearConnections = true) + 0x1b4 bytes
Microsoft.SharePoint.dll!Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(Microsoft.SharePoint.WebPartPages.SPWebPartManager manager = {Microsoft.SharePoint.WebPartPages.SPWebPartManager}, System.Xml.XmlReader reader = {None}, bool clearConnections = true, System.Uri webPartPageUri = {http://v-sp2007/testsite/default.aspx?PageView=Shared}, Microsoft.SharePoint.SPWeb spWeb = {Microsoft.SharePoint.SPWeb}) + 0x8e bytes
Microsoft.SharePoint.dll!Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(Microsoft.SharePoint.WebPartPages.SPWebPartManager manager = {Microsoft.SharePoint.WebPartPages.SPWebPartManager}, System.Xml.XmlReader reader = {None}, bool clearConnections = true, Microsoft.SharePoint.SPWeb spWeb = {Microsoft.SharePoint.SPWeb}) + 0xa1 bytes
Microsoft.SharePoint.dll!Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument = "http%253A%252F%252Fv%252Dsp2007%252F%255Fcatalogs%252Fwp%252FClientSideDocumentsWebPart%252Ewebpart;ClientSideDocumentsWebPart") + 0x288 bytes
System.Web.dll!System.Web.UI.Page.RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl, string eventArgument) + 0xc bytes
System.Web.dll!System.Web.UI.Page.RaisePostBackEvent(System.Collections.Specialized.NameValueCollection postData) + 0xb2 bytes
...the rest of the stack is the same as when opening a page normally.
Try setting up a solution package to deploy code access security settings. You definitely need SqlClientPermission. Check out my post on Code Access Security for web parts for more information.
Just as a reference for the next ones coming, here there's one of the many articles were code in web part constructor is marked as a big NO-NO.
That is odd. Maybe you could special case your web part to not do the database call when the page is in edit/design mode. Wouldn't that fix your problem?
As a simple test, you could deploy the assemby containing the web part into the GAL. There it will run with Full Trust.
Personally, I would not recommend establishing a database connection in the constructor of a web part unless you had a compelling reason to do so.
[updated 3009-03-27]
Debugging is often about ruling out causes. Even though you believe the web part is running in Full Trust, I recommend testing the GAC'ed case. Remember to remove the .dll from the Bin directory for the test. This will only take 5-10 minutes and you'll know where you stand.
My solution was to move the data access code to the OnInit method, but that is irritating. Does anyone have any insight?
When SharePoint is going through and processing the request the first thing that it will be doing is executing your constructor to create a new instance of the object. The Constructors that it calls are parameterless so that they can be serialized and deserialized for import/exports. Inside of the constructor none of the security constructs or associated objects have been set in the newly created object. It may therefore be the case that your object does not have any context information about where it is living or what it is doing.
By moving your code into the OnInit method you have shifted the time of execution back as some of your related objects and what not have been bound automatically by this point. In the ASP.net lifecycle, OnInit methods work from the from the top down and OnLoad methods work from the bottom up. So that may also influence whether your parent or children have had their related code executed yet.