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.

March 23

Catch Up on Visual Studio 2017 and Visual Studio for Mac with Channel 9

I was honored to be part of the Visual Studio 2017 keynote, where I got to highlight how easy it is to build beautiful, cross-platform native iOS, Android, and Windows apps in C# with Xamarin and Visual Studio 2017. Visual Studio 2017 brings an exciting range of new features and improvements for developers, along with a brand new preview of Visual Studio for Mac.

Channel 9 has put together an extensive collection of content from the Visual Studio 2017 launch, and in this post I wanted to share a few of my favorite recordings from the event.

Building Mobile Apps with Xamarin & Visual Studio 2017

Visual Studio 2017 includes everything you need to start building mobile apps for iOS, Android, and Windows in C# with Xamarin. In this session, Xamarin University’s Rob Gibbens and Adrian Stevens walk you through the basics of building apps with Xamarin and Visual Studio from the ground up.

New Connected App Templates

We wanted to build mobile app templates that reflect the type of apps our developers are building. Looking at the various app stores, for example, you’ll see that many mobile apps are simply a list view populated by data pulled down from the web, possibly with some form of social or enterprise authentication. With our new templates, you can bootstrap your next mobile project at the click of a button to produce a mobile app for iOS, Android, and Windows 10 that includes tabbed navigation, MVVM, settings, and more. By clicking “Host in the cloud,” you can take your mobile project to the next level by provisioning a backend for your mobile app, complete with client-side code for online/offline synchronization and automatic conflict resolution. In this mini session, I walk you through the new templating experience in Visual Studio.

Introducing Visual Studio for Mac

Visual Studio for Mac is an IDE for mobile-first, cloud-first workloads with support for building iOS, Android, and Mac apps in C# and F# with Xamarin, as well as web and server apps with .NET Core and ASP.NET Core. You’ll find the same Roslyn-powered compiler, IntelliSense code completion, and refactoring experience you would expect from a Visual Studio IDE. And, since Visual Studio for Mac uses the same MSBuild solution and project format as Visual Studio, developers working on Mac and Windows can share projects across Mac and Windows transparently. This mini session from Mikayla Hutchinson shows how to get started with Visual Studio for Mac and explores its rich capabilities for developing mobile apps with Xamarin and cloud back-ends with .NET Core.

Don’t Miss All the Channel9 Xamarin Content

Be sure to visit Channel 9 for the complete selection of Visual Studio 2017 launch videos, including the keynote as well other sessions for mobile developers. For more content, be sure to follow The Xamarin Show for a weekly look at cross-platform mobile development for iOS, Android, macOS, and Windows with Xamarin.

The post Catch Up on Visual Studio 2017 and Visual Studio for Mac with Channel 9 appeared first on Xamarin Blog.

March 22

Organize a Xamarin Dev Days!

Xamarin Dev Days are in full swing across the globe and now it’s time to get free, hands-on mobile development training in your city! It’s fun, easy, and exciting to organize a Xamarin Dev Days of your own, and today we’re going to show you how.

To start off, we’ll provide you and your speakers with three in-depth, presentation-ready slide decks and demos along with an optional step-by-step workshop for attendees to build their first ever cloud-connected mobile app with Xamarin.Forms.

XDD-Praavi16

Step 1: Recruit a Team of Local Speakers and Volunteers

Get a group of three to four volunteers to present and to help onsite with registration, catering delivery, and the afternoon workshop. Some great candidates include:

Step 2: Reserve a Date and Venue

Find a date that works for you, your volunteers, and your community and reserve space at a local venue for your event. The following is what you should look for in a venue:

  • Available on Saturday from 09:00–16:00 (preferred)
  • Room for a minimum 40–200+ attendees
  • Has an Audio/Video system and Wi-Fi available

Local Microsoft offices are often a great option!

Step 3: Fill Out the Form!

Now it’s time to submit your event details and make things official. Once reviewed, the Xamarin team will:

  • Create your official Event Registration Page
  • Order and ship swag to you for the event (while supplies last)
  • ms-azureGenerate FREE 1 Month + $100 Azure Passes for your attendees!
    That’s right, Xamarin Dev Days organizers can now offer free Azure passes to all of their attendees just by hosting an event before June 30, 2017*!

*Further details will be provided after event submission

Step 4: Promoting Your Xamarin Dev Days

Once your event link is live, you’ll be able to share your event with the world and start promoting open registration. Xamarin will help with the promotion by:

  • Including your event in the upcoming blog post announcements on April 7, May 5, and June 2
  • Hosting the event link on the official Xamarin Dev Days website
  • Publicizing your event through the @XamarinEvents Twitter and with the hashtag #XamarinDevDays

