Xamarin.Forms Android CardView

When Google introduced Material Design for Android they introduced a new view called CardView. Xamarin.Forms doesn’t have support for CardView by default but you can easily create your own view that renderers a CardView on Android.

First step is to create a Xamarin.Forms control in your shared project.

public class CardContentView : ContentView
{
 
 
		public static readonly BindableProperty CornerRadiusProperty = 
			BindableProperty.Create<CardContentView,float> 
		( p => p.CornderRadius, 3.0F);   
 
 
 
        public new static readonly BindableProperty BackgroundColorProperty =
            BindableProperty.Create<CardContentView, Color>
        (p => p.BackgroundColor, Color.White);
 
        public float CornderRadius
        {
            get { return (float)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }
 
        public new Color BackgroundColor
        {
            get { return (Color)GetValue(BackgroundColorProperty); }
            set { SetValue(BackgroundColorProperty, value); }
        }
 
		protected override SizeRequest OnSizeRequest (double widthConstraint, double heightConstraint)
		{
			if (Content == null)
				return new SizeRequest(new Size(100, 100));
 
			return Content.GetSizeRequest (widthConstraint, heightConstraint);
		}
	}

Next step is to create a custom renderer for Android, on iOS and Windows it will be rendered as a regular ContentView.
You need to add a NuGet package named Xamarin.Android.Support.v7.CardView to get the Android CardView. The renderer will inherit form CardView and implement the IVisaulElementRenderer interface. To get card shadow on both Android KitKat and Android Lollipop you have to set UseCompatPadding to true. You have to remove all view from the ViewGroup, if you don’t do that you will get problems when you using the control in a ListView. The Load method on the VisualElementPackager will load content in to the Card.

[assembly:ExportRendererAttribute(typeof(CardContentView), typeof(CardViewRenderer))]
namespace CardViewFormsAndroid
{
	public class CardViewRenderer : CardView, 
		IVisualElementRenderer
	{
		public CardViewRenderer () : base (Forms.Context)
		{
		}
 
		public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
 
		bool init;
		ViewGroup packed;
		public void SetElement (VisualElement element)
		{
			var oldElement = this.Element;
 
			if (oldElement != null)
				oldElement.PropertyChanged -= HandlePropertyChanged;
 
			this.Element = element;
			if (this.Element != null) {
 
				this.Element.PropertyChanged += HandlePropertyChanged;
			}
 
            ViewGroup.RemoveAllViews();
				//sizes to match the forms view
				//updates properties, handles visual element properties
				Tracker = new VisualElementTracker (this);
 
            Packager = new VisualElementPackager(this);
            Packager.Load();
 
            UseCompatPadding = true;
 
            SetContentPadding((int)TheView.Padding.Left, (int)TheView.Padding.Top,
                   (int)TheView.Padding.Right, (int)TheView.Padding.Bottom);
 
                Radius = TheView.CornderRadius;
                SetCardBackgroundColor(TheView.BackgroundColor.ToAndroid());
 
			if(ElementChanged != null)
				ElementChanged (this, new VisualElementChangedEventArgs (oldElement, this.Element));
		}
 
 
 
 
		public CardContentView TheView
		{
			get { return this.Element == null ? null : (CardContentView)Element; }
		}
 
 
		void HandlePropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Content") {
 
                //Packager.Load();
 
                Tracker.UpdateLayout();
            } else if (e.PropertyName == CardContentView.PaddingProperty.PropertyName) {
				SetContentPadding ((int)TheView.Padding.Left, (int)TheView.Padding.Top,
					(int)TheView.Padding.Right, (int)TheView.Padding.Bottom);
			} else if (e.PropertyName == CardContentView.CornerRadiusProperty.PropertyName) {
				this.Radius = TheView.CornderRadius;
			} else if (e.PropertyName == CardContentView.BackgroundColorProperty.PropertyName) {
				if(TheView.BackgroundColor != null)
				SetCardBackgroundColor (TheView.BackgroundColor.ToAndroid ());
 
			}
		}
 
		public SizeRequest GetDesiredSize (int widthConstraint, int heightConstraint)
		{
			packed.Measure (widthConstraint, heightConstraint);
 
			//Measure child here and determine size
			return new SizeRequest (new Size (packed.MeasuredWidth, packed.MeasuredHeight));
		}
 
		public void UpdateLayout ()
		{
			if (Tracker == null)
				return;
 
			Tracker.UpdateLayout ();
		}
 
		public VisualElementTracker Tracker {
			get;
			private set;
		}
 
        public VisualElementPackager Packager
        {
            get;
            private set;
        }
 
        public Android.Views.ViewGroup ViewGroup {
			get{ return this; }
		}
 
		public VisualElement Element {
			get;
			private set;
		}
 
 
    }
}

You can browse the complete code with a working example on GitHub, https://github.com/dhindrik/Xamarin.Forms-Awesome-Controls
The repository is a fork from James Montemagno’s repository for awesome Xamarin.Forms controls. What I have done is that I have changed a few things so can have layouts as content, a StackLayout for example.

Get started with Xamarin.Forms for Windows

Xamarin has finally released support for Windows apps using WinRT. This make it possible to write apps for Windows Phone 8.1 (the stable release uses Windows Phone 8 Silverlight but can be upgraded to Windows Phone 8.1 Silverlight by changing target platform) and Windows 8.1. It’s still in preview and Xamarin not recommending that we uses it for production apps yet. This post will show you how to add Windows apps to your existing Xamarin.Forms project.

First thing to do is to make sure that you have the correct PCL profile for your shared Xamarin.Forms project. If you have created your project from Xamarin.Forms PCL template you have to check Windows Phone 8.1.

PCL Target type

Next step is to create a Blank Windows App.

Create black Windows app

When you have done that you have to add the nuget package for Xamarin.Forms to the Windows project.

Run Install-Package Xamarin.Forms.Windows -Pre in the “Package Manager Console”.

When the package is installed open up MainPage.xaml and add the Xamarin.Forms namespace and change Page to forms:WindowsPage.

