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.

June 27

Going Global with Xamarin and Azure Cosmos DB

Imagine that MyTeaCompany is a locally renowned business in Pune, India, supplying tea to the area from their ten shops within the city. They supply a huge variety of teas from Darjeeling to Assam and Thai to Korean, among others. They decide they want to take their business to the next level and create a worldwide presence on the internet.

Today, we’re going to take a look at how utilizing the Azure Cosmos DB database solution in their new Xamarin mobile app can help them leverage a wider customer-base on the global platform.

Building the Azure Cosmos DB solution

Azure Cosmos DB is a scalable, globally distributable solution for all your data requirements. It supports different models, including Graph, Table, and DocumentDb, with APIs available in different technologies, such as .NET, Python and Java. This makes it the perfect solution for all of MyTeaCompany’s data needs.

You can use the Azure Cosmos DB Emulator for developing and testing apps locally. However, for today’s blog post, we’ll use our Microsoft Azure Subscription.

Create an Azure Cosmos DB Account

Head to Azure Portal and create an Azure Cosmos DB account using the ‘+’ sign and navigating to Databases > Azure Cosmos DB. Once created, click on “Keys” and note the details, as those will be required in future steps.

It’s important to decide on the partition key, which helps to span data across servers or partitions, when creating a collection. It’s also important to carefully select your Request Units (RUs), which can play a major role in expected performance. The guide on the Request Unit Calculator is a great resource to help you gauge your requirements.

Xamarin.Forms Mobile App

Since we’re targeting multiple platforms, Xamarin.Forms is the perfect choice for MyTeaCompany, allowing us to maximize code sharing while still being able to use the native controls and features of each individual platform.

Create a Xamarin.Forms Project

In Visual Studio 2017, create a Xamarin.Forms solution by selecting New Project… > Cross-Platform > Cross-Platform App (Xamarin) > Blank / Shared Project. We’ll want to add the Microsoft.Azure.DocumentDB.Core NuGet package to the projects in order to use the package responsible for communicating with the Cosmos DB services.

Define Endpoint Constants

We need to define the endpoints in the Constants.cs file in order to connect the Xamarin.Forms application with Cosmos DB:

//copy details from your Keys section here
public static readonly string EndpointUri = "https://my-tea-company.documents.azure.com:443/";
public static readonly string PrimaryKey = "SKAF9lv43HeXicHgH-----------2yiFff7HPBOyFV0A==";
public static readonly string DatabaseName = "my-tea-company";
public static readonly string CollectionName = "my-tea-company";

Our model is StoreInfo which represents the MyTeaCompany store details.
StoreInfoManager is the helper class that wraps around IDocumentDBService. This class helps us perform CRUD operations on our data. The DocumentDBService class implements IDocumentDBService and uses the details provided in the Constants.cs file to perform these CRUD operations.

class DocumentDBService : IDocumentDBService
{
   DocumentClient client;
   Uri collectionLink;
   public DocumentDBService()
   {
      client = new DocumentClient(new Uri(Constants.EndpointUri), Constants.PrimaryKey);
      collectionLink = UriFactory.CreateDocumentCollectionUri(Constants.DatabaseName, Constants.CollectionName);
   }
...
}

Going Global

After MyTeaCompany deploys their app using Azure Cosmos DB and Xamarin, they see a huge opportunity in Seattle, WA. They decide to open a store there and start serving customers through the existing app. With few changes the app can be configured to serve users in that geographic area. First, they needed to replicate the store and product data to the new Azure Regions, which can be done from the Azure Portal.

Once the the data is replicated, using ConnectionPolicy nearest Azure Regions could be set as PreferredLocations to keep the latency low.

public DocumentDBService()
{
   ConnectionPolicy connectionPolicy = new ConnectionPolicy();
   connectionPolicy.PreferredLocations.Add(LocationNames.WestUS);
   client = new DocumentClient(new Uri(Constants.EndpointUri), Constants.PrimaryKey, connectionPolicy);
   collectionLink = UriFactory.CreateDocumentCollectionUri(Constants.DatabaseName, Constants.CollectionName);
}

By making two simple changes, the entire solution was made available in an entirely new region. Tomorrow, if MyTeaCompany wanted to open a store in Europe, they could expand their reach to the region in just a couple of clicks.

Conclusion

Azure Cosmos DB makes it easy to build globally distributed, scalable, highly available and low latency data solutions, which can be easily integrated with Xamarin mobile apps. You can check out the completed sample described in this post here and the documentation for Azure Cosmos DB can be found here. You can also see our guide on Storing Data in a Document Database for more information.

