Xaml

A colleague of me is always pretty unsure what to set. So he always looks it up, so maybe one day he will find this post.. This is for you Fabian.

# Adding Themes to Xamarin.Forms App

I just want to make some short notes about themes in Xamarin.Forms Apps, since there are already a lot of tutorials available online, that go way deeper.

Themes
Themes are actually ResourceDictionaries. Each atomic type you use in your XAMLs and Styles, will be defined here. Types are f.e. Color, Double (for font sizes), etc.

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ShoppingList.Themes.DarkTheme">
<Color x:Key="BackgroundColor">#333333</Color>
<Color x:Key="TextColor">#eeeeee</Color>
<Color x:Key="PlaceholderTextColor">#55ffffff</Color>
<Color x:Key="ControlBackground">#111111</Color>
<Color x:Key="ButtonBackgroundColor">#11ffffff</Color>
</ResourceDictionary>


Be sure to have a code behind file for your ResourceDictionary, that calls InitializeComponent(). Otherwise this will only work on UWP (without .NET Toolchain) and no other platforms.

Styles
In most cases the styles are not part of your themes, because using themes just makes you change the look of your pages and controls, not the styling of specific controls. Perhaps styles are using the resources, that you define in your theme. Be sure to use DynamicResource for linking to the key of the resource, otherwise you can not change themes during runtime. (Restart will be needed)

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ShoppingList.Resources.Styles">
<Setter Property="BackgroundColor" Value="{DynamicResource BackgroundColor}"/>
<Setter Property="BarBackgroundColor" Value="{DynamicResource BackgroundColor}"/>
<Setter Property="BarTextColor" Value="{DynamicResource TextColor}"/>

</Style>
<Style TargetType="Label">
<Setter Property="TextColor" Value="{DynamicResource TextColor}" />
</Style>
<Style TargetType="Entry">
<Setter Property="BackgroundColor" Value="{DynamicResource ControlBackground}" />
<Setter Property="TextColor" Value="{DynamicResource TextColor}" />
<Setter Property="PlaceholderColor" Value="{DynamicResource PlaceholderTextColor}" />
</Style>
<Style TargetType="Button">
<Setter Property="TextColor" Value="{DynamicResource TextColor}" />
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonBackgroundColor}" />

</Style>
</ResourceDictionary>


Changing the theme
Now you just need to add the following code to your App.xam.cs, then you can just call App.SetTheme(typeof(DarkTheme)) to change the theme during runtime.

Be sure to add all your style-ResourceDictionaries and a standard theme to your App.xaml in the Application.Resources-Section

internal static void SetTheme(Type themeType)
{
Preferences.Set("Theme", themeType.FullName);
var resDict = (ResourceDictionary)Activator.CreateInstance(themeType);
App.Current.Resources.MergedDictionaries.Add(resDict); // this line replaces all keys of the current dictionary with the value of the selected dictionary, only the keys that are present in the selected dictionary will be replaced
}


In your “OnInitialize” method of your App.xaml.cs you can put the following code, to load the saved theme on startup:

if (Preferences.ContainsKey("Theme"))
{
var themeTypeName = Preferences.Get("Theme",null);
var themeType = Type.GetType(themeTypeName);
if (themeType != null)
{
SetTheme(themeType);
}
}


# CSC : error CS1703: Multiple assemblies with equivalent identity have been imported (iOS)

I recently encountered a problem compiling my Xamarin.Forms iOS project. Everything worked well when testing the UWP App during development, but when I tried to test the iOS project, the compiler threw the following error:

CSC : error CS1703: Multiple assemblies with equivalent identity have been imported (iOS)'[..]\packages\system.reflection.emit\4.3.0\ref\netstandard1.1\System.Reflection.Emit.dll’ and ‘C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\Xamarin.iOS\v1.0\Facades\System.Reflection.Emit.dll’. Remove one of the duplicate references.

Checking those two files mentioned, you’ll find out, that those have two different versions (nuget cache: 4.3.0, VisualStudio: 4.0.0), also the path (and file size) states, that the file from the VisualStudio folder is only a facade.