<forms:WindowsPage
    x:Class="MyApp.WinStore.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyApp.WinStore"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:forms="using:Xamarin.Forms.Platform.WinRT"
    mc:Ignorable="d">
 
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    </Grid>
</forms:WindowsPage>

You also have to remove that MainPage is inherits from Page in MainPage.xaml.cs. To start the forms application run LoadApplication with the App class from the shared project as an argument.

 public sealed partial class MainPage
    {
        public MainPage()
        {
            this.InitializeComponent();
 
            LoadApplication(new MyApp.App());
        }
    }

The last step is to call the Xamarin.Forms Init method (Xamarin.Forms.Forms.Init(e);) in App.xaml.cs. The call should be in the OnLaunched method after before if (e.PreviousExecutionState == ApplicationExecutionState.Terminated). It will be around line 65.

if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                // Set the default language
                rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
 
                rootFrame.NavigationFailed += OnNavigationFailed;
 
                Xamarin.Forms.Forms.Init(e);
 
                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }
 
                // Place the frame in the current Window
                Window.Current.Content = rootFrame;

Xamarin Forms for WinRT

If you want to use Xamarin.Forms for a Windows Phone 8.1 (with WinRT) app follow the same steps, for a Windows Phone 8.1 project.

Xamarin.Forms: Placeholder text color password box Windows Phone

When using the Entry control in Xamarin.Forms with IsPassword set to true the text color property will not affect placeholder text on Windows Phone. To solve this you need to create a custom renderer for entry in your Windows Phone project.

The native control will be a Grid that contains a PasswordBox (PhoneTextBox if IsPassword is false). The easiest way to find the PasswordBox is to loop through all controls in the Grid and set Foreground color to the text color specified on the Xamarin.Forms control.

[assembly: ExportRenderer(typeof(Entry), typeof(ImprovedEntryRenderer))]
namespace MyApp.WinPhone.Renderers
{
      public class ImprovedEntryViewRenderer : EntryRenderer
      {
            protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            {
                 base.OnElementPropertyChanged(sender, e);
 
                 if(e.PropertyName == "Renderer" || e.PropertyName == "TextColor")
                 {
                      foreach(var ctrl in Control)
                      {
                           var control = (System.Windows.Controls.Control)ctrl;
                           control.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromArgb(byte.Parse(TextColor.A), byte.Parse(TextColor.R), byte.Parse(TextColor.G), byte.Parse(TextColor.B)));
                      }
                 }
            }
      }
}

You have to run the code both if e.PropertyName is “Renderer” and if it’s “TextColor”. That’s because first time the control is rendered it will use “Renderer” as property name, if text color then is changes it will be used as property name.

You have to set the foreground in OnElementPropertyChanged, if you set it in OnElementChanged it will be changed by the base class. If you set it in OnElementPropertyChanged after you have called the base method it will be the last that is running in the renderer.

Preserve data when deploying Xamarin.Android app

By default all your data from your previous runs is deleted when you’re deploying an Xamarin.Android app. In many cases you don’t want the data to be deleted.

Visual Studio
To preserve data go to Tools -> Options -> Xamarin -> Android Settings and check “Preserve application data/cache on device between deploys”.Visual Studio

Xamarin Studio
To preserve data go to Tools -> Options -> Android and check “Preserve data/cache between application deploys”.
Xamarin Studio

Serialization of default values Web Api and Json.NET

If you’re using ASP.NET Web Api and some properties isn’t serialized when serializing to json if the value is default value. An example is when bool properties with false as value not are serialized try to add the following code in the Register method of the WebApiConfig class.

config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling =
                                   Newtonsoft.Json.DefaultValueHandling.Include;

MSDN-förmåner

Du vet väl av att du som har ett MSDN abbonemang har tillgång både till Azure och gratis utbildning? Väldigt många har helt missat att det följer med förmåner som bara försvinner om man inte utnyttjar dem.

Med ditt MSDN.abbonemang följer möjligheten att använda resurser för mellan 50-150 $ månad. Väldigt bra om man vill testa något i befintlig eller kika på nästa version av Microsoft produkter. Framförallt finns också möjligheterna att labba med TFS & Visual Studio!

Det finns ingen risk för ”omedvetna” kostnader och ingen betalkort info krävs för aktivering. För att aktivera Azure-förmånen, logga in på MSDN, https://msdn.microsoft.com/sv-se/subscriptions/manage

MSDN Pluralsight förmån
Med ditt MSDN abbonemang får du också tillgång till ett begränsat utbud (beroende på MSDN abbonemanget) av Pluralsights kurser. Där finns tex kurser om Microsoft Test manager, Fakes, Intellitrace och Scrum med TFS. Klicka bara på länken och logga in med det Microsoft Account (LiveId) som är kopplat till ditt MSDN abbonemang. https://msdn.microsoft.com/sv-se/subscriptions/manage

Building a ScreenshotManager to capture the screen with code

This blog post will show you how to build a screenshot manager to use from shared code when building apps with Xamarin for Windows Phone, Android and iOS.

First of all we need to create an interface in the shared code library. In this example there will be one method in the screenshot manager. This method will capture the screen and return a byte array that you for example can save to a server.

 public interface IScreenshotManager
 {
        Task<byte[]> CaptureAsync();
 }

All platforms that we will target capture the screen in different ways. Therefor will each platform have a own implementation of the interface. If you register the interface with a platform specific implementation for each platform you can call the ScreenshotManager from shared code.

Windows Phone
For Windows Phone you need to render the root frame into a WritableBitmap.

public class ScreenshotManager : IScreenshotManager
    {
        public async Task<byte[]> CaptureAsync()
        {
            var rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
 
            var screenImage = new WriteableBitmap((int)rootFrame.ActualWidth, (int)rootFrame.ActualHeight);
            screenImage.Render(rootFrame, new MatrixTransform());
            screenImage.Invalidate();
 
            using (var stream = new MemoryStream())
            {
                screenImage.SaveJpeg(stream, screenImage.PixelWidth, screenImage.PixelHeight, 0, 100);
                var bytes = stream.ToArray();
                return bytes;
            }
        }
    }