The post Going Global with Xamarin and Azure Cosmos DB appeared first on Xamarin Blog.

June 26

Interactive 3D with UrhoSharp and Workbooks

Humans live in a three-dimensional world, which we navigate from the time we’re infants. We might, therefore, assume that 3D graphics programming would be an intuitively natural fit to our lifetime of experience; after all, we simply need to translate familiar concepts (left and right, up and down, forward and back) into an X-Y-Z coordinate system.

For most people, however, 3D graphics is quite daunting. It’s hard to get a mental feel for 3D objects and how they move through space, and the mathematics involved can be truly hairy. It’s very common for beginning 3D graphics developers to programmatically define a camera, light source, and a 3D object, and then see nothing at all on the screen.

Imagine if you could then fiddle with the code a bit, perhaps change that positive Z coordinate to a negative, for instance, and immediately see the new result.

This is what the combination of UrhoSharp and Xamarin Workbooks now offers. 3D graphics programming has become more accessible to developers, as well as more enticing, by becoming more interactive.

UrhoSharp is Xamarin’s C# wrapper for the open-source Urho3D cross-platform game engine. This is a powerful, industrial-strength 3D graphics API whose major deficiency is that it has so many features it can seem overwhelming to a 3D newcomer (and to developers who already have some 3D coding experience!).

Xamarin Workbooks are documents that combine text and code. Workbooks allow you to edit and execute code in tiny pieces and get immediate feedback. To get started, download the Workbooks application from the Xamarin Workbooks page, and then begin exploring the almost 100 Workbooks that already exist for a variety of platforms.

Getting Started

If you know some UrhoSharp, it might not seem like the optimal platform for Workbooks. Normally, you create a UrhoSharp application by deriving a class from Application, overriding several methods, and then calling a method named Run. This Run method is blocking; it doesn’t return until the application has completed. Within a Workbook, this application architecture is not conducive to an interactive experience.

For that reason, a new UrhoSharp class has been created specifically for Workbooks. This class is called SimpleApplication. You can simply call the static method SimpleApplication.Show with an optional ApplicationOptions argument within the Workbook, and you’re ready to go.

There are currently eight UrhoSharp Workbooks, with more in the works. Four of these eight are demonstrations of UrhoSharp features, while four others take a more tutorial approach suitable for aspiring 3D graphics programmers. You can run these Workbooks on a PC or Mac directly from the Workbooks page, or you can download the whole Workbooks GitHub repository. The UrhoSharp Workbooks are in the graphics/urhosharp directory.

One of the crucial aspects of 3D graphics programming is defining solid objects in 3D space. UrhoSharp provides several ways to do this. The most professional approach is to use specialized modeling software. UrhoSharp supports numerous model formats. The Animated Model Workbook is the shortest of the Urho Workbooks because it does little more than load in a model of a 3D mutant and animate it:

It’s also possible to create 3D shapes algorithmically by defining or deriving all the 3D vertices right in the Workbook. This approach is demonstrated in two Workbooks: Working with Urho Custom Geometries and Building Polyhedra with UrhoSharp.

The simplest approach, however, can be found in the Urho.Shapes namespace, which contains seven classes that let you make common geometric objects: Box, Cone, Cylinder, Plane, Pyramid, Sphere, and Torus. This is certainly the fastest way to get up and running with an UrhoSharp Workbook.

Creating The Workbook

To begin creating your own UrhoSharp Workbooks, you’ll want to download the Workbooks GitHub repository. In the directories for the existing UrhoSharp Workbooks, you’ll see three library files: one for the PC (mono-urho.dll), another for the Mac (libmono-urho.dylib), and the third that’s common to both platforms (Urho.dll). You’ll need these files in the same directory as your new Workbook file.

Note: Since we’re copying the library files specifically created for Workbooks, there’s no requirement to add the UrhoSharp library from NuGet.

Using the Workbooks application, create a new Console Workbook. In a code cell, add a reference for the UrhoSharp library and include two using directives:

#r "Urho.dll"
using Urho;
using Urho.Shapes;

Now create an instance of SimpleApplication:

SimpleApplication app = SimpleApplication.Show();

When that method executes, a window will pop up on your screen to host the UrhoSharp graphics. SimpleApplication creates a default camera, a point light source, and a root node. A 3D scene in UrhoSharp is a tree of nodes. This hierarchical node architecture turns out to be quite convenient when you want to reference a whole subset of 3D components with a single object.