Step 5: Supporting Your Event

Raise awareness of local technology companies by having them participate in your event as sponsors. Through providing lunch or covering venue fees they will receive:

  • Their logo on the official registration page
  • The ability to send or give goodies and prizes to attendees
  • An opportunity to network with passionate developers throughout our global community

If you’re unable to find a sponsor for lunch, we have a Subway Catering Offer for qualified events. Further details will be provided after event submission.

DevDaysMadrid16_BraventTips and Tricks for a Great Event

  • Partner with other local user groups on event tasks, promotion, and facilitation onsite to help build a stronger developer community.
  • Quality photos posted on Twitter or Instagram with #XamarinDevDays may be featured in future event blog announcements and/or on the Xamarin social channels.
  • Start gathering details for your event submission as soon as possible – swag, catering, and Azure passes are limited!

The post Organize a Xamarin Dev Days! appeared first on Xamarin Blog.

March 21

Play Audio and Video with the MediaManager Plugin for Xamarin

This is a special guest post on MediaManager for Xamarin, written by Xamarin MVP, Martijn van Dijk.

Martijn works at Xablu as a Xamarin consultant. You can find him on Twitter at @mhvdijk and on Github at @Martijn00.

Media apps, more than others, benefit from working together with the native platform. Some things, like handling interruptions with audio focus, network connectivity, and communication between notifications and other playback controls, make this a complicated matter.

To enable Xamarin developers to access these native platform functions, we decided to build a cross-platform Xamarin plugin that abstracts away the difficulties. We created a portable class library using the Bait & Switch pattern that contains all the interfaces for the native code, with the base classes shared across the apps to make it as easy as possible for you to interact with audio and video in your mobile apps.

The MediaManager Plugin for Xamarin is designed to be simple and easy-to-use, and has the following features:

  • Native playback of media files from remote and local sources
  • Native media notifications and remote controls
  • Playback status (Playing, Buffering, Loading, Paused, Progress)

Best of all, the MediaManager plugin works with all platforms, including iOS, Android, UWP, macOS, tvOS, and even Xamarin.Forms. In this blog post, we’ll explore the various components of the MediaManager Plugin for Xamarin and how you can easily integrate it into your mobile applications.

Audio

Both your eyes and ears are engaged when playing video. When playing audio, you’re listening, but you can also work with a different app at the same time. There’s a different design for each use case.

An audio player does not always need to have its user interface visible. Once it begins to play audio, the player can run as a background task. The user can switch to another app and work while continuing to listen.

To play audio takes only one line of code, and handles all of this for you:

await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");

Android ExoPlayer

ExoPlayer is an open source library that exposes the lower-level Android audio APIs. ExoPlayer supports high-performance features like DASH and HLS streaming that are not available in MediaPlayer. You can customize the ExoPlayer code, making it easy to add new components. ExoPlayer can only be used with Android version 4.1 and higher.

To make use of ExoPlayer, add the following code to your `MainActivity`:

((MediaManagerImplementation)CrossMediaManager.Current).MediaSessionManager = new MediaSessionManager(Application.Context, typeof(ExoPlayerAudioService));
var exoPlayer = new ExoPlayerAudioImplementation(((MediaManagerImplementation)CrossMediaManager.Current).MediaSessionManager);
CrossMediaManager.Current.AudioPlayer = exoPlayer;

Video

A video app needs a window for viewing content. For this reason, a video app is usually implemented on a single screen.

CrossMediaManager.Current.Play("https://archive.org/download/BigBuckBunny_328/BigBuckBunny_512kb.mp4", MediaFileType.Video);

The video player for the MediaManager Plugin for Xamarin.

Notifications

A well-designed media app should “play well together” with other apps that play audio. It should be prepared to share the phone and cooperate with other apps on your device that use audio. It should also respond to hardware controls on the device, including:

  • Change the volume when the user adjusts a hardware volume control
  • Stop playing if the headphones are disconnected while in use
  • Stop playing, or lower the volume, when another app takes over the audio output stream

Media buttons are hardware buttons found on Android devices and other peripheral devices; for example, the pause/play button on a Bluetooth headset.


AndroidNotification    iOSNotification

Audio controls on a TV with the MediaManager Plugin for Xamarin.

Queueing Audio and Video

If you want to play a sequence of media items, it’s helpful to have a queue. To add a list of media files to the queue, simply CrossMediaManager.Current.Play() an Enumerable of MediaFiles. With the queue, you are able to shuffle and repeat playback, loop through certain media files, and so on.