iOS
For iOS you need the view from the RootViewController to create a screenshot from. This code will work for iOS7 and above.

public class ScreenshotManager : IScreenshotManager
    {
        public async System.Threading.Tasks.Task<byte[]> CaptureAsync()
        {
            var view = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
 
            UIGraphics.BeginImageContext(view.Frame.Size);
            view.DrawViewHierarchy(view.Frame, true);
            var image = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
 
            using(var imageData = image.AsPNG())
            {
                var bytes = new byte[imageData.Length];
                System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
                return bytes;
            }
 
        }
    }

Android
To create a screenshot in Android you need to have access to a activity. The easiest way to access a activity is to create a static method on the ScreenshotManager that you setting before using the ScreenshotManager.

public class ScreenshotManager : IScreenshotManager
    {
        public static Activity Activity { get; set; }
 
        public async System.Threading.Tasks.Task<byte[]> CaptureAsync()
        {
            if(Activity == null)
            {
                throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
            }
 
            var view = Activity.Window.DecorView;
            view.DrawingCacheEnabled = true;
 
            Bitmap bitmap = view.GetDrawingCache(true);
 
            byte[] bitmapData;
 
            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
                bitmapData = stream.ToArray();
            }
 
            return bitmapData;
        }
    }

Using Context Actions in Xamarin.Forms ListView

One of the news in Xamarin.Forms 1.3 is what Xamarin call context actions. With context actions you can make a ListView much more richer. What you can do is to add a menu to every row in the ListView. On Windows Phone and Android is the menu showing when you’re long pressing on a item, on iOS you will swipe left on the item to show the menu. As you can see on the screenshots below the menu looks different on each platform. On Windows Phone the menu will pop up, on iOS it will be be on the row and on Android at the top of the screen.

contextactions contextactions_android contextactions_ios

To use context action add them to the ViewCell in the ItemTemplate as shown in the code below.

 <ViewCell.ContextActions>
       <MenuItem Text="Share" />
       <MenuItem Text="Buy" Command="{Binding AddToBasket}" />
</ViewCell.ContextActions>

MenuItem has four properties that is good to know:
Text: What’s shown to the user
Clicked: Adds a event listener to the menu item.
Command: Bind a command to the menu item.
IsDestructive: Will make the menu item red on iOS if it’s set to true.

 <ListView ItemsSource="{Binding Products}" VerticalOptions="Start" RowHeight="40">
 
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <ViewCell.ContextActions>
              <MenuItem Text="Share" />
              <MenuItem Text="Buy" Command="{Binding AddToBasket}" />
            </ViewCell.ContextActions>
 
            <ContentView Padding="0,10">
              <Grid>
                <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="2*" />
                  <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
 
              <Label Text="{Binding Product.Name}" TextColor="Black" />
              <Label Grid.Column="1" HorizontalOptions="End" Text="{Binding Product.Price, StringFormat='{0:0.00} kr'}" TextColor="Red" />
 
              </Grid>
            </ContentView>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>

Grouping a ListView – Xamarin.Forms

In many cases when you want a list of items you want to group them in the list. To use groups in a ListView with Xamarin.Forms is very easy.

Below are screenshots from Android, iOS and Windows Phone where there is no HeaderTemplate used.
android_groups ios_groups wp_groups

First step is to create a group class that inherits from ObservableCollection and create two properties, one for title and one for short title.

public class ListViewModel
{
     ObservableCollection<MyListViewGroup> Groups {get; set;}
}
 
public class MyListViewGroup : ObservableCollection<MyListViewItem>
{
     public string Title {get; set;}
     public string ShortTitle {get; set;}
}
 
public class MyListViewItem
{
     public string Name {get; set;}
}

IsGroupingEnabled is the keyword to enable grouping for the ListView, if it’s value is true the ListView will be grouped.

GroupTitle is the group title.

GroupShortTitle is the value that will be shown when you tap a group title in Windows Phone and the value at the left side on iOS. Android will not use GroupShortTitle. It will be used to jump a specific group.

To style the header use the GroupHeaderTemplate property.

 <ListView Grid.Row="1" ItemsSource="{Binding Groups}" 
           GroupShortNameBinding="{Binding ShortTitle}" IsGroupingEnabled="true" 
           GroupDisplayBinding="{ Binding Title }">
            <ListView.GroupHeaderTemplate>
              <DataTemplate>
                <ViewCell>
                  <ViewCell.View>
                    <Label Text="{Binding Title}" />
                  </ViewCell.View>
                </ViewCell>
              </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
              <DataTemplate>
                   <TextCell Text="{Binding Name}" />
              </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

Monitor an app with Xamarin Insights

I Think it’s really important to monitor apps. Of course the most important part is to log errors in the app. But I also like to track how my users uses my apps. For the lastest app I have built I have used a monitoring tool from Xamarin called Insights, http://xamarin.com/insights.

While I alwas have crossplatform and testability in mind when I buildning apps I first create a logger interface.

public interface ILogger
{
     Task InitializeAsync();
 
    //Log exceptions
     void LogException(Exception ex);
 
     //Log information about events, for example view navigation
     Task TrackAsync(string identifier, Dictionary<string, string> details = null);
 
     //Log information about a user
     Task Identify(string userId, Dictionary<string, string> details = null);
}

While Xamarin Insights is compatible with Portable Class Library I writing the implementation in a project that I can share between platforms.

public class InsightsLogger : ILogger
{
     public virtual Task InitializeAsync()
     {
     }
 
     public void LogException(Exception ex)
     {
           Insights.Report(ex, ReportSeverity.Error);
     }
 
     public Task TrackAsync(string identifier, Dictionary<string, string> details = null)
     {
           Insights.Track(identifier, details);
     }
 
     public Task Identify(string userId, Dictionary<string, string> details = null)
     {
          Insights.Identify(userId, details);
     }
}

