Xamarin.Tip – PCL Profile Problems

New to Xamarin now that Microsoft is pushing it harder with Visual Studio 2017 and Visual Studio for Mac? Can’t create a new PCL and reference it in your Out of the Box Xamarin.Forms project? This post is for you, and I assure you – you are not alone.

 

The Problem

The core of the problem is this shift within the Microsoft Stack from many different versions of the .NET framework and tools into a “standard” – .NET Standard. However, certain parts of Xamarin aren’t quite there. These are things that worked in Visual Studio 2015, but are now new problems for VS 2017 and VS for Mac, especially if you’re working on a team that uses a mix of these.

There are multiple types of Profiles available for a Portable Class Library. Here’s a quick matrix of the different Profiles and where they compare to .NET Standard versions and supported profiles:

PCL Profile .NET Standard PCL Platforms
Profile7 1.1 .NET Framework 4.5, Windows 8
Profile31 1.0 Windows 8.1, Windows Phone Silverlight 8.1
Profile32 1.2 Windows 8.1, Windows Phone 8.1
Profile44 1.2 .NET Framework 4.5.1, Windows 8.1
Profile49 1.0 .NET Framework 4.5, Windows Phone Silverlight 8
Profile78 1.0 .NET Framework 4.5, Windows 8, Windows Phone Silverlight 8
Profile84 1.0 Windows Phone 8.1, Windows Phone Silverlight 8.1
Profile111 1.1 .NET Framework 4.5, Windows 8, Windows Phone 8.1
Profile151 1.2 .NET Framework 4.5.1, Windows 8.1, Windows Phone 8.1
Profile157 1.0 Windows 8.1, Windows Phone 8.1, Windows Phone Silverlight 8.1
Profile259 1.0 .NET Framework 4.5, Windows 8, Windows Phone 8.1, Windows Phone Silverlight 8

Now we can look at the different .NET Standard versions and their supported platforms:

 

.NET Standard 1.0 1.1 1.2 1.3 1.4 1.5 1.6 2.0
.NET Core 1.0 1.0 1.0 1.0 1.0 1.0 1.0 2.0
.NET Framework (with tooling 1.0) 4.5 4.5 4.5.1 4.6 4.6.1 4.6.2
.NET Framework (with tooling 2.0 preview) 4.5 4.5 4.5.1 4.6 4.6.1 4.6.1 4.6.1 4.6.1
Mono 4.6 4.6 4.6 4.6 4.6 4.6 4.6 vNext
Xamarin.iOS 10.0 10.0 10.0 10.0 10.0 10.0 10.0 vNext
Xamarin.Android 7.0 7.0 7.0 7.0 7.0 7.0 7.0 vNext
Universal Windows Platform 10.0 10.0 10.0 10.0 10.0 vNext vNext vNext
Windows 8.0 8.0 8.1
Windows Phone 8.1 8.1 8.1
Windows Phone Silverlight 8.0

 

