System.IO.FileNotFoundException in SimpleData - windows-server-2008-r2

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.

Related

Error after upgrading to Azure Mobile Services 1.3.1

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.

How can I implement 'RenderPartial' method for 'ServiceStack.Razor.RazorFormat'?

I added ServiceStack.Razor configuration to the ServiceStack sample project RestIntro, added a Views folder containing _Layout.cshtml and Customers.cshtml, when i browse the app
http://webserver:5000/Customers.cshtml
i get the error msg below:
Exception Details: System.TypeLoadException: Method 'RenderPartial' in type 'ServiceStack.Razor.RazorFormat' from assembly 'ServiceStack.Razor, Version=3.9.42.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
What didnt i do right?
I'd need to see your Customers.cshtml markup to know for sure, but based on the exception try replacing your RenderPartial method calls with just Partial.
ServiceStack's HtmlHelper doesn't include a RenderPartial implementation. Although looking at the source code, it's implementation of Partial is actually equivelent to MVC's RenderPartial (i.e. it doesnt return the rendered partial as a string, but writes it direct to the output buffer, even though the method sig returns a string, its always null). Not sure if this is by design or an issue, I found this question looking for an answer to exactly that!

What is System.Windows.ni.dll?

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

How to inherit from DataAnnotations.ValidationAttribute (it appears SecureCritical under Visual Studio debugging host in .NET 4 !)

I have an [AllowPartiallyTrustedCallers] class library containing subtypes of the System.DataAnnotations.ValidationAttribute. The library is used on contract types of WCF services.
In .NET 2/3.5, this worked fine. Since .NET 4.0 however, running a client of the service in the Visual Studio debugger results in the exception "Inheritance security rules violated by type: '(my subtype of ValidationAttribute)'. Derived types must either match the security accessibility of the base type or be less accessible." (System.TypeLoadException)
The error appears to occure only when all of the following conditions are met:
a subclass of ValidationAttribute is in an AllowPartiallyTrustedCallers assembly
reflection is used to check for the attribute
the Visual Studio hosting process is enabled (checkbox on Project properties, Debug tab)
So basically, in Visual Studio.NET 2010:
create a new Console project,
add a reference to "System.ComponentModel.DataAnnotations" 4.0.0.0,
write the following code:
.
using System;
[assembly: System.Security.AllowPartiallyTrustedCallers()]
namespace TestingVaidationAttributeSecurity
{
public class MyValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{ }
[MyValidation]
public class FooBar
{ }
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ValidationAttribute IsCritical: {0}",
typeof(System.ComponentModel.DataAnnotations.ValidationAttribute).IsSecurityCritical);
FooBar fb = new FooBar();
fb.GetType().GetCustomAttributes(true);
Console.WriteLine("Press enter to end.");
Console.ReadLine();
}
}
}
Press F5 and you get the exception !
Press Ctrl-F5 (start without debugging), and it all works fine without exception...
The strange thing is that the ValidationAttribute will or will not be securitycritical depending on the way you run the program (F5 or Ctrl+F5). As illustrated by the Console.WriteLine in the above code. But then again, this appear to happen with other attributes (and types?) too.
Now the questions...
Why do I have this behaviour when inheriting from ValidationAttribute, but not when inheriting from System.Attribute ? (Using Reflector I don't find special settings on the ValidationAttribute class or it's assembly)
And what can I do to solve this ? How can I keep MyValidationAttribute inheriting from ValidationAttribute in an AllowPartiallyTrustedCallers assembly without marking it SecurityCritical, still using the new .NET 4 level 2 security model and still have it work using the VS.NET debug host (or other hosts) ??
Thanks a lot!
Rudi
Why do I have this behaviour when inheriting from ValidationAttribute, but not when inheriting from System.Attribute ? (Using Reflector I don't find special settings on the ValidationAttribute class or it's assembly)
This is because the System.ComponentModel.DataAnnotations assembly is conditionally APTCA i.e. it is marked with the following attribute.
[assembly: AllowPartiallyTrustedCallers(PartialTrustVisibilityLevel = PartialTrustVisibilityLevel.NotVisibleByDefault)]
Something about the way Visual Studio starts the host process causes the CLR not to respect APTCA on this assembly even though the default AppDomain is fully trusted. This implies that all the types and methods in the DataAnnotations assembly are SecurityCritical. Since a security transparent type (MyValidationAttribute) cannot inherit from a security critical type (ValidationAttribute), this exception is thrown.
And what can I do to solve this ? How can I keep MyValidationAttribute inheriting from ValidationAttribute in an AllowPartiallyTrustedCallers assembly without marking it SecurityCritical, still using the new .NET 4 level 2 security model and still have it work using the VS.NET debug host (or other hosts) ??
It seems like this is a bug with the VS host, which is unfortunate for your situation. On the other hand, you should really be sure that you want your assembly to be APTCA. If it's necessary, then you have a couple of options.
You can leave your assembly as is. This is advantageous because in the most typical partial trust environment, ASP.NET, the DataAnnotations assembly will always be considered APTCA. Of course, you lose the ability to use the debugger in the VS hosting process.
You can mark your assembly C-APTCA as well. You'll be able to use the debugger in the VS hosting process, but consumers of your assembly in ASP.NET will need to add your assembly to the <partialTrustVisibleAssemblies> element in the web.config in order for it to be APTCA.
You could make your attribute SecurityCritical, so you'll be able to use the debugger and will not require any special configuration in ASP.NET, but all classes that use your attribute must also be critical.
For some reason the site posted the text into a completely different question from the one that was on the page when I was writing - weird.

Weird Silverlight Designer Error

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

Resources