The InitializeAsync method is virtual so it can be overridden, when using Xamarin Insights each platform has to have the Initialize code. Because of that I also need to create a logger class for each platform.

While I don’t want errors from development together with production data I use to create two apps in Insights, one for development and one for production. I using conditional compile for to initialize with the right app key.

 public class WinPhoneInsightsLogger : Logging.InsightsLogger
    {
        public override async Task Initialize()
        {
#if DEBUG
            Insights.Initialize("key for debug use");
#else
            Insights.Initialize("key for production use");
#endif
        }
    }

if you want to read more about Xamarin Insights you can do it here, http://xamarin.com/insights

Crossplatform and storage strategies

Many applications need to store data related to the application. If you’re building applications for multiple platforms the APIs for storage is different.

Following five storage types is the most common ones:

Local storage
Storage to store application data locally on the device.

Remote storage
Storage to store application data in the cloud, for example OneDrive or iCloud. Data that is saved in the cloud could be accessible from different devices.

Cache storage
Storage to use when caching data. Platforms that have a separate storage for cache data will not contain cache storage in the backup, WinRT for an example. Cached data is not necessary to have in a backup, it will be cached again after restore of the backup.

Settings storage
Storage to store application settings locally on the device.

Remote settings storage
Storage to store application settings in the cloud, for example OneDrive or iCloud. Settings will be synced for all devices you have installed the application on.

You can handle storage in different ways, one strategy is to create one interface for each of the storage types above, for example ILocalStorage and IRemoteStorage. Every interface will have an implementation for each platform. With help of an IoC-container (Inversion of Control) we can use the interface to call platform specific code from shared code.

public interface ILocalStorage
{
     Task AddAsync(string key, object value);
     Task<T> GetAsync(string key, object value);
     Task<bool> ContainsAsync(string key);
     Task RemoveAsync(string key);
}

One other strategy is to create one storage interface, IStorage and have a method with storage type as an argument. As with the first strategy each platform will have a platform specific implementation that can be used from shared code with help of IoC.

public enum StorageTypes
{
    Local,
    Remote,
    Cache,
    Settings,
    RemoteSettings
}
 
public interface IStorage
{
     Task AddAsync(string key, object value, StorageTypes storageType);
     Task<T> GetAsync(string key, object value, StorageTypes storageType);
     Task<bool> ContainsAsync(string key, StorageTypes storageType);
     Task RemoveAsync(string key, StorageTypes storageType);
}
 
public class Storage : IStorage
{
     public async Task AddAsync(string key, object value, StorageTypes storageType)
     {
          switch(storageType)
          {
                 case StorageTypes.Local:
                      //code for local storage
                      break;  
                 case StorageTypes.Remote:
                      //code for remote storage
                      break;  
                 case StorageTypes.Cache:
                      //code for cache storage
                      break;  
                 case StorageTypes.Settings:
                      //code for settings storage
                      break;  
                 case StorageTypes.RemoteSettings:
                      //code for remote settings storage
                      break;  
          }     
     }

I prefer the first strategy beacause I like small classes with one role, the maintainability will be much higher and you can make changes to one implementation without the risk of breaking other functionality than that one you want to change.

As an example, one platform maybe don’t have CacheStorage, then the LocalStorage and CacheStorage will be pretty much the same. But if that platform will get CacheStorage in the future you can change the implementation of ICacheStorage without touching the working code for LocalStorage.

Xamarin.Forms and panorama in a Windows Phone app

One common scenario when building an app is that we want to use tabs on iOS and Android and a Panorama on Windows Phone. Xamarin.Forms has a control called TabbedPage that render tabs on iOS and Android. At the bottom of the page for iOS and at the top of the page under the ActionBar for Android, for Windows Phone a Pivot is rendered. To render a Panorama instead is a quite simple with conditional compile and a custom render.

Xamarin.Forms has a control that renders a Panorama on Windows Phone that is called CarouselPage. But we don’t want to use it for iOS and Android. The solution for that is to use conditional compile.

In the tab host page you want to inherit from CarouselPage instead of TabbedPage. To use conditional compile for the inheritance of the class we can’t have a XAML file for the page. The example below inherits from CustomCarouselPage, it is only an empty class that inherits from CarouselPage, the only reason is that we want to create a custom renderer for the CarouselPage.

#if WINDOWS_PHONE
    public partial class MainView : CustomCarouselPage
    {
#else
    public partial class MainView : ExtendedTabbedPage
    {
#endif

To get it work with conditional compile we also need to add “WINDOWS_PHONE” to conditional compile symbols under the Build tab on project properties for the shared project. I recommend to create a two new build configurations for the solution, I use to call them Debug_WP (copy settings from Debug) and Release_WP(copy settings for Release).

The CarouselPage doesn’t have titles for the panorama items. To fix that we need to create a custom renderer in the Windows Phone project. While we want to extend the default renderer we can inherit from CarouselPageRenderer. If we want to style the PanoramaHeader and the PanoramaItemHeader we can do it by creating templates and then add them to the Panorama as shown below.

[assembly: ExportRenderer(typeof(CustomCarouselPage), typeof(CustomCarouselPageRenderer))]
namespace MyApp.WinPhone.Renderers
{   
    public class CustomCarouselPageRenderer : CarouselPageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
 
            var titleTemplate = App.Current.Resources.SingleOrDefault(x => x.Key.ToString() == "PanoramaTitle").Value as System.Windows.DataTemplate;
            if (titleTemplate != null)
            {
                TitleTemplate = titleTemplate;
            }
 
            var headerTemplate = App.Current.Resources.SingleOrDefault(x => x.Key.ToString() == "PanoramaItemHeader").Value as System.Windows.DataTemplate;
            if (headerTemplate != null)
            {
                HeaderTemplate = headerTemplate;
            }
 
            for (int i = 0; i < Items.Count; i++)
            {
                var item = Items[i] as PanoramaItem;
                var page = Element as CarouselPage;
                item.Header = page.Children[i].Title;
 
                var content = item.Content as CarouselPagePresenter;
                content.Margin = new System.Windows.Thickness(0, -30, 0, 0);
            }
        }
    }
}

Here is an example how the templates in App.xaml (in the Windows Phone project) can look like:

