How-to: Load a type from a referenced assembly at runtime using a string in Silverlight - silverlight

I have tried this, specifying the assembly name:
Type.GetType(string.Format("{0}.{1}, {0}", typeToLoad.AssemblyName, typeToLoad.ClassName));
Which throws the following:
The requested assembly version conflicts with what is already bound in the app domain or specified in the manifest
Trying the same without including the trailing assembly name like this:
Type.GetType(string.Format("{0}.{1}", typeToLoad.AssemblyName, typeToLoad.ClassName));
-- returns null.
So, I am looking for a way to instantiate a class by providing its fully qualified name in Silverlight 4.0.
Any ideas would be greatly appreciated, Thanks.

I had the same issue and it worked when I tried the assembly qualified type name in the following format :
", , Version="", Culture=, PublicKeyToken="

Related

Installing Static Data Types with Dependencies via Package

I've developed a package that contains two static data types (IClient and IClientHour). One of the static data types (IClientHour) has a dependency on the other static data type (IClient).
I'm attempting to add the data types to my instance of Composite C1 via a package. I would like to leverage the DataTypePackageFragmentInstaller and DataTypePackageFragementUninstaller classes to register and drop my data types with the package.
The problem I'm facing is that the package is failing to validate and spits out the following error:
Failed to build data type descriptor for interface
'Builders.Data.IClientHour' The type 'Builders.Data.IClient' could not
be found.
Both types are in a DLL that I am copying to the CMS via the FilePackageFragmentInstaller. In searching the Composite C1 forum I found a suggestion of adding assemblyLoad="true" to the File element for the assembly that contains the types. This suggestion did not solve the issue I'm facing.
Below is a condensed version of my install.xml displaying the sections related to the data types and assembly:
<mi:PackageFragmentInstallers>
<mi:Add installerType="Composite.Core.PackageSystem.PackageFragmentInstallers.FilePackageFragmentInstaller, Composite" uninstallerType="Composite.Core.PackageSystem.PackageFragmentInstallers.FilePackageFragmentUninstaller, Composite">
<Files>
<File sourceFilename="~\Bin\Builders.dll" targetFilename="~\Bin\Builders.dll" allowOverwrite="false" assemblyLoad="true" />
</Files>
</mi:Add>
<mi:Add installerType="Composite.Core.PackageSystem.PackageFragmentInstallers.DataTypePackageFragmentInstaller, Composite" uninstallerType="Composite.Core.PackageSystem.PackageFragmentInstallers.DataTypePackageFragmentUninstaller, Composite">
<Types>
<Type name="Builders.Data.IClient, Builders" />
<Type name="Builders.Data.IClientHour, Builders" />
</Types>
</mi:Add>
</mi:PackageFragmentInstallers>
Any assistance/suggestions with accomplishing this task is greatly appreciated.
After asking the same question on CodePlex, wysocki and burningice were able to lead me in the right direction to correct the issue that I was facing.
In a nutshell, I had used a string to reference the type of my IClient data type from the IClientHour data type. If you use a string you must also include the Assembly name in the reference (e.g. Builders.Data.IClient, Builders).
As per Composite C1 examples and burningice's guidance you should avoid using a string and instead reference your foreign key using typeof.
Here is an example of how I orginally tried to reference my data type:
[ForeignKey("Builders.Data.IClient", AllowCascadeDeletes = true,
NullReferenceValue = "{00000000-0000-0000-0000-000000000000}")]
Here is how I should have referenced it using a string:
[ForeignKey("Builders.Data.IClient, Builders", AllowCascadeDeletes =
true, NullReferenceValue = "{00000000-0000-0000-0000-000000000000}")]
Per Composite C1 examples and guidance from burningice this is how you should reference another data type (Note: when using this method you must also include the name of the field that you wish to use in the relationship):
[ForeignKey(typeof(Builders.Data.IClient), "Id", AllowCascadeDeletes =
true, NullReferenceValue = "{00000000-0000-0000-0000-000000000000}")]
References:
CodePlex Forum Thread: http://compositec1.codeplex.com/discussions/652976
Composite Documentation: http://docs.composite.net/Console/Static-IData-Types/Example2

XAML How to get a project name

Im learning XAML with microsoft visual studio 2013 wpf application.
I want to make a textblock display my Project Name from a some kind of resource(?) - I want to make a template :) .
Thank you for help in advance :) .
string name = Assembly.GetEntryAssembly().GetName().Name;
or
string name = Assembly.GetExecutingAssembly().GetName().Name;
Alternatively, you can get the Assembly object from any known type in the assembly:
Assembly assy = typeof({class name here}).Assembly;
This also allows another option to get the the name only:
string name = typeof({class name here}).Assembly.GetName().Name;
Here's the link

