Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

April 25

Unite Berlin 2018: First sessions announced!

Unite Berlin is the perfect opportunity to connect and collaborate with thousands of developers all focusing on technology, creativity, and games. Get ready for advanced hands-on demo workshops, technical sessions–customized for different levels, previews of upcoming Unity tech, the Made with Unity showcase, and of course an after-party with delicious food and plenty of dancing. […]

April 24

Inside Tribeca Film Festival: Made with Unity projects debut at Tribeca Immersive

Of the 27 projects in the Tribeca Immersive program this year, 17 are made with Unity. From multiplayer musical playgrounds to powerful mixed-reality documentaries, the lineup this year was yet another reminder that ambitious design, thematic creativity, and technical innovation are still flourishing within Unity’s global community. Below are just a few of the many […]

From app to Games: 01 - Introduction and starting up Word Unscramble using ReactJS

From app to games is a series of posts here in the Plastic SCM blog where we are going to share some ideas and challenges faced by an app developer when creating some games. We are going to start by creating games for the web, but later we are going to develop for game engines as well, such as Unity, GameMaker and others. In this first post, we are going to design and start the creation of an anagram game using a top trending web library named ReactJS.

Welcome to React
Read more »

April 23

Kanye West Just Ripped a Hole in Reality

On Sunday, Kanye West tweeted 7 words that just made a bunch of people lose their minds.

Following that was a tweet storm about thinking for yourself and not giving in to the thought police.

Then, this morning, Kanye followed up with a bunch of snippets of Scott Adams' periscope[1][2][3][4][5][6][7][8][9] explaining the whole situation which is definitely worth watching if you haven't already.

For your convenience, I found a link to the original video on youtube so you can watch the video uninterrupted. I also skipped ahead to the beginning of where Kanye's fragmented video tweets start (which is essentially where Scott Adams begins talking about how Kanye ripped a hole in reality).

I find this fascinating. I hope you do, too.

Using TensorFlow and Azure to Add Image Classification to Your Android Apps

TensorFlow is a well established, open source machine learning and deep learning framework that can be used to create and run a wide range of different models, usually using powerful machines in the cloud. In addition, TensorFlow also supports running models on mobile devices through the TensorFlow.Mobile library, taking advantage of the hardware acceleration available on modern phones to run models incredibly fast on low powered mobile devices.

In this post, we’ll discuss how to build an image classifier to identify different fruits using the Azure Custom Vision service, and create a simple Android app to use this model to classify images.

Getting Started

Creating ML models can be time consuming and require large data sets. To make it easier to create image classification models, Microsoft has created the Custom Vision Service, which uses a technique called transfer learning to allow you to train an image classifier using only a small number of images, instead of the thousands that traditionally would be required to train such a model. These models can be exported as TensorFlow models (or CoreML if you are on iOS) and used from inside an Android app.

Lets start by creating a project in the Custom Vision service. Make sure you select one of the compact domains, the compact domains create models that are small enough to be exported and used from a mobile device.

Creating a new Custom Vision project with a General (compact) domain

Image classifiers are trained by being given images with one or more tags, which are text labels that indicate what is in that image. For example, you might upload five pictures of oranges with the tag of orange, five pictures of bananas with the tag banana, and so on for different fruits.

To train your model, you will need at least five images for each tag you want to use, so the first step is to gather the data by photographing whatever fruit you have to hand. Next, click the Add Images button and upload the images of the first fruit, setting the appropriate tag. Repeat this for the rest of the fruits. Finally click the Train button on the top menu to train the model.

Uploading and tagging images, and training the model

Once trained, click the Export button to export the model for use with TensorFlow.

Exporting the model to be used with TensorFlow

This will download a zip file containing two files: model.pb and labels.txt.

Adding the Model to Your Android App

Now that we have the model, it’s time to add it to an Android app project and use it to classify images.

Add the Model and TensorFlow.mobile to the Project

Create a new Android app by going to File -> New Project -> Android -> Single View App in Visual Studio. Add the model.pb and labels.txt files to the Assets folder, and make sure the build action is set to Android Asset.

TensorFlow.Mobile is available as a NuGet package that wraps the native Android libraries. Install the Xam.Android.Tensorflow package in your Android app.

Initializing the Model and Labels

To use the model, we need to create an instance of the TensorFlow interface using our model file. We also need to load the labels file; the model from TensorFlow doesn’t contain the actual tag values, so these come from the labels file.