Xamarin.Forms is created to support everything from Windows Silverlight 8.0 and up. This means that Xamarin.Forms projects are created using a Profile 259 PCL. This is fine, however, Profile 259 is on it’s way out the door, and therefore can’t be created in Visual Studio 2017! When you create a new PCL in VS 2017, it is created with the latest version of .NET Standard that supports .NET Core, UWP, and Xamarin (as of now this is default to Profile7. However, this is incompatible with Profile 259 and therefore cannot be referenced by your newly created Xamarin.Forms project. There’s no way in the IDE or properties to get it to 259, so if you do still want to support Windows Phone and Windows 8 with your Xamarin Projects in Visual Studio 2017, read below. If you don’t, update your Xamarin.Forms project to remove support for Windows 8 and Windows phone and your profiles will be matching again.

Here’s what the default Xamarin.Forms project targets are:
Screen Shot 2017-07-03 at 11.42.45 AM

And here is what a newly created PCL project targets are with everything selected:

Screen Shot 2017-07-03 at 11.42.58 AM

 

The Solution

We need to get our newly created PCLs to Profile 259 in order to reference them in our Xamarin.Forms project. We can’t do this in the IDE, so we need to dive into the .csproj file itself and make some changes:

NewPCL.csproj

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import ... />
  <PropertyGroup>
    <MinimumVisualStudioVersion>10.0</MinimumVisualStudioVersion>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{4a6a9117-1715-47ea-a6c7-6b0fd5b31bdb}</ProjectGuid>
    <OutputType>Library</OutputType>
    <RootNamespace>NewPCL</RootNamespace>
    <AssemblyName>NewPCL</AssemblyName>
    <DefaultLanguage>en-US</DefaultLanguage>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

    <!-- THIS IS WHAT NEEDS TO CHANGE -->
    <TargetFrameworkProfile>Profile7</TargetFrameworkProfile>


    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
  </PropertyGroup>
...
</Project>

Take that line of Profile7 and update it to Profile259 so that it looks like this all together:

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import ... />
  <PropertyGroup>
    <MinimumVisualStudioVersion>10.0</MinimumVisualStudioVersion>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{4a6a9117-1715-47ea-a6c7-6b0fd5b31bdb}</ProjectGuid>
    <OutputType>Library</OutputType>
    <RootNamespace>NewPCL</RootNamespace>
    <AssemblyName>NewPCL</AssemblyName>
    <DefaultLanguage>en-US</DefaultLanguage>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

    <!-- THIS IS WHAT HAS CHANGED -->
    <TargetFrameworkProfile>Profile259</TargetFrameworkProfile>


    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
  </PropertyGroup>
...
</Project>

 
Now you’ll be able to add this project as a reference in your Xamarin.Forms PCL project and continue on.

I know this is pretty annoying to do on large projects that contain many different project files. Take a look at my Onion Architecture project as an example…

This is something that is happening because of this weird in-between state we are at with .NET tooling and the move to .NET Standard. Going forward, Xamarin.Forms will be dropping support for Windows Phone Silverlight which will no longer require Profile259 in order to build our applications in Xamarin.Forms. However, for now, this is the fix for new projects!

Still Broken?

Still having issues with your project structures? Leave a comment and I’ll try to help resolve it.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Fixing the Highlighting Drop In Your Xamarin.Android Projects

I’ve seen a few people run into this issue in both Visual Studio 2015 and 2017. For those of you who don’t know what I’m talking about, the issue is that code highlighting drops completely in newly opened files. I’ve personally seen it happen in both Xamarin.Forms PCLs and in Xamarin.Android projects. The reason you lose your highlighting is because the project fails to load properly, and your files will then open as “Miscellaneous Files”:

MiscFilesError

These should be opening up as part of the project and thus getting the references required for highlighting, so the goal here is to fix the project load and get these files to open as part of that project.

So here are a few steps that have worked for everyone who has reached out for help:

  1. Don’t panic! This will be quick.
  2. Try unloading the project and reloading it (Right click the project in the Solution Explorer > Unload Project, Right click > Reload Project)
  3. Still happening when you open files in that project? Keep reading.
  4. Check your Error List, there might be warnings to give you hints here.

In this post, we will look at resolving the issue for Xamarin.Android projects. If you are looking for resolving issues in your Xamarin.Forms PCL projects look at this earlier post: Xamarin.Tips – Fixing the Highlighting Drop In Your Xamarin.Forms Projects

Xamarin.Android Project Issues

There are two common issues that are particular to Xamarin.Android projects that cause this.

Dependencies aren’t built

The first is a known bug in Xamarin projects (especially when first created). The problem is that it relies on it’s dependencies to load properly, however, if you have not built one or more of the projects that the Android project depends on, you will get this load error:

Warning1

along with it’s partner:

Warning2

However, you may have seen this and followed the steps listed without fixing anything or learning more about the issue:

1. Close Visual Studio
2. Open a Visual Studio Developer Command Prompt
3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true)
4. Delete .vs directory/.suo file
5. Restart VS from the command prompt you set the environment variable (devenv)
6. Open the solution

THE SOLUTION:
1. Unload the Android project
2. Build all the other projects in your solution
3. Reload your Android project

A Corrupt or Broken Android Resource

This one can be elusive because it does not always throw errors or warnings, but is also quite common. The problem is that one of your Android resources has an error. This is likely in your layouts or your values folders.

THE SOLUTION:
1. Go through your error list for warnings about your Android resources
2. If you have any issues there, fix those problems and unload > reload the Android project.
3. If you do NOT see any items in your Error List, go through each of your layout and value files (like colors.xml and styles.xml) and search for errors. They are more likely to show warning squiggles in your editor.
4. Resolve all issues and unload > reload the Android project.

 