The solution is quite simple, just add a package reference to your project-file excluding all assets:

<PackageReference Include="System.Reflection.Emit" Version="4.3.0">
<ExcludeAssets>all</ExcludeAssets>
</PackageReference>


.. just add it in an ItemGroup block with other package references and you solved that issue.

# read and write properties on dynamic objects in .NET/C#

Ok, the headline sounds a little bit funny, because first of all, dynamic objects have no properties. Also you can not use reflection on a dynamic type, because it’s dynamic. What I actually want to do, is to access values of a dynamic object by its name – but I don’t know the name of the property on compile time, but during execution.

I want to do something like that:

dynamic obj = GetDynamicObject();
string myPropertyValue = DynamicExtension.GetValue(obj, "MyProperty");
DynamicExtension.SetValue(obj, "MyProperty", "some cool value");


So how can we do this? Reflection is not possible, and not all dynamic types impement IDictionary like ExpandoObject.

But how can we achieve this? By looking at the disassembled code, of a dynamic class, and the way it is accessed, we can find out, how we can access it ourself…

dynamic dynObj = new TestClass
{
TestProperty = "Hello World",
TestInt = 20
};
var val = dynObj.TestProperty;
dynObj.TestProperty = "Hello C#";


Because I don’t want to flood this post, I just copied the essentials from the IL. Basically there are 2 parts:
1. create a Binder
2. create a CallSite to execute the getter/setter.

// the getter
var binder = Binder.GetMember(
CSharpBinderFlags.None,
"TestProperty",
typeof(object),
new CSharpArgumentInfo[] {

CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.NamedArgument, null)
});

var getter = CallSite<Func>.Create(binder);
var val = getter.Target(getter,  dynObj);

// the setter
var setterBinder = Binder.SetMember(
CSharpBinderFlags.None,
"TestProperty",
typeof(object),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) });
// the IL actually uses string as value type, but we use object here, to be more flexible
var setter = CallSite<Func>.Create(setterBinder);
setter.Target(setter, dynObj, "Hello C#");



So now just wrap it up to our two functions:

    public static class DynamicHelper
{
public static object GetValue(object obj, string name)
{
var binder = Binder.GetMember(
CSharpBinderFlags.None,
name,
typeof(object),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(
CSharpArgumentInfoFlags.NamedArgument,
null)
});

var getter = CallSite<Func>.Create(binder);
return getter.Target(getter, obj);
}

public static void SetValue(object obj, string name, object value)
{
var setterBinder = Binder.SetMember(
CSharpBinderFlags.None,
name,
typeof(object),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) });
// the IL actually uses string as value type, but we use object here, to be more dynamic
var setter = CallSite<Func>.Create(setterBinder);
setter.Target(setter, obj, value);
}
}


# C# Creating Types during runtime (.Net Core)

This is really fancy stuff, no one would probably never ever get along doing this. And I actually have no real straight forward “all day” use-case, I would ever recommend this for. But guess what, there is always an exception.

### So why am I doing this?

My situation is the following: On one hand I have a database (actually a Realm.io database). I want to copy that Realm into another Realm, but I didn’t find a tool, doing that for me. Because that is an object oriented database, we need the model definitions right when opening the database, but I wanted to create a tool, to copy data from one realm to another, without actually knowing the class models at all. So there is a pretty neat construct called “DynamicRealm”, one can just open those by passing a parameter while opening the Realm called “IsDynamic”. Then I don’t need to have the actual classes in my code. When I then open an existing Realm, it shows me all information about the schema, that is stored in the database (properties, attributes, etc.)…

So far, so good, .. I can read data. But my destination Realm is absolutely blank, no schema, no data. And in .NET there is no method implemented to create my own schema. There is only one thing I can do – adding Types while opening the Realm, and Realm will take care of creating the schema. So I need to impement type-creation from the schema during runtime.

### Creating the type during runtime