 <Application.Resources>
        <DataTemplate x:Key="PanoramaTitle">
            <ContentPresenter>
                <TextBlock Text="{Binding}" FontSize="100" Foreground="#FFFFFF" Margin="0,40,0,0" />
            </ContentPresenter>
        </DataTemplate>
        <DataTemplate x:Key="PanoramaItemHeader">
            <Grid>
                <ContentPresenter>                  
                    <TextBlock Text="{Binding}" FontSize="30" Foreground="#FFFFFF" Margin="-10,20,0,0"  />
                </ContentPresenter>
            </Grid>
        </DataTemplate>
    </Application.Resources>

Dependency Graph with NDepend

Right now I evuluating a new software called NDepend. NDepend is installad as a Visual Studio plugin. I havn’t use it much yet, but I have already found a feature that I like a lot. It is the dependency graph. The graph show how assemblies is related to other assemblies in your Visual Studio solution and to external assemblies. You can easily show information about an assembly buy hover over an assembly in the graph.

With Visual Studio Ultimate you can generate dependency graphs out of the box. But I think that the tool for dependency graphs in NDepend gives me a much better overview than the tool in Visual Studio Ultimate and  it much easier to use.

When I have evulated it more I will write a full review of the software.

 

 

Extend Label in Xamarin.Forms with a font color property

The label control in Xamarin.Forms does not have a FontColor property. But the control is easy to extend.

First create a new class that inherits from Label.
Create a FontColor property of type string. The value of the FontColor will in this example be an RGBA string.

public class CustomLabel : Label
    {
 
         public static readonly BindableProperty FontColorProperty = 
             BindableProperty.Create<CustomLabel, string>( 
                 p => p.FontColor, ""); 
 
 
         public string FontColor
         { 
             get 
             { 
                 return (string)GetValue(FontColorProperty); 
             } 
             set 
             { 
                 SetValue(FontColorProperty, value); 
             } 
         } 
 
    }

Next step is to write a custom renderer for each platform.

iOS

[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace MyApp.iOS.Renderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
 
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
 
            if(e.PropertyName == "FontColor")
            {
                var view = (CustomLabel)Element;
 
                var values = view.FontColor.Split(',');
 
                Control.TextColor = UIColor.FromRGBA(int.Parse(values[0]), int.Parse(values[1]), int.Parse(values[2]), int.Parse(values[3]));
            }
        }
    }
}

Android

[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace MyApp.Android.Renderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
 
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
 
            if(e.PropertyName == "FontColor")
            {
                var view = (CustomLabel)Element;
 
                var values = view.FontColor.Split(',');
 
                var color = Color.Argb(int.Parse(values[3]),int.Parse(values[0]), int.Parse(values[1]), int.Parse(values[2]));
 
                Control.SetTextColor(color);            
            }
        }
    }
}

Windows Phone

[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRenderer))]
namespace MyApp.WinPhone.Renderers
{
    public class CustomLabelRenderer : LabelRenderer
    {
 
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
 
            if(e.PropertyName == "FontColor")
            {
                var view = (CustomLabel)Element;
 
                var values = view.FontColor.Split(',');
                Control.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromArgb(byte.Parse(values[0]), byte.Parse(values[1]), byte.Parse(values[2]), byte.Parse(values[3])));
            }
        }
    }
}

To use the custom label in XAML you need to declare the namespace.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
					   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
					   x:Class="MyApp.Views.MyView"
            xmlns:controls="clr-namespace:MyApp.CustomControls;assembly=MyApp">

Then you can use the control i XAML like this:

<controls:CustomLabel FontColor="255,255,255,255" Text="My custom label" />

Sogeti Inspiration Day 2014

Den 9 oktober anordnar Sogeti i Borlänge Sogeti Inspiration Day, temat är “Lyckas med din digitala resa”. Jag och Johan Karlsson(http://www.johankarlsson.net/ kommer att vara föreläsare på en session om att utveckla appar med C# och Xamarin. Där kommer vi berätta hur man kan använda Xamarin för att utveckla appar för alla stora mobila plattformar med en gemensam kodbas.

Ta chansen att komma och lyssna på oss och andra duktiga talare! Mer information och anmälan hittar du på följade länk, http://www.sogeti.se/Nyheter-Media/Kalendarium/SogetiInspirationDayblge14/.

Johan Karlsson och Daniel Hindrikes, Sogeti

Handle Windows Phone back button pressed when using MVVM

When I building an app with a MVVM framework I want to have my view models in a portable class library so I can use same view models for the Windows Phone app as for the iOS and Android app when building apps using Xamarin.

If I press the back button in a Windows Phone app built using MvvmCross (a MVVM framework), the app will be placed in background. That is the behavior I want if I’m on the first view of the app. But if I have navigated to Another view I would like to return to the previous view. To do that I need to handle the back button event. I want to have the code for handle the back button event in my view models that is placed in a portable class library, but the code for handling the event is platform specific. This post will show how to handle the back button event in a Windows Phone app built using WinRT. You can of course use this way to handle platform specific events for other events than the back button event.

First of all I creating an interface, I use to name it IPlatformEvents.

public interface IPlatofrmEvents
{
     event EventHandler BackButtonPressed;
}

In my view models I using IoC (Inversion of Control) and constructor injection to resolve the interface. In my method for handling the back button pressed I using the Close method to close the current view and return to the previous one in the stack. Don’t forget to remove the handler from the event in the handler method. If you do not, it can cause problems later.

public class MyViewModel : MvxViewModel
{
     private IPlatformEvents _platformEvents;     
 
     public MyViewModel(IPlatformEvents platformEvents)
     {
          _platformEvents = platformEvents;
 
          _platformEvents.BackButtonPressed += BackButtonPressed;
     }
 
     void BackButtonPressed(object sender, EventArgs e)
     {
         Close(this);
         _platformEvents.BackButtonPressed -= BackButtonPressed;
     }
}

If you want to read more about IoC and MvvmCross you can read my post about MvvmCross and IoC and my post about how to use a different IoC provider then the built-in when using MvvmCross.

Next step is to write the platform specific implementation of the interface. For an Windows Phone app using WinRT the implementation would look like this.

public class WindowsPhoneEvents : IPlatformEvents
{
      public event EventHandler BackButtonPressed;
 
      public WindowsPhoneEvents()
      {
          HardwareButtons.BackPressed += HardwareButtons_BackPressed;
      }
 
      void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e) 
      { 
             if(BackButtonPressed != null) 
             { 
                   BackButtonPressed(this, new EventArgs()); 
                   e.Handled = true; 
             } 
      } 
 
}

