I have a C# application and I modified it to show a new window using the lines:
private void button1_Click(object sender, EventArgs e)
{
WelcomeScreen channelBar = new WelcomeScreen(true, "http://www.trade-ideas.com/cms_static/ChannelBar/channelbar.html");
}
It compiles just fine, but when I run the app and click on the button, I get this error:
An unhandled exception of type 'System.TypeLoadException' occurred in WindowsFormsApplication1.exe
Additional information: Could not load type 'TradeIdeas.TIProData.OddsMakerColumnConfiguration' from assembly 'TIProData, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
What doesn't make any sense is that WelcomeScreen comes from TIProGUI.dll not TIProData. I have included both dll's in the project along with a 3rd dll:
using TradeIdeas.TIProData;
using TradeIdeas.TIProGUI;
using TradeIdeas.TIProData.Configuration;
Also, when I run the project initially, I see a very strange message. It says:
Loading symbols from TIProData.dll from:
\\MissionControl\Users\KLewis2\Documents\CVSRoot\C_Sharp\TIProData\Obj\Release
Needless to say, there is no path to that from my machine.
Any clues as to what is causing this would be greatly appreciated.
There are many reasons and one of common once is exceptions in static initializers.
To diagnose - debug program with exceptions set to "break when thrown" and disabled "my code only". When exception happen take note of call stack and check all exceptions thrown from static initializers.
Location of options:
Tools-> Options -> Debug -> My Code only (uncheck)
Debug -> Exceptions -> Common Language Runtime Exceptions (check "thrown")
Sample code that will cause that error:
class MyClass
{
static int value = ReadFromConifg();
static int ReadFromConifg()
{...
throw new ConfigMissingException();
}
}
Related
Getting following exception when loading :
speechRecognizer = new Microsoft.CognitiveServices.Speech.SpeechRecognizer(config);
Inner exception : InnerException = {"Unable to load DLL
'Microsoft.CognitiveServices.Speech.csharp.bindings.dll': The
specified module could not be found. (Exception from HRESULT:
0x8007007E)"}
Microsoft.CognitiveServices.Speech.Internal.carbon_csharpPINVOKE.SpeechConfig_FromSubscription(String
jarg1, String jarg2) at
Microsoft.CognitiveServices.Speech.Internal.SpeechConfig.FromSubscription(String
subscription, String region) at
Microsoft.CognitiveServices.Speech.SpeechConfig.FromSubscription(String
subscriptionKey, String region) |ERROR|The type initializer for
'SWIGExceptionHelper' threw an exception. 2019-01-03
16:02:50.2178|ERROR|The type initializer for
'Microsoft.CognitiveServices.Speech.Internal.carbon_csharpPINVOKE'
threw an exception.
As the exception says, you are missing "Microsoft.CognitiveServices.Speech.csharp.bindings.dll" . You have to include the dll in the project and mark it as part of the deploy. Make sure it appears in the deployed folder in the IIS , copy it manually as last option.
Actually it is very strange exception, because it happens only when I build the project as Release and does not happen at all when I choose Debug. In debug mode, the app works perfect and the following code works well.
Here is the code of my extension method:
public static T DeepClone<T>(this T source) where T : UIElement
{
T result;
// Get the type
Type type = source.GetType();
// Create an instance
result = Activator.CreateInstance(type) as T; //throws exception here only if I build project as (release)
CopyProperties<T>(source, result, type);
DeepCopyChildren<T>(source, result);
return result;
}
The exception is:
An exception of type 'System.MissingMethodException' occurred in
System.Private.Reflection.Execution.dll but was not handled in user
code
Additional information: MissingConstructor_Name,
Windows.UI.Xaml.Controls.RelativePanel. For more information, visit
http://go.microsoft.com/fwlink/?LinkId=623485
I've found some related questions to this exception, but they all are pointing to missing libraries or update libraries like this but didn't change anything in my app.
This problem is related to the fact that Release build of UWP apps uses the .NET native toolchain. In this mode reflection needs some hints to work properly. Aparently the constructor of the RelativePanel is not available for reflection.
Luckily there is a workaround for this as described in this blogpost.
In your UWP project's Properties folder is a file called default.rd.xml. Open it and add the following line inside the <Applications> element:
<Type Name="Windows.UI.Xaml.Controls.RelativePanel"
Dynamic="Required All" Activate="Required All" />
The Dynamic attribute should ensure reflection is possible and the Activate attribute should ensure the constructors are available for activation - which is key for your case.
This should include all members of RelativePanel for reflection and everything should work as expected.
You can see more details on the default.rd.xml file structure here.
I have the following method:
private void DoSomething(CoolClass coolClass)
{
if (coolClass == null)
{
throw new ArgumentNullException("coolClass");
}
coolClass.Name = "Pepe";
}
With Code Contracts we can write it like this:
private void DoSomething(CoolClass coolClass)
{
Contract.Requires<ArgumentNullException>(coolClass != null, "IS NULLL!");
coolClass.Name = "Pepe";
}
The second method is shorter and simpler. The problem that I have is that when you build it, in runtime it does not throw the exception, it shows this:
Description: An assembly (probably "CodeContractsTest") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.Requires and the CONTRACTS_FULL symbol is defined. Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild. CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. After the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane. Ensure that "Perform Runtime Contract Checking" is enabled, which will define CONTRACTS_FULL.
Unless with VS you download the CodeContracts for .net from here.
And then you check the "Runtime check" in the project, so that when you build it in runtime, the exception is thrown.
Our app is build with Jenkins with PowerShell scripts. Is there any way to check in runtime and throw the exception, with a simple command or attribute, or something easy?
By changing following project properties I could eliminate getting this exception while running.
Right click on project -> Properties -> Code Contract (Tab)
change the assembley mode to "Standard Contract Requires" also select checkbox - Perform Runtime contract checking
Why don't you just write your own version of the method, if you like the simplicity?
public class CustomContract
{
public static void Requires<TException>( bool Predicate, string Message )
where TException : Exception, new()
{
if ( !Predicate )
{
Debug.WriteLine( Message );
throw new TException();
}
}
}
Using Code Contracts just to have a friendly API sounds like shooting sparrows with a cannon.
I am trying to load dlls into my program at runtime that match a specific assembly attribute that I have set. In order to make sure that the dll is loadable before I check its flag I have written the following method:
private bool IsValidDll(string dll) {
try {
System.Reflection.Assembly.LoadFrom(dll);
return true;
} catch (Exception ex) { return false; }
}
I can loop through dlls in my current directory and call this method to see if it will be safe to load the dll and check its assembly attributes. However, I am hitting a dll that is not throwing/catching an Exception and is still just directly crashing the program. The relevant output window information is as follows:
LoaderException: System.IO.FileLoadException: Mixed mode assembly is built against
version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information. - Adapters.Spryware.SprywareAdapter
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
I have tried catching the specific Exception (System.IO.FileLoadException) but the catch block is still skipped over and I still crash. Any thoughts?
Also, I find that this is a pretty heavy handed way of checking for my assembly attribute. Is there a way to check for my flag without having to load the dll with Reflection first?
Have to confess, I dont see why your code doesnt work either:
I made a .net 4 thing and ran and mine did catch it:
private void button1_Click(object sender, EventArgs e)
{
// foreach (String file in Directory.GetFiles("c:\\windows", "*.dll"))
String file = #"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Data.dll";
{
try
{
//System.Reflection.Assembly.ReflectionOnlyLoadFrom(file);
System.Reflection.Assembly.LoadFrom(file);
}
catch (Exception ee)
{
textBox1.Text += ee.Message + Environment.NewLine;
}
}
}
On clicking the text box reads:
Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Data.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.
You can probably solve this problem and be less heavy handed by loading the assemblies into the reflection-only context.
Basically, instead of fully loading the assembly, this gives you the ability to reflect over the assembly without the ability to do things like instantiate objects. This expressly allows you to look at assemblies that are built against different .NET framework versions than the one on which your application is running.
A thorough treatment is available on MSDN: http://msdn.microsoft.com/en-us/library/ms172331.aspx
I have this weird problem that I cannot handle myself. A class in the model of my mvp-project designed as singleton causes an InvalidCastException.
The source of error is found in this code line where the deserialised object is assigned to the instance variable of the class: engineObject = (ENGINE)xSerializer.Deserialize(str);. It occurs whenever I try to add one of my UserControls to a Form or to a different UC. All of my UCs have a special presenter that accesses the above mentioned instance variable of the singleton class.
This is what I get when trying to add a UC somewhere:
'System.TypeInitializationException: The type initializer for 'MVP.Model.EngineData' threw an exception. ---->
System.InvalidCastException: [A]Engine cannot be cast to [B]Engine. Type A originates from 'MVP.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither'
at location '[...]\AppData\Roaming\Microsoft\VisualStudio\9.0\ProjectAssemblies\uankw1hh01\MVP.Model.dll'.
Type B originates from 'MVP.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither'
at location '[...]\AppData\Roaming\Microsoft\VisualStudio\9.0\ProjectAssemblies\u_hge2de01\MVP.Model.dll'
...
So I somehow have two assemblies and they are not accessed from my project folder, but from a VS temp folder? I googled a lot and only found this: IronPython Exception: [A]Person cannot be cast to [B]Person. There is a solution offered, but it concerns IronPhyton and I don't know where to use it within my project.
Types are per-assembly; if you have "the same" assembly loaded twice, then types in each "copy" of the assembly are not considered to be the same type.
These issues normally crop up when the two assemblies are in the Load and LoadFrom contexts. See
Difference between LoadFile and LoadFrom with .NET Assemblies?
and the link to suzcook's blog for details on that issue.
Also, consider using the fusion log viewer to help diagnose the problem.
http://msdn.microsoft.com/en-us/library/e74a18c4%28VS.71%29.aspx
Judging by the context in which the assembly is getting loaded (the context is "LoadNeither"), some developers may be doing something like loading an assembly that has been internally packaged as a resource with your application. If you do this, you will be using the AppDomain.CurrentDomain.AssemblyResolve event handler, so that your application can specify where .NET should get any particular assembly that it needs.
My answer will not explain the machinations of how to do that - but I'm mentioning it because this process led directly to the same exact error encountered by the original poster. As Eric Lippert mentions, types are per-assembly. So if you load an individual assembly more than once, the same defined class will appear as different classes - even though visual inspection shows that they appear to be the same.
We've seen instances in which .NET will call the ResolveEventHandler more than once for the same DLL. I'm not sure why .NET sometimes does this (it happened on some machines, but not all machines). But to resolve the problem, we needed keep a global list of handles to loaded assemblies, so that if .NET wanted to load the assembly again, we returned a handle to the same Assembly that was originally loaded, instead of loading another copy into memory.
I have included the code that caused the issue for us, and notes about how to handle it properly.
public void AppStartup (object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
public System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
dllName = dllName.Replace(".", "_");
if (dllName.EndsWith("_resources")) return null;
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
byte[] bytes = null;
try
{
bytes = (byte[])rm.GetObject(dllName);
}
catch (Exception ex)
{
}
if (bytes != null)
{
// the following call will return a newly loaded assembly
// every time it is called
// if this function is called more than once for the same
// assembly, you'll load more than one copy into memory
// this can cause the InvalidCastException
// instead of doing this, you keep a global list of loaded
// assemblies, and return the previously loaded assembly
// handle, instead of loading it again
return System.Reflection.Assembly.Load(bytes);
}
return null;
}
My situation involved two copies of the same dll. One was in the bin folder and one was in a sub-folder of the same bin folder. Both were loaded, amazingly some things worked fine, but some things didn't and that's when this error message appeared:
System.InvalidOperationException; There was an error generating the XML document.; Source: System.Xml; TargetSite: Void Serialize(System.Xml.XmlWriter, System.Object, System.Xml.Serialization.XmlSerializerNamespaces, System.String, System.String);
Hidden in this was the following inner exception (this was to do with Microsoft Dynamics CRM 4.0, but could relate to anything)
System.InvalidCastException; [A]XXX.CRMCustomCode.YYY.CreateCompanyRequest cannot be cast to [B]XXX.CRMCustomCode.YYY.CreateCompanyRequest. Type A originates from 'XXX.CRMCustomCode, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadFrom' at location 'C:\Program Files\Microsoft CRM\Server\bin\assembly\XXX.CRMCustomCode.dll'. Type B originates from 'XXX.CRMCustomCode, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Program Files\Microsoft CRM\Server\bin\XXX.CRMCustomCode.dll'.;
I simply deleted the duplicate dll (in C:\Program Files\Microsoft CRM\Server\bin) and the error went away.
My particular case - class library referenced in web application was renamed and rebuilt. Older version of library was still in bin folder under old name. The framework loads whatever in bin folder (both libraries) and emits this error. So it happens not only when assemblies are loaded explicitly.
The obvious solution in my case is to clean bin folder.
I got it working when I tried changing this cast:
var t = (TeacherWebPages)Session["TeachersAD"];
To this:
var t = Session["TeachersAD"] as TeacherWebPages;
However the assembly/session/memcache was different and no data got back but no error occurred. So later I still had to delete specific temporary files every time source page was changed from the folder it was complaining about which would require me to kill IIS process from task manager. Or in my case I can just logout and it clears the session state.