using using Org.Tensorflow.Contrib.Android;
    ...
    var assets = Application.Context.Assets;
    inferenceInterface = new TensorFlowInferenceInterface(assets, "model.pb");
    var sr = new StreamReader(assets.Open("labels.txt"));
    var labels = sr.ReadToEnd()
                   .Split('\n')
                   .Select(s => s.Trim())
                   .Where(s => !string.IsNullOrEmpty(s))
                   .ToList();

Recognizing Images

To recognize an image, first we need to capture one from somewhere. To use the camera, I’d recommend using the Xam.Plugin.Media NuGet package. This package has helpers to open the camera and extract the photo taken by the user.

Preparing the Input for the Model

Once you have a photo, it needs to be converted for the Custom Vision model. These models require the input to be of the correct size and format to work; they don’t understand images, as such, but instead understand binary data. For the models created by the Custom Vision service, you need the images to be 227×227 pixels in size, converted to an array of floating point values, one per red, green, and blue value for each pixel, with some model-specific adjustments to the color value. The following code converts an Android Bitmap to the correct format.

var resizedBitmap = Bitmap.CreateScaledBitmap(bitmap, 227, 227, false)
                              .Copy(Bitmap.Config.Argb8888, false);
    var floatValues = new float[227 * 227 * 3];
    var intValues = new int[227 * 227];
    resizedBitmap.GetPixels(intValues, 0, 227, 0, 0, 227, 227);
    for (int i = 0; i < intValues.Length; ++i)
    {
        var val = intValues[i];
        floatValues[i * 3 + 0] = ((val & 0xFF) - 104);
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - 117);
        floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - 123);
    }

Running the Model

Now that we have our image in the right format, we can run the model against our data. Running the model involves feeding it named inputs, running it for named outputs, then retrieving the output you’re interested in by name. Each model can take multiple inputs and give multiple outputs, but in our case we only have one input and need one output. The following code shows this for our Custom Vision model.

var outputs = new float[labels.Count];
    inferenceInterface.Feed("Placeholder", floatValues, 1, 227, 227, 3);
    inferenceInterface.Run(new[] { "loss" });
    inferenceInterface.Fetch("loss", outputs);

The outputs array is filled with floating point values, each one representing the confidence that the image matching a tag in the labels list at the same array position. For example, if you had three labels in the list in the following order:

  • Apple
  • Banana
  • Mango

Then output[0] would be the confidence that the image is an apple, using values ranging from 0-1 with 1 representing 100%. output[1] would be the confidence that the image is a banana, and so on. You can then use the tag with the highest confidence as the most likely result.

The app takes a photo of a Mango and detects this successfully

Conclusion

It’s easy to get started building image classifiers using Azure, and access them from Xamarin.Android, using TensorFlow.Mobile. Head to GitHub to see the final sample code. Check out the documentation here to learn more about training your own Custom Vision models.

Discuss the post on the forums!

The post Using TensorFlow and Azure to Add Image Classification to Your Android Apps appeared first on Xamarin Blog.

April 20

Unity recognized as #8 Best Place to Work in the Bay Area

We’re proud to announce that we’ve been recognized by San Francisco Business Times’ and Silicon Valley Business Journal’s 2018 Best Places to Work List for the second consecutive year! At Unity, we work hard to ensure that all Unity employees come to work feeling comfortable, supported and inspired. In the past year alone, we are […]

Community Books on Xamarin Development

Xamarin development is constantly growing and evolving to meet the needs of developers. To help you find the right resources for your development education, we’ve curated a list of community books written about Xamarin.

Books on Xamarin

 
Xamarin Cross-platform Application Development: Second Edition
Author: Jonathan Peppers
Published: April 2015

This book is a practical guide to building real-world mobile applications with Xamarin. It outlines the basics of Xamarin by building a chat application, complete with a backend web service and native features, such as GPS location, camera, and push notifications. You’ll learn how to use external libraries with Xamarin and Xamarin.Forms to create shared user interfaces to make app-store-ready apps. With this book, you can transform yourself from an amateur mobile developer to a professional mobile developer.

 

What you’ll learn:

  • Understanding Apple’s MVC design pattern
  • Understanding the Android activity lifecycle
  • Designing user interfaces that can be shared across different platforms
  • Sharing C# code across platforms
  • Calling native Objective-C or Java libraries from C#
  • Working with unit testing for mobile applications
  • Creating a web service with Azure Mobile Services
  • Deploying your application on mobile devices
  • Debugging your application on mobile devices
  • Preparing your applications for distribution

 

Creating Mobile Apps with Xamarin.Forms
Author: Charles Petzold
Published: January 2016

