Strong typing DisplayAttribute reference to Resources

Let’s say there is a decorated member with DisplayAttribute in code, i.e.:

public enum SomeEnum
{
	[Display(Name = "ResourceKey", ResourceType=typeof(Resource)]
	SomeValue
}

That’s all right except for one problem. If Name is mistyped or given resource key is latter changed then DisplayAttribute will point to an incorrect value and compiler won’t help. Resources designer doesn’t help as well, at least indirectly, because it doesn’t generate externally usable key names. It generates strong typed getters though, like:

internal static string ResourceKey {
        get {
             return ResourceManager.GetString("ResourceKey", resourceCulture);
        }
}

So, these getters are the only strong typed artifact that can be used to achieve strong typed reference. Luckily there is one C# (also VB) feature that was introduced in 6.0 and it is very useful in improving strong typed aspect of code. it is nameof keyword. it is evaluated at compile time and replaces the given expression with a string representation.

In other words, the sample above can be rewritten in strong typed manner:

public enum SomeEnum
{
	[Display(Name = nameof(Resources.ResourceKey), ResourceType=typeof(Resource)]
	SomeValue
}

This way the name is guaranteed to match since it is checked at compile time. So, no more mismatch between the key name and reference to it.

Of course, nameof can be used in many other places. Most notably in INotifyPropertyChanged/MVVM scenario.

Fixing connection problems between Visual Studio and Mac when building iOS applications

I’ve been digging a bit into problems of connection between Visual Studio (Xamarin.iOS) and a Mac and wanted to share a few tips here.

It all started with my Visual Studio being unable to build an iOS application due to the connection issues. Basically I could connect through Xamarin Mac Agent (XMA) through Visual Studio but then the build would fail saying that it couldn’t log to target Mac given my username.

For starters one might read Connecting to the Mac and Connection Troubleshooting topics. But my problem wasn’t listed there or anywhere else. So I had to figure it out on my own.

First hint was that XMA required me to type in the username/password for connecting to the Mac. It connected and I could show the iOS simulator but I couldn’t build. When configured properly it shouldn’t ask for credentials, perhaps only for the first time. For me it was asking for credentials each time I started Visual Studio.

After reading, digging and googling I understood that XMA is using SSH tunnel to connect to the Mac. First thing was inspecting the log files (VS Help/Xamarin/Open Logs…). I didn’t find much there (other than failed connection to the host lines), or so I thought. Next thing was – checking the SSH connectivity (command prompt, ssh username@host). Using my default private key I had no problems connecting to the Mac but Visual Studio kept failing the build process. Next thing to try was Xamarin’s own SSH diagnostics app (provided as C# sources – kudos) which would throw Permission Denied (publickey) upon Connecting to host. Since the public key is on host, the problem obviously has to do with the host – but why since it was working from command prompt. Using this app I also found out what private key is XMA using. And it isn’t my default one, which I tested the connection with.

The thing is that XMA is using its own private key which you can find it at %LocalAppData%Xamarin/MonoTouch/id_rsa. So next thing I tried was connecting through command prompt/ssh using –i PATH argument (forces what key is used), i.e. (replace %LocalAppData% with value) ssh –i %LocalAppData%Xamarin/MonoTouch/id_rsa user@host. And yes, it didn’t work. So definitely a key issue.

The solution

Time for looking at Mac, specially in file /Users/username/.ssh/authorized_keys  where public keys for my profile are stored. And as anybody would guess, it was missing Xamarin’s public key. To get one from the private key I used Puttygen (a part of PuTTY): imported XMA’s private key and copy & pasted the public key portion right into the new line of authorized_keys file on Mac (I had my default public key already in there). This time the ssh command line tool connected without problems. And so did XMA from Visual Studio. Happy me.

The cause

This let me thinking, why does it usually works without intervention. After further examination of log files, it was clear. XMA first tries using its private key, if it doesn’t succeed it tries to cat the public key portion to authorized_keys file on Mac (probably using the credentials you have to enter ). But what happens if the authorized_keys file is read-only? Ha, nothing, a log entry and that’s it. This was my case, I had authorized_keys file as read only. I wouldn’t mind a clear warning: “hey dude, XMA was unable to modify your authorized_keys file, please enter this public_key manually”. It’d certainly spared me some time.

The security considerations

Let me repeat what happens when first time connecting to Mac. XMA would create a private key and put its public part into authorized_keys on Mac. Were you aware of that? No? Neither was I. To make things complicated, the private key in question isn’t password protected. Theoretically an app that user runs (no admin privileges required) could use the key (or worse, copy it through the Internet) to connect to your Mac and gain your credentials on the Mac, which are most probably administration ones. It still would have to type in password for su access, but nevertheless, this isn’t something that should be taken easily IMO.

I certainly wish that the connection mechanism was better documented and people were aware what’s going on. If nothing else, we could pinpoint the problems more easily. Also, an option to use password protected private key would be much more secure.

Use async keyword only when required

While async keyword is very useful it shouldn’t be used when it isn’t required. Imagine this method

public async Task DoSomethingAsync()
{
	await Task.Delay(1000);
}

The method works but it has too much code generated unnecessarily. The thing is that async triggers a lot of code generation at compile time that is invisible at design time. When using .Net Reflector, compiled code looks like:

[AsyncStateMachine(typeof(<dosomethingasync>d__1)), DebuggerStepThrough]
public Task DoSomethingAsync()
{
	<dosomethingasync>d__1 stateMachine = new lt;dosomethingasync gt;d__1 {
		<>4__this = this,
		<>t__builder = AsyncTaskMethodBuilder.Create(),
		<>1__state = -1
	};
	stateMachine.<>t__builder.Start<<dosomethingasync>d__1>(ref stateMachine);
	return stateMachine.<>t__builder.Task;
}

[CompilerGenerated]
private sealed class lt;dosomethingasync>d__1 : IAsyncStateMachine
{
	public int <>1__state;
	public Program <>4__this;
	public AsyncTaskMethodBuilder <>t__builder;
	private TaskAwaiter <>u__1;

	private void MoveNext()
	{
		int num = this.<>1__state;
		try
		{
			TaskAwaiter awaiter;
			if (num != 0)
			{
				awaiter = Task.Delay(0x3e8).GetAwaiter();
				if (!awaiter.IsCompleted)
				{
					this.<>1__state = num = 0;
					this.<>u__1 = awaiter;
					Program.<dosomethingasync>d__1 stateMachine = this;
					this.<>t__builder.AwaitUnsafeOnCompleted gt;taskawaiter program.="" ,=""><dosomethingasync>d__1>(ref awaiter, ref stateMachine);
					return;
				}
			}
			else
			{
				awaiter = this.<>u__1;
				this.<>u__1 = new TaskAwaiter();
				this.<>1__state = num = -1;
			}
			awaiter.GetResult();
			awaiter = new TaskAwaiter();
		}
		catch (Exception exception)
		{
			this.<>1__state = -2;
			this.<>t__builder.SetException(exception);
			return;
		}
		this.<>1__state = -2;
		this.<>t__builder.SetResult();
	}

	[DebuggerHidden]
	private void SetStateMachine(IAsyncStateMachine stateMachine)
	{
	}
}

I won’t dig into what’s actually generated at this point, but while this code is perfectly functional and correct, it is all for nothing in this simple case. Since the only asynchronous operation is the last one, the original method can be easily rewritten as:

public Task DoSomethingAsync()
{
	return Task.Delay(1000);
}

This way it works the same except for the missing pile of generated code.

So, when there is a single asynchronous operation inside the method and no code is executed after it, the async (and await) keyboard can be omitted and you’ll save yourself from too much unnecessarily generated code plu the application will run a bit faster.

Porting a .net application to Linux/Mono/MonoDevelop

I have a small .net application that I wanted to run on Linux since it is a deamon/service sort of app. Basically is an app that peridically retrieves data from a REST service and stores it to a PostgreSQL database using LLBLGenPro 5.0 CTP2. So I created a .net 4.6.1 console application that uses HttpClient/ModernHttpClient package, NLog package for logging and System.Collections.Immutable package for immutable collecitons obviously. That was on Windows using Visual Studio 2015. After I added all the necessary code it run perfectly well on Windows.

Then I tried to open the same solution on Linux. I cloned the repository and opened it in MonoDevelop 5.10/Mono 4.2.1 (both latest). And it didn’t work out of the box. I stumbled over several issues I will describe here.

.net version

MonoDevelop doesn’t work with anything over .net 4.5 for the time being due to the MSBuild thing – at least that was the complaint.

Hence I downgraded my project to .net 4.5. No problems since I didn’t use anything .net 4.6ish.

System.Collection.Immutable

It won’t install System.Collection.Immutable package because System.Linq package (which System.Collection.Immutable depends on for some reason) won’t install unless NuGet Package Manager is 3.0 or newer. MonoDevelop uses NuGet Package Manager 2.8.7. While this is only a NuGet Package installation issue, it is annoying. First, because System.Collection.Immutable doesn’t really require System.Linq package on Mono/.net 4.5 and next becuse it isn’t smooth as it should be. Funny thing is that at NuGet web page it says that System.Collection.Immutable requires NuGet 2.8.6 or higher. I guess it should be 3.0 or higher since a package that it depends on requires it.

Hence I dropped System.Collection.Immutable package which wasn’t difficult because I wasn’t using it extensively. Hopefully MonoDevelop catches up with NuGet and that is fixed.

HttpClient/ModernHttpClient

ModernHttpClient speeds up communication since it uses native networking libraries. However it won’t work on Linux.

Dropped it since it doesn’t affect the functionallity at all.

NLog

I had configure NLog though nlog.config file. And it works on Windows perfectly. Hower when run on Linux I didn’t get any output whatsoever. Just like there was no configuration file. As a Windows guy I was a bit puzzled why. Since NLog is open source, I downloaded the code and tried debugging. Sadly MonoDevelop didn’t allow me to step into NLog code for some reason but luckily old school “Console.WriteLine” approach worked as usual. After some strategically placed Console.WriteLine calls within NLog library I found the reason, which might be apparent to a Linux guy. Bloody file name casing. I was using nlog.config and Windows doesn’t care about file name casing.

On Linux file name casing does and thus changing the name to NLog.config did the trick.

Linux specific addition

If app wants to gracefully handle SIGTERM signal (like when somebody/something tries to kill it) it might use UnixSignalWaiter NuGet package. While only at version 0.0.1 it seems to work just fine. It is also safe to use it on non-Linux systems where it does nothing (one might also check whether the feature is supported).

Conclusion

If .NET Core has proper database support (PostgreSQL in my case, but more more importantly LLBLGenPro doesn’t work due to lack of ado.net support – I don’t know about you but for me the proper ado.net stack on server is one of the most important aspects) I’d try to use it as well. But since it doesn’t, well, someday in the future I guess.

Anyway, after learning all the problems and the workarounds above I feel more confident in my Mono/Linux skills and the application compiles fine and works as expected. I also think that Xamarin/mono guys are doing really great job. Kudos.

Did I mention that I’m using Docker to run the application? I guess that’s a topic for a future post.

TwoWay binding trap on Windows Store apps

Imagine having a TextBox bound to a viewmodel’s property in a TwoWay mode. In between a converter that does possibly an asymmetric conversion – in this case the text is uppercased (it should do for this demo).

Like this:

<StackPanel>
    <StackPanel.Resources>
        <local:UppercaseConverter x:Key="cnv" />
    </StackPanel.Resources>
    <TextBox Text="{Binding Text, Mode=TwoWay, Converter={StaticResource cnv}}" Margin="0,60,0,0" />
    <TextBlock Text="{Binding Text, Mode=OneWay}" />
    <Button Content="Test" Click="Button_Click" />
</StackPanel>

Below is an additional TextBlock for feedback and a button that assigns a value to the property bound.Here is the WPF converter (Windows Store version has a slightly different method signature)

public class UppercaseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;
        else
            return ((string)value).ToUpper();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}

and the viewmodel with a single property and INPC implementation:

public class Tubo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string text;
    public string Text
    {
        get
        {
            return text;
        }
        set
        {
            if (text != value)
            {
                text = value;
                OnPropertyChanged("Text");
            }
        }
    }