Creating Objects

The following code creates a new node and associates it with the Box shape:

Node boxNode = app.RootNode.CreateChild("boxNode");
Box box = boxNode.CreateComponent<Box>();

When that code executes, you’ll see a box on the UrhoSharp window:

These simple shapes become much more versatile when you realize that you can apply transforms to them. You can move them around the scene, of course, but you can also apply scaling and rotation that’s different in the three dimensions:

boxNode.Scale = new Vector3(3, 0.25f, 0.25f);
boxNode.Rotation = Quaternion.FromAxisAngle(Vector3.UnitZ, 45);

Now the box has become a thin bar that’s no longer constrained to the axes of the 3D coordinate system:

And, of course, you can set a different color or use a bitmap for texturing. These shapes become a fast and easy approach to creating 3D graphics for visualization purpose, as demonstrated by the Charts Workbook, which uses the Box class to create a little bar chart:

You can also combine these basic shapes to create more complex objects. The Creating Compound Shapes Workbook exploits this technique to the max: it starts with a torus, two cylinders that are scaled to a skinny size, and two circles that are squashed to shapes that look like propeller wings:

Now the node hierarchy implemented by UrhoSharp comes in very handy, for nodes can be cloned and can have transforms applied that also impact all child nodes. This technique allows one arm to be cloned into four arms:

The Workbook goes on to describe the animations to make the wings rotate, and then lets you fly the quadcopter around the screen.

The latest Urho Workbook is called Building Polyhedra with UrhoSharp. This one might have a special appeal to anybody who spent at least part of their childhood making 3D figures out of folded cardboard.

The workbook begins with constructing a plain old dodecahedron:

The dodecahedron has 12 faces (as its name suggests), each of which is a pentagon. As a convex regular polyhedron, it’s one of five possible Platonic solids.

But then the Workbook builds upon this figure to make another figure that is certainly related but looks quite different. Each of the pentagon faces in the dodecahedron becomes the center pentagon of a five-pointed star:

This is a process known as stellating the polyhedron, and this particular result is called the small stellated dodecahedron. It’s still considered a regular polyhedron because all of the faces are the same five-pointed star, but it’s definitely not convex any more.

The Workbook then takes another step by replacing the five-pointed stars with pentagons whose vertices are the same as the points of the stars:

This is known as the great dodecahedron, and yes, another step can replace those pentagons with larger five-pointed stars to create the great stellated dodecahedron… but to see that, you’ll have to run the Workbook!

(It’s definitely more fun that way.)

Summary

Workbooks is an incredibly valuable learning tool, and the Workbooks demonstrate the power and versatility of UrhoSharp and the ability to create professional 3D objects and animations. Workbooks allows you to quickly and easily try new ideas, as well as create samples and tutorials for others.

Don’t forget to check out our guides on both Workbooks and UrhoSharp, as well as the Xamarin Workbooks page containing all our sample Workbooks.

The post Interactive 3D with UrhoSharp and Workbooks appeared first on Xamarin Blog.

June 23

Podcast: WWDC 2017, Fastlane, Xamarin.Forms Embedding, and more!

In this episode of the Xamarin Podcast, I’m joined by James Montemagno, Principal Program Manager for Mobile Developer Tools at Microsoft, to discuss what’s new for Xamarin developers, including our thoughts on WWDC 2017, new features in Visual Studio and Visual Studio for Mac, why Xamarin.Forms Embedding matters, and more. Be sure to download today’s episode from your favorite podcasting app!



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 to ensure you don’t miss an episode.

The post Podcast: WWDC 2017, Fastlane, Xamarin.Forms Embedding, and more! appeared first on Xamarin Blog.

June 21

Building Xamarin.Forms Apps with .NET Standard

.NET Standard libraries bring our code to more platforms and give us even more APIs from the Base Class Libraries with which to build amazing apps. Developers have been able to use .NET Standard libraries with Xamarin to share code across platforms, and use Xamarin.Forms to create a shared user interface across iOS, Android, UWP, macOS, for a long time. When combined, .NET Standard and Xamarin.Forms are a match made in heaven for maximizing the amount of code we can share across platforms, both in our underlying business logic as well as our user interface layer.

In this blog post, you’ll learn how to combine .NET Standard libraries and Xamarin.Forms to maximize code sharing and productivity.

