Tuesday, November 26, 2013

Getting Support V7 working with MvvmCross

Recently Xamarin added Support V7 AppCompat and GridView to their Component store, which you now can use instead of ActionBarSherlock or LegacyBar and it is Google's official way to support ActionBar's on API's which natively do not support it. However it does not work straight out of the box and you need to mimic what MvxActivity does in your own implementation. So here's the code I used to re-create MvxActivity to inherit from ActionBarActivity instead of Activity, which Support V7 needs.

This way you only need to replace MvxActivity with MvxActionBarActivity where needed and also add one of the AppCompat Themes to your Activity: Theme = "@style/Theme.AppCompat.Light"

Friday, November 15, 2013

Xamarin officially announced PCL support and more...

It has been a little while since last update from me. Since then a lot of stuff has happened in the Xamarin world. They have teamed up with Microsoft and released official PCL support, while Microsoft has loosened up their licenses on Bcl and their HttpClient among others. This is really great news!

I have already heard about people releasing their libraries for Xamarin because of the PCL support, among them is Jon Skeet, which is working with his team on Noda Time. There was some questions about what is actually supported in the various profiles, and I have spent the day today to track that down and test various PCL's. For now I have only tested for async/await and Tasks support and which profile supports which targets and contains which subsets.

This can be seen in the table below or by visiting my Google Spreadsheet I have made with it.



From what I can see the best choice for a profile to pick in your project seems to be either profile 78 or 158. The former is reported to not have Timer and ThreadPool in it and if you need support for Silverlight 5, profile 158 seems to be the best choice overall.

Friday, October 18, 2013

Generating QR Code using Google Charts API in C#

We are playing with QR Codes at work and needed a quick and simple way to generate QR Codes. I discovered the Google Charts API has a hidden way to generate these. This lead me to make a quick small LinqPad script to generate these. Find it here or see below.


Monday, September 23, 2013

How to Implement "IntPtr Handle and Dispose" in Xamarin.Android

Now you might have come by some interfaces you want to implement and then all of the sudden they want you to implement a Handle property which is of the type IntPtr and a Dispose method. If you leave them be your code will most likely never get called. Then you scratch your head and wonder why this is, also you might ask yourself what this Handle is. The brief explanation is that the Handle provides an Android Callable Wrapper to Android. All native Android interfaces extend IJavaObject so they will expect that to be implemented. So the simple answer is that you do not implement Handle or Dispose yourself, however you inherit from Java.Lang.Object which does that for you. So your code will end up looking like this:


Given that IStuff extends IJavaObject. More on this topic can be read in the Xamarin documentation on Android Callable Wrappers

Friday, September 13, 2013

New Mobile podcast with a healthy emphasis on .NET and Xamarin

A wild podcast has appeared, this one is called Gone Mobile and made by some cool guys including Greg Shackles (@gshackles), Nic Wise (@fastchicken) and Jonathan Dick (@redth). The podcast as the title says is about Mobile stuff, including news, interviews with people in the industry and much more. The first episode has already aired, which I though was quite enjoyable and I will listen to it in the future.
If you have not given it a listen, I advise you to and see for yourself if it is interesting. The podcast is also available on iTunes if you are into that kind of stuff.

Wednesday, July 24, 2013

Apple Y U NO FIX Developer Center?!

Apple Y U NO FIX Developer Center?! I need a new provisioning certificate and I need to add an App!

Xamarin Activation issues

I've been having Activation Issues with the Xamarin products numeral times now, although it has become better over time. Today it seems like Xamarin is having issues with their servers. My Xamarin products worked well yesterday. Now when I try to start VS and open up a Xamarin project it tries to call home to Xamarin and Activate my product... Why is it necessary to call home every time I open up a Xamarin project?


Below you see a screenshot of the log, telling me that there is an Internal Server Error when contacting Xamarin Activation Server.


And here is a screenshot of their store page, which just dumps source code.