    protected virtual void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, 
                new  PropertyChangedEventArgs(name));
    }
}

Finally the code behind the XAML page:

public partial class MainWindow : Window
{
    private Tubo source;
    public MainWindow()
    {
        InitializeComponent();
        source = new Tubo();
        DataContext = source;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        source.Text = "Tubo";
    }
}
Everything is pretty much straightforward. The instance of Tubo is created and assigned as DataContext. On button click a value is assigned to Tubo’s Text property. Binding picks up the PropertyChanged notifications and displays the UppercaseConverter converted value in TextBox and a raw value in TextBlock.

Now the question. What will be the two values displayed in a WPF application and in a Windows Store application after pressing the Test button? Can you guess?

I’d expect TUBO (uppercased) in TextBox and tubo in TextBlock since there is no conversion applied and user didn’t change anything.

And that’s the case with the WPF application. But the surprise result comes from Windows Store application. It shows both values as uppercased. It gets even worse, this behavior isn’t consistent, more on this later.

What actually happens is that Windows Store app (who invented that name anyway) TwoWay binding does both directions on value change: it picks the modified value from viewmodel and immediately stores it back into viewmodel. So without any user intervention the uppercased value is stored in viewmodel. Nasty I’d say.

But it gets worse. This behavior is only for visible UIElements. In other words, if the TextBox isn’t visible (Collapsed) at property change time it will act like expected, just pick the value from viewmodel but it won’t write it back to viewmodel.