What is this .NET Standard thing?

.NET Standard is a formal specification of .NET APIs that are intended to be available on all .NET runtimes (such as .NET Framework, Mono, and .NET Core). In real terms, you can think of this as a simplified, yet expanded, Portable Class Library. Any code added to a .NET Standard library can be used on any runtime that supports the .NET Standard Platform. In addition, we get expanded access to APIs within the .NET base class libraries, support more platforms, and we don’t ever have to deal with the madness that is PCL profiles.

.NET Standard Diagram

Bringing Xamarin.Forms to .NET Standard

The Xamarin.Forms 2.3.5-pre release added compatibility with .NET Standard. In addition to shared projects and Portable Class Libraries, you can now add .NET Standard libraries to your code sharing tool belt.

File -> New

Let’s get started by creating a new Xamarin.Forms app. If you already have an existing Xamarin.Forms app you’re looking to migrate to a .NET Standard, you can skip directly to the next step.

In Visual Studio, click File -> New Project -> Cross-Platform -> Cross-Platform App. Select Master Detail, and click OK. This is going to create a scaffolded mobile app for iOS, Android, and UWP with Xamarin.Forms that displays some data in a list—a common mobile development recipe.

Shows a File -> New Project for a mobile app in Visual Studio.

In Visual Studio for Mac, you can create a similar template by going to File -> New -> Multiplatform -> Forms App.

Adding a .NET Standard Library

Adding a .NET Standard library to your app is super easy; it works just like adding any other library to your project!

If you’re using Visual Studio 2017, right-click the solution and click Add -> New Project. Navigate to the .NET Standard section and add a .NET Standard project.

Add a .NET Standard library to your project.

Developers using Visual Studio for Mac can create a .NET Standard library by navigating to Multiplatform -> Library -> .NET Standard Library. If you’re using Visual Studio 2015, be sure to follow our getting started guide to create and convert a Portable Class Library to a .NET Standard library.

Adding Xamarin.Forms to a .NET Standard Library

Just like Portable Class Libraries, we can add NuGets to .NET Standard libraries. Open the NuGet Package Manager by right-clicking the project and selecting Manage NuGet Packages. Switch to the Browse tab, select Include prerelease, and search for Xamarin.Forms. At the time of this blog post, only the prerelease version of Xamarin.Forms has compatibility with .NET Standard, although it is likely that .NET Standard compatibility will be included in the next stable release.

Add Xamarin.Forms NuGet to a .NET Standard library.

In each of the other projects (such as iOS, Android, UWP, etc.), upgrade to the latest prerelease Xamarin.Forms NuGet, add a reference to the .NET Standard library we created, and remove the reference to the shared project or PCL that contains your Xamarin.Forms UI logic.

Finally, if you’re migrating, copy over files from your shared project or PCL to our .NET Standard library. That’s it! You’re now using a .NET Standard library with Xamarin.Forms to share code:

Using .NET Standard to share code across all the platforms with Xamarin.Forms.

Wrapping Up

In this blog post, we created a brand new cross-platform mobile app and used a .NET Standard library as our code sharing strategy to reach all the platforms. To learn more about .NET Standard for Xamarin (without Xamarin.Forms), check out our blog on .NET Standard support. If you’re still curious as to what .NET Standard is all about, I suggest you check out Immo Landwerth’s introductory video, read up on the documentation on docs.microsoft.com, or follow along on GitHub.

The post Building Xamarin.Forms Apps with .NET Standard appeared first on Xamarin Blog.

June 20

Minnesota Twins Hits a Home Run with Cloud-Powered Scouting Apps

Rapid development cycles and outstanding mobile experiences are a competitive advantage, and we’re always happy to learn how our customers use .NET to deliver five-star apps. With high stakes requirements and an aggressive timeline, the Minnesota Twins recently released its first ever mobile app to field scouts and internal teams—and end users love it. Now, scouts who travel around the world to evaluate players are free to work offline, capture game notes in real time, and automatically sync information with the convenience of mobile devices.

Jeremy Raadt, Senior Developer of Baseball Systems for the Minnesota Twins, joins us to share how his team uses Xamarin for Visual Studio and Visual Studio for Mac, Azure, and Team Foundation Server to streamline development and construct apps that deliver new experiences for any device or internet connectivity.

Tell us a little bit about your company and role.