The queue can be accessed by:

var queue = CrossMediaManager.Current.MediaQueue;

Media Information

Media files contain a lot of information about the file. Details like title, album, artist, and more can be extracted from the metadata. It’s very easy to do this using the MediaManager:

CrossMediaManager.Current.MediaFileChanged += (object sender, MediaFileChangedEventArgs e) => {
var artist = e.File.Metadata.Artist;
    // Access any other metadata property through the file
};

Xamarin.Forms

The MediaManager can be used in a native app but also in a Xamarin.Forms app through a custom renderer for the Native Video view:

Make sure to call VideoViewRenderer.Init() from your platform code before starting playback, otherwise the view will not be prepared to display your video.

MediaManager In Action: The Scott Hanselman App!

Even the Hanselman App runs on the MediaManager, thanks to Erlend Angelsen! Using the implementation of MediaManager, the app now has improved audio playback, but what’s even more exciting is that all Hanselman videos from Channel 9 are available in the app! It also uses notifications to control the current media playing. In the future, this will be extended to make use of the queue and other advanced functionality. For more information about this app check out James Montemagno‘s Github repository.

The official app of Scott Hanselman, using the MediaManager Plugin for Xamarin.

Wrapping Up

There are many other samples for the Xamarin MediaManager available, including:

To get started, all you need to do is download the plugin from NuGet and install it into each project that utilizes MediaManager.

If you want to learn more about media playback, make sure to follow me on Twitter at @mhvdijk to receive updates. Future plans include support for Android Auto, Chromecast, CarPlay, and seamless switching between output sources such as Bluetooth, TV, or DLNA. If you have ideas, find bugs, or want to help with development, make sure to check out the source code on GitHub.

The post Play Audio and Video with the MediaManager Plugin for Xamarin appeared first on Xamarin Blog.

March 20

Apply now for Summer of Code 2017!

Student applications are now open for the Mono Project in the 2017 Google Summer of Code!

We have a list of project ideas to help you get started, and our guidance page has a lot of useful information and links to help get involved in our community and put together a good proposal. Remember in your proposal to show us how passionate you are about building great tools and frameworks, and demonstrate that you're able to research and develop things independently but also know when to ask smart questions.

We strongly recommend that you submit your application early. The deadline is April 3, 2017 at 12:00 (Eastern Daylight Time) and late applications cannot be accepted for any reason. You can submit your application as a draft in order to receive early feedback, so don't delay.

If you have any questions about the Mono Project in Google Summer of Code that are not answered by our GSoC page or in the Mono gitter IRC or Mono mailing list, please email soc@xamarin.com. Good luck!

March 17

Xamarin University Webinar Recording | Building Your First Android App with Xamarin for Visual Studio

You can register for the remaining Xamarin University Presents webinars here. Xamarin University is a leader in providing online mobile development training and offers a 30-day free trial, including access to Self-Guided Learning. To register for a free trial or sign up for Xamarin University visit the Xamarin University homepage.

.NET developers everywhere can easily add native mobile developer to their resume with Xamarin for Visual Studio. Judy McNeil, Xamarin University mobile expert, shows you how to build your first Android app completely in C# with Xamarin.Android and Visual Studio.

In this recording, you will:

  • Explore the Xamarin.Android project templates installed with Visual Studio
  • Create a fully native Android app, utilizing all of the Android APIs
  • Use the Android Designer in Visual Studio to create a beautiful UI
  • Add logic to your applications to respond to user input and interact with the UI
  • Deploy and test your apps from Visual Studio, using Google’s Android emulators and your own Android devices
  • Ask questions and receive guidance from Xamarin University professors and mobile experts
  • Get the sample app code and documentation you need to get started

 


You can register for the remaining Xamarin University Presents webinars here. Xamarin University is a leader in providing online mobile development training and offers a 30-day free trial, including access to Self-Guided Learning. To register for a free trial or sign up for Xamarin University visit the Xamarin University homepage.

The post Xamarin University Webinar Recording | Building Your First Android App with Xamarin for Visual Studio appeared first on Xamarin Blog.

MSpec (Machine Specifications) support for .csproj-based .NET Core projects now available

I am pleased to announce that it is now possible to use and run Mspec (Machine Specification) tests when using .csproj based .NET Standard / .NET Core projects including multi-targeting scenarios.

The runner (Machine.Specifications.Runner.VisualStudio nuget package) supports:

  • dotnet test
  • Visual Studio’s Test Explorer
  • vstest.console
  • Visual Studio Team Services and TFS