Why is it that when Xamarin has problem with their servers, I have to stop developing my products and wait till they fix that?

To your information I am running the latest Xamarin Alphas where it is said that these issues should be fixed and should not require Internet connection once activated. I see something different.

Xamarin, please fix these issues. I love your products, except your Activation :(

Monday, July 22, 2013

MvvmCross Plugin Bootstrapping on iOS

Usually when creating bootstrap files to load Plugins in Mvx, you just write something in the lines of
However this does not work with iOS, because it is not as cool as WP8 and Android, as it does not use cool JIT compilation. Hence, in order to get Plugin Bootstrapping to work you have to use MvxLoaderPluginBootstrapAction instead to tell iOS AOT compiler a bit more about this Plugin.
This way you avoid a nasty MvxException telling you that there is no Plugin registered for a specific type.

Silly iOS...

Wednesday, July 17, 2013

Creating a MapMarker to imitate XML Drawable - Maps V2

I spent a lot of time yesterday debugging why BitmapDescriptorFactory was throwing a null pointer exception all the time. After a while I realised it was only when I was using a Drawable I had created using XML, more specifically a layer-list with a shape and an item which has a Drawable. This should show up as a slightly translucent circle with an image on top, and works very fine when using it as a source for an ImageView. However, when trying to use it as Icon for a Marker with the new Google Maps v2 API, it just throws a null pointer exception, without much reason why :-(

So from here I have two choices, either create an image with the desired marker, or draw it programatically on a Bitmap Canvas. The first one is easy enough and I will not show that here, it is just a simple image you pop into the drawable folders in your Android project. The latter is way more fun and could be useful to you. The sample will be using Xamarin.Android to demonstrate how it is done there, however, it may be applicable to Java Android.

So first you need to know how big you want to have the marker to be.

In this case I just set it to 60dp, you can experiment with that. Now you have to do the drawing action.

Now that you have your BitmapDescriptor you can set it as an Icon for the map Marker.

There, done!

Monday, July 15, 2013

Fragments and ViewPager with Mvx

I've been toying around with MvvmCross (Mvx) and Fragments lately and found out that my binding for the ViewPager is only working if you are using old type of Activities and Views. So in this blog post I will describe what I did to get the ViewPager to work nicely with Fragments and Mvx.

I have made some code samples which are shown in the bottom of this blog post and which I will refer to. So to start with, let me explain why this approach is necessary. There are currently no official bindings for the ViewPager for Mvx for Xamarin.Android. However, I did make one, and it works pretty well and binds to the ViewPager like you would with a ListView. In fact you can use different ItemTemplates such that you can display different kinds of Views inside the ViewPager. How to do that is decribed in the Working with Collections Tutorial in the MvvmCross Tutorials repository.
With Fragments that approach changes. Now a FragmentPagerAdapter is required, which creates instances of Fragments and keeps track of which are shown on the screen and which to cache, much in the same fashion as a normal Adapter for ListViews. However Fragments are a lot different as they have their own life-cycle and with Mvx each of them have their own ViewModel as well, just like you previously would have a ViewModel for an Activity. The binding of the View associated to a Fragment also happens inside that Fragment. So the binding action which previously was inside the Adapter, now is handled in the Fragment. This means a lot less work for me! So since I cannot use the bindings I previously made I had to come up with something new.

Anyways let us get to the fun stuff and let me explain the code below.
  • Home.axml is the Android View, which contains the ViewPager and an optional ViewPagerIndicator (will post source for this soon, look out for another blog post meanwhile you can use this) - very simple no bindings here.
  • HomeViewModel.cs is a simple ViewModel, similar to one you would use for a Tab kind of View, which instantiates other ViewModels to use for each tab, or in this case for each page in the ViewPager.
  • MvxViewPagerFragmentAdapter.cs is what we need to inform ViewPager about our Fragments. It needs to know about at least the Type of the Fragment and the ViewModel associated to it. The Title is just for convenience when using a ViewPagerIndicator. Basically what happens in GetItem is that a Fragment of a specific Type gets instantiated and the DataContext for that Fragment is set. This way the Fragment itself can create bindings to Properties and Commands internally. GetPageTitleFormatted is simple for a ViewPagerIndicator. FragmentJavaName and FragmentInfo was highly inspired by the MvxTabsFragmentActivity which kind of does the same thing as this Adapter but with a lot more stuff to make it work with a TabHost.
  • HomeView.cs now this last piece of code, simply creates the FragmentInfo instances for the Fragments I want to display in the ViewPager and gives that information to the Adapter which is set for the ViewPager.
This is basically it. See the video for a quick run through of the code and how it looks at the end of it.


Wednesday, July 3, 2013

Working with PCL's in the latest Xamarin.Android

Recently Xamarin released version 4.7.10 alpha of Xamarin.Android, which stated:
"PCL support!
(Cross your fingers, sacrifice your favorite meal under the full moon, and your PCL projects should Just Work! Testing wanted.)"
So I kind of wanted to find out if it really was true, and it also happens to be that I am doing a project which needs to fetch something from the Internet, which is great to test out HttpClient in PCL's as well. The project also uses Stuart Lodge's fantastic MvvmCross framework, also with the new PCL stuff, and everything seems to work. However there are some things you have to work around until Xamarin releases tooling that allows you to reference PCL's in your Android and iOS projects in the Visual Studio plugin.

So what I have tried:
  1. Download MvvmCross from the GitHub Repo, and rebuild the whole thing with the new Xamarin.Android version.
  2. Create a new PCL Library project in either Xamarin Studio or Visual Studio. I choose to target WP8, Store apps and .NET 4.5.
  3. Grabbed prerelease Microsoft.Net.Http package for the PCL. This also imports some Bcl stuff which allows you to use Async in the PCL. Now you should be able to use HttpClient and Async, sweet!
  4. For the Android project, here what is tricky. VS will complain that the Android project does not support PCL's, but it is lying! What you can do is either manually add a reference in the .csproj file or open up the project in Xamarin Studio and do it there.
  5. You will also have to grab the DLL's from the packages folder in your solution and import System.Net.Http, System.Net.Http.Extensions and System.Net.Http.Primitives from the Microsoft.Net.Http NuGet package you downloaded. I took if from the portable-net40+sl4+win8+wp71 folder.
  6. Now do your MvvmCross stuff, I just bound a button to a Command in my ViewModel, which calls a method in a service, which then in turn uses HttpClient to fetch some stuff from a Web Service.
This should also work for Xamarin.iOS and also on WP7 and WP8, Store Apps etc. As long as you use Microsofts BCL and Http packages in your projects.

Made a video describing the whole thing in more details:
Sample code can be found in my GitHub repo

Sunday, May 5, 2013

ParallaxScrollView

I had a little time while watching the WEC race on Spa yesterday to port a pretty interesting View to work on Xamarin.Android. If you have ever played the Mario games, you might have noticed, that the background  moves slowly while the foreground moves faster while you advance in the level. This is basically what this View does. How it works is that the ParallaxScrollView scales the Background View to fit the parallax factor. So lets say the factor is 0.5, this will mean the Background View is half the size of the Foreground View's content. When you scroll the Foreground it will scroll the Background at half speed of the Foreground. Setting the factor to 1 scrolls both Views at the same speed. Setting it above one, scrolls the Background faster than the Foreground. To have it look good, a View that stretches well is recommended, such as a repeatable pattern or such.

I made a quick demo of the port, which is based on the original demo, only difference is that the Background View is a bit different.


You can find the ParallaxScrollView in my GitHub repo, I also plan to release it in the Xamarin Component Store soon.

Last but not least a shoutout to Christopher Jenkins (@chrisjenx) who originally made this View for Android and did all the hard work, I simply ported it to Xamarin.Android. Thanks a bunch for your work!

Wednesday, March 27, 2013

MonoDroid.ActionBar is now LegacyBar!

Behold! LegacyBar!

Ever since Xamarin renamed Mono for Android to Xamarin.Android with their Xamarin 2.0 release, I have been thinking of a new name for the MonoDroid.ActionBar project.

If you don't know MonoDroid.ActionBar, it is a project which aims to bring an ActionBar across all Android API levels all the way back to API 4! How do we do this? By making our own from scratch mimicking the built in into Android. It started as a quick and dirty port of the android-actionbar by Johan Nilson and quickly people from the Mono for Android community started using it and forking it and one day a guy named James Montemagno started making pull requests on GitHub. Ever since then James and I have been sparring and making changes to the ActionBar implementation.

Now that Xamarin has renamed Mono for Android to Xamarin.Android we thought it was time to rename our project too. Since the ActionBar is meant to support legacy versions of Android, why not call it LegacyBar? So from now on the project is called LegacyBar! My personal aim for LegacyBar from now on is to make it ready to put in the Xamarin Component store, make a bunch of documentation. When that is done extending it to support a lot more of the same things as the native Android ActionBar.

Stay tuned for more LegacyBar goodies and feel free to fork it on GitHub!

Tuesday, February 26, 2013

Adding images to TextView and EditText using Spannables in Mono for Android

I've just been playing around with Spannables in an attempt to help out a user on the Xamarin Forums, his topic is "Text With Image". Just from looking at that topic name, I thought: "Hey, he probably just want to show an image next to some text or something, this should be easy enough". Then I looked inside, and they guy actually wanted text inline with text when actually editing it. Now I thought: "How do I do that?!"
I think I have touched the concept of Spannables briefly before, when I helped a guy making a sub-part of a text bold or something, but I never thought they could be used for displaying images inline with text. I guess this is how it is done in all those messaging apps, which show emoticons. I decided to use that as a sample.

I started out with a super simple sample trying to get an Image shown in a TextView. I googled up some solutions and sure, Spannables allow using ImageSpan inside of them! There were nice samples and such, and I came up with this.
Easy, huh? And you can add loads of other Spans to the Spannable, such as StyleSpan, which you can style your fonts with bold, italic and other styles.

Since that was so easy, I quickly tried to do that with an EditText. It also works just fine, so moving on. How do I imitate those messaging apps, which replace ":-)" with an actual smiley. Now EditText has some nice events which you can listen to for changes. I listen for AfterTextChanged, from here I can get the Editable Property from the argument, which is essentially a Spannable you can edit and the changes will be reflected in the EditText. This is probably a good place to replace text with images.
Next I cooked up a class which holds a Dictionary of strings and ints. The string keys are the text representation of the smileys, i.e. :), :-), :D, :P and so on. The ints are the Android Resource ids for the Drawables representing the smileys. Then I have a method for replacing all the matches in the string with their respective Drawables. It looks like this.
Now you might notice I am removing all the images if they are present. This is because it is not possible to have two Spans at the same index in a Spannable, hence they need to be removed. Don't worry all the images are added at the end. This simply loops all the string matches in the Spannable and adds ImageSpans for the matches. Very simple. To get all the indices in a string which match I use a simple extension I found on StackOverflow.
Now the AddSmiles() method is hooked up to the AfterTextChanged event for the EditText, and voila. Text is replaced with images!
Pretty awesome smileys :-D 
The complete sample code can be found in this Gist: https://gist.github.com/Cheesebaron/5034440