If none of these solutions fixed your problem, read below for more generic solutions for this issue.

Refresh Your Intellisense Cache

Your Intellisense cache could be corrupt, so try clearing it. Close all your open files then:

Edit > IntelliSense > Refresh Local Cache 

Or Ctrl + Shift + R

Clearing Your Local Data

Close Visual Studio Completely, then go to %appdata%\Microsoft\VisualStudio{your_version_number}\ReflectedSchemas and delete all the content.

Reset your Visual Studio Settings

In Visual Studio, go to Tools > Import and Export Settings and hit Reset all settings.

Restart Visual Studio.

Fix All Errors and Warnings In the Error List

Similarly to how we talked about fixing your XAML error, try making sure all of your errors and warnings are fixed. Some other common issues that can cause the project to load with errors include:

  1. Circular References
  2. Missing project references
  3. Failed nuget downloads
  4. Duplicate files
  5. Broken/wrong typed partial classes

 

Still Not Working?

Leave a comment describing all the detail you can about the errors and warnings you are seeing and we can work together to fix your problems!

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Fixing the Highlighting Drop In Your Xamarin.Forms Projects

I’ve seen a few people run into this issue in both Visual Studio 2015 and 2017. For those of you who don’t know what I’m talking about, the issue is that code highlighting drops completely in newly opened files. I’ve personally seen it happen in both Xamarin.Forms PCLs and in Xamarin.Android projects. The reason you lose your highlighting is because the project fails to load properly, and your files will then open as “Miscellaneous Files”:
MiscFilesError

These should be opening up as part of the project and thus getting the references required for highlighting, so the goal here is to fix the project load and get these files to open as part of that project.

So here are a few steps that have worked for everyone who has reached out for help:

  1. Don’t panic! This will be quick.
  2. Try unloading the project and reloading it (Right click the project in the Solution Explorer > Unload Project, Right click > Reload Project)
  3. Still happening when you open files in that project? Keep reading.
  4. Check your Error List, there might be warnings to give you hints here.

In this post, we will look at resolving the issue for Xamarin.Forms PCL projects, and will look at fixes for Xamarin.Android projects in another article.

Xamarin.Forms PCL Issues

The most common issue here is that there is an issue in your XAML. For some reason, XAML errors/warnings can throw off the entire project load.

Here’s a quick look at what that might look like:

XamlErrors

  1. From your Error List view, find the XAML page culprit.
  2. Fix the error in your XAML file.
  3. Close all files in the project that is having issues.
  4. In the Solution Explorer, click the refresh button at the top.SolutionRefresh
  5. Re-open the files that were breaking, and you should see everything is back to normal.

Didn’t solve your problem? Let’s look at some of the conventional fixes for this then:

Refresh Your Intellisense Cache

Your Intellisense cache could be corrupt, so try clearing it. Close all your open files then:

Edit > IntelliSense > Refresh Local Cache 

Or Ctrl + Shift + R

Clearing Your Local Data

Close Visual Studio Completely, then go to %appdata%\Microsoft\VisualStudio{your_version_number}\ReflectedSchemas and delete all the content.

Reset your Visual Studio Settings

In Visual Studio, go to Tools > Import and Export Settings and hit Reset all settings.

Restart Visual Studio.

Fix All Errors and Warnings In the Error List

Similarly to how we talked about fixing your XAML error, try making sure all of your errors and warnings are fixed. Some other common issues that can cause the project to load with errors include:

  1. Circular References
  2. Missing project references
  3. Failed nuget downloads
  4. Duplicate files
  5. Broken/wrong typed partial classes

 

Looking for solving this problem for your Android projects? Stay tuned for another post about some of the Android specific issues that might be causing project load fails.

 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tips – Extending Xamarin Plugins

An Introduction to Plugins

If you’re on my blog, you know I love Xamarin. Writing cross-platform applications and sharing as much code as possible is, in my opinion, the way to go. The Xamarin community has taken an awesome technology, and made it even more awesome by building tons and tons of plugins. These plugins allow us to access platform-specific functionality from shared code, which simply allows us as application developers to write even more code in our portable projects.