The Minnesota Twins has a reputation for innovation, on and off the field. I joined a few years ago to collaborate with the Baseball R&D team, which acts as a service group for our entire baseball department. We create technology that helps our business partners make better decisions: delivering and maintaining data driven solutions to evaluate players, improve player performance, and provide a range of statistical analytics. There’s so much data and information from a variety of sources, and we bring it all together in a cohesive platform to produce intelligence, not just facts and figures.

I’ve been a software developer for 20 years, mostly for the web, and I’ve been lucky to learn many languages and platforms, from Cold Fusion to Java to NodeJS to ASP.NET. Fifteen years ago, I got my start in “mobile” building custom applications for Palm Pilots and other devices. At that time, mobile development was incredibly difficult and time consuming.

Tell us about your app and what prompted you to build it. What does it allow users to accomplish?

Minnesota Twins app homescreenWe’ve put a huge amount of effort into building a great web platform that allows the baseball department to store data and to perform research and advanced analytics. However, many of our users, such as scouts and coaches, are often are not in an office; they’re traveling to high schools, colleges, minor league, major league, and international baseball games. Being on the road, they’re also plagued with spotty internet connections. We needed the ability to coordinate schedules, deliver information, and analyze data between scouts, coaches, and front office staff, whenever and wherever they are. Mobile allows us to extend our powerful web-based system, using the same APIs that connect our data store to our web app, to deliver features and functionality tailored specifically for mobile use, such as offline access, real time updates, notifications, and data sync.

We started with a project to give amateur scouts (scouting high school and college players) the ability to view game schedules based on area, importance, and various other factors. Historically, coordinating coverage at key events consisted of a massive email barrage across dozens of scouts. Now, scouts filter the most important games with a simple click and always have the most up-to-date game details so they can ensure they’re watching the best players.

This app is a game changer for our organization, and we plan to continue releasing more game changing features.

Why did you choose Xamarin? What alternatives did you consider? 

Since scouts use a variety of mobile devices, we have to support a wide range of platforms, operating systems, and hardware manufacturers. We wanted a framework that was highly performant today and would allow us to grow for years to come. I was in a similar situation in a prior role, and we initially tried HTML5, but quickly ran into performance issues. Our small bootstrapped team was forced to rewrite in Java and Obj-C, and we were never able to deliver all the features we wanted with the quality we demanded.

Fast forward to the Minnesota Twins: I knew trying to manage separate codebases wouldn’t work for our small team, who also supports our web application (which has an increasing number of features on the roadmap). So, I searched for a better way.

We needed a long term solution, that provided us:
Schedule on the Minnesota Twins app 

  • Native performance: A smooth, performant user experience. Lagging and slow load times would make us look less professional and we’d lose credibility. With hundreds of thousands of datasets, including players, stats, reports, game details, and more, we demanded high performance. To increase adoption from our scout and front office personnel, our mobile experience needed to feel extremely professional and load information quickly.
  • Reliability and security: Users needed to feel safe and confident adding their (highly confidential) scouting information, proprietary algorithms, and all the other data that’s an invaluable part of our competitive advantage. Like any company with highly sensitive data, we needed to ensure the highest levels of security. Xamarin and Microsoft provide not only the framework, but monitoring tools as well.
  • Consistent user experience: We needed high fidelity access to the camera, GPS, notifications, and other device-specific capabilities that felt, looked, and behaved as users expected.

 
 
Xamarin intrigued me right away, due to its ability to provide native support across device platforms while using our C# skills (our web app is built on ASP.NET Core). After exploring and really testing its performance, I was impressed. With our first version, we not only have native performance, we’re also sharing 99% code across Android and iOS thanks to Xamarin.Forms.

How did you get up to speed with cross-platform mobile development?

Xamarin University was invaluable; even though I knew C#, there are nuances and patterns that help you build better apps. I spent three weeks completing the Xamarin Certification courses, and we also had the Xamarin team onsite, working side-by-side to help us build a rock solid foundation. This acted like a jet pack, accelerating us ahead by months.

We (developers, along with our stakeholders, and upper management) were shocked when we had a working prototype in just five days. We knew immediately that we’d made the right decision, and one that would pay dividends in the future.

Describe your development process. 

Minnesota Twins app schedule on iOSWe started prototyping on Monday. By Friday, we showed our stakeholders and management a working prototype. Without Xamarin, we’d still be working on an early prototype. Honestly, I’m not sure we’d have started creating a mobile experience, since we don’t have the resources to learn Obj-C and Java and support two mobile codebases along with a 3rd code base for our web application.