For information on how to migrate from project.json to .csproj-based mspec tests please refer to this wiki page.

Another news is that Machine.Fake 2.8.0 is now also available with .NET Core (.NET Standard) support for Moq, FakeItEasy and NSubstitute.

Here is an example .csproj targeting both .NET Core 1.1 and .NET Framework 4.6:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>    
    <TargetFrameworks>netcoreapp1.1;net46</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Machine.Specifications" Version="0.11.0" />
    <PackageReference Include="Machine.Specifications.Runner.VisualStudio" Version="2.*" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.*" />
  </ItemGroup>
</Project>

Example output:

C:\code\mspec-test-sample\MSpecSampleSolution\Sample>dotnet test
Build started, please wait...
Build completed.

Test run for C:\code\mspec-test-sample\MSpecSampleSolution\Sample\bin\Debug\netcoreapp1.1\MSpecSample.dll(.NETCoreApp,Version=v1.1)
Microsoft (R) Test Execution Command Line Tool Version 15.0.0.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Machine Specifications Visual Studio Test Adapter - Executing Specifications.
Machine Specifications Visual Studio Test Adapter - Executing tests in C:\code\mspec-test-sample\MSpecSampleSolution\Sample\bin\Debug\netcoreapp1.1\MSpecSample.dll
Complete on 1 assemblies

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 0.8338 Seconds


Test run for C:\code\mspec-test-sample\MSpecSampleSolution\Sample\bin\Debug\net46\MSpecSample.dll(.NETFramework,Version=v4.6)
Microsoft (R) Test Execution Command Line Tool Version 15.0.0.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Machine Specifications Visual Studio Test Adapter - Executing Specifications.
Machine Specifications Visual Studio Test Adapter - Executing tests in C:\code\mspec-test-sample\MSpecSampleSolution\Sample\bin\Debug\net46\MSpecSample.dll
Complete on 1 assemblies

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 0.7364 Seconds

March 16

Introducing the Kimono Designer for SkiaSharp

The modern app developer faces a challenge when it comes to developing the high quality graphics required to build exciting and engaging user interfaces: because of the various screen sizes and resolutions across devices in a given OS, multiple copies of each graphic asset have to be created, implemented, and maintained.

This is especially true when dealing with cross-platform development, which not only increases the number of assets, but requires different techniques to implement on each OS. We launched SkiaSharp in February of last year to address these issues.

SkiaSharp offers developers a cross-platform, high-performance 2D API for .NET, available across mobile, desktops, and servers. It’s powered by Google’s Skia library, the same library that powers Google Chrome, Firefox, and Android’s graphic stacks.

SkiaSharp is great for developing cross-platform, pixel-perfect, resolution independent graphic assets, but requires that the developer design the graphic as code, which why we’re launching Kimono Designer for macOS today.

Kimono Designer allows a developer or graphic artist to graphically edit SkiaSharp based graphic objects, that can be converted to code and included in any cross-platform language and OS that SkiaSharp supports.


Check out the Kimono Designer Preview

Kimono Designer provides several key features that make it the perfect tool for designing SkiaSharp graphics, including:

  • Groups with Boolean Operations and Masks
  • Named Color Palettes
  • A Visual Gradient Editor
  • Named Styles
  • Linked Properties
  • A built in scripting language with Script Libraries
  • Portfolios, containing multiple Sketches

Shows the main Kimono Designer User Interface

Consuming Kimono Assets

As the sketch is designed and edited, source code will be generated for the requested operating system, language, and support library:

Shows an example of the code generation from Kimono Designer

The developer can include this code directly, or embed the portfolio in their app project and use the cross-platform KimonoCore library to consume it.

The Future

While the editor is currently implemented in Xamarin.Mac and only runs on macOS, the project was designed to be built cross-platform. It’s hoped that the front end will be ported to other platforms such as Windows UWP, iOS for iPad, and for Android tablets.

Kimono Designer is a work in progress, and as such, still has some rough areas and missing features (such as copy and paste), which is why we’re sharing it with our community today! Feel free to check out the GitHub repository at https://github.com/xamarin/KimonoDesigner.

The post Introducing the Kimono Designer for SkiaSharp appeared first on Xamarin Blog.

Apply Now for Microsoft’s Go Mobile Tech Workshops

Don’t miss your team’s opportunity to discuss app development and architecture best practices one-on-one with Microsoft engineering experts.