I ran into an interesting forum post talking about the structure of plugins made a standard by Xamarin. A lot of use these plugins, but of course, they are not made for everyone! I’ve seen many repositories riddled with issues asking for more and more features in the plugin. This post is going to show some ways to expand on those features with your own code! As well as show techniques to use these plugins with Inversion of Control and Dependency Injection, rather than through the Singleton that the standard ships with.

Suggested Resources Before Starting

It might be a good idea to read up on my blogs and watch my videos about calling platform specific code from a PCL. Check out the YouTube playlist for some different techniques. Specifically looking at the Singleton method and Dependency Injection method.

Resources for Examples

We are going to look at arguably my all time favorite plugin: UserDialogs by Allan Ritchie

If you haven’t used it yet, it’s a cool plugin that allows you to call platform specific pop ups and dialogs including alerts, toasts, prompts, action sheets, confirmation messages, and more.

We are also going to be using MvvmLight (as I tend to do) in order to use SimpleIoc for our Inversion of Control and Dependency Injection.

Let’s first look at using IoC and DI, then look at extending the functionality.

Use Dependency Injection to Call Your Plugins

If we look at Singleton of UserDialogs, we see that it simply changes the Init method based on the platform, and uses that to set the platform-specific implementation of IUserDialogs. The core of the functionality comes from that implementation of IUserDialogs. So rather than going through the Init method of the Singleton, we can instead register the implementation to an IoC container, and inject it into the constructor of our ViewModel or Service that calls it!

Let’s create a ViewModel that takes an IUserDialogs in its constructor:

public class MyViewModel : ViewModelBase
{
    ...
    private readonly IUserDialogs _userDialogs;
    public MyViewModel(IUserDialogs userDialogs)
    {
        _userDialogs = userDialogs;
    }
    ...
 }

Now that our ViewModel has a reference to an IUserDialogs, we can make calls to it from ICommands or methods.

public void ErrorToast(string message)
{
    // show a toast message with a red background
    _userDialogs.Toast(new ToastConfig(message).SetMessageTextColor(System.Drawing.Color.White).SetBackgroundColor(System.Drawing.Color.FromArgb(255, 213, 0, 0)));
}

 

 

Now all we need to do is register both our IUserDialogs platform implementation and our MyViewModelto our IoC container.

In our PCL or SharedLibrary:


...
ServiceLocator.SetLocatorProvider(() =&gt; SimpleIoc.Default);
...
SimpleIoc.Default.Register&lt;MyViewModel&gt;();
...

Then in our Android project:


...

 ActivityLifecycleCallbacks.Register(activity);
var userDialogsImplementation = new UserDialogsImpl(() =&gt; ActivityLifecycleCallbacks.CurrentTopActivity);
SimpleIoc.Default.Register&lt;IUserDialogs&gt;(() =&gt; userDialogsImplementation);
...

And in iOS:

...
// note iOS doesn't require registering lifecycle callbacks like iOS does.
SimpleIoc.Default.Register&lt;IUserDialogs, UserDialogsImpl();
...

Now when we create our MyViewModel, we don’t do it through calling new MyViewModel(), we will call to get the instance from the ServiceLocator. For example, we can set the BindingContext of a Page:

 

...
public MyMainPage()
{
    BindingContext = ServiceLocator.Current.GetInstance&lt;MyViewModel&gt;();
}
...

That’s all we need to do! As long as we make those Register calls for our MyViewModel and IUserDialogs before the call to the MyMainPage constructor, everything will be wired up and Injected.

Now that we have our application using Dependency Injection instead of the Singleton, it makes it even easier to override and extend the functionality of the plugin.

Changing Features and Functionality

There are only two things we need to change to our implementation from above.

  1. Create a new platform implementation of IUserDialogs that inherits from the UserDialogsImpl.
  2. Change the IoC Registration to use our new implementation.

Let’s create a new class called MyUserDialogsImpl that will inherit from UserDialogsImpl. In this class, we will override the Alert method and do something like change the Tint color on iOS:


public class MyUserDialogsImpl : UserDialogsImpl
{
    ...
    public override IDisposable Alert(AlertConfig config)
    {
        return this.Present(() =&gt;
        {
             var alert = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert);

            // custom piece:
            alert.View.TintColor = UIColor.Red;

             alert.AddAction(UIAlertAction.Create(config.OkText, UIAlertActionStyle.Default, x =&amp;amp;amp;amp;amp;gt; config.OnAction?.Invoke()));
             return alert;
         });
     }

 ...
}