I credit our speed to two things: (1) we share almost 99% code across Android and iOS. This is huge for us, since we’re a small team, and we need to support the app and continuously deliver new features and (2), since we integrate with Azure AD for authentication, the libraries, documentation, and simple set up made it easy to get up and running quickly without worrying about building authentication ourselves.

Currently, our team codes our web and mobile apps and manages our DevOps pipeline. It’s key to automate as much of the process as we can, so we can concentrate on business-specific items and delivering features to users. We can’t afford downtime since our users are all over the world, in various time zones, working 24/7.

To achieve this, our team uses both Visual Studio for Mac (Preview) and Xamarin tools for Visual Studio, which is another nice thing about the platform. Our team has developers on Mac and Windows platforms so we can bring up our favorite environments and it just works. In addition to Xamarin, we store our data in SQL Server, and an ASP.NET Core API connects to both our web and mobile apps. Team Foundation Server (TFS) acts as our source control, build, and deployment platform (currently we build and deploy our web and API from TFS, but when time permits, we’re planning to move mobile). We use Visual Studio Mobile Center (Preview) to distribute our apps to beta testers and internal stakeholders.

Tell us more about how you’re using Microsoft Azure.

Most notably, we use Azure AD, which allows our scouts to use the same credentials, whether they’re accessible via web or mobile. For our upcoming video capture functionality, we’re using Azure Media Services, and we’re looking into Microsoft Cognitive Services for voice recognition, speech-to-text, and more.

What’s the most compelling or exciting aspect of your app? 

For me, it’s creating something that is invaluable to our scouts; making sure they’re at the right games, with the right information. If a top prospect is announced to pitch in a game tomorrow, we need the right scouts to know about it right away.

We’re delivering a high quality, impactful experience, and enabling never-before-possible scenarios, now and with our future releases.

What have your users said about your app? Your boss? 

They absolutely love it! Scouts have the information they need immediately searchable at their fingertips, instead of lost in email, and they’re excited for what’s next.

We’re bombarded with requests and ideas for new features, which tells us that they’re enthusiastic and that our work has been a success. Our leadership team sees the potential and how fast we can build and deploy new features, and they’ve placed a high priority on its continued development.

In fact, the project has gotten so much attention that we’re growing our team to help us continue expanding on our mobile vision. One of the requirements: Xamarin mobile development skills.

We’ve accomplished our initial goal, proving a small team can provide a world class mobile experience, and now we have many new goals that we’re aiming to tackle.

What’s your team planning to build next?

We have many features planned, with our immediate development focused on video capture (allowing scouts to capture and share from anywhere and at any time) and making advanced player stats and game locations available offline. Video capture is extremely powerful for scouting; watching and sharing video clips gives us a feel for players that just isn’t possible with text.

The entire Scouting Department and I are excited for what’s possible and where we can take mobile unique capabilities.

What advice do you have for developers who are just starting out or investigating mobile development? 

Start small. Download and try some Xamarin apps to get a feel for how performant they are, and prepare to be amazed!
 
 
Visit xamarin.com/customers to learn how our customers across industries and geographies deliver amazing mobile apps, and visit xamarin.com/download to start building your own.

The post Minnesota Twins Hits a Home Run with Cloud-Powered Scouting Apps appeared first on Xamarin Blog.

June 19

Add Push Notifications to iOS Apps with Azure Notification Hubs

Push Notifications have become ubiquitous in mobile apps since they were first introduced. One of the major advantages of push notifications is being able to deliver a contextual notification without having the app manually check (or poll) a server; this saves a lot of battery life due to reduced CPU usage. Another key advantage of push notifications is the ability to keep users engaged with the app when it’s not running in the foreground.

Azure Notification Hubs allow you to send push notifications to any platform from any backend service in a scalable manner. Unlike setting up a custom delivery system, combining Azure with Xamarin.iOS is simple.

In this blog post, we’ll run through all the steps required to set up and configure a Notification Hub on Azure and implement the code required in a Xamarin.iOS app.

To complete this tutorial, you must have an active Azure account. If you don’t have an account, you can create a free trial account in only a couple of minutes. You can sign up for an Azure Free Trial here.

Signing and Provisioning

Unlike local notifications, you must register your App ID with Apple and enable Push Notifications in order for them to work; this is also the case even when just running a debug build.

To set up the certificates and provisioning profiles required, follow this part of our guide on the Apple Push Notification System.