But before we create a type, we need to create an Assembly and Module, that type is going to be in. Be careful to use names, that aren’t already used. There are 3 Builders we use from the assembly System.Reflection.Emit : AssemblyBuilder, ModuleBuilder, TypeBuilder . In fact this part is pretty easy:

var parent = typeof(BaseClass); // the type of the baselcass for this type (can be null)
var name = "MyCoolTypeName"; // name of the new type

// 1. create assembly name
var assemblyName = new AssemblyName(\$"SomeAssemblyName{name}");
// 2. create the assembly builder
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
// 3. that is needed to create a module builder
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
// 4. and finally our TypeBuilder (a public class)
TypeBuilder tb = moduleBuilder.DefineType(name,
TypeAttributes.Public |
TypeAttributes.Class
, parent);
Type type = tb.CreateType(); // of type Type, we can even create instances of that type


But when we want to create a real POCO we also need to add some properties to that type.

### Add properties to the created Type (TypeBuilder)

This is not as easy, as it sounds like. We have to be aware, what is actually needed to create a property:
1. a backing field
2. a get method
3. a set method
Since we are in runtime mode, we need to create the method bodys in IL (which is the byte code used by .NET), so we cannot use plain C#.
(Be careful: all this can only run on systems with JIT compiler, so you cannot do that in UWP (with .Net Toolchain active) or iOS, Mono should be fine, but I didn’t test it yet)

So how to find out what IL to use? Just create a TestClass and produce some IL (I prefer using dotPeek from JetBrains):

.method public hidebysig specialname instance string
get_Text() cil managed
{
IL_0000: ldarg.0      // this
IL_0001: ldfld        string RealmCopy.TestClass::'_backingField'
IL_0006: ret

} // end of method TestClass::get_Text

.method public hidebysig specialname instance void
set_Text(
string 'value'
) cil managed
{
IL_0000: ldarg.0      // this
IL_0001: ldarg.1      // 'value'
IL_0002: stfld        string RealmCopy.TestClass::'_backingField'
IL_0007: ret

} // end of method TestClass::set_Text


After that, we can just write down the code for adding a property to the TypeBuilder:

public static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
if (propertyType == null) // when the propertytype is null, we assume, it's the Type itself (so we set it to the TypeBuilder)
{
propertyType = tb;
}

if (propertyType == typeof(IList<>)) // same thing here for a IList with no generic type parameter -> we assume it's the type (we could probably do that for every generic type without type parameter)
{
propertyType = propertyType.MakeGenericType(tb);
}

FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private); //creates the backing field
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

//get method
MethodBuilder getMethod = tb.DefineMethod(
"get_" + propertyName
,MethodAttributes.Public
| MethodAttributes.SpecialName
| MethodAttributes.HideBySig
, /*returnType*/ propertyType
, /*parameter types*/ Type.EmptyTypes); // see IL for the right MethodAttributes
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
// create the code in the get method
getIl.Emit(OpCodes.Ldarg_0); //this
getIl.Emit(OpCodes.Ldfld, fieldBuilder); //backingfield
getIl.Emit(OpCodes.Ret);

// set method
MethodBuilder setPropMthdBldr =
tb.DefineMethod(
"set_" + propertyName,
MethodAttributes.Public
| MethodAttributes.SpecialName
| MethodAttributes.HideBySig
, /*returnType*/ null
, /*parameter types*/ new[] { propertyType }); // see IL for the right MethodAttributes

ILGenerator setIl = setPropMthdBldr.GetILGenerator();
// create the code in the set method
setIl.Emit(OpCodes.Ldarg_0); //this
setIl.Emit(OpCodes.Ldarg_1); // 'value'
setIl.Emit(OpCodes.Stfld, fieldBuilder); // backingfield

setIl.Emit(OpCodes.Nop);
setIl.Emit(OpCodes.Ret);

// add methods to the propertyBuilder
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}


# Problem with ResourceDictionary in Xamarin Forms .Net Native

Last week a colleague had the idea, to split the Resources, that we have defined in App.xaml in several ResourceDictionaries. Since our App.xaml has grown to over 400 lines, we thought this would be a very good idea, and did it as always:

 <Application.Resources>
