Windows Metadata Exporter Crashes when Compiling Windows Runtime Component - windows-runtime

I'm attempting to create a Windows Runtime Component for use in a Windows 8 app.
This is essentially a helloworld level application and so has nothing complex. The only thing that I need to do to replicate the issue is to include a pair of methods such as the following:
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new List<string>().ToArray();
}
Whenever I compile the project, the Windows Metadata Exporter crashes.
I've dug into the errors generated in the output window by increasing the build verbosity and I've found that the error occurs after "Exporting 'obj\Debug\HelloWorld.Logic.winmdobj'."
By attempting to run winmdexp.exe from command line with the same parameters, it seems that it's having trouble finding metadata for the System.Xml files. (warning WME0004 : Could not find referenced metadata 'C:\Program Files(x86)\ReferenceAssemblies\Microoft\Framework.NETCore\v4.5.1\System.Xml.Serialization.dll'.)
The full stack trace of the error is:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Tools.WinMDExp.AssemblyReferenceExtensionMethods.IsWindowsRuntimeMetadata(IAssemblyReference assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.IsWindowsRuntimeType(ITypeReference type, Boolean allowGenericParam)
at Microsoft.Tools.WinMDExp.ExportValidator.<>c__DisplayClasse.<GetAlternativeTypes>b__8(<>f__AnonymousType0`2 <>h__TransparentIdentifier5)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativeTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& isTask, Boolean allowGenericTypeParam)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativesTypesForGenericTypes(IGenericTypeInstanceReference parameterType, IMethodDefinition containingMethod, String& errorMsg)
at Microsoft.Tools.WinMDExp.ExportValidator.CheckAlternateTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportParameterType(IMethodDefinition containingMethod, ITypeReference parameterType, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportMethod(IMethodDefinition method)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IEnumerable`1 methods)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(INamedTypeDefinition namedTypeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Traverse(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Dispatcher.Visit(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataReader.ObjectModelImplementation.NamespaceType.Dispatch(IMetadataVisitor visitor)
at Microsoft.Tools.WinMDExp.ExportValidator.Validate(ITypeDefinition type)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IModule module)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IAssembly assembly)
at Microsoft.Cci.MetadataTraverser.Traverse(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.Export(IAssembly assembly)
at Microsoft.Tools.WinMDExp.Exporter.Export()
at Microsoft.Tools.WinMDExp.Program.Main(String[] args)
If anyone has any idea what's going on and how I can get my component compiling I'd be grateful.
James
P.S. I transferred the project to a colleague's PC and they had the same issue so I doubt if it's anything to do with my setup (Windows 8.1 x64, Visual Studio 2013 Ultimate).

I've managed to figure this out myself.
It seems as though there is a bug when using string[] (or other arrays) as the generic type for IAsyncOperation.
I have managed to work around this because actually I will want to return IDictionary objects and ILists, which work fine:
/* //Won't Work - crashes Windows Metadata Exporter
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new [] {"I am a string"};
}
*/
//This Works
public IAsyncOperation<IList<string>> GetThingsList()
{
return GetThingsListAsync().AsAsyncOperation();
}
private async Task<IList<string>> GetThingsListAsync()
{
return new[] { "I am a string" };
}
Hopefully this will be of use to anyone else who comes across this weird behaviour.

Related

Startup.cs error (ASP.Net Core configuration)

I am trying to set up an ASP.Net Core application to read in configuration settings from a json file. I am using VS2015 and .NetCore 1.0 (with .Net Core Tools preview 2). I am having problems getting a simple piece of boiler plate code to compile.
I am using the following code, which was published at
http://asp.net-hacker.rocks/2016/03/21/configure-aspnetcore.html
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights
// pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
However, the IDE/compiler complains that 'the name "Configuration" does not exist in the current context' (last line of code). The only suggestion from the IDE is to include Microsoft.Extensions.Configuration. However this is a namespace which does not contain an object or property named "Configuration".
In addition 'AddApplicationInsightsSettings' fails with does IConfigurationBuilder not contain a definition for AddApplicationInsightsSettings and no extension method AddApplicationInsightsSettings accepting a first argument of type IConfigurationBuilder could be found
Any suggestions please ?
Thanks
Simply add Configuration property to your Startup class, tutorial has missed this 'step':
public IConfigurationRoot Configuration { get; set; }
ConfigurationBuilder.Build() method just returns instance of IConfigurationRoot, that you should save, if need to get settings further in Startup class (in ConfigureServices method for example).
Regarding second error, looks like you didn't add the Application Insights dependency:
{
"dependencies": {
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0"
}
}

Resolve caste windsor failing

Recently upgraded to version 3.2.1 of castle windsor and receiving an error when attempting to resolve a service that previously didn't occur in version 3.0 of the windsor framework.
IWindsorContainer container = new WindsorContainer();
The following code no longer works
// Throws component not found exception
InstallerHelper.ProcessAssembliesInBinDirectory(
assembly => container.Register(
Classes
.FromAssembly(assembly)
.BasedOn<IWindsorInstaller>()
.WithService.FromInterface()
.LifestyleSingleton()
));
var installers = container.ResolveAll<IWindsorInstaller>();
container.Install(installers);
// Fails here, is it related to a hashcode mismatch in SimpleTypeEqualityComparer?
var credentialCache = container.Resolve<ICredentialCache>()
// works fine if explicity install installers individually
container.Install(new CredentialsInstaller());
var credentialCache = container.Resolve<ICredentialCache>()
Where ProcessAssembliesInBinDir is:
public static void ProcessAssembliesInBinDirectory(Action<Assembly> action)
{
var directoryName = GetDirectoryName();
foreach (var dll in Directory.GetFiles(directoryName, "*.dll"))
{
var fileInfo = new FileInfo(dll);
if (!IgnoreList.Any(x=>fileInfo.Name.StartsWith(x)))
{
var assembly = Assembly.LoadFile(dll);
action(assembly);
}
}
}
Where credential installer is:
public class CredentialsInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<ICredentidalCache>()
.ImplementedBy<CredentidalCache>()
.LifestyleSingleton()
);
// This works fine
var credentialCache = container.Resolve<ICredentialCache>()
}
}
Class implementation
public interface ICredentidalCache {}
public class CredentidalCache : ICredentidalCache{}
This is being run from an MVC application
version 4.5 of the .net framework
the credential installer lives inside another assembly, referenced by the website
using the Windsor source, the successful attempt to resolve occurs when the typeof(ICredentialCache).GetHashCode() is the same as what has been registered. For some reason when returning out of the installer the hashcode has changed for the type. Putting a debug line inside SimpleTypeEqualityComparer.GetHashCode(Type obj) shows that hashcodes are different for the same Type.
inspecting the container inside the debugger shows the ICredentialCache successfully installed.
Edit
Manage to move forward by manually registering installers, ie. not relying on the resolve<IwindsorInstaller>() and use container.install(new Installer(), ...). If i find out more I'll update the SO question.
This works fine for me:
public sealed class AppServiceFactory
{
...
public T Create<T>()
{
return (T)container.Resolve(typeof(T));
}
...
}
AppServiceFactory.Instance.Create<IYourService>();
The problem is caused by the InstallerHelper and how it goes about loading an assembly. This SO post pointed me in the right direction,
https://stackoverflow.com/a/6675227/564957
essentially the way the assembly was loaded was failing using Assembly.LoadFile(string fileName) was causing the problem, changing this to be Assembly.Load(string assemblyName) rectified the issue.
#Eric Lippert does a good job explaining
[when] loading an assembly by its path, and one via loading the same
assembly by its assembly name... reflection will
consider types from the two loadings of the same assembly to be
different types. Any assembly loaded from its path is considered to be
distinct from an assembly loaded by its assembly name.