Follow the guide to the end until you have a Personal Information Exchange (PKCS12) certificate (.p12 file). You will need this to set up the Azure Notification Hub in the next step.

Azure Set Up

Head over to the Azure Portal and sign in. Once logged in, click on “+ New” and search for “Notification Hub”. Next, we need to fill out some information, such as the name for the hub, a unique namespace, server location, and a name for your resource group. Once done, click create and wait for the hub to be set up by Azure; this normally takes no longer than a couple of minutes.

Once the Notification Hub is ready, go to “Manage” then choose “Notification Services”, and then “Apple (APNS)”. Here, we need to upload the .p12 file that we created earlier; make sure Authentication Mode is set to “Certificate”, select the file, enter the password for the certificate (if set), and choose “Sandbox” for the Application Mode. Click “Save” and that’s it! The Notification Hub is set up and ready to use for development!

While still in the Azure portal, we need to grab the EndPoint string for use later on. You can find this under “Manage” > “Access Policies” and copy the connection string for the DefaultListenSharedAccessSignature policy.

The Code

Now we need to add some code to our app so we can receive push notification from the Notification Hub. With Xamarin.iOS, this is really simple; start by adding the Xamarin.Azure.NotificationHubs.iOS NuGet package to your project by right-clicking the “Packages” folder and selecting “Add Packages…”

Following this, we need to add some code to AppDelegate.cs to register for notifications and handle them when received. At the top of the file add:

using WindowsAzure.Messaging;


Next, we need to declare a SBNotificationHub and the connection parameters at the class level:

private SBNotificationHub Hub { get; set; }


public const string ConnectionString = "Endpoint=sb://…";

public const string NotificationHubPath = "AzurePushHub";


The ConnectionString is the string we copied from Azure previously and the NotificationHubPath is simply the name of your Notification Hub.

Now we need to register our preferred notification settings for the app and register to receive push notifications. Add the following code in FinishedLaunching.

var settings =  UIUserNotificationSettings.GetSettingsForTypes( UIUserNotificationType.Alert |  UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet());


UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);

UIApplication.SharedApplication.RegisterForRemoteNotifications();


Here, we’re specifying that by default, unless overrided by the user, we want to display alerts, a badge on the app icon, and play a sound when a notification is received.

iOS will now go ahead and register the app for remote push notifications. It will let us know this is complete by calling RegisteredForRemoteNotifications; we need to override this to handle the result and register the device with our Azure Notification Hub.

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
  // Create a new notification hub with the connection string and hub path
  Hub = new SBNotificationHub(ConnectionString, NotificationHubPath);
  // Unregister any previous instances using the device token
  Hub.UnregisterAllAsync(deviceToken, (error) =>
  {
    if (error != null)
    {
      // Error unregistering
      return;
    }
    // Register this device with the notification hub
    Hub.RegisterNativeAsync(deviceToken, null, (registerError) =>
    {
      if (registerError != null)
      {
        // Error registering
      }
    });
  });
}

Once this is done, iOS will automatically display received alerts for your app when the app is backgrounded. If we want to handle alerts when the app receives a push notification, we can use ReceivedRemoteNotification:

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{

  // This method is called when a remote notification is received and the

  // App is in the foreground - i.e., not backgrounded


  // We need to check that the notification has a payload (userInfo) and the payload

  // has the root "aps" key in the dictionary - this "aps" dictionary contains defined

  // keys by Apple which allows the system to determine how to handle the alert

  if (null != userInfo && userInfo.ContainsKey(new NSString("aps")))
  {

    // Get the aps dictionary from the alert payload

    NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;


    // Here we can do any additional processing upon receiving the notification


    // As the app is in the foreground, we can handle this alert manually

    // here by creating a UIAlert for example

  }


}


If you want to run code when a notification is received while the app is backgrounded, you can do so by using DidReceiveRemoteNotification

Testing

Deploy your app to your iOS device from Visual Studio. Once deployed, hit the home button to send it to the background. Next, go to the Azure Portal, open your Notification Hub, and go to “Support + Troubleshooting” > “Test Send”.

From here we can send a test notification to our app, so set the platform to “Apple” and click “Send”. It may take up to a minute to see the notification appear on your device, depending on connectivity, but usually it will be received in a matter of seconds. The result should look like this:

Summary