We’re excited to announce that the Microsoft engineering team is offering a limited number of technical sessions to help your team build better mobile apps faster. The Go Mobile Tech Workshops are three-hour sessions dedicated to your team to cover everything from your technology stack and architecture to the latest in Visual Studio 2017 and DevOps best practices.
 

Register

What’s in it for you

  • Dedicated time with Microsoft technical experts to help you analyze your technology stack and application development practices.
  • Common patterns, architectures, and best practices for mobile to help you go faster and avoid common pitfalls.
  • Q&A with the engineering team to address your technical questions.

Blog_1600x900_Go Mobile

Don’t miss out—apply for a workshop today!

The post Apply Now for Microsoft’s Go Mobile Tech Workshops appeared first on Xamarin Blog.

March 15

Xamarin University Webinar Recordings | Intro to Xamarin for Visual Studio and Building Your First Xamarin.Forms App

You can register for the remaining Xamarin University Presents webinars here. Xamarin University is a leader in providing online mobile development training and offers a 30-day free trial, including access to Self-Guided Learning. To register for a free trial or sign up for Xamarin University visit the Xamarin University homepage.

Intro to Xamarin for Visual Studio: Native iOS, Android, and Windows Apps in C#

 
Xamarin’s James Montemagno shows you how to use the power of C# and the .NET framework to create, debug, test, and deploy fully native Android, iOS, and Windows apps. With Xamarin for Visual Studio, you use the language and IDE you know and love to get to market fast, sharing one codebase across all platforms.

In this session, you will:

  • Explore Xamarin for Visual Studio, including Xamarin.Android and Xamarin.iOS
  • Learn how to structure your code to maximize code sharing
  • Get technical resources and code samples
  • Ask questions and receive guidance from Xamarin University professors and mobile experts
  • Leave ready to translate your ideas into fully native mobile apps

 

Building Your First Xamarin.Forms App with Xamarin for Visual Studio

 
Adrian Stevens, Xamarin University mobile expert, shows you how to build your first Xamarin.Forms app with Xamarin for Visual Studio. With Xamarin.Forms, you’re able to get maximum code reuse to quickly build fully native apps for Android, iOS, and Windows. In this recording, you’ll learn how to share C# code to define the UI and business logic, enabling you to design your screens, fix bugs, and write your app just once.

In this webinar, you will:

  • Create your first Xamarin.Forms project targeting Android, iOS, and Windows
  • Maximize code reuse across platforms and deploy fully native Android, iOS, and Windows apps
  • Explore Xamarin.Forms 40+ out-of-the-box custom controls, pages, and layouts
  • Design your UI in XAML, and use Xamarin.Forms Previewer to see changes immediately, straight from the IDE
  • Deploy and test your apps from Visual Studio
  • Get the sample app code and documentation you need to get started
  • Ask questions and receive guidance from Xamarin University professors and mobile experts

 


You can register for the remaining Xamarin University Presents webinars here. Xamarin University is a leader in providing online mobile development training and offers a 30-day free trial, including access to Self-Guided Learning. To register for a free trial or sign up for Xamarin University visit the Xamarin University homepage.

The post Xamarin University Webinar Recordings | Intro to Xamarin for Visual Studio and Building Your First Xamarin.Forms App appeared first on Xamarin Blog.

March 14

Simplified Android Keystore Signature Discovery

The Android Keystore is at the heart of every Android application. It enables us to sign our applications and ship them to the app store securely, but also holds additional signature information needed for Google Play services and other APIs, such as Facebook. Traditionally, we would have manually run commands via the command prompt against Java keytool to find the MD5 and SHA signatures for your debug and release keystores, but no more! We’re now able to use the our very own Jon Dick‘s new Android Keystore Signature Tool Extension for Visual Studio and Xamarin Studio.

Installation

It couldn’t be easier to get started with this new tool. In Visual Studio 2017 (coming soon to VS 2015), simply go to Tools -> Extensions and Updates and search for “keystore” to find the extension.

Capture

After downloading, just re-start Visual Studio and you’ll see it in the Tools menu.

Tool

On the Xamarin Studio side, open the Add-ins dialog under the Xamarin Studio menu, and under Gallery and Mobile Development, you’ll find “Android Signature Tool.”

Pasted image at 2017_03_08 10_02 AM

You’ll see it under the Tools menu after installation.

Finding The Signatures

After installing the tool and launching it, we have the option to find the signatures of the default keystore or specify the path to our own custom created keystore. If we select our own, we’ll have to enter the alias and passwords associated with the keystore and then tap Generate Signature.

FindKey

Learn More