You can also watch this video for a demonstration

Saturday, February 23, 2013

Using Dialogs in Mono for Android

Using Dialogs in Mono for Android is very similar to what you do when writing Java code for Android. But maybe let us first briefly look into what we can use Dialogs for. There are several things they are really useful for:
  • Showing Alerts - The user gets notified about something important happening in the application, or the application failed. You might know the Alert Dialog, which shows when an application becomes unresponsive and you get the choice to either Wait or Force Close the application.
  • Selecting a values from lists - The user chooses a field and gets presented with a short list of choices. This could be for instance that you are already showing another dialog, where you want the user to write his username and password, but additionally you want the user to choose a server from a list of the available ones, this could get presented in a new dialog.
  • Adjusting settings - For instance when you have to adjust the brightness of your screen on your phone, you are shown a dialog with sliders for adjusting the brightness. This is also the case for volume etc.
  • Picking a Date or Time - This is used widely in Alarm clock and calendar applications.
There are probably many more uses, but I think you get the idea about the use of Dialogs and what they are good for. If you notice the pattern, Dialogs are made for making the user take an action. What are Dialogs less good for? I highly recommend not using them for progress indications. Taking away the focus from the app to show a Dialog with a Progress Indicator is not good use, you should rather, if possible, show a ProgressBar or Activity Indicator in your view, and let your user navigate around your application, to be able to do something else in your application while they wait for the other task to end. This could be uploading a file to a server, people do not want to wait and watch a ProgressBar in a Dialog and not being able to do anything else, they will get bored quickly.