This third edition ebook, now with 16 chapters, is about writing iOS, Android, and Windows phones applications using Xamarin.Forms. Xamarin.Forms lets you write shared user-interface code in C# and XAML that maps to native controls on these three platforms. Written for C# programmers who want to write applications using a single code base that targets the three most popular mobile platforms, this book assumes that you know C# and are familiar with the use of the .NET Framework. Notably, however, Charles does discuss some C# and .NET features that might be somewhat exotic or unfamiliar to recent C# programmers at a somewhat slower pace.

 

What you’ll learn:

  • How Xamarin.Forms fits in
  • Anatomy of an app
  • Scrolling the stack
  • XAML vs. code
  • Platform-specific API calls
  • XAML markup extensions
  • Data binding
  • Page navigation and Page varieties
  • Custom layouts and Custom Renderers

 

Mastering Xamarin.Forms
Author: Ed Snider
Published at: January 2016

This easy to follow, code-rich book will help you master Xamarin.Forms to build useful, cross-platform mobile apps. Following a step-by-step approach to teach you the basic and advanced tools of Xamarin, it maps out more advanced features along with proper implementation in mobile apps. You’ll also learn tips and workflows to improve your testing and debugging process, including the ability to solve your own problems along the way.

The author covers a variety of APIs built into Xamarin for custom features, along with the MVVM framework popularized for .NET development. Later chapters get into analytics testing and data tracking to find memory leaks and bugs while your apps are in use.

 

What you’ll learn:

  • Using architecture patterns to build more robust apps with Xamarin.Forms
  • Implementing the Model-View-ViewModel (MVVM) pattern and data-binding in Xamarin.Forms mobile apps
  • Working with the Xamarin.Forms navigation API for a custom ViewModel-centric navigation service
  • Leverage the inversion of control
  • Using dependency injection patterns in Xamarin.Forms mobile apps
  • Working with online and offline data in Xamarin.Forms mobile apps
  • Using platform-specific APIs to build rich custom user interfaces
  • Testing both business logic and user interface code in Xamarin.Forms mobile apps
  • Maximize the testability, flexibility, and overall quality of your Xamarin.Forms mobile app
  • Improving mobile app quality with analytics and crash reporting using Xamarin Insights

 

Xamarin Blueprints
Author: Michael Williams
Published: July 2016

Xamarin Blueprints is a practical guide that will teach you to create professional-grade apps with Xamarin. This book offers instruction on Xamarin.Forms, Xamarin.Android, and Xamarin.iOS by following a learn-as-you-build approach for eight full-fledged applications. If you’re the kind of developer who loves to learn by building, then this is the perfect book for you. After completing this guide, you’ll be a professional app developer across multiple platforms.

 

You’ll learn to build:

  • A Gallery Application
  • A SpeechTalk Application
  • A GPS Locator Application
  • An Audio Player Application
  • A Stocklist Application
  • A Chat Application
  • A Building a File Storage Application
  • A Camera Application

 

Cross-Platform Localization for Native Mobile Apps with Xamarin
Author: Christopher Miller
Published: December 2016

This book is intended to teach you all aspects of Xamarin.Forms necessary to build a multilingual mobile application that runs on Android, iOS, and Windows platforms, and handle the localization and internationalization on each platform. You’ll learn how the Xamarin platform helps you build native apps using a single shared set of language resources in the .NET Framework, and how to tailor your apps to compete in the global market. You’ll also learn how to test applications for localization support and to avoid common pitfalls. Using Xamarin.Forms and Visual Studio, the sample app constructed is implemented for Android, iOS, and Windows 10 UWP, with 99% of the code shared across the platforms.

 

What you’ll learn:

  • Fundamental concepts of localization and internationalization of apps
  • Support for multiple languages on each platform
  • Working with resource files
  • To use Microsoft’s Multilingual App Toolkit to manage language resources
  • Creating a localized, cross-platform app with Android Studio, Xcode, Xamarin, and Visual Studio tools
  • Handling cultural differences such as dates and currencies.

 

Mastering Xamarin UI Development
Author: Steven F. Daniel
Published: January 2017

This book provides you with the practical skills required to develop real-world Xamarin applications. You’ll learn how to implement UI structures and layouts, create customized elements, and write C# scripts to customize layouts. You’ll also create UI layouts from scratch so you can tweak and customize a given UI layout to suit your needs using Data Templates. Moving on, you’ll use third-party libraries, such as the Razor template engine that allows you to create your own HTML5 templates within the Xamarin environment, to build a book library hybrid solution that uses the SQLite.Net library to store, update, retrieve, and delete information within a SQLite local database. You’ll also implement key data-binding techniques to make your user interfaces dynamic, and create personalized animations and visual effects within your user interfaces using Custom Renderers and the PlatformEffects API to customize and change the appearance of control elements.

 