When I have created the platform specific implementation I just have to register it to the IoC container. You can read how to do it if you read the post that I linked to above.

Use a different IoC provider then the built-in when using MvvmCross

As I wrote in an earlier post, MvvmCross has IoC built-in. If you for some reason want to use a different IoC provider then the built-in when using MvvmCross you can write your own provider and use for example Autofac or TinyIoC. This post will show you how to use Autofac.

I create an own project (of type Portable Class Library) so I don’t have to reference Autofac in my core project. I can have it in my client project but then I can’t reference it from other client projects.

In my Autofac resolver I have to implement the IMvxIoCProvider interface and the class has to inherit from MvxSingleton if it should work.

public class AutofacMvxProvider : MvxSingleton<IMvxIoCProvider>, IMvxIoCProvider
    {
        private IContainer _container;
 
        public AutofacMvxProvider(IContainer container)
        {
            _container = container;
        }
 
        public void CallbackWhenRegistered(Type type, Action action)
        {
            _container.ComponentRegistry.Registered += (sender, args) => {
                if(args.ComponentRegistration.Services.OfType<TypedService>().Any( x => x.ServiceType == type))
                {
                    action();
                }
            };
        }
 
        public void CallbackWhenRegistered<T>(Action action)
        {
            CallbackWhenRegistered(typeof(T), action);
        }
 
        public bool CanResolve(Type type)
        {
            return _container.IsRegistered(type);
        }
 
        public bool CanResolve<T>() where T : class
        {
            return _container.IsRegistered<T>();
        }
 
        public object Create(Type type)
        {
            return Resolve(type);
        }
 
        public T Create<T>() where T : class
        {
            return Resolve<T>();
        }
 
        public object GetSingleton(Type type)
        {
            return Resolve(type);
        }
 
        public T GetSingleton<T>() where T : class
        {
            return Resolve<T>();
        }
 
        public object IoCConstruct(Type type)
        {
            return Resolve(type);
        }
 
        public T IoCConstruct<T>() where T : class
        {
            return Resolve<T>();
        }
 
        public void RegisterSingleton(Type tInterface, Func<object> theConstructor)
        {
            var builder = new ContainerBuilder();
            builder.Register(x => theConstructor()).As(tInterface).AsSelf().SingleInstance();
            builder.Update(_container);
        }
 
        public void RegisterSingleton<TInterface>(Func<TInterface> theConstructor) where TInterface : class
        {
            var builder = new ContainerBuilder();
            builder.Register(x => theConstructor()).As<TInterface>().AsSelf().SingleInstance();
            builder.Update(_container);
        }
 
        public void RegisterSingleton(Type tInterface, object theObject)
        {
            var builder = new ContainerBuilder();
            builder.RegisterInstance(theObject).As(tInterface).AsSelf().SingleInstance();
            builder.Update(_container);
        }
 
        public void RegisterSingleton<TInterface>(TInterface theObject) where TInterface : class
        {
            var builder = new ContainerBuilder();
            builder.RegisterInstance(theObject).As<TInterface>().AsSelf().SingleInstance();
            builder.Update(_container);
        }
 
        public void RegisterType(Type tFrom, Type tTo)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType(tTo).As(tFrom).AsSelf();
            builder.Update(_container);
 
        }
 
        public void RegisterType(Type t, Func<object> constructor)
        {
            var builder = new ContainerBuilder();
            builder.Register(x => constructor()).As(t).AsSelf();
            builder.Update(_container);
        }
 
        public void RegisterType<TInterface>(Func<TInterface> constructor) where TInterface : class
        {
            var builder = new ContainerBuilder();
            builder.Register(x => constructor()).As<TInterface>().AsSelf().SingleInstance();
            builder.Update(_container);
        }
 
        public void RegisterType<TFrom, TTo>()
            where TFrom : class
            where TTo : class, TFrom
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<TTo>().As<TFrom>().AsSelf();
            builder.Update(_container);
        }
 
        public object Resolve(Type type)
        {
            return _container.Resolve(type);
        }
 
        public T Resolve<T>() where T : class
        {
            return _container.Resolve<T>();
        }
 
        public bool TryResolve(Type type, out object resolved)
        {
            return _container.TryResolve(type, out resolved);
        }
 
        public bool TryResolve<T>(out T resolved) where T : class
        {
            return _container.TryResolve<T>(out resolved);
        }
    }

To use your own IoC provider you have to override the CreateIocProvider method in your Setup class.

protected override Cirrious.CrossCore.IoC.IMvxIoCProvider CreateIocProvider()
{
            var builder = new ContainerBuilder();
 
            builder.RegisterType<MyType>().As<IMyType>();
 
            var container = builder.Build();
 
            return new AutofacMvxProvider(container);
}

MvvmCross and IoC

MvvmCross has IoC built-in, in this post I will show how to use it. The Mvx class has a few static metods that you can use for configure the IoC container.

RegisterType
Use the register type method to register new types to the IoC container.

//Register a type
Mvx.RegisterType<IMyType,MyType>();
 
//Register a type as a singleton
Mvx.RegisterSingleton<IMySingleton>(new MySingleton());

Resolve
Use the resolve method to create instances from interfaces.

var myInstance = Mvx.Resolve<IMyType>();

