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.

Advertisements

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(() => SimpleIoc.Default);
...
SimpleIoc.Default.Register<MyViewModel>();
...

Then in our Android project:


...

 ActivityLifecycleCallbacks.Register(activity);
var userDialogsImplementation = new UserDialogsImpl(() => ActivityLifecycleCallbacks.CurrentTopActivity);
SimpleIoc.Default.Register<IUserDialogs>(() => userDialogsImplementation);
...

And in iOS:

...
// note iOS doesn't require registering lifecycle callbacks like iOS does.
SimpleIoc.Default.Register<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<MyViewModel>();
}
...

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(() =>
        {
             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 => 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<IUserDialogs, MyUserDialogsImpl>();
...

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("Hello", "World");
    }
}

Next, we need to update our IoC Register call:

 

 


...
SimpleIoc.Default.Register<ICustomDialogs, MyUserDialogsImpl>();
...

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