What you’ll learn:

  • Building native cross-platform apps using the Xamarin.Forms framework
  • Working with the different UI layouts to create customized layouts using the C# programming language
  • Customizing the user interface using DataTemplates and CustomRenderers
  • Using the Platform Effects API to change the appearance of control elements
  • Building hybrid apps using the Razor Template Engine
  • Creating Razor Models that communicate with an SQLite database
  • Using the MVVM pattern architecture to navigate between each of your ViewModels
  • Using location-based features within your app to display the user’s current location
  • Using data Binding to display and update information
  • Working with the Microsoft Azure Platform to incorporate API Data Access
  • Implementing third-party features within your app using the Facebook SDK and the Open Graph API
  • Performing unit testing on your Xamarin.Forms applications
  • Distributing your apps to the Google Play Store and Apple App Store

 

Xamarin in Action: Creating Native Cross-Platform Mobile Apps
Author: Jim Bennett
Published: November 2017

Xamarin in Action
 teaches you how to build Xamarin apps on iOS and Android from scratch while maximizing code reuse. This layer-by-layer guide starts by showing you the MVVM design pattern and explaining how it increases code sharing. Next, you’ll start building an app from the ground up. You’ll learn the different layers inside a well written Xamarin app and discover how most of your code can be shared between iOS and Android, how this code sharing can be best designed to allow unit testing of your business layer as well as your UI logic, and dig into code that can’t be shared, like user interface code that’s device specific. Finally, you’ll learn how to take your app from final code to a tested and deployed version on the relevant store. By the end, you’ll be able to build a high-quality production-ready Xamarin app on iOS and Android from scratch with a high level of code reuse.

 

What you will learn:

  • MVVM and how it maximizes code reuse and testability
  • How to build a mobile app from rough design through final deployable product
  • Creating cross-platform model and UI logic layers
  • How to build device specific UIs for iOS and Android
  • Testing apps through the unit and automated UI testing
  • How to prepare apps for publication with user tracking and crash analytics

This book is great for C# developers with just a few months of experience, as well as those with many years of experience who want to build native mobile apps for iOS and Android using the language and toolset they already know. Use code “xamarininaction” at xam.jbb.io to get 42% off the cover price!

 

Xamarin Unleashed
Author: Alec Tucker
Published: January 2018

In this book, you’ll learn the fundamentals behind the entire Xamarin workflow. The author explains how MVVM fits into your development workflow and how to utilize best practices when writing your applications. Not just a simple intro guide, you’ll dive into the deep end of the Xamarin swimming pool, even though concepts are presented in a way that anyone can understand (even with little-to-no mobile dev experience).

 

What you will learn:

  • To use the best-practice MVVM pattern
  • How to write C# apps which can access all the APIs and hardware facilities provided by each top mobile platform
  • Ensure a truly native, state-of-the-art user experience while maximizing the amount of code you can share across platforms
  • How to make the most of Xamarin’s mature and robust toolset
  • How to integrate it with the new Visual Studio 2015 to further accelerate your cross-platform development processes
  • About individual libraries, the C# codebase, and the Xamarin Studio software.

 

Xamarin.Forms Essentials: First Steps Toward Cross-Platform Mobile Apps
Author: Gerald Versluis
Published: January 2018

Xamarin.Forms Essentials provides a brief history of Xamarin as a company, including how it has become one of the most used cross-platform technologies for enterprise applications and app development across the world. Examples in the book are built around the real-life example of an actual app in Google Play and in the Apple App Store and has thousands of downloads between iOS and Android. You’ll learn how an application is set up from scratch, and will benefit from the author’s hard-won experience and tips in addressing various development challenges.

 

What You’ll Learn

  • Creating cross-platform user interfaces from one code base for both iOS and Android
  • How a commercial application is built and then deployed for sale in the app stores
  • To integrate your Xamarin.Forms applications with third-party, RESTful APIs
  • To arrange application architecture to avoid pitfalls and optimize your design
  • New features released as part of Xamarin.Forms
  • Choosing appropriately between Xamarin.Forms and traditional Xamarin, depending upon your application needs and goals

 

Books Coming This Year