But I recommend to use constructor injection so much as possible. This because you can use it to resolve interfaces in a class library without referencing the assembly that contains the IoC container.

public class MyClass
{
     private IMyType _myType;
 
     public MyClass(IMytype myType)
     {
          _myType = myType;
     }
}

I use to register types in the create app method in the Setup class on each client.

 

 

WordRoom – vägen till cross platform med Xamarin och Azure

Att bygga ett onlinespel innebär många utmaningar, att bygga ett onlinespel cross platform innebär ännu fler utmaningar. Under TechDays kommer jag och Johan Karlsson att berätta om våra erfarenheter efter att vi byggde ordspelet WordRoom där vi använde Xamarin dels för att kunna använda C#, men främst för att kunna dela klientkod mellan alla plattformarna för att spara utvecklingstid och öka förvaltningsbarheten. Som backend använder vi en lösning hostad i Windows Azure, en lösning som är fullt skalbar för att kunna skalas både upp och ner beroende på hur belastningen ser ut.

Under vår session på TechDays kommer vi att fokusera på dessa områden

  • Hur man bygger en cross platform lösning för mobila enheter med hjälp av Xamarin
    Vi kommer att berätta varför vi valde Xamarin och vilken arkitektur vi använder för WordRoom för att kunna dela så mycket kod som möjligt mellan de olika plattformarna, vilken kod man kan dela och vilken kod som måste vara plattformsspecifik.
  • Vad man behöver tänka på för att bygga en skalbar backend med hjälp av Azure
    WordRoom använder flera olika tjänster i Azure. Vi kommer att berätta vilka vi använder och hur vi tänkte när vi byggde en arkitektur anpassad för att kunna utnyttja Azure optimalt.

 

WordRoom finns att ladda mer för Windows 8+, Windows Phone, iOS och Android.

Xamarin, MvvmCross and ValueConverters

This post will show you how to use ValueConverters in an Android app built with Xamarin. For an introduction to Xamarin and MvvmCross read this blog post.

If you want to convert values before you bind it to a property you can use value converters. For example if you want to view an element if a string property is not null you can use a value converter to convert it to a boolean.

First you will create a new class that inherit from MvxValueConverter and then override the Convert method and write your code there, in this case a simple null check. The class has to name end with ValueConverter.

public class IsNullValueConverter : MvxValueConverter
{
    public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
          return !String.IsNullOrEmpty(value as string);
    } 
}

Then name of the value converter will be the first part of the class name, so my IsNullValueConverter class will be used as IsNull in the Android Xml and the argument will be the property in your view model that you want to use.

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        local:MvxBind="Visible IsNull(Name)">

ValueConverters is a very effective and simple way to do convert values without to create a property in the ViewModel for it.

Xamarin.Forms: Change background color on iOS ListView

The ListView control in Xamarin.Forms has a background color property. But iOS has a default color on each cell, because of that it will not work to set a color with that property. One solution is to use a custom renderer for the ListView on iOS.

A custom renderer can be created for the ListView control, but I prefer to create a new control that inherit from ListView. Then I can use the ListView as standard as I want and I can use my customized ListView if I want.

The first step i to create a new control that inherits from ListView.

public class MyListView : ListView
{
}

Next step is to create the CustomRenderer for iOS. To do that create a new class in your iOS project (If you don’t create a custom ListView for the other platforms, the standard renderer will be used). Your new class will inherit from ListViewRenderer. In the custom renderer you will override the OnElementPropertyChanged method.
In this method you can do the changes you want to do to the ListView. This code will run every time a property is changed on the ListView. In this case we only need to run our code when it’s the ItemsSource property that is changed.

public class MyListViewRenderer : ListViewRenderer
{
    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
 
            if(e.PropertyName == "ItemsSource")
            {
                var control = (UITableView)Control;
 
                foreach (var cell in control.VisibleCells)
                {
                    cell.BackgroundColor = UIColor.FromRGB(255, 0, 0);
                }
            }
 
        }
}

To use the custom renderer we need to add an assembly attribute outside the class and the namespace.

[assembly: ExportRenderer(typeof(MyListView), typeof(MyListViewRenderer))]
namespace MyApp.iOS
{

To use your new control i your XAML you need to include the namespace for it.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:myControls="clr-namespace:MyApp.Controls;assembly=MyApp"

Then you can use it with the alias you assign to it in the namespace declaration.

<myControls:MyListView>
   <!-- ListView content -->
</myControl:MyListView>

Building a tabbed app using Xamarin.Forms

Xamarin.Forms is one of the biggest news with Xamarin 3. With Xamarin.Forms you can build UI for 3 platforms (Windows Phone, iOS and Android) with one shared codebase. What is unique for Xamarin.Forms is that the UI code you are writing with Xamarin.Forms will render native UI controls. That means that the UI will look like a Windows Phone app when running the code on a Windows Phone and it will look like a iPhone app when running the code on an iPhone and the same on Android.

Create a Xamarin.Forms project in Visual Studio
This post will show you the basics when building an app with Xamarin.Forms in Visual Studio 2013. You can also build apps using Xamarin.Forms with Xamarin Studio but for the Windows Phone project you need to use Visual Studio.

To create an app with Xamarin.Forms open the new project dialog. Xamarin.Forms project templates is located under “Mobile Apps”. There are three types of project you can create, a blank app with the code in a project of type portable class library (the project will be referenced in each client project), a blank app with shared code (you have to link the each file to each client project) and a class library of type portable class library.

In this tutorial I will use the first choice because I want Visual Studio to create the client projects (projects for Windows Phone, iOS and Android) and I think it’s easier to reference an assembly than linking files.

Create dialog

Now Visual Studio has created four projects, the client projects and a project for the shared UI code.

In the shared project I add a new item based on the template called “Forms Xaml Page”. Then a XAML-file and a code behind file is created.

Many of the tutorials I have read writes the most of the code in the code behind file, but I want to use XAML as much as possible. One disadvantage to use Visual Studio is that there is not intellisense for the XAML-code. If you miss it to much you can use Xamarin Studio instead.

Create an app with tabs

The app in this tutorial will be a app with two tabs/views and for that we will use a tabbed page. This post will just use standard styles. But you can both style the app for all platforms or you can do platform specific styling.

In the view we just created ad the code below. This will be a container for the views in the app.

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
					   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
					   x:Class="FormsDemo.FirstView"
            Title="News">
 
</TabbedPage>

You also need to go to the code behind file and make the class inherit from “TabbedPage”.

Next step is to create the content views, this app will have one for news and one for settings, so I add two new forms xaml pages to the shared project. Before I starting to create each view I will add them to the tabbed page. This is done from the code behind file of our “container”.

public partial class FirstView : TabbedPage
    {
        public FirstView()
        {
            InitializeComponent();
 
            Children.Add(new NewsView());
            Children.Add(new SettingsView());
 
        }
    }

The title for the tabs will be the title we set as Title property on ContentPage for each view.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
					   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
					   x:Class="FormsDemo.NewsView" Title="News">

Add a list to the app
My first tab will be a list with news. For that I using the ListView control that is included in Xamarin.Forms.

<ListView x:Name="News" ItemsSource="{Binding News}" RowHeight="80" BackgroundColor="Transparent">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <ViewCell.View>
            <StackLayout Orientation="Vertical" Spacing="0" Padding="10">
              <Label Font="Bold,20" Text="{Binding Header}" />
              <Label Font="16" Text="{Binding Text}" />
            </StackLayout>
          </ViewCell.View>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

And the code behind will look like this:

public partial class NewsView
    {
        public NewsView()
        {
            InitializeComponent();
 
            BindingContext = new NewsViewModel();
        }
    }
 