Whether it’s sending updates, reminders, messages or more, using remote notifications in your apps is a powerful way to keep users engaged. Using an Azure Notification Hub with Xamarin.iOS makes this a simple task and allows you to leverage all the other benefits provided by Azure. Azure is able to scale with your app, can quickly send millions of messages, and can be integrated into almost any back-end service, whether it’s Microsoft .NET, PHP, Java, or Node.js (to name just a few).

As well as the standard use cases, you can also use push notifications to update your app in the background by using silent notifications. Find out more about this by reading our documentation.

The full code for this blog post can be found on the GitHub repo for this post.

The post Add Push Notifications to iOS Apps with Azure Notification Hubs appeared first on Xamarin Blog.

June 16

Easy iOS App Provisioning with Fastlane and Visual Studio for Mac

iOS developers know that app and device provisioning is a huge pain. Just to deploy an iOS app to a device for the first time, you must request a development certificate, generate a signing key, add a device in the Apple Developer Center, and create a development provisioning profile for the app that includes your device in the list of approved devices to deploy to. That was a mouthful.

We wanted to make it as easy as possible for you to get started with iOS development by streamlining this key pain point of app and device provisioning. Visual Studio for Mac now integrates with the open source project fastlane, which was created to simplify the app provisioning process from app and device provisioning to team provisioning management. In this blog post, you’ll learn how to quickly provision a new device and app in less than five minutes with the click of a few buttons.

Easy Provisioning with Fastlane

The fastlane toolchain has been integrated into Visual Studio for Mac 15.3. To access these features, simply change the updater channel to Alpha. Install fastlane from GitHub with HomeBrew, the installer script, or via Rubygems. To provision your apps, you’ll need to be a member of the Apple Developer Program.

File -> New Project

The best time to provision apps is at creation, so we’ve integrated fastlane directly into our File -> New Project wizard in order to ensure every app you create is properly provisioned. In Visual Studio for Mac, select File -> New Project -> iOS -> Single View App. Click Add Team.

File -> New Project dialog where you can now add an iOS developer team.

The Apple Developer Accounts tab within the Preferences window will appear. This is where you can manage all of your developer accounts across all of the apps you’re working on. Click the + icon to add your account. Enter your Apple ID and password to enable fastlane to integrate with your iOS developer account.

Sign into your Apple Developer Account using fastlane from Visual Studio for Mac.

From this dialog, you can create certificates and manage provisioning profiles for all teams you’re a member of. Click OK and return to the File -> New dialog. Select your team from the dropdown, click Next, and click Create.

Create a Signing Identity

Right-click the iOS app you’ve just created, and select Options -> iOS Bundle Signing. The team you selected during the File -> New Project wizard is automatically set as the default team. Next to the Signing Identity heading, click the dropdown, and select Create signing identity. This automatically creates a new signing identity for you and associates it with your Apple developer account.

Generating a signing identity with fastlane and Visual Studio for Mac.

It’s worth noting that all setup up until this point only needs to be done once per Visual Studio for Mac installation.

Create a Provisioning Profile

Now that we have a signing identity, it’s time to create a provisioning profile for your app. In the iOS Bundle Signing tab, select the Provisioning Profile dropdown and click Create provisioning profile. In less than ten seconds, we have successfully provisioned our new app.

iOS app provisioning in Visual Studio for Mac.

Provision a Device

To be able to deploy to a device, we must provision the device and “attach” it to the provisioning profile we just created. Normally, we would go to the Apple Developer Portal to do this, but Visual Studio for Mac provides a way to provision new devices directly within the IDE.

Plug your device into your Mac via the Lightning to USB cable. If the device attached is not associated with the provisioning profile selected, Visual Studio for Mac will suggest you provision the device. Click Register, followed by Add, and Visual Studio for Mac will add the device to your Apple developer account and associate it with the selected provisioning profile.

What’s Next?

In this blog post, we successfully generated a development provisioning profile for a new app. Publishing iOS apps (either Ad Hoc for testing or for release in the App Store) requires a separate distribution certificate and provisioning profile. Now in Visual Studio for Mac 15.3, you can easily create distribution signing identities for use in your app publishing workflow without leaving the IDE:

Publishing workflow with fastlane.

Wrapping Up

Visual Studio for Mac’s fastlane integration makes it super easy for you to provision apps and devices directly from the IDE with just a few clicks. For more information, read our documentation on using the fastlane tools with Xamarin. In the future, we will be working to bring easy app and device provisioning to Visual Studio on Windows and continue to integrate additional features of fastlane directly into the IDE.

The post Easy iOS App Provisioning with Fastlane and Visual Studio for Mac 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