Building Xamarin.Forms Apps Using XAML: Mobile Cross-Platform XAML and Xamarin.Forms Fundamentals
Author: Dan Hermes
Contributor: Dr. Nima Mazloumi
To be published: 2018

Building Xamarin.Forms Mobile Apps Using XAML is a starter guide to creating Xamarin.Forms apps using XAML (Extensible Application Markup Language), and you’ll learn and leverage Xamarin.Forms to build iOS and Android apps with a single, cross-platform approach. The book begins with an overview of Xamarin.Forms, followed by an in-depth XAML primer covering syntax, namespaces, markup extensions, constructors, and the XAML standard. You’ll explore the core of the Xamarin.Forms mobile app UI, including using layouts and FrameLayouts to position controls and views to design and build screens, formatting your UI using resource dictionaries, styles, themes and CSS, and coding user interactions with behaviors, commands, and triggers. You’ll learn how to create industry-standard menus and help your user get around your app using Xamarin.Forms navigation patterns, bind your UI to data models using data binding and using the MVVM pattern, and customize your UI elements by platform using effects, custom renderers, and native view declaration. You’ll also see how to use XAML to build sophisticated, robust cross-platform mobile apps. Building Xamarin.Forms Mobile Apps Using XAML is a XAML companion edition to the C# guide Xamarin Mobile Application Development. This guide includes screenshots on iOS and Android, and XAML and C# code examples with downloadable code available from Apress.com.

What You Will Learn:

  • How to build world-class mobile apps for iOS and Android using C# and XAML
  • XAML fundamentals for building a UI decoupled from the C# code behind
  • Designing UI layouts such as FrameLayout, controls, lists, and navigation patterns
  • Styling your app using resource dictionaries, styles, themes, and CSS
  • Customizing controls to have platform-specific features using effects, custom renderers, and native views
  • Data binding, local data access, enterprise cloud data solutions, and building a data access layer for mobile apps

The post Community Books on Xamarin Development appeared first on Xamarin Blog.

April 19

Faces of Unity: Sarah Stumbo

Unity is an amazing place to work, fueled by equally amazing people! We hope you will enjoy getting to know our company and our staff a little better through the Faces of Unity blog series. Each post in this series will spotlight an employee whose work plays an integral part in creating the engine you […]

April 18

Automatic Provisioning with Visual Studio 2017

iOS device provisioning is largely regarded by all iOS developers, Xamarin or otherwise, as being one of the biggest barriers to getting started with iOS. To test and deploy your app on a device, you must enroll in Apple’s Developer Program, create a certificate to sign the app, create an app ID, and register your device with Apple. We’ve written some great documentation on the subject as it’s a complicated process with many points of failure.

We also always want to make things as simple as possible for Xamarin.iOS developers, so you can spend your time focusing on creating great apps, not on iOS provisioning. A few months ago, we introduced Automatic Provisioning to Visual Studio for Mac, and we’ve finally brought these capabilities to Visual Studio 2017 with Version 15.7 Preview 3. In this post, you’ll learn how to use the new automatic signing feature in Visual Studio to deploy your app to a device in about 30 seconds.

Connecting your Apple Account

To begin the automatic signing process, make sure you’ve signed in to Visual Studio with an Apple ID via the Apple Account options. iOS provisioning requires that you be a member of the Apple Developer Program. If you haven’t signed up yet, now is a good time to do it.

To open the account management window, go to Tools > Options > Xamarin > Apple Accounts. Select the Add button and enter your Apple ID and password. Your credentials are saved in the secure Keychain on your machine, and fastlane is used to handle your credentials securely while passing them to Apple’s developer portal.

Enabling Automatic Signing

Once you’ve ensured you have an Apple ID connected to Visual Studio, you’re ready to enable Automatic Signing.

In your iOS project, right-click on the project name and go to Properties > iOS Bundle Signing:

Select the Automatic Provisioning scheme radio button:

Then, select your team from the Team dropdown:

This starts the automatic signing process. Visual Studio then attempts to generate an App ID, provisioning profile, and a signing identity to use these artifacts for signing. You can see the generation process in the Build output:

When automatic signing has been enabled, Visual Studio updates the provisioning artifacts, if necessary, when any of the following things happen:

  • When an iOS device is plugged in to the Mac build host.
    • Visual Studio checks to see if the device is registered on the Apple Developer Portal. If it is not, then the device is added and a new provisioning profile is generated.
  • When the bundle ID of your app is changed.
    • Visual Studio updates the app ID to match the bundle ID. A new provisioning profile containing this app ID is generated.
  • When a supported capability is enabled in the Entitlements.plist file.
    • This capability is added to the app ID and a new provisioning profile with the updated app ID is generated.
    • Not all capabilities are currently supported.