    public class NewsViewModel
    {
        public NewsViewModel()
        {
            News = new List<NewsItem>()
            {
                new NewsItem()
                {
                    Header = "Header 1",
                    Text = "Text 1"
                },
                new NewsItem()
                {
                    Header = "Header 2",
                    Text = "Text 2"
                }
            };
        }
 
        public List<NewsItem> News { get; set; }
    }
 
    public class NewsItem
    {
        public string Header { get; set; }
        public string Text { get; set; }
    }

iPhone

Windows Phone

Android

On the settings page I using the Switch control to turn news sources on or off.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
					   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
					   x:Class="FormsDemo.SettingsView">
  <StackLayout Orientation="Vertical" Padding="10">
	  <Label Font="Bold,20" Text="News sources" />
    <StackLayout Orientation="Horizontal">
      <Label Text="Xamarin" VerticalOptions="Center" />
      <Switch VerticalOptions="Center" />
    </StackLayout>
    <StackLayout Orientation="Horizontal">
      <Label Text="Microsoft" VerticalOptions="Center" />
      <Switch VerticalOptions="Center" />
    </StackLayout>
  </StackLayout>
</ContentPage>

Windows Phone

Android

iPhone


That was the basics to build an tabbed app with Xamarin.Forms. Of course you can do much more than this with Xamarin.Forms.

Error when syncing iOS SDK version with Xamarin build host

When I would deploy to the iOS simulator from Visual Studio I got a message that I hade to sync iOS SDK version with the build. But when I tried to sync I got an error that the sync process couldn’t connect to the server.

Then I tried to open Xamarin Studio to check if there was any updates for any of the Xamarin products. And there was an update for Xamarin 3.1, after installing that update I could sync the iOS SDK without errors.

It looks like you have to install updates (other than the Visual Studio plugin) to Xamarin via Xamarin Studio.

Problems with Xamarin iOS project and web project in same solution

In my Visual Studio solution I have both client projects and server side projects. The client projects are for Windows Phone, Xamarin iOS, Xamarin Android and WPF. The server side project is a Mobile Services .NET backend project.

My problems started yesterday when I would publish the latest update of my backend to Azure. I right clicked on the project and hit publish, then shown a dialog with the following text “object reference not set to an instance of an object”. To verify if it was a problem with my project or with Visual Studio I created a new solution with a new Mobile Services .NET project, and it worked. Then added the project from the old solution to the new solution and it worked. Then I started to think about the diffrences in my both solutions, so I added new client projects. After that I have added a new iOS project I got the same error when I trying to publish the Mobile Services project to Azure. When I removed the iOS projects from the old soultion and restarted Visual Studio it worked there to.

I also tried to create a new solution with a MVC project and a Xamarin iOS project to investigate if the problem was just for Mobile Services projects or for all web projects. It looks like the problem is for all web projects when you have a Xamarin iOS project in the same solution.

I using Visual Studio 2013 with update 2.

Debug Android emulator remotly

When developing apps for Android I’m using Xamarin and Visual Studio. I’m running Windows under Parallels.Therefor I can’t use the x86 emulator with HAXM for hardware acceleration. But Android emulator is really slow without hardware acceleration, because of that i running the emulator on the host OS, in my case OS X.

To set up remote debugging there are a few steps to follow.

  • Enable “Remote Login” in OS X. You find it under “System Preferences” – > “Sharing”.
  • Install the Android SDK on the host OS.
  • Open SDK manager and install the Intel x86 Atom System Image for the API version you want the emulator to run on. If you have Xamarin Studio installed I think that is the easist way to start the SDK manager.

SDK Manager

 

Create emualtor dialog

  • Start your new emulator, if it start and using HAXM successfully you will se the text “HAX is working and emulator runs in fast virt mode” during the startup process.
  • Kill the adb server on the host OS using the command adb kill-server.
  • Kill the adb server on the guest OS using the command adb kill-server.
  • Install Putty on your Windows machine, that can be downloaded from here, http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
  • Open Putty and type the hostname or IP address to your host OS.
  • Under SSH -> Tunnel, configure port forwarding on port 5554 and port 5555.

Putty

 

  • Open a new session and type your login credentials when Putty asks for them.
  • Start the adb server on the host OS using the command adb start-server. To verify that the emulator is connected use the command adb devices. 
  • You will now be ready to start debug your app in the emulator remotely.