SSIS Script Component runtime error

I got a valid issue when I run my package. It runs failed in my PC and success in anyone else.
The error is caused by Script Component (turned red), and it is in Post Execute phase, not the post execute in the script componet, but in the runtime of package. The error is:
Information: 0x40043008 at Data Flow Task, SSIS.Pipeline: Post Execute phase is beginning.
Error: 0xC0047062 at Data Flow Task, Script Component [263]: System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSVariables100'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{22992C1D-393D-48FB-9A9F-4E4C62441CCA}' failed due to the following error: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).
I guess the issue is related to variables, because when I remove all the code related to variables, the package run successfully. The code in script component:
private int scheduled550;
private int scheduled620;
private int scheduled720;
private int scheduled820;
public override void PreExecute()
{
base.PreExecute();
scheduled550 = Variables.Count550;
scheduled620 = Variables.Count620;
scheduled720 = Variables.Count720;
scheduled820 = Variables.Count820;
}
public override void PostExecute()
{
base.PostExecute();
}
Did anyone ever encounter the same issue? Can anyone tell me what will POST Execute phase do? Thanks
More info: I have tried to re-install SQL Server, but this is not help. And not all the script component with variables failed running in my SSIS (not in the same package with the error one)
All the tasks/containers in an SSIS have the same lifecycle. You can see some of this by watching the Event Handlers fire. In a script component, inside a Data Flow Task, is going to under go various steps. Part of that is Validation (this contract says I should have a column from this table that is an integer type- can I connect, does it exist, is it the right type, etc).
After validation, tasks will have setup and tear down steps to perform. Since you appear to be working with SSIS Variables in your script, part of that pre/post execute time is spent allowing the translation of Variable (SSIS) to variable (.net) and back again.
Until I see the specific code in your PostExecute method that was causing the failure, I can't state what the code issue might have been.
I cannot recreate your issue. While this is the 2012 release of Integration Services, the Script Component as you are using it will behave the same. I did not send my output to Excel but that should not matter given it's the Script that is failing.
My Script component. I have selected my Variable, User::Count550 as a ReadOnly variable in the menu before editing my code.
public class ScriptMain : UserComponent
{
private int scheduled550;
public override void PreExecute()
{
base.PreExecute();
this.scheduled550 = Variables.Count550;
}
public override void PostExecute()
{
base.PostExecute();
//this.Variables.Count550 = scheduled550;
//this.VariableDispenser.LockForWrite("Count550");
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
if (true)
{
this.scheduled550++;
}
}
}