Deploying your App

To deploy your app to a provisioned device, plug your device in to your Mac build host and select it from deployment target list. Alternatively, if your iOS device is connected to the Mac build host wirelessly, you’ll be given an option to select it from the deployment target list.

Wrapping Up

This blog post introduced the new automatic signing capabilities in Visual Studio 2017 15.7 Preview 3 and demonstrated just how quickly you can now deploy your iOS, tvOS, and watchOS apps to a device.

For more information on Device Provisioning, refer to our documentation on Setting up a device for development.

Discuss this post in the Xamarin Forums!

The post Automatic Provisioning with Visual Studio 2017 appeared first on Xamarin Blog.

April 16

A Brief History of .NET Standard

Xamarin (and before that, Mono) allowed .NET code to run on multiple platforms for years. These days, there’s a new push in cross-platform with .NET Core and .NET Standard. This post looks at the history of code sharing in .NET and where cross-platform .NET is going with Core and Standard.

History of .NET Standard

In the early days of the .NET framework, there was little need to share code between applications. When Windows Presentation Foundation (WPF) was released in 2006, it was a choice between WinForms or WPF, and developers didn’t have to support the same application in both frameworks. Though sharing files was sometimes needed between client and server apps, it was infrequent.

Microsoft then released Silverlight, a smaller, portable framework on Windows, Mac OS, and Linux. Suddenly, developers were asked to code two versions of the same application: a full-featured version made in WPF to only run in Windows and a smaller version that ran cross-platform in Silverlight. The Silverlight plugin was able to run these apps outside of the browser (OOB) which made it possible to build cross-platform applications. There was even some hope that Silverlight would eventually run on mobile phones. Though this never came to be, the need to have the same code run on multiple platforms became more crucial and more complex.

Add As Link

To add a class to both a Windows Presentation Foundation and a Silverlight application, one would have to Add As Link. To do this in Visual Studio, add the actual file to one of the two applications. For example, here’s how to add it to WPF:

  1. Right-click on the other project.
  2. Select Add Existing Item (Will open the corresponding dialog.)
  3. Navigate to the location of the original file and select it.
  4. Open the combo box located in the Add  button.
  5. Then Add As Link (Creates a shortcut to the original file.)

After the file has been added as a link, it shows up in the Solution Explorer with a small blue arrow. If you browse to the folder, you’ll see the file is not physically present. Visual Studio added a Link item to the project file, for instance:

<Compile Include="..\SharedFiles\ViewModel\MainViewModel.cs">
  <Link>ViewModel\MainViewModel.cs</Link>
</Compile>

Today, Add As Link still has utility, as when sharing images between applications. In Xamarin.Forms, you have the possibility to create a project using a Shared Project to share your source files. Under the cover, Visual Studio is using the same shortcuts shown above.

A Xamarin.Forms application with a Shared project

Portable Class Libraries (PCL)

The maintenance of shared files can be challenging. Every time a new class is added, links to that file also need to be added to every application. With that in mind, in 2011 Microsoft released a new type of class libraries called Portable Class Libraries. A project type that creates a binary file compatible with multiple frameworks.

Creating a new Portable Class Library

The available APIs are reduced each time a new target framework is selected. For example, if a class is available in .NET Framework 4.5.1 but not in Windows Universal 10.0, it won’t be available in the PCL targeting both these frameworks. The combinations of the target frameworks is called a Profile.

While PCLs were a breakthrough at the time of their creation, it was sometimes difficult to find information on which APIs were available and where to find them. In time, it became clear to the .NET team that a simpler approach was needed.

The Birth of .NET Core

.NET Core is an implementation of .NET running on various platforms, including Windows, Mac OS, and Linux. It was developed openly on Github by the Microsoft .NET team and external contributors. The first version was used to implement ASP.NET Core, a revamped version of ASP.NET running on Linux or Windows.

Executing .NET code on Linux or Mac OS is great, but we already have cross-platform implementations of .NET, such as Xamarin. Ideally, .NET libraries created for ASP.NET Core would also run seamlessly on these other platforms. As in Portable Class Libraries, this brings a well-known issue to light: how do developers know which APIs are supported on which platform?

A Specification: .NET Standard

In PCLs, the problem was solved by creating profiles. However, this led to a situation where developers couldn’t easily find out which APIs were available to them. Documenting the profiles was challenging and there were too many to keep track of.