Can't find file with UserControl but not (in this case) Label

I have a UserControl in a the DLL Controls, a converter in the DLL Base and language resources in the DLL Languages.
When I combine everything the following way, everything works fine:
<Label Content="{Binding FallbackValue='[Design] Name', ConverterParameter='Name', Converter={StaticResource Translate}}"
ContentStringFormat="{}{0}:"/>
No errors and when I run my application the correct word for the parameter Name is loaded (in my case Naam for Dutch).
I also try this on my WatermarkTextBox like this:
<c:WatermarkTextBox Watermark="{Binding FallbackValue='[Design] Name *', ConverterParameter='Name', Converter={StaticResource Translate}}" />
But then I get the following error:
Could not load file or assembly 'file:///C:...\Languages.dll' or one of its dependencies. The system cannot find the file specified.
Why does this happen with my WatermarkTextBox in Controls DLL and not with the Label?
The first step here is to make sure, that the assembly file Languages.dll is actually present in the application directory (usually, bin/Debug/). If it isn't - as the error message says - the system cannot find the file specified... The solution in this case is to reference the assembly Languages.dll in your application project. To avoid this, make sure that every time you add a reference to an assembly, you also add references to this assembly's dependencies. I.e. if you have an application project App which references a library LibA.dll and LibA references a library LibB.dll, you should add a reference to LibB.dll in your App project as well. That way, all required assemblies will always be copied to the output directory.
If the assembly is correctly located in the output directory, but you still get the error message, in 99% of the cases the problem is a mismatch in the building targets, alas the platform for which the assemblies were built. Make sure all projects target the same platform (x86, for example). You can check the target in the projects Properties tabs.
EDIT:
Ok, I just now understood you're talking about the design time error in Visual Studio's XAML Designer :) The issue is the name of the assembly: Noru.Languages.dll. I suppose, the ending .Languages is considered a resource name and Visual Studio prohibits resource names in assembly names. There's a registry entry HKLM\Software\Microsoft\VisualStudio\12.0\Designers\AllowResourcesInFilename, maybe experimenting with that can resolve the issue. Not 100% sure, though. Anyway, if you rename the assembly to Nori.Language.dll in the project's properties and rebuild everything, design time support is back and the controls show up correctly in the designer.
EDIT 2:
Really strange behavior altogether... Well, this line in the Class Language might very well be the cause? Try specifying the full string here... Does this work?
ResourceManager rm = new ResourceManager("Noru.Languages.Language", System.Reflection.Assembly.LoadFrom("Noru.Languages.dll"));
EDIT 3:
Obviously, the problem was the line I mentioned above in Edit 2. I've experimented a bit:
/// <summary>
/// Will return the requested text in the language the application is in. Case sensitive.
/// </summary>
/// <param name="s">Provide a listed String from the language files.</param>
/// <returns>Will return a System.String in the language of the application.</returns>
public static string GetText(string s)
{
//return Culture.ToString();
//return Assembly.GetExecutingAssembly().FullName;
//ResourceManager rm = new ResourceManager("Noru.Lang.Resource1", Assembly.GetAssembly(typeof(Language)));
//ResourceSet rs = rm.GetResourceSet(Culture, true, true);
var rs = LanguageResource.ResourceManager;
try
{
return rs.GetString(s);
}
catch (Exception)
{
return "not found";
}
}
The last version (not commented out) works, because I've generated code for the resource files by setting AccessModifier to public in the resource editor (double click on the resource file, you'll find it in the toolbar).
This version (never mind about the resource name, I tried different versions here):
ResourceManager rm = new ResourceManager("Noru.Lang.Resource1", Assembly.GetAssembly(typeof(Language)));
threw another error, saying it cannot find the resource inside the assembly. I think there was something wrong about the usage of ResourceManager here. I'm not an expert here, so I can't tell why. I just know that the last version seems to work as expected... I hope, you'll find the same ;)

Reflection error when using F# sprintf "%A" on Windows Phone