Before we get our hands dirty in code let me explain the two methods to create Dialogs. One is you create it inline of the code where you need to show it. That could be in an EventHandler for a Button. Another way is to use the OnCreateDialog methods in an Activity, however note that these were Deprecated in API level 8 and 13 when Fragments were introduced. The instantiation of a Dialog has not changed. It is recommended to use a DialogFragment in API level 13 and above which I will cover at a later point in this blog post.

Dialogs in Activities

Get the sample code here!

Now that is covered why don't we get our hands a bit dirty with some code samples? The first couple of samples are going to show what the default Dialog classes can show without using custom views inside, then some more advanced stuff will be shown. Also the first samples will use the old style of creating Dialogs inside activities, and the last samples will show the DialogFragment introduced in API level 13.

This first sample shows how to create a simple Yes/No type of dialog, which shows when a user presses a button. I use an AlertDialog.Builder to create this dialog, and you will see this approach used throughout the samples. An AlertDialog has loads of properties which can be set, such as the title, messsage, negative button and positive button. Here a message is set, the negative and positive buttons. The EventHandlers are empty in this sample, but could be used to do an action in your application. When using AlertDialog.Builder you need to call Create() at the end to get the actual AlertDialog instance, which then can be shown by calling Show(). The resulting dialog can be seen in Figure 1.
Figure 1 - Simple Yes / No Dialog