The solution was to create a specification that would state which APIs were supported in which version of the specification. Each version of the specification would be backward compatible with the previous versions.

This specification can seem more complex than it actually is, so let’s look at an example of it in action. There’s a full compatibility table on the .NET Standard website. Here’s an extract of that table:

.NET Standard support table.

Decoding the Extract

The table can be decoded as follows: an Android application developed with V7.0 of the Xamarin.Android SDK will support references to class libraries developed with up to V1.6 of .NET Standard. However, you will need to upgrade your Xamarin.Android to V8.0 if you want to add a reference to a class library developed with V2.0 of .NET Standard.

In practice, it makes a difference because V2.0 of .NET Standard includes many more APIs than V1.6 (about 20,000 additional APIs!). Fewer Android devices support V8.0 than V7.0, so there’s also a tradeoff: access to more APIs or to more devices.

A good rule of thumb is:

  • Application developers: Target the highest possible version of .NET Standard. This will give your application more APIs and make it compatible with more libraries.
  • Libraries developers: Target the lowest possible version of .NET Standard. Which will make your library compatible with more applications, but you will have fewer APIs at your disposal.

For example, the MVVM Light Toolkit was recently converted to .NET Standard V1.0, meaning that MVVM Light is compatible even with .NET Framework 4.5 (older WPF applications). While this may sound unnecessary, it gives significant flexibility to developers who want to use the .NET Standard version without having to upgrade their pool of machines to a newer version of .NET.

Xamarin Cross-Platform Applications

When you create a new Xamarin.Forms application in Visual Studio 2017, you have .NET Standard as a choice for the Code Sharing Strategy. In fact, Portable Class Libraries in Visual Studio 2017 are marked as legacy, marking a clear indication that you should gradually move away from PCL and on to .NET Standard.

Creating a new Xamarin.Forms app with .NET Standard

Conclusion

In the long story of cross-platform compatibility, .NET Standard is a great new chapter. Portable Class Libraries were a real innovation in their time, but they also brought along some confusion, which .NET Standard has since clarified. At the same time, the additional compatibility with platforms, such as Linux, is a really exciting opportunity, especially for a web application.

Here’s a sample of a .NET Core console application using MVVM Light’s SimpleIOC, with instructions to run it on Windows and Ubuntu.

With Xamarin embracing .NET Standard, it’s now time to take a good look at these old PCLs and start converting them to .NET Standard.

Discuss this post on the forums!

The post A Brief History of .NET Standard appeared first on Xamarin Blog.

Animation Instancing – Instancing for SkinnedMeshRenderer

As developers, we’re always aware of performance, both in terms of CPU and GPU. Maintaining good performance gets more challenging as scenes get larger and more complex, especially as we add more and more characters. Me and my colleague in Shanghai come across this problem often when helping customers, so we decided to dedicate a […]

April 13

Using the iOS 11 Drag and Drop APIs in Xamarin.iOS Apps

iOS 11 introduced drag and drop, a feature that allows users to easily move or copy data within or between apps. With drag and drop, users can:

  • Select items to drag
  • Add extra items to a drag after it has started
  • Transfer data asynchronously between applications

On iPads, drag and drop works within or between applications. On iPhones, drag and drop is restricted to a single app.

Drag and Drop Sample App

This post describes how the drag and drop APIs are used in a single-screen iPhone app that has users sort even and odd numbers:

The EvenOddNumberDrag sample

To follow along, download the code for the EvenOddNumberDrag app.

Enable User Interaction

Three elements of the app’s user interface (found in Main.storyboard) are relevant to dragging and dropping:

  1. NumberLabel displays the number which is to be dragged.
  2. EvenNumbersLabel is the label on which even numbers should be dropped.
  3. OddNumbersLabel is the label on which odd numbers should be dropped.

Since users will be interacting with these labels, each must have its UserInteractionEnabled property set to true. This is done in ViewController.cs:

protected void SetupDragAndDrop()
{
   NumberLabel.UserInteractionEnabled = true;
   EvenNumbersLabel.UserInteractionEnabled = true;
   OddNumbersLabel.UserInteractionEnabled = true;
   // …
}

Enable Dragging