<ResourceDictionary xmlns:local="clr-namespace:TestResources">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/Buttons.xaml" />
<ResourceDictionary Source="/Resources/Labels.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>


Looks good, and when we were testing the App, it worked well. But as soon, as we wanted to ship the App to our customer, it totally crashed during start up. What was the difference? We always test Debug builds, but without .Net Native
Toolchain active, but for shipping, we made a Release build with .Net Native builds activated.

The following error occured:

Unhandled exception at 0x05B6B264 (Windows.UI.Xaml.dll) in TestResources.UWP.exe: 0xC000027B: Anwendungsinterne Ausnahme (parameters: 0x0B477CF8, 0x00000003).

In the output window we see a lot of error messages:

Unhandled exception at 0x05B4B264 (Windows.UI.Xaml.dll) in TestResources.UWP.exe: 0xC000027B: internal error(parameters: 0x0B44D9B0, 0x00000003).

Unhandled exception at 0x777AF989 (combase.dll) in TestResources.UWP.exe: 0xC0000602: Ein sofortiger Ausnahmefehler ist aufgetreten. Die Ausnahmehandler werden nicht aufgerufen, und der Prozess wird sofort beendet.

Unhandled exception at 0x77627ED3 (combase.dll) in TestResources.UWP.exe: 0xC0000005: Access violation reading location 0x00000008.

I am not quite sure, why this happens but the solution is quite simple:

• Add a code behind file (in our case Buttons.cs).
• In the constructor, call “InitializeComponent()”.
• Now we can include the ResourceDictionary directly in the App.xaml
• In our case the Buttons.xaml.cs looks like this:

   public partial class Buttons : ResourceDictionary
{
public Buttons()
{
InitializeComponent();
}
}


..and the App.xaml

<Application.Resources>
<ResourceDictionary xmlns:local="clr-namespace:TestResources">
<ResourceDictionary.MergedDictionaries>
<local:Buttons />
<!--<ResourceDictionary Source="/Resources/Buttons.xaml" />-->
<!--<ResourceDictionary Source="/Resources/Labels.xaml" />-->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>


If you have a clue, why we need to go this way, just leave me a comment.

# Error 0xC000041D using GetCallingAssembly()

Reflection is very cool, the meta data system of .Net is pretty cool. You can create objects of a given class, without knowing it at compile time, by just looking it up and instantiating it using reflection. But how can I look up a type? Some times you only know the name of a type you want to create, without knowing the correct assembly. Let’s say we have an assembly, that holds a service implementation to create a object:

class MyService
{
object GetObject(string typeName)
{
}
}


The class we want to create, is in the assembly from where that function gets called. That is ok, but we don’t know that assembly at compile time, we can only find it out, when the function gets called. But how?

The regular solution would be, to use System.Reflection.Assembly.GetCallingAssembly(). But when we do this in .Net Nativ, we get an exception at runtime:

Unhandled exception at 0x78A7B264 (Windows.UI.Xaml.dll) in BlankApp3.UWP.exe: 0xC000027B

I think this is a bug within the .Net native compiler. But how can we find a workaround for that problem?

## 1. using a fully qualified type name

object GetObject(string typeName)
{
var type = Type.GetType(typeName);
return Activator.CreateInstance(type);
}


You can then actually use the complete name, including the namespace, when calling the function. (Something like: GetObject(“BlankApp3.Views.MainPage”)), so it’s not possible to lookup a type by name. But for our use case, it is enough.

## 2. lookup the assembly by name

object GetObject(string assemblyName, string typeName)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembly = assemblies.FirstOrDefault(asm =>
asm.GetName().Name.Equals(assemblyName));
var type = assembly.GetTypes().FirstOrDefault(t =>
t.Name.Equals(typeName));
return Activator.CreateInstance(type);
}


This is the most flexible solution in our case (but it takes more time). You can even look through all loaded assemblies, and find types by name. Please be aware that there is another bug, preventing you from getting all types from all loaded assemblies (the solution can be found on stackoverflow).