Now lets look at how to create an Alert type of Dialog, screenshot can be seen in Figure 2, with an icon and title and a couple of buttons. Notice how this time I am calling ShowDialog inside the Click Event and how I have consts defined in the top of my class. This is due to the int id which is passed in ShowDialog is the same id which is passed as argument in OnCreateDialog where I create my dialogs, which is the pattern used pre API level 13.
This kind of Alert Dialog can of course also have some description text which is simply set with the SetMessage() method.
Figure 2 - Alert Dialog
Now let us try something more exciting. Let us make a dialog with an item you can select from a list.
Figure 3 - List Dialog
The AlertDialog class has a nice method SetSingleChoiceItems which takes a list of items either from Arrays.xml or a an array of items. You also need to provide it with an EventHandler for what happens when an Item in the list is selected. Otherwise it is the same approach as the other two Dialogs shown. Instead of using lambda expressions for the Event Handlers for the positive and negative buttons you can also make methods for handling the events. The result of this dialog can be seen in Figure 3.

AlertDialog also has a nice method for making Multiple Choice Dialogs, so it shows a list of items which have checkboxes. This is done by giving the method SetMultiChoiceItems an array of items either from Resource or an instance, you can choose which items are checked or not and lastly add an Event Handler for handling which items are chosen.
Figure 4 - Multi Choice List Dialog
You might also have noticed that I've passed a second argument to the AlertDialog.Builder, which actually allows you to set the theme of the Dialog, in this case it sets the theme to Holo Light, which can be seen in Figure 4, this can be done when using API level 13 and above. But again, very simple stuff!