The combination of both might result in edge case bugs one would really not expect and might not be caught easily.

Luckily there is a workaround. The source updating has to be done manually by

  1. Setting Binding’s UpdateSourceTrigger=Explicit
  2. Implementing own logic when to update the source (this might be tricky)

Here is how one does update the source in an overriden TextBox (better to create a Behavior though).

BindingExpression be = GetBindingExpression(TextProperty);
if (be != null)
{
    be.UpdateSource();
}

NCrunch and SQLite testing problem and solution

I have some NUnit tests on .net 4.5.1 class library against PCL and both use SQLite.Net PCL, the former uses its Win32 platform.
When running from a test runner (like CodeRush Unit Test Runner) it works just fine.
But NCrunch would throw an exception when trying to create a SQLiteConnection instance:

            path = Path.GetTempFileName();
            connection = new SQLiteConnection(new SQLitePlatformWin32(), path);  // exception thrown here

SetUp : System.TypeInitializationException : The type initializer for 'SQLite.Net.Platform.Win32.SQLiteApiWin32Internal' threw an exception.
  ----> System.Exception : Failed to load native sqlite library


I've found out that this behavior is due to the missing Interop assemblies that aren't copied by NCrunch by default (x64 and x86 folder in bin\Debug folder) to optimize the unit testing process.