A basic drag interaction requires only a few pieces:

  • A UIDragInteraction object that is attached to the view that will be draggable and explicitly enabled:

    protected void SetupDragAndDrop()
    {
        // …
        var numberDragInteraction = new UIDragInteraction(this);
        NumberLabel.AddInteraction(numberDragInteraction);		
    
        // On iPad, this defaults to true. On iPhone, this defaults to 
        // false. Since this app should work on the iPhone, enable the 
        // drag interaction.
        numberDragInteraction.Enabled = true;
        // …
    }

  • An IUIDragInteractionDelegate that acts as the delegate for the drag interaction object. In this sample, ViewController itself is the IUIDragInteractionDelegate. Only one of the delegate methods needs to be implemented:

    public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) 
    { 
        bool isEven = Convert.ToInt16(NumberLabel.Text) % 2 == 0; 
        var provider = new NSItemProvider(new NSString(NumberLabel.Text)); 
        var item = new UIDragItem(provider) 
        { 
            LocalObject = new NSNumber(isEven) 
        }; 
        return new UIDragItem[] { item } ; 
    }

    This method returns an array of UIDragItem objects, each representing a piece of data to be included in the drag and drop operation. Each drag item contains an NSItemProvider that holds a representation of the data to be transferred.

    In this case, the NSItemProvider is given an NSString, which implements the INSItemProviderWriting interface, one of the data representations supported by NSItemProvider.

    The UIDragItem has a LocalObject property that is accessible only within the application that initiated the drag. Since this example focuses on a single app, for convenience GetItemsForBeginningSession sets the LocalObject to a NSNumber. This represents whether or not the dragged number is even.

Enable Dropping

To enable a drop interaction, you will need:

  • A UIDropInteraction object for each view on which items can be dropped:

    protected void SetupDragAndDrop()
    {
        // …
        evenDropInteraction = new UIDropInteraction(this);
        EvenNumbersLabel.AddInteraction(evenDropInteraction);
        oddDropInteraction = new UIDropInteraction(this);
        OddNumbersLabel.AddInteraction(oddDropInteraction);
    }

  • An IUIDropInteractionDelegate object. In this sample, ViewController serves as the drop delegate.
  • An implementation of the SessionDidUpdate method from the IUIDropInteractionDelegate interface extension methods:

    [Export("dropInteraction:sessionDidUpdate:")] 
        public UIDropProposal SessionDidUpdate(UIDropInteraction interaction, IUIDropSession session) 
        { 
            UIDropProposal proposal; 
            var isEven = (session.Items[0].LocalObject as NSNumber).BoolValue; 
            if (interaction == oddDropInteraction && !isEven) 
            { 
                proposal = new UIDropProposal(UIDropOperation.Copy); 
            } 
            else if (interaction == evenDropInteraction && isEven) 
            { 
                proposal = new UIDropProposal(UIDropOperation.Copy); 
            } 
            else 
            { 
                proposal = new UIDropProposal(UIDropOperation.Forbidden);
            }
            return proposal;
        }

    This method is called any time there’s a change that will potentially affect the outcome of the drop; for example, when the drop location changes in the target view because the user has moved the item being dragged. It looks at the IUIDropSession to determine whether or not the drop should proceed, proposing (with a UIDropProposal containing a UIDropOperation) to move the dropped data, copy the dropped data, cancel the drop, or forbid the drop.

    In this example, LocalObject (set up in GetItemsForBeginningSession) provides an easy way to determine whether or not the dragged number is even or odd. A copy is proposed if the potential drop is valid, and the drop is forbidden if it is invalid.

    Proposing a copy or forbidding a drop both add helpful icons to the dragged item:

    Drop indicators

  • An implementation of the PerformDrop method from the IUIDropInteractionDelegate interface extension methods:

    [Export("dropInteraction:performDrop:")]
    public void PerformDrop(UIDropInteraction interaction, IUIDropSession session)
    {
        var label = interaction == oddDropInteraction ? OddNumbersLabel : EvenNumbersLabel;
        session.LoadObjects<NSString>(strings =>
        {
            if (String.IsNullOrEmpty(label.Text))
            {
                label.Text = strings[0];
            }
            else
            {
                label.Text = $"{strings[0]}, {label.Text}";
            }
        });
        GenerateNumber();
    }

    This method is used for dropping numbers on both the even bucket and the odd bucket. The drop target is determined by checking the identity of the passed-in drop interaction.

  • Lastly, the LoadObjects method on IUIDropSession fetches the data and adds it to the even or odd bucket.

Learn More

This post only scratches the surface of the iOS 11 drag and drop APIs. To dig deeper, check out the following resources:

Have questions or comments about this post? Discuss them in the Xamarin forums!

The post Using the iOS 11 Drag and Drop APIs in Xamarin.iOS Apps appeared first on Xamarin Blog.

Monologue

Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.

Bloggers