Final example shows how to make a Dialog with a custom view inside of it. Approach is exactly the same as with the other examples, however this time I use the SetView() method of AlertDialog to set the custom view, which I have inflated. The OnClicked handler also shows you how to get the data from the elements in custom view.
Figure 5 - Custom View Dialog
So what happens in the OkClicked Event Handler, is that it conveniently receives the AlertDialog in the sender object, which we can use to find all the views contained in it. This allows us to simply use FindViewById to find the two EditText's contained in the custom view which were set.

Dialogs in Fragments

You might think that this is all to know about Dialogs, but sorry there are still some stuff to cover. I've pointed out that some methods were deprecated in API level 8 and 13, and a new pattern was introduced around that time called Fragments. Creating Dialogs in Fragments is slightly different that in Activities; hence I will show you two examples on how that is done. However creating the actual Dialog is still done with AlertDialog, but I will also show you one of the built in Dialogs in Android.
Lets just dive into the code!
This is a very simple dialog inflating a view with a couple of buttons. Their Click events are set to instantiate a some dialogs, which are not shown. But this approach is the way you show Dialogs when using Fragments. Actually you are displaying DialogFragments. It also implements a couple of listeners for the two different Dialogs which I will show you now.

Figure 6 - DatePickerDialogFragment
For the DatePickerDialogFragment, we are lucky that Android actually have a DatePickerDialog implemented already which just needs to be wired up to a listener and set a date inside of it. The listener allows us to listen for date changes in the Dialog. Using a DialogFragment requires you to create a Dialog inside of OnCreateDialog. That is it, here you can create all the Dialogs I have shown you in the previous samples with the AlertDialog.Builder, you just have to create these DialogFragments, instead of putting them into Activities OnCreateDialog(). The DatePickerDialogFragment can be seen in Figure 6.

Just to show another example, let us create a Custom View DialogFragment, which allows you to pick a number from a NumberPicker, see Figure 7.
Figure 7 - NumberPickerDialogFragment

Now you have seen a lot of different Dialogs, both using the old deprecated Activity approach and the newer Fragment approach. The entire sample can be seen in my GitHub repository for this blog post.

Thursday, January 31, 2013

Awesome MvvmCross Swiss Bindings for MonoDroid and MonoTouch

Recent changes in MvvmCross introduced Swiss Bindings for MonoDroid and MonoTouch. What is so great about them? Mainly readability, but it is also a lot more easy to write. Instead of having to write JSON you make bindings in a similar manner as it is done in XAML.

Let's dive straight into some samples to see how awesome it is!

Binding a TextView
So before you had to write all sorts of tags to bind stuff, this is not the case anymore. Comparing the two approaches below quickly show, how much less effort you have to put in making your bindings and the Swiss Bindings look a lot more clean. 16 less characters to write! Binding a Spinner
Now lets try something a bit more complicated, like binding a Spinner! See that! So much more clean and readable! Sweet mother of god, in this case we skip 35 characters! Swiss Bindings are really awesome, or at least that is what I think!

To try them out you do not really have to do anything. Just use them, they are already there to use in your projects and the binding parser is made so that it detects what kind of binding you are using depending on the first character.

Syntax
The syntax of Swiss Bindings is pretty simple and I have made a simple grammar and diagrams to visualise it:
Railroad Diagram (Click for Large)

The ChainedViewModelProperty can be a lot of things, so to simplicity I have left out all the posibilities and described it with a single parameter. But just like in XAML it can be a Path to the Property you want to display so: I hope you get the picture, modelling all the possibilities would have been a huge job to do. Also I know that the BNF grammar is sort of wrong, but it gets the job done for me describing how this Swiss Bindings work. If you need help using it, join us at JabbR.Net in the #mvvmcross chat.