Hence adding these two folders to "Additional files to include" NCrunch project configuration property does the trick - that way NCrunch will include the missing assemblies.

Find more info about troubleshooting missing files when NCrunching here.

A hidden bug in Windows Store’s ComboBox

Since some time ago I’ve been using Immutable Collections as much as I could due to their immutability contract – nothing ever changes. So far so good, but today I’ve stumbled upon an odd and occasional (at least at beginning) bug with Windows Store/8.1 ComboBox bound to an ImmutableList<T> through ItemsSource property.

I was sporadically seeing crashes in application mostly when ComboBox was somehow in between changes on the page. The random crashes is really the worst type of problem one can imagine. The Exception wasn’t saying much but it put me on the right track. It said that it couldn’t cast ComboBoxItem to T (of which ImmutableList I was using) in ImmutableList<T>.IList.IndexOf(object item) method.

Luckily I’ve found a way to crash it easily – just fill more than 10 items as ItemSource, focus ComboBox and press up or down. It would crash after 5 or so changes each time. Being able to repro the problems asap and 100% reliable is a big benefit. Huge actually.

Then I’ve exprerimented with a normal List<T> instead of an immutable one and it worked without any problem. Odd, I thought.

Now, luckily Immutable Collections are open source on github as a part of corefx. I was being ready for a pull request if I could fix the bug. I was cloning the repository in no time and then tried to reference sources instead of NuGet package. There were two obstacle on my way:

  1. The version of Immutable Collections in corefx is using .net 4.5 which is not a good framework for a Windows Store app. Hence I created a blank Windows Store library and copied all sources there. That worked almost perfectly.
  2. Exceptions were using localized strings from a static class SR which I really didn’t have time to figure out where it comes from. I merely commented out these exceptions and replaced them with new Exception();

At this point the project compiled and I was ready to debug with sources. And soon it stopped in the offending method: ImmutableList<T>.IList.IndexOf(object item). The thing is that ComboBox was passing an ComboBoxItem (even though I was using items of type T) and ImmutableList<T> doesn’t care to fail softly when it gets an incompatible item type (note that IList isn’t generic). As, I discovered later, is the case with List<T>: it would return –1 when an incompatible type is passed whereas ImmutablList<T> would just crash.

 

However, I figured out that this is not a problem of ImmutableList<T> but of rather poor implementation of ComboBox in Windows Store (and perhaps of other similar types). Now, to make it worse, there are no sources for Windows Store ComboBox since it is a C++ dude and is virtually unfixable in the time I’d need the fix if I were to report the error somehow.

So the only solution for the time being is to switch to List<T> and avoid ImmutableList<T> even though it doesn’t mutate ever.

You’ve been warned!

 