Now where we registered the IUserDialogs before, we just substitute our new implementation!

 

...
// note iOS doesn't require registering lifecycle callbacks like iOS does.
SimpleIoc.Default.Register&lt;IUserDialogs, MyUserDialogsImpl&gt;();
...

So now our IoC set up will automatically set up our new implementation, so when we call the Alert method, it will show the Tint color as Red.

Adding New Features to Plugins

Similarly to how we changed functionality, we can add completely new functionality in just a few steps:

  1. Create a new Interface that inherits IUserDialogs in our shared code.
  2. Add a new method to that interface
  3. Change our new implementation to also implement that new interface
  4. Change our IoC Registration to register our implementation as our new interface instead of IUserDialogs
  5. Change our injected dependency in our MyViewModel to our new interface

In our shared code, let’s create an interface called ICustomDialogs and add a method to its definition:


public interface ICustomDialogs : IUserDialogs
{
    void SayHello();
}

 

Now, let’s update our MyUserDialogsImpl to implement our new interface:


public class MyUserDialogsImpl : UserDialogsImpl, ICustomDialogs
{
    public void SayHello()
    {
        this.Alert(&quot;Hello&quot;, &quot;World&quot;);
    }
}

Next, we need to update our IoC Register call:

 

 


...
SimpleIoc.Default.Register&lt;ICustomDialogs, MyUserDialogsImpl&gt;();
...

Lastly, let’s change our MyViewModel to use our new interface:

public class MyViewModel : ViewModelBase 
{ 
    ...
    private readonly ICustomDialogs _userDialogs; 
    public MyViewModel(ICustomDialogs userDialogs)
    {
        _userDialogs = userDialogs; 
    } 
    ...
}

Now we can call our SayHello method from our ViewModel too!

Recap

  1. Xamarin Plugins are awesome
  2. You don’t have to use Plugin Singletons!
  3. You can use dependency injection to inject your plugin implementations
  4. You can override methods in your platform specific implementations of your plugins
  5. You can create new functionality through another interface and updated injections!

[Video Series] Xamarin.Tips: Calling Platform-Specific Code from a PCL

Learn how to use 4 methods to call platform specific code from shared code in Xamarin. Make calls to the HockeyApp iOS SDK from a Portable Class Library.

  1. Singleton Method
  2. Xamarin.Forms Dependency Service
  3. Service Locator
  4. Dependency Injection

 

Source Code: https://github.com/SuavePirate/Xamarin.HockeyApp.Portable 

[VIDEO] Xamarin.Tips: Calling Platform-Specific Code from a PCL (All 4 Methods)

Using all 4 methods to call platform specific code from shared code in Xamarin. Make calls to the HockeyApp iOS SDK from a Portable Class Library.

 

Source Code: https://github.com/SuavePirate/Xamarin.HockeyApp.Portable 

[VIDEO] Xamarin.Tips: Calling Platform-Specific Code from a PCL (Dependency Injection)

Using Dependency Injection to call platform specific code from shared code in Xamarin. Make calls to the HockeyApp iOS SDK from a Portable Class Library.

 

Source Code: https://github.com/SuavePirate/Xamarin.HockeyApp.Portable 

[VIDEO] Xamarin.Tips: Calling Platform-Specific Code from a PCL (Service Locator {anti}Pattern)

Using the Service Locator anti-pattern to call platform specific code from shared code in Xamarin. Make calls to the HockeyApp iOS SDK from a Portable Class Library.

 

Source Code: https://github.com/SuavePirate/Xamarin.HockeyApp.Portable 

[VIDEO] Xamarin.Tips: Calling Platform-Specific Code from a PCL (Xamarin.Forms DependencyService)

 

Using the Xamarin.Forms DependencyService class to call platform specific code from shared code in Xamarin. Make calls to the HockeyApp iOS SDK from a Portable Class Library.

 

Source Code: https://github.com/SuavePirate/Xamarin.HockeyApp.Portable 

[VIDEO] Xamarin.Tips: Calling Platform-Specific Code from a PCL (Singleton Method)

 

Source Code: https://github.com/SuavePirate/Xamarin.HockeyApp.Portable