You can learn more about the Android keystore files on the official documentation and browse the source code to the Signature Tool on Jon’s GitHub. Be on the lookout for full support for Visual Studio 2015 soon!

The post Simplified Android Keystore Signature Discovery appeared first on Xamarin Blog.

March 13

Getting Started with Async / Await

Async programming is all the rage in mobile app development for good reasons. Using async methods for long running tasks, like downloading data, helps keep your user interface responsive, while not using async methods, or the improper use of async/await, can cause your app’s UI to stop responding to user input until the long running task completes. This can result in a poor user experience, which can then lead to poor reviews on the app stores, which is never good for business.

Today we’ll take a look at the use of async and how to utilize it to prevent jerky and unexpected behaviors in a ListView.

What is async/await?

The async and await keywords were introduced in .NET 4.5 to make calling async methods easier and to make your async code more easily readable. The async/await API is syntactic sugar that uses the TPL (Task Parallel Library) behind the scenes. If you wanted to start a new task and have code run on the UI thread after the task completes prior .NET 4.5, your code would have looked something like this:

// Start a new task (this launches a new thread)
Task.Factory.StartNew (() => {
    // Do some work on a background thread, allowing the UI to remain responsive
    DoSomething();
// When the background work is done, continue with this code block
}).ContinueWith (task => {
    DoSomethingOnTheUIThread();
// the following forces the code in the ContinueWith block to be run on the
// calling thread, often the Main/UI thread.
}, TaskScheduler.FromCurrentSynchronizationContext ());

That’s not very pretty. Using async/await, the above becomes:

await DoSomething();
DoSomethingOnTheUIThread();

The above code gets compiled behind the scenes to the same TPL code as it does in the first example, so as noted, this is just syntactic sugar, and how sweet it is!

Using Async: Pitfalls

In reading about using async/await, you may have seen the phrase “async all the way” thrown around, but what does that really mean? Simply put, it means that any method that calls an async method (i.e. a method that has the async keyword in its signature) should use the await keyword when calling the async method. Not using the await keyword when calling an async method can result in exceptions that are thrown being swallowed by the runtime, which can cause issues that are difficult to track down. Using the await keyword requires that the calling method also use the async keyword in its signature. For example:

async Task CallingMethod()
{
    var x = await MyMethodAsync();
}

This poses a problem if you want to call an async method using the await keyword when you can’t use the async modifier on the calling method, for instance if the calling method is a method whose signature can’t use the async keyword or is a constructor or a method that the OS calls, such as GetView in an Android ArrayAdapter or GetCell in an iOS UITableViewDataSource. For example:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    // Can’t use await keyword in this method as you can’t use async keyword
    // in method signature due to incompatible return type.
}

As you may know, an async method has to return either void, Task, or Task<T>, and returning void should only be used when making an event handler async. In the case of the GetView method noted above, you need to return an Android View, which can’t be changed to return Task<View> as the OS method that calls it obviously does not use the await keyword and so can’t handle a Task<T> being returned. Thus you can’t add the async keyword to the above method and therefore can’t use the await keyword when calling an async method from the above method.

To get around this, one might be tempted, as I have been in the past, to just call a method from GetView (or similar method where the signature can’t be changed regardless of the platform) as an intermediate method, and then call the async method from the intermediate method:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    IntermediateMethod();
    // more code
}
async Task IntermediateMethod()
{
     await MyMethodAsync();
}

The problem here is that IntermediateMethod is now an async method and thus should be awaited just like the MyMethodAsync method needed to be. So, you have gained nothing here, as IntermediateMethod is now async and should be awaited. In addition, the GetView method will continue running all of the code after calling IntermediateMethod(), which may or may not be desirable. If the code following the call to IntermediateMethod() depends on the results of the IntermediateMethod(), then it isn’t desirable. In such a scenario, you may be tempted to use the Wait() method call (or Result property) on the async task, e.g.:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    IntermediateMethod().Wait();
    // more code
}

Calling Wait() on the async method causes the calling thread to pause until the async method completes. If this is the UI thread, as would be the case here, then your UI will hang while the async task runs. This isn’t good, especially in an ArrayAdapter that is supplying the data for the rows of a ListView. The user will not be able to interact with the list view until the data for all of the rows has been downloaded, and scrolling will likely be jerky and/or completely non-responsive, which isn’t a good user experience. There’s also a Result property you can call on the async task. This would be used if your async task was returning data by using Task<T> as the return type of the async method. This would also cause the calling thread to wait for the result of the async task:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    view.Text = IntermediateMethod().Result;
    // more code
}
async Task<string> IntermediateMethod()
{
     return await MyMethodAsync(); // MyMethodAsync also returns Task<string> in this example
}