Here is the repro code, just create a Windows Store app, get ImmutablCollections from NuGet and paste this xaml:

<ComboBox x:Name="combo" VerticalAlignment="Center" FontSize="70" Width="500"
           SelectedValue="{Binding ItemId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Id">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Text}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

and this codebehind:

public sealed partial class MainPage : Page
    {    
        Tubo tubo;
        public MainPage()
        {
            this.InitializeComponent();
            List<Item> items = Enumerable.Range(1, 20)
                 .Select(i => new Item { Id = i, Text = i.ToString() }).ToList();
            tubo = new Tubo();
            tubo.ItemId = 5;
            DataContext = tubo;

            combo.ItemsSource = items.ToImmutableList();
        }
    }

public class Item
{
    public int Id { get; set; }
    public string Text { get; set; }
}

public class Tubo
{
    public int ItemId { get; set; }
}
Update: I've checked with Windows 10 preview and VS2015CTP and the same bug is still there. Yuck.

(Android) Emulator on Hyper-V

An apparently great news is that Microsoft has been cooking up an Android emulator. It appears that every company now feels compelled to create one. Right now we have Google’s emulator, Intel HAXM support for it, Genymotion, Xamarin Android emulator and now the Visual Studio’s one. It is getting crowded, isn’t it?

So, why I did write an apparently great news. Because the VS Android emulator, just like Windows Phone emulator, runs on top of Hyper-V. Which is not bad from the technical point of view but it is certainly not a good option on a developer machine. And that’s because turning on Hyper-V means that no other virtualization host can coexist. That’s right, forget about VMWare Workstation and Virtual Box when Hyper-V is turned on. Which makes sense on a server but on a developer machine it is sort of silly. The solution? According to Hyper-V crowd it is simple:

Just reboot with Hyper-V turned on or off, depending on your needs.

Which is … silly and really annoying. Heck, even Microsoft acknowledges this problem and it even lists it as one of the motivations beneath Visual Studio’s Emulator for Android:

Conflict with Hyper-V on Windows. Many emulators require you to disable Hyper-V or don’t work as well with Hyper-V as they do without. Using Hyper-V is part of the development setup for many developer activities, so asking you to restart your machine (multiple times a day) to toggle Hyper-V is not acceptable.

I agree that switching Hyper-V on and off is not acceptable. Bot nor is this solution. Instead of getting rid of (or modifying) Hyper-V when it comes to emulators, Microsoft decided to start creating all sort of emulators based on Hyper-V instead. Which is somehow conflicting with the awesome direction of open sourceness and multi platforms MS recently took. On the one hand they are going all nuts with open source and collaboration with other OS (amazing, btw) while on the other hand they are trying to monopolize virtualization on workstation machines. In the times when a mobile developer has to work with all sorts of different tools and software!

Other issues with the Hyper-V based emulator are that they require SLAT support (won’t run on older CPUs) and that they require Windows 8.x Pro or better. Both VMWare Workstation and Virtual Box run on “every” Windows you throw at them. Ah, and don’t forget that it will hardly support Google Play out of the box due to the Google’s silly restrictions (no emulator is allowed to ship Google Play except Google’s own).

So, the bottom line is, that yet another Android emulator is welcome, but it could be done much better. I’ll probably stick with Genymotion for the time being, since it works regardless of Hyper-V and is more feature packed that the rest.

Thinking about delayed getters on properties in C#6.0 or after that

Here is a typical scenario where one postpones property value creation until the property getter is accessed:

private SomeType something;

public SomeType Something 
{
   get
   {
     if (something == null)
     {
       something = new SomeType();
     }
     return something;
   }
}

This pattern is usually applied when property SomeType is rarely used. It doesn’t make much difference on desktop applications (unless there is a ton of these properties) but it might make some performance gains on mobile apps where performance is more critical and memory is less abundant. Of course, one could use Lazy<T> but that would create an instance of Layz<T> instead plus the instance of SomeType eventually.

Now, there is a Expression bodies on property-like function members proposition for C# 6.0 that allows getter-only properties to be implemented with an expression, i.e.:

public string Name => First + " " + Last;

However, full lambdas aren’t supported thus something field can’t be assigned and we’d end up with a new SomeType instance each time.

So, I was thinking a bit about how that could be implemented and here is my proposition for delayed getter-only property assignment:

public SomeType Something => const new SomeType();

This would cause the instance of SomeType to be created only when getter is first time accessed and after that the same instance would be used just like in the original example.

What do you think?