Operation not permitted on IsolatedStorageFileStream

I'm building this WP7 app that uses a video game API to get the statistics of someone's character (just to help learn silverlight). It grabs the players details from the web service and stores them on isolated storage on the phone to relieve strain from the server.
Originally I had a class which had both the cache writing and reading function, but now i've had to seperate it out into two seperate classes. The cache writing class doesn't matter at the moment, just the cache reading class.
On line 7, it throws an exception saying "Operation not permitted on IsolatedStorageFileStream.", but only during the second time it instantiates the class. I've done some checking with debug and it says the file definately exists, but it stops after the second using clause.
Can anyone help me with this please? I feel like I'm missing something really obvious.
public class CacheReader
{
public PlayerData GetPlayerData(string gamertagIn)
{
using (IsolatedStorageFile CachedReachData = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = CachedReachData.OpenFile(gamertagIn + ".xml", FileMode.Open))
{
Debug.WriteLine("Data Retrieved from cache");
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
PlayerData loadedPlayer = (PlayerData)serializer.Deserialize(stream);
return loadedPlayer;
}
}
}
}
[EDIT 1]
This is the stack trace i get:
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFile.OpenFile(String path, FileMode mode, FileAccess access)
at ReachPhoneApp.CacheReader.GetPlayerFromCache(String gamertagIn)
at ReachPhoneApp.Page2.GetPlayerData()
at ReachPhoneApp.Page2.cacheWriter_UpdateComplete()
at ReachPhoneApp.CacheWriter.WritePlayerDataToCache(String fileNameIn, Object objectIn)
at ReachPhoneApp.CacheWriter.client_GetGameHistoryCompleted(Object sender, GetGameHistoryCompletedEventArgs e)
at ReachPhoneApp.ReachAPI.ReachApiSoapClient.OnGetGameHistoryCompleted(Object state)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
Check that you don't somehow have two threads accessing IsolatedStorage at the same time (ie. in VS Debug.View.Threads and verify that at the time of the exception you don't have multiple paths through the same IsoStore code).
This happened in my WP7 code once every few days and was tricky to find, as it seemed to occur only when not connectected to the debugger.
You need to call:
stream.Close();
before
return loadedPlayer;
I think the problem is that you didn't specify that multiple threads could read/write at the same time by specifying a System.IO.FileShare.ReadWrite or whatever access you need as the last parameter of OpenFile.
See the discussion here on the Microsoft Forums.
I ran into this issue as well, but for completely different reasons as mentioned above. I hadn't created the directory that I was saving into.
private void SaveStringDataToStorage(string sDirectory, string sFileName, string sFileContent)
{
string sPath;
//
using (IsolatedStorageFile oFile = solatedStorageFile.GetUserStoreForApplication())
{
if (!oFile.DirectoryExists(sDirectory))
oFile.CreateDirectory(sDirectory);
//
sPath = Path.Combine(sDirectory, sFileName);
//
using (var oWriter = new StreamWriter(new IsolatedStorageFileStream(sPath, FileMode.Create, oFile)))
oWriter.Write(sFileContent);
}
}
Using this code will work if you had the same problem as me, plus it's pretty simple so you can adapt it to whatever you need. I was using this code before I had issues, but I'd forgotten the ! so the directory was never created haha. Just typical. Hope this helps :)
EDIT
Looking closer at the original question, it may be that the file didn't exist. I think it's always best to do IsolatedStorageFile.DirectoryExists() and IsolatedStorageFile.FileExists() before trying to access either location, whether you are reading or writing.
By default when you use IsolatedStorageFile.OpenFile("filename", FileMode.Open) your file gets locked by this thread and no other thread would be able to access this file until 1st thread close it. But if you like to share your file in multiple threads for read purpose only then I would recommend you to use following override
IsolatedStorageFile.OpenFile("filename", FileMode.Open, FileAccess.Read, FileShare.Read)
see details here