In fact doing the above may cause your UI to hang completely and for the ListView never to be populated, which is a non-starter. It may also just be jerky:

JerkyListView

In general, you should avoid using Wait() and Result, especially on the UI thread. In the iOS and Android sample projects linked at the end of this blog, you can look in ViewControllerJerky and MainActivityJerky respectively to see this behavior. Those files are not set to compile in the sample projects.

Using Async All the Way

So how do I get “async all the way” in this scenario?

One way around the above problems is to revert to the old TPL upon which async/await is based. You’re going to use TPL directly, but only once to start the chain of async method calls (and to start a new thread right away). Somewhere down the line the TPL will be used directly again, as you need to use TPL to start a new thread. You can’t start a new thread using only the async/await keywords, so some method down the chain will have to launch the new thread with TPL (or another mechanism). The async method that launches a new thread will be a framework method, like a .NET HttpClient async method in many, if not most, cases. If not using async framework methods, then some method of yours down the chain will have to launch a new thread and return Task or Task<T>.

Let’s start with an example using GetView in an Android project (though the same concept will work for any platform, i.e. Xamarin.iOS, Xamarin.Forms, etc.) Let’s say I have a ListView that I want to populate with text downloaded from the web dynamically (more likely one would download the whole list of strings first and then populate the list rows with the already downloaded content, but I’m downloading the strings row by row here for demonstration purposes, plus there are occasions where one may want to do it this way anyway). I certainly don’t want to block the UI thread waiting for the multiple downloads; rather, I would like the user to be able to start working with the ListView, scroll around, and have the text appear in each ListView cell as the text gets downloaded. I also want to make sure that if a cell scrolls out of view, that when it is reused it will cancel loading the text that is in the process of being downloaded and start loading new text for that row instead. We do this with TPL and cancellation tokens. Comments in the code should explain what’s being done.