I have a set of F# record types like this:
type Course =
{ Id : int
Title : string
Instructor : string
Duration : string
StartDate : string
IconUrl : string
Url : string
LectureSections : LectureSection list }
and LectureSection =
{ Title : string
Completed : bool
Lectures : Lecture list }
and Lecture =
{ Title : string
VideoUrl : string }
and at some point I call
sprintf "%A" course
where course is an instance of the Course record
On a regular .NET project this works fine, but on a Windows Phone 7.1 / Silverlight 4 F# project (I'm using Daniel Mohl's templates), I get this error:
Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
The problem seems to be the lists. Does anyone know of any way around this problem?
The templates should come with a custom built FSharp.Core.dll that disable features that are not available on Windows Phone. Are you sure you are compiling against this dll, and not the Windows PC one?
I had similar problems with Xbox360 and XNA. The F# team sent me a dll suitable for use for the Xbox360, along with some brief instructions on the settings used to build the dll.
Here is the propertygroup we've used to compile FSharp.Core:
<PropertyGroup Condition="'$(TargetFramework)'=='Xbox360\CompactFramework\3.7'">
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<XnaFrameworkVersion>v4.0</XnaFrameworkVersion>
<XnaPlatform>Xbox 360</XnaPlatform>
<XnaProfile>HiDef</XnaProfile>
<XnaCrossPlatformGroupID>a8d70e6b-9a75-4aec-80f8-62cf373f7368</XnaCrossPlatformGroupID>
<XnaOutputType>Game</XnaOutputType>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DefineConstants>$(DefineConstants);FX_NO_ARRAY_LONG_LENGTH;FX_NO_DEBUG_PROXIES;FX_NO_EXIT;FX_FSLIB_IOBSERVABLE;FX_NO_WEB_CLIENT;FX_NO_WEB_REQUESTS;FX_NO_CHAR_PARSE;FX_NO_DEFAULT_DEPENDENCY_TYPE;FX_SIMPLE_SECURITY_PERMISSIONS;FX_NO_TRUNCATE;FX_NO_CULTURE_INFO_ARGS;FX_NO_REFLECTION_MODULE_HANDLES;FX_NO_OPERATION_CANCELLED;FX_NO_TO_LOWER_INVARIANT;FX_NO_EXIT_CONTEXT_FLAGS;FX_NO_BASED_ARRAYS;FX_NO_DOUBLE_BIT_CONVERTER;FX_NO_BINARY_SERIALIZATION;FX_NO_ASCII_ENCODING;FX_NO_DEFAULT_ENCODING;FX_NO_FILE_OPTIONS;FX_NO_NONBLOCK_IO;FX_NO_COMMAND_LINE_ARGS;FX_NO_ENVIRONMENT;FX_NO_PROCESS_START;FX_NO_APP_DOMAINS;FX_NO_PROCESS_DIAGNOSTICS;FX_FSLIB_STRUCTURAL_EQUALITY;FX_FSLIB_LAZY;FX_FSLIB_TUPLE;FX_NO_REFLECTION_EMIT</DefineConstants>
<Tailcalls>false</Tailcalls>
<!-- It would be better to use MSBuild resolution here, but the TargetFrameworkIdentifier etc. aren't set up quite correctly as yet -->
<OtherFlags>$(OtherFlags) --simpleresolution -r:"C:\Program Files\Microsoft XNA\XNA Game Studio\v4.0\References\Xbox360\mscorlib.dll"</OtherFlags>
</PropertyGroup>
and the new .targets we use:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\XNA Game Studio\Microsoft.Xna.GameStudio.targets" Condition="'$(TargetFramework)'=='Xbox360\CompactFramework\3.7'"/>
The dll they sent me was working fine, and I never had to use these instructions, but they might be useful to someone who wants to build an FSharp.Core.dll for a new platform. Note in particular the DefineConstants part.

Array[Nothing with java.lang.Object] required in Scala 2.9.1

I have a weird compilation error. The offending lines are:
val comboBoxLanguage = new javax.swing.JComboBox
//...
comboBoxLanguage.setModel(new javax.swing.DefaultComboBoxModel(
Array[Object]("Scala", "Java")))
and the error:
error: type mismatch;
found : Array[java.lang.Object]
required: Array[Nothing with java.lang.Object]
Note: java.lang.Object >: Nothing with java.lang.Object, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Nothing with java.lang.Object`. (SLS 3.2.10)
comboBoxLanguage.setModel(new javax.swing.DefaultComboBoxModel( Array[Object]("Scala", "Java")))
According to JavaDoc the constructor of DefaultComboBoxModel expects an Object[], which can be a String[] or whatever array type in Java, since arrays are covariant, but in Scala they are not, so we have to use Array[Object], which shouldn't be a problem.
Why is the compiler expecting Array[Nothing with java.lang.Object]? How can I fix it?
This seems to be new with version 2.9.1 of Scala. My application used to compile until I installed 2.9.1 a couple of days ago. A confusing / worrying thing is that I haven't changed the project compiler library version in IntelliJ, but somehow it seems to be using it, perhaps grabbing it from my SCALA_HOME environment variable?
I think it is not an issue of scala 2.9.1 but new JDK. In JDK7 JComboBox is generic and in your code it is JComboBox[Nothing]. You should explicitly declare comboBoxLanguage variable as
val comboBoxLanguage = new javax.swing.JComboBox[Object]

Resources