Groovy end exception different from exception thrown

I am running into an extremely strange behavior in Groovy. When I throw an exception from a closure in a Script, the end exception that was thrown was different.
Here are the code and the details:
public class TestDelegate {
def method(Closure closure) {
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.delegate = this;
closure.call();
}
public static void main(String[] args) {
// Make Script from File
File dslFile = new File("src/Script.dsl");
GroovyShell shell = new GroovyShell();
Script dslScript = shell.parse(dslFile);
TestDelegate myDelegate = new TestDelegate();
dslScript.metaClass.methodMissing = {
// will run method(closure)
String name, arguments ->
myDelegate.invokeMethod(name, arguments);
}
dslScript.metaClass.propertyMissing = {
String name ->
println "Will throw error now!"
throw new MyOwnException("errrrror");
}
dslScript.run();
}
}
class MyOwnException extends Exception {
public MyOwnException(String message) {
super(message);
}
}
Script.dsl:
method {
println a;
}
So the plan is that when I run the main() method in TestDelegate, it will run the DSL script, which calls for the method method(). Not finding it in the script, it will invoke methodMissing, which then invokes method() from myDelegate, which in turns invoke the closure, setting the delegate to the testDelegate. So far, so good. Then the closure is supposed to try printing out "a", which is not defined and will thus set off propertyMissing, which will will throw MyOwnException.
When I run the code, however, I get the following output:
Will throw error now!
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: a for class: TestDelegate
Now, it must have reached that catch block, since it printed "Will throw error now!" It must have thrown MyOwnException too! But somewhere along the lines, MyOwnException was converted to MissingPropertyException, and I have no idea why. Does anyone have any idea?
P.S. if I remove closure.setResolveStrategy(Closure.DELEGATE_FIRST) from TestDelegate#method(), the code acts as expected and throws MyOwnException. But I really need the setResolveStrategy(Closure.DELEGATE_FIRST) for my DSL project. And I would prefer to know the root cause of this rather than just removing a line or two and see that it works without understanding why.
I think this is what essentially happens: With a delegate-first resolve strategy, the Groovy runtime first tries to access property a on myDelegate, which results in a MissingPropertyException because no such property exists. Then it tries propertyMissing, which causes a MyOwnException to be thrown. Eventually the runtime gives up and rethrows the first exception encountered (a design decision), which happens to be the MissingPropertyException.
With an owner-first resolve strategy, propertyMissing is consulted first, and hence MyOwnException is eventually rethrown.
Looking at the stack trace and source code underneath should provide more evidence.