public override View GetView(int position, View convertView, ViewGroup parent)
{
    // We will need a CancellationTokenSource so we can cancel the async call
    // if the view moves back on screen while text is already being loaded.
    // Without this, if a view is loading some text, but the view moves off and
    // back on screen, the new load may take less time than the old load and
    // then the old load will overwrite the new text load and the wrong data
    // will be displayed. So we will cancel any async task on a recycled view
    // before loading the new text.
    CancellationTokenSource cts;
    // re-use an existing view, if one is available
    View view = convertView; // re-use an existing view, if one is available
    // Otherwise create a new one
    if (view == null) {
        view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);
    }
    else
    {
        // If view exists, cancel any pending async text loading for this view
        // by calling cts.Cancel();
        var wrapper = view.Tag.JavaCast<Wrapper<CancellationTokenSource>>();
        cts = wrapper.Data;
        // If cancellation has not already been requested, cancel the async task
        if (!cts.IsCancellationRequested)
        {
           cts.Cancel();
        }
    }
    TextView textView = view.FindViewById<TextView>(Android.Resource.Id.Text1);
    textView.Text = "placeholder";
    // Create new CancellationTokenSource for this view's async call
    cts = new CancellationTokenSource();
    // Add it to the Tag property of the view wrapped in a Java.Lang.Object
    view.Tag = new Wrapper<CancellationTokenSource> { Data = cts };
    // Get the cancellation token to pass into the async method
    var ct = cts.Token;
    Task.Run(async () => {
        try
        {
            textView.Text = await GetTextAsync(position, ct);
        }
        catch (System.OperationCanceledException ex)
        {
            Console.WriteLine($"Text load cancelled: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }, ct);
    return view;
}

In a nutshell, the above method checks to see if this is a reused cell and, if so, we cancel the existing async text download if still incomplete. It then loads placeholder text into the cell, launches the async task to download the correct text for the row, and returns the view with placeholder text right away, thereby populating the ListView. This keeps the UI responsive and shows something in the cell while the launched task does its work of getting the correct text from the web. As the text gets downloaded, you’ll see the placeholders change to the downloaded text one-by-one (not necessarily in order due to differing download times). I added a random delay to the async task to simulate this behavior since I’m making such a simple, quick request.

Here’s the implementation of GetTextAsync(...):

async Task<string> GetTextAsync(int position, CancellationToken ct)
{
    // Check to see if task was cancelled; if so throw cancelled exception.
    // Good to check at several points, including just prior to returning the string.
    ct.ThrowIfCancellationRequested();
    // to simulate a task that takes variable amount of time
    await Task.Delay(rand.Next(100,500));
    ct.ThrowIfCancellationRequested();
    if (client == null)
        client = new HttpClient();
    string response = await client.GetStringAsync("http://example.com");
    string stringToDisplayInList = response.Substring(41, 14) + " " + position.ToString();
    ct.ThrowIfCancellationRequested();
    return stringToDisplayInList;
}

Note that I can decorate the lambda passed into Task.Run() with the async keyword, thus allowing me to await the call to my async method, and thereby achieving “async all the way.” No more Jerky ListView!

SmoothListView

See it in action

If you want to see the above in action for Xamarin.iOS, Xamarin.Android, and Xamarin.Forms, check it out on my GitHub repo. The iOS version is very similar to the above, the only difference being in how I attach the CancellationTokenSource to the cell since there is no Tag property as there is in an Android View. Xamarin.Forms, however, does not have a direct equivalent to GetView or GetCell that I’m aware of, so I simulate the same behavior by launching an async task from the main App class constructor to get the text for each row.

Happy async coding!

The post Getting Started with Async / Await appeared first on Xamarin Blog.

March 12

Mono Summer of Code 2017

Hey everyone! The Mono team is pleased to announce that we are a mentor organization in the Google Summer of Code 2017! This is the twelfth year of Summer of Code for us, and we're really excited to work with a new group of students.

This is a great opportunity to spend the summer with a great community working on cutting edge open-source C# tools and frameworks. You can hone your development skills by working on large and complex codebases with experienced mentors, and get paid for your hard work too.

If you're an eligible student, the application period runs from March 20th to April 3rdBut don't let that stop you from starting on your proposals! Feel free to introduce yourself to the community and mentors, talk about your ideas, and do some preliminary research to make your proposal as strong as it can be. If you're feeling particularly ambitious, you could even get started on some quick bugfixes and patches to show off your skills; while this isn't required, it is really helpful in seeing how you work and getting your name out in the community. Show us how excited you are about coding!

Same as in previous years, our project ideas and rules are available on our GSoC ideas page, and we'll be updating the list as we come up with new ideas. Don't let these ideas limit you though; if you have your own idea for a great project for the summer, put it in a proposal and send it our way. Or, if you can't decide, you can always submit multiple proposals. Keep in mind, though, quality is better than quantity in this case. Check out our application guidelines for advice on making a good proposal.


Our project mailing lists should be your first stop for questions about contributing to Mono. There are many lists for different topics, but the main ones are monomono-devel and monodevelop-develFor external projects, you should also contact the developers in their project mailing lists. 

And of course IRC is where you can find everyone online, on the irc.gnome.org server. There's the #mono channel for general Mono discussions, #monodev for Mono development, #monodevelop (and gitter) for MonoDevelop and Xamarin Studio, and #monosoc for Summer of Code-specific questions and saying "Hi" to your fellow students. Hang around a while after asking a question - we have mentors in many timezones so they may be asleep or busy when you visit.

If you're not a student, you can participate in Summer of Code by helping the students feel welcome in our community! Or, if you're interested in mentoring C# tools and libraries under the Mono umbrella, send an email to the Mono GSoC administrator at soc@xamarin.com.

To stay up to date with the applications process and the work of our students, follow us on Twitter and Google+.
Good luck, and here's to another great summer of coding!

March 10

Podcast: What’s New in Xamarin Cycle 9, Visual Studio 2017, and More!

In this episode of the Xamarin Podcast, James Montemagno and Pierce Boggan announce exciting changes for the Xamarin Podcast and cover what’s new in Xamarin, including the stable release of Cycle 9, the Visual Studio 2017 launch, and more. Be sure to download today’s episode from your favorite podcasting app.

Check Out Our Awesome New Website

We’re also happy to announce a brand new website for the Xamarin Podcast at xamarinpodcast.com! This new web portal for the podcast is the best place to view detailed show notes and learn about the Xamarin Podcast hosts and guests. Be sure to check it out, and let us know what you think!



Subscribe or Download Today

Keeping up with the latest in .NET, C#, and Xamarin is easier than ever with the Xamarin Podcast! Cohosts Pierce Boggan and James Montemagno cover topics relevant to Xamarin developers, from designing mobile apps to identity management. Be sure to subscribe to the Xamarin Podcast on iTunes, Google Play Music, Stitcher, or your favorite podcast app you use so you don’t miss an episode.

The post Podcast: What’s New in Xamarin Cycle 9, Visual Studio 2017, and More! 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