September 04, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #56

Upcoming Xamarin University Guest Lectures
Karina Ung, from Xamarin Inc., gets us back to school with some guest lectures.

Gone Mobile 28: Behind the Scenes of Xamarin Forms with Jason Smith
Greg Shackles and Jon Dick grill the creator of Xamarin.Forms Jason Smith.

Xamarin.Android Custom Controls
Chris Swain gets cohesive with this custom Android control.

Extending the ListView to make it clickable
Johan Karlsson extends the ListView so that it’s always clickable.

52 Weeks of Xamarin: Week 4 – Binding A List of Data
Jesse Liberty adds another week to his year long series.

Add NuGets To All Projects In Xamarin Studio with 1 Click
James Montemagno, from Xamarin Inc., has a new favorite add-in to Xamarin Studio.

Pull To Refresh Any(ish) Xamarin.Forms View!
James Montemagno, from Xamarin Inc., adds “pull to refresh” to all things Xamarin.

Improve Discoverability with Search in iOS 9
Mike James, from Xamarin Inc., helps you help users find your app in the App store.

Skype style animations with Xamarin.Forms
John Miller makes some impressive animation in Xamarin.Forms. You don’t want to miss this.

31 Days of Xamarin.Android
Venkata Koppaka, from Falafel Software, completes his 31 straight days of Xamarin.Android.

  • Day 28: Using SQLite.Net with Xamarin.Android
  • Day 29: Plugins for Xamarin.Android
  • Day 30: Monitoring your Xamarin.Android applications using Xamarin Insights
  • Day 31: Distributing your Android App and Wrap-up

The post Weekly Xamarin Newsletter Issue #56 appeared first on Syntax is my UI.

September 03, 2015 6:18 GMT

Pull To Refresh Any(ish) Xamarin.Forms View!

If you have read motz.codes then you know I love, love, love, love, love pull to refresh! In face this is my sixth blog alone on adding pull/swipe to refresh to either MVVMCross or Xamarin.Forms applications. So why am I back with another blog seeing that the Xamarin.Forms team already add Official Pull to Refresh to 1.4? I am back because you asked me for it so nicely on GitHub, StackOverflow, and the Xamarin Forums for a way to update and upgrade my Xamarin.Forms pull to refresh controls for iOS and Android. The main ask is the ability to be able to pull to refresh ANYTHING and put that pull to refresh control inside of ANYTHING! That isn’t a simple ask, but do not fear I am back with exactly what you need, well almost. Introducing:

PullToRefreshLayout

What is PullToRefreshLayout you may ask? Well it is a type of Xamarin.Forms Layout that can house another Layout. This means that the pull to refresh now can be applied to anything. Do you want to pull to refresh a ScrollView? Sure! How about a StackLayout? Sure! And Grids? GO FOR IT! Heck I even made it so you can do it with custom controls and even the ability to fine tune how the scroll moves up and down. To really really top it off I even made it so PullToRefreshLayout can replace Xamarin.Forms ListView’s built in pull to refresh features.

Alright, so sure you can add it to any view, but what is it really supported on. Well think of the PullToRefreshLayout as a wrapper around any control that is bundled up. However, you really must have something scrollable such as a Xamarin.Forms ScrollView or TableView.

Updated BindingProperties

This time around I did a strict one to one mapping of Xamarin.Forms ListView pull to refresh binding:

public bool IsPullToRefreshEnabled { get; set; } = true;
public bool IsRefreshing { get; set; } = false;
public ICommand RefreshCommand { get; set; } = null;

However, I modified it so IsPullToRefreshEnabled is defaulted to true and I added a few colors that you can set:

public Color? RefreshColor { get; set; } = null;
public Color? RefreshBackgroundColor { get; set; } = null;

If you don’t set anything, don’t worry as they will take on the system defaults.

Common Control

In the past I developed the iOS and Android controls completely separate with different bindings, names, and base types. Well no more! Simply create a new PullToRefreshLayout and you are done!

Here it is in action with a ScrollView:

And here is the code to insert a PullToRefreshLayout:

There you have it, but where can you get it? Well I highly recommend that you actually add either a submodule or copy and paste in the control from GitHub if you want to actively debug or add custom controls that can be pulled to refreshed. So head over to my GitHub page, star the repo, follow me, and read the README! Or if you really really want I have published it to NuGet for your consumption!

See it on Motz Codes Live!

Next Friday Sept 11th at 9AM Pacific I will be showing off all sorts of Pull to Refresh goodness with Xamarin.Forms. RSVP here on Google Hangouts!
September 03, 2015 5:03 GMT

Improve Discoverability with Search in iOS 9

ios-9-searchHistorically, iOS has limited its search capabilities to the web and/or system apps that come pre-installed with iOS. With the release of iOS 9, though, Apple is enabling developers to take advantage of search to make their app’s content more accessible than ever.

Apple has provided three options for implementing search on iOS 9. I’ll be covering these in detail over the coming weeks, but today will focus on my favorite: Activity Indexing.

Why Implement Search?

Accessing search in iOS 9 provides a new way for users to interact with their devices. Let’s take the case of a user who wants to learn about a particular wine. The user will no longer need to search the App Store to find a wine app; they will simply ask Siri or use iOS search. iOS will search the publicly indexed data from other users’ wine review apps and return the most popular results. The user can then click on the result and be taken straight to the App Store page, ready to install the app. Once installed, the app launches and takes the user straight to the wine they were initially interested in learning about. If you’re not indexing your data, your application’s content will not be discoverable and you will struggle to compete for downloads.

Get started

First you’ll need to ensure you’ve got the latest version of the Xamarin.iOS 9 Preview and the latest Xcode beta installed. Make sure you open Xcode at least once after installing it to ensure it is initialized and has finished installing its necessary components. You’ll then need to point Xamarin Studio to the Xcode beta.

Screen Shot 2015-09-01 at 14.51.40

Monkey Searching

In this example, I’ve got a list of monkeys that I wish to make searchable outside of my app. The data is coming from a helper class, which contains a list of monkey objects. You may be familiar with this demo, which my colleague James Montemagno originally Simulator Screen Shot 1 Sep 2015 14.24.52created with Xamarin.Forms. Using this dummy data, I populate a UITableView with the names of the monkeys. At this point, the monkey data isn’t accessible to iOS 9. We know this because when I search for a squirrel monkey using Spotlight, I only receive results from the iBook store and Wikipedia.

In order for iOS to know that my app contains information about squirrel monkeys, I’m going to create an NSUserActivity, make it eligible for search, and set a couple of properties. If you’re unfamiliar with NSUserActivity, Apple added it in both iOS and OS X last year to allow developers to easily capture application state. This enables handoff to pass the application state between a Mac and iPhone or other iOS device.

NSUserActivity CreateActivity()
{
    var activity = new NSUserActivity(activityName);
    activity.EligibleForSearch = true;
    activity.EligibleForPublicIndexing = true;
    activity.EligibleForHandoff = false;
    activity.Title = monkey.Name;
    activity.AddUserInfoEntries(NSDictionary.FromObjectAndKey(new NSString(monkey.Name), new NSString("Name")));
    var keywords = new string[] { monkey.Name, "Monkey" };
    activity.Keywords = new NSSet(keywords);
    activity.ContentAttributeSet = new CSSearchableItemAttributeSet(monkey.Details);
    return activity;
}

I call the above code every time the user enters the details page of a monkey. If the user taps on ‘Baboon’, we’ll add it to the index, ready for iOS search to discover. Now when searching for squirrel monkeys, my app is listed as a top hit.

Simulator Screen Shot 1 Sep 2015 14.25.37

 

Wrapping Up

Search is going to play an essential role in iOS 9 and will change the way users discover useful apps. I’d say that adding search to my apps is my number one priority for the iOS 9 update, and you can see thats it’s extremely straightforward to get started. You can learn more about NSUserActivity and download a sample project on my GitHub

The post Improve Discoverability with Search in iOS 9 appeared first on Xamarin Blog.

September 03, 2015 12:41 GMT

Skype style animations with Xamarin.Forms

I want to try and recreate some of the animations that the new Skype of iOS app has using Xamarin.Forms. If you are not familiar with what I am talking about, take a quick look at Brian Lovin's Design Details blog on Skype.

A quick search brings up this post by Arkadiusz Holko. Arkadiusz put his solution on GitHub, so I decided to see what I could learn from that and port it to a Xamarin.Forms project. Here is what I ended up with:

Animation 3 Animation 3 Android

I'm hoping this can be used for a custom alert sheet style view, just like Skype uses.

Animation

Xamarin.Forms already has built in routines to animate position changes. LayoutTo(position, duration, Easing) gives me everything I need to animate my views around the screen.

myView.LayoutTo(position, 500, Easing.SpringOut);  

With just these pieces in place, I was able to get something basic up and running that looks similar to what Arkadiusz has done.

Animation 1

Easing

To change the animation curve, we can provide an easing function. The curve that Easing.SpringOut provides is pretty close to what I wanted. Unfortunately, there is no way to customize the coefficients it uses. So instead, I used a custom easing method so I could change the elasticity:

new Easing((x) => {  
    return ((x - 1) * (x - 1) * (( sidecoeff + 1 ) * (x - 1) + sidecoeff) + 1);
})

see here for the original BackEaseOut method used. Simplification explained here

And the result after some tweaking:

Animation 2

Drawing

I don't currently know of an API to do this that is built into Xamarin.Forms. Another quick search brings me to Christian Falch's NControl library. This gives you the NControlView class which provides cross-platform drawing APIs. Here is what I ended up with:

public override void Draw (NGraphics.ICanvas canvas, NGraphics.Rect rect)  
{
    base.Draw (canvas, rect);

    double yOffset = 20;
    double width = rect.Width;
    double height = rect.Height;

    var points = new PathOp[] {
        new MoveTo(0, yOffset - delta),
        new CurveTo(new NGraphics.Point(width / 2, yOffset + delta),
        new NGraphics.Point(width / 2, yOffset + delta), 
        new NGraphics.Point(width, yOffset - delta)),
        new LineTo(width, height),
        new LineTo(0, height)
    };

    canvas.DrawPath(points, null, new SolidBrush(new NGraphics.Color(0, 0.722, 1, 1)));
}

Arkadiusz's post talks about using CADisplayLink to get a calback for each frame of the animation where the curve can be updated. I did not find a great place to do something similar in shared code, so I put it in the custom easing method which I figured is called similarly.

new Easing((x) => {  
    UpdateCurve();
    return ((x - 1) * (x - 1) * (( sidecoeff + 1 ) * (x - 1) + sidecoeff) + 1);
})

The UpdateCurve() method simply calculates the delta of the side and center helper views and calls Invalidate() on the actual NControlView being drawn. This means that each time the easing method is called, the view will be invalidated and cause the curve to be updated each step of the animation. The end result is pretty good.

Animation 3 Animation 3 Android

I'm hoping I can turn this into a control and fine tune the animation to be even closer to what Skype has done. If you have not already, I encourage you to stop by Arkadiusz's GitHub page and take a look at the work he's done.

September 02, 2015 6:27 GMT

Simplified Office Integration with the O365 Unified API

Office365The world of Office 365 APIs is immense, with a plethora of capabilities that enable developers to access Office 365 and add rich functionality to their mobile apps, all from shared code. In fact, we’ve already covered several Office 365 topics, including integration of SharePoint Online, Outlook(Mail), and OneDrive, as well as authentication .

To consume these services, we followed several steps to register our native app in Azure AD, set proper permissions, authenticate, and receive an ‘access token’ using the Active Directory Authentication Library (or ADAL). Once an access token is obtained, it can be used for subsequent API calls against any of the Office 365 services listed above. Consuming a custom WebAPI secured by Azure AD is straightforward enough that you can call any of the Office 365 services by using HTTPClient and passing the ‘access token’.

There used to be a few more steps to consume an O365 API. For instance, before calling an Office 365 service API, developers were required to call Discovery Service, which “discovers” and provides different end-points for various O365 services. As you can imagine, this was a cumbersome and tedious task.

365 Preview

At Microsoft Build this year, Microsoft revealed the new Office 365 Unified API, which provides a single-unified-end-point to call any services hosted within O365.

In this post, we’ll see how we can use the O365 Unified API in a Xamarin.Forms app by reusing the sample we built in the blog post Put Some Azure Active Directory in Xamarin.Forms. You may want to revisit the blog post for reference.

Step 1: Give permission to access the Office 365 APIs

In the Azure Portal, we must set the required permissions so we can access the Office 365 services from our mobile apps. In this sample, we’ll cover the Me (the logged-in user’s details) and Files APIs. We covered these before in our post on OneDrive.

O365-Unified-01

Step 2: Call Office 365 Services

In our sample from the previous blog post, when the login button was clicked, we asked the user to authenticate. Upon successful authentication, we displayed the user’s name in a message box. We’re going to extend this same method to create a new Tabbed Page with two tabs, one to display the user’s information and the other to list OneDrive documents.

Calling the “Me” API

The Me API is all about fetching details about a user who is signed in. We can use the following code to call this API.

private async void MePageAppearing(object sender, EventArgs e)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.AuthenticationResult.AccessToken);
    var meData = await client.GetStringAsync("https://graph.microsoft.com/beta/me");
    var userData = JsonConvert.DeserializeObject<UserModel>(meData);
    //Set Inforation
    this.DisplayName.Text = userData.DisplayName;
    this.Mail.Text = userData.Mail;
    this.Country.Text = userData.Country;
}

When we run the app, we should see the following output, which resembles the details stored on the Office 365 portal:

O365-Xamarin-Forms-1

Calling the “Files” API

Previously, calling the Files API was part of adding the SharePoint permissions and accessing it using the discovery service. With the unified Files API, it has become much easier. The following code gives us all of the files in our OneDrive.

private async void FilesPageAppearing(object sender, EventArgs e)
{
   var client = new HttpClient();
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
   client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.AuthenticationResult.AccessToken);
   var meData = await client.GetStringAsync("https://graph.microsoft.com/beta/me/files");
   var data = JsonConvert.DeserializeObject<FilesModel>(meData);
   var files = from file in data.Value
          where file.Type.ToLower() == "file"
          select file.Name;
   this.FileList.ItemsSource = files.ToList();
}

Again, if we run the app, we should be able to see a list of files from OneDrive for Business in the app:

O365-Xamarin-Forms-2

Get Started Today

In this post, we’ve seen how easy it is to integrate Office 365 into Xamarin mobile apps using ADAL and the Office 365 Unified API. Using these APIs, it’s possible for anyone to build the next best mail, calendar, or meeting request app.

Get up and running today with the Office 365 Unified API by downloading this sample, adding your Client ID and Redirect URI in the HomePage.xaml.cs file, and registering the app in Azure AD with the proper permissions.

The post Simplified Office Integration with the O365 Unified API appeared first on Xamarin Blog.

August 31, 2015 9:01 GMT

Join Xamarin at the Jenkins User Conference

Jenkins User Conference LogoWe’re headed to our first Jenkins User Conference in Santa Clara, CA from September 2-3, and we’d love to see you there. We’ll have members from the Xamarin team available to answer your questions, discuss your apps and projects, and show you what’s new in Xamarin Test Cloud.

The Jenkins User Conference is the world’s biggest conference for Jenkins users with a focus on using Jenkins for continuous integration and continuous delivery. Be sure to check out our guide on how to set up Jenkins as a continuous integration server and automate compiling mobile apps created with Xamarin.

Stop by our table and say hello — we can’t wait to see you in Santa Clara!

The post Join Xamarin at the Jenkins User Conference appeared first on Xamarin Blog.

August 31, 2015 7:30 GMT

Upcoming Xamarin University Guest Lectures

Whether you’ve had previous experience with Xamarin or are completely new to C# or mobile development, Xamarin University offers an extensive course library that caters to developers of all levels. The program offers live, interactive, lab-based classes taught by Xamarin mobile experts from around the world, at all hours of the day. In addition to the constantly-updated list of regular courses, subscribers also have access to Guest Lectures, which are live webinars given by notable speakers in the community.

Xamarin University CrestNeed to brush up on a subject? Attend a live session again, watch a video recording, self-study with downloadable course material, or attend a 30-minute Office Hour session with an instructor! And don’t forget—Xamarin Mobile Developer Certification is included at no extra cost with your Xamarin University subscription.

With Xamarin University, the knowledge and tools to build beautiful cross-platform mobile applications is at the tip of your finger.

Guest Lectures in September

In honor of the “Back to School” season, we’ve scheduled several special Guest Lectures in September that you can register for now:

 

james September 10th at 9:00am PST
James Montemagno – Using and Developing Plugins for Xamarin
September 17th at 8:00am PST
Pierce Boggan – Spice Up your Xamarin.Forms UIs with Custom Renderers
pierce
krystin September 24th at 8:00am PST
Krystin Stuteman – Prototyping with Xamarin.Forms
September 29th at 8:00am PST
Greg Shackles – Testing your Apps: A Crash Course
greg

 

Guest lectures are recorded, so don’t sweat if you aren’t available when they’re happening live. With your Xamarin University subscription, you’ll have access to all recorded sessions at any time.

Sounds fantastic, now what?

Head over to the Xamarin University page to learn more. From there, you can enroll for a year-long subscription or you can start a free 30-day trial, which gives you access to all of these amazing Guest Lectures throughout the month of September!

The post Upcoming Xamarin University Guest Lectures appeared first on Xamarin Blog.

August 30, 2015 9:21 GMT

Caviar is Cavalier About Privacy

The "on-demand economy" is everywhere these days. With the tap of a screen you can summon a taxi or have food delivered from your favorite restaurant. Often these services even provide you with real-time updates on the location of the car or courier so you know exactly when they'll be showing up. From a user's perspective this is awesome, but there are pretty big privacy implications at play here for both users of the service as well as those working for them.

To that point, I'd like to discuss some glaring privacy issues I found when using Caviar, a courier service that focuses on delivering food from local restaurants.

TL;DR - if you're a courier for Caviar or a user of Caviar, you should request that they fix these issues as soon as possible.

Courier Tracking

Back on July 11 I ordered a delivery through Caviar. Once the courier was en route to my house the page started updating to show their location. Like most developers, I cracked open the browser developer tools to see how they were doing it. Were they using web sockets? Long polling? It's always interesting to see how different companies set up their solutions for this sort of thing. For anyone curious, they're actually using a less-exciting method of just doing occasional full page refreshes via a meta tag.

On each page load Caviar is dropping the coordinates of the courier into JavaScript variables, along with my coordinates, and then showing those on a map. Simple enough. After the delivery came the map reverted to just showing my location, but I noticed something very alarming: the variables for the courier's location were continuing to get updated long after the delivery was made. In fact, simply flipping a variable named out_for_delivery from false to true as the page was loading would result in the courier's current location being displayed nicely on the map.

For posterity, I've published a gist containing the relevant snippet of code responsible for this. There's not a whole lot going on there, but it's a good example of why you should never completely rely on client-side security rules.

Once I realized this was not resolving itself, I contacted Caviar's support to let them know about the issue. The next day I got a response saying that their engineers would be looking into the problem. Awesome! Problem solved, right?

Fast forward to today, and if I pull up the order status page for that July 11 order it still has moving courier coordinates being dropped onto the page. I also placed another order a couple nights back that now exhibits the same behavior, so it's definitely still an issue.

This is a huge privacy violation for Caviar's couriers. As a user of the service I should not be able to have any knowledge of the courier's location outside of the context of my own delivery. As soon as my delivery is complete, the page should no longer need to be updated with any information about the courier. Instead, if I wanted to I could continue tracking that courier indefinitely. I could mine the data for delivery patterns, pickup and dropoff locations, working hours, and probably even deduce where the courier lives based on where the location settles after hours. This is not information I have any right to, nor is it something I even want to know, so I did nothing of the sort but that doesn't change the fact that it was still there for the taking.

Security by Good Samaritans is not a good long-term strategy.

Insecure Order Status Pages

One other thing I noticed in using Caviar is a privacy issue for both users and couriers. As is the case with basically every system out there, there's a standardized URL for checking on your order status in the form of /orders/{order-id}. This is the same page discussed in the previous section that exposed the courier's location. In addition to that, it also has my full name, address, and even telephone number.

There's one problem here: the page is public. You don't need to be authenticated to view order details and get access to all of this personal information. I have a small sample size here, but the order ID seems to be 8 characters long and a case-sensitive mix of letters, numbers, and underscores. Anyone that comes across the right combination of these characters can easily access all of this data. It's not hard to imagine a brute force attach on this URL to try generating valid order IDs and harvesting private information. Just as before, this is not information I even want to have, so I did not make any attempts to exploit the weakness.

In Closing

None of this is meant to disparage Caviar, or imply that any privacy violations observed here were intentional or malicious. As a user I've had good experiences in using their service. I had hoped that contacting their support would result in these issues being resolved, and now hope that publishing this will accomplish that. If you're a user or a courier for them, I strongly advise that you contact them to get this patched up.

I also want to highlight the importance of privacy in general with services like these, especially given their continued rise to ubiquity. The burden of responsibility falls to us as software engineers to make privacy and security a top priority. When users trust us with sensitive information, it's on us to do the best we can to protect it and use it responsibly. We can do better.


Update 8/31:

Looks like Caviar quietly rolled out a fix to the first part here, as I can no longer see the courier's coordinates on the order. Great!

Unfortunately, the second problem is still present and I can still view the status page without being authenticated.

August 28, 2015 7:05 GMT

Xamarin Events in September

Xamarin is back in session with tons of new workshops, seminars, Dev Days, user groups, and conferences happening this September all over the world!

September meetup-banner

Get involved this month in events near you:

Seattle Mobile .NET Developers us

  • Seattle, WA: September 1st
  • What’s new in C# 6 and F# 4! with James Montemagno and Xamarin MVP, Frank Krueger

XHackNight powered by IBM Bluemix & Xamarin in

  • Bangalore, India: September 5th – 6th
  • LEARN.HACK.WIN – a Cross Platform Mobile Hackathon

Gauteng Xamarin User Group in

  • Johannesburg­, South Africa: September 8th
  • Real World Xamarin.Forms (a case study)

Xamarin Dev Days – Jacksonville us

  • Jacksonville, FL: September 12th
  • Come learn Xamarin awesomeness with your community in Jacksonville

NYC Mobile .NET Developers us

  • New York, NY: September 15th
  • Xamarin Navigation Patterns with Xamarin MVP, Dan Hermes

Noser Engineering Breakfast ch

  • Zurich, Switzerland: September 16th
  • Noser, Go Mobile with Xamarin

Slalom us

  • Boston, MA: September 15th
  • Rapidly Delivering High Quality Mobile Experiences with Xamarin

Slalom us

  • Chicago, IL: September 16th
  • Rapidly Delivering High Quality Mobile Experiences with Xamarin

H&D International Workshops & Training Germany

  • Hanover, Germany: September 21st – 25th
  • Five days of extensive training in the world of Xamarin!

Xamarin Dev Days – Miami us

  • Miami, FL: September 26th
  • Come learn Xamarin awesomeness with your community in Miami

Be sure to check out the Xamarin Events Forum for even more Xamarin events, meetups, and presentations happening near you!

Interested in getting a developer group started? We’re here to help! Here’s a tips and tricks guide on staring a developer group, an Introduction to Xamarin slide deck, and, of course, our community sponsorship program to get you started. Also, we love to hear from you, so feel free to send us an email or tweet @XamarinEvents to help spread the word and keep an eye out for events in your neck of the woods!

The post Xamarin Events in September appeared first on Xamarin Blog.

August 28, 2015 12:00 GMT

Weekly Xamarin Newsletter Issue #55

Easily Automate Your Xamarin.Forms Apps
James Montemagno, from Xamarin Inc., tries to knock the tedium out of testing.

Episode 28: Behind the Scenes of Xamarin.Forms with Jason Smith
Greg Shackles and Jon Dick talk with the legend Jason Smith from Xamarin.

Rapid Mobile App Prototyping with Xamarin.Forms
Krystin Stutesman, from Xamarin Inc., shows off some prototyping with Xamarin.Forms. Looks awesome.

Back To School! Adding A Custom Bindable Property To Xamarin Forms
Matthew Soucoup, from Code Mill Technologies, brings us back to school with some of the basics.

Securing Your App with Touch ID
Mike James, from Xamarin Inc., helps you add some security to your app with Touch ID.

31 Days of Xamarin.Android
Venkata Koppaka, from Falafel Software adds even more days to his month long series.

Day 21 Recycler View
Day 22 Scroll View and WebView
Day 23 TabLayout
Day 24 Toasts and Snackbars
Day 25 Notifications Local
Day 26 Notifications Remote

Xamarin Evolve + Open Source Save The Date App
James Montemagno, from Xamarin Inc., announces the new Evolve app for the Xamarin Evolve 2016 conference.

Using iOS standard icons in Xamarin Forms
Johan Karlsson fires up a renderer to get iOS icons for your Xamarin.Forms project.

Xamarin Dev Days – Madison Recap!
Matthew Soucoup recaps his Xamarin Dev days event and the Mission Impossible style bagel delivery.

Create Modern Android Apps with the Design Support Library
Greg Shackles helps you take advantage of Googles new Material Design in your Android apps.

Mobile Apps with Visual Basic & Xamarin.Forms
Craig Dunn, from Xamarin Inc., let’s us know that we now can use Visual Basic for mobile app dev.

Initial Steps with Xamarin.UITest for Hybrid Apps
Juan Maria Laó, from Plain Concepts, gets us started with Xamarin.UITest.

Yet Another Podcast #141: Greg Shackles on Xamarin
Jesse Liberty has Greg Shackles on the podcast to talk about Olo, MVVMCross and a bunch of other topics.

Xamarin: Join Xamarin at GOTO London & GOTO Copenhagen
Richard Hopkins, from Xamarin Inc., invites you to learn more about create mobile apps at GOTO.

The post Weekly Xamarin Newsletter Issue #55 appeared first on Syntax is my UI.

August 28, 2015 6:32 GMT

Extending the ListView to make it clickable

The problem

The ListView is a fantastic control to use in Xamarin Forms. It has one big drawback, however and that is that if you navigate away from a selected item in the list and then navigate back, the same item is still selected and nothing happens when you tap it again.

The solution

We want to add a new command to the ListView and we start by adding a new class that inherits from the original ListView control. I usually create a folder called "Controls" in the Forms PCL and put stuff I want to use in the XAML in there.

   public class ListView : Xamarin.Forms.ListView
    {
        public static BindableProperty ItemClickCommandProperty = 
            BindableProperty.Create<ListView, ICommand>(x => x.ItemClickCommand, null);

        public ListView()
        {
            this.ItemTapped += this.OnItemTapped;
        }


        public ICommand ItemClickCommand
        {
            get { return (ICommand)this.GetValue(ItemClickCommandProperty); }
            set { this.SetValue(ItemClickCommandProperty, value); }
        }


        private void OnItemTapped(object sender, ItemTappedEventArgs e)
        {
            if (e.Item != null && this.ItemClickCommand != null && this.ItemClickCommand.CanExecute(e))
            {
                this.ItemClickCommand.Execute(e.Item);
            }

            this.SelectedItem = null;
        }
    }


The key here is the ItemClickCommand property. This will be the command that gets executed when we tap on an item. We also listen to the OnItemTapped event and the magic goes here by simply setting the SelectedItem to null again, allowing for the item to be tapped again.

Enter a ViewModel

Since MVVM is the way to go we need a view model. We are omitting the INotifyPropertyChanged stuff to keep it simple. What we have is an ObservableCollection of Duck objects that simple has a property called Name. We also define a command where we put the code that we want to execute when an item is tapped. In this case we navigate to a new page that simply displays the name of the duck. In the real world you should use IoC and also create a view model for the Duck view.

    // INotifyPropertyChanged implementation omitted - use fody!
    public class MainViewModel
    {
        public MainViewModel()
        {
            Ducks = new ObservableCollection<Duck>()
            {
                    new Duck() { Name = "Bob" },
                    new Duck() { Name = "Tommy" },
                    new Duck() { Name = "Donald" }
            };
        }

        public INavigation Navigation { get; set; }

        public ObservableCollection<Duck> Ducks
        {
            get;
            set;
        }

        public Command<Duck> DuckSelected
        {
            get
            {
                return new Command<Duck>(async (d) =>
                    {
                        var duckView = new DuckView();
                        duckView.LoadData(d);
                        await Navigation.PushAsync(duckView);
                    });
            }
        }

    }

    public class Duck
    {
        public string Name { get; set; }
    }

And the View 

This binds it all together. We assign the source of items from our view model as well as the command that we want to execute when an item is clicked.

xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:FancyList.Controls;assembly=FancyList"
             x:Class="FancyList.MainView" Padding="20">
    <ContentPage.Content>
        <local:ListView ItemsSource="{Binding Ducks}" ItemClickCommand="{Binding DuckSelected}">
            <ListView.ItemTemplate>
                <DataTemplate>
                      <ViewCell>
                        <ViewCell.View>
                              <Label Text="{Binding Name}" />
                          </ViewCell.View>
                      </ViewCell>
                </DataTemplate>
             </ListView.ItemTemplate>     
        </local:ListView>

    </ContentPage.Content>
</ContentPage>

Code behind

We also need to set the BindingContext in the code behind for the view. There are several navigation patterns out there and in this sample we take the easy path by simply passing in the Navigation object from the page (view) itself.

    public partial class MainView : ContentPage
    {
        public MainView()
        {
            InitializeComponent();

            var viewModel = new MainViewModel();
            viewModel.Navigation = this.Navigation;

            BindingContext = viewModel;
        }
    }

Summary

It's easy to extend controls in Xamarin Forms. This sample does however omit a lot of good practices like IoC and Fody. 

Resources

August 27, 2015 11:26 GMT

Add NuGets To All Projects In Xamarin Studio with 1 Click

I simply love Matt Ward, a wonderful developer who works on NuGet inside of Xamarin Studio. He is always blogging about all of the recent updates to NuGet in XS, so be sure to follow his blog. Matt does so much more though including an awesome add-in for Xamarin Studio to add some awesome new features when using Xamarin Studio. My favorite feature is Solution Level adding of NuGet packages. Why do I love this feature? Well because I use tons of Plugins for Xamarin (and so should you). 

Installing and Using The Add-in

To get started all you need to do is go to the Xamarin Studio Add-in Manager.

You will need to turn on the alpha channel under the Gallery tab by selecting Manage Repositories:

Then turn on Alpha Channel, Hit Close, and then Refresh the list.

You will now see the NuGet Package Manager Extensions available under IDE extensions:

With the add-in installed you can now open up your cross platform native mobile app or create a new one. Now if I want to add my Settings Plugin to all of my projects all I have to do is Right Click on your solution and you will see “Manage Packages”. 

This will bring up an older NuGet package manager (not the new fancy official one), but you can search for a NuGet and then hit Manage to select which projects you want to install them in.

There you have it, easily adding NuGet packages at a solution level to all of your projects. You will then receive all of your normal updates Xamarin Studio offers and still have access to the per platform NuGet Package Manager.

August 27, 2015 8:12 GMT

Join Xamarin at GOTO London & GOTO Copenhagen

Highly regarded in the software development community, the GOTO Conference series of annual events has been firmly established in Europe since 2009. This year, for the first time, the UK is getting it’s own three-day conference at GOTO London 2015.

GOTO London 2015 – September 16th to 18th (Workshops Sept. 15-16)

GOTO London 2015 BannerJoin Xamarin Developer Evangelist Mike James on Friday, September 18 to learn about creating native apps with up to 100% cross-platform code sharing with Xamarin.Forms. We’ll also have our team of mobile experts on hand at the Xamarin booth to answer your questions and help you understand how Xamarin can help you build, test, and monitor apps. Drop by for a chat—and maybe some of our popular Xamarin t-shirts and other swag!

GOTO Copenhagen 2015 – October 5th to 6th (Workshops Oct. 7-8)

GOTO Copenhagen 2015

If you can’t catch Mike’s talk in London, you have another chance to get the lowdown on Xamarin.Forms just a few weeks later at GOTO Copenhagen 2015 in Denmark. While you’re there, don’t miss Niels Frydenholm, Senior iOS Developer at eBay Classifieds, who will be presenting invaluable advice on the topic of “Continuous Delivery of Native Apps”, including automated UI testing with Xamarin Test Cloud.

We look forward to seeing you soon!

The post Join Xamarin at GOTO London & GOTO Copenhagen appeared first on Xamarin Blog.

August 27, 2015 5:13 GMT

Easily Automate Your Xamarin.Forms Apps

When developing mobile applications, it’s extremely time consuming and tedious to manually test your app for every new feature added or bug fixed. Of course, it’s possible to test an app’s business logic with common unit testing practices using nUnit or xUnit, but what about the user interface? UITestHow can we ensure that an application’s user interface is not only behaving properly, but also looks right on the thousands of unique iOS and Android devices out in the world?

This is where automated user interface testing with Xamarin.UITest, combined with the power and scale of Xamarin Test Cloud, comes in. In the past, we’ve looked at creating tests for traditional Xamarin iOS and Android applications by setting the Accessibility and Resource IDs to gain access to user interface controls in Xamarin.UITest, and today we’ll look at how to use UITest with Xamarin.Forms apps.

Meetup Manager in Test Cloud

Accessing Controls

When creating applications with Xamarin.Forms, we create our user interface with Xamarin.Forms controls in C# or XAML. At runtime, Xamarin.Forms handles laying down and displaying the native controls for the application. Since we’re developing against Xamarin.Forms controls, there’s a special way to gain access to them in our Xamarin.UITests through a special property called StyleId. The StyleId can be set to any string that can be accessed when creating your tests and will be the same between iOS and Android, which means there is no special management of Ids when developing with Xamarin.Forms.

XAML

<Button x:Name="ButtonLogin"
        StyleId="ButtonLogin"
        Grid.Row="5"
        BackgroundColor="#F44336"
        BorderRadius="0"
        TextColor="White"
        Text="Login to Meetup"
        Command="{Binding LoginCommand}" />

C#

var buttonLogin = new Button
  {
    StyleId = "ButtonLogin",
    Text = "Login to Meetup",
    BorderRadius = 0,
    TextColor = Color.White,
    BackgroundColor = Color.FromHex("F443336")
  };

The last thing to do is to add a few lines of code in your iOS and Android applications to apply the StyleId to the native controls, which actually does expose them to Xamarin.UITest. These lines of code should be commented out for final app store submissions.

iOS Setup

Open the AppDelegate.cs file in your iOS project. Add the following lines in FinishedLaunching method after Xamarin.Forms’ Init is called:

Forms.ViewInitialized += (sender, e) =>
{
  if (null != e.View.StyleId)
  {
    e.NativeView.AccessibilityIdentifier = e.View.StyleId;
  }
};

Android Setup

Open the MainActivity.cs file and add the following lines in OnCreate method after Xamarin.Forms’ Init is called:

Xamarin.Forms.Forms.ViewInitialized += (sender,  e) =>
{
  if (!string.IsNullOrWhiteSpace(e.View.StyleId))
  {
    e.NativeView.ContentDescription = e.View.StyleId;
  }
};

Now, if I was to run a UITest and open the REPL, ButtonLogin will be visible in the tree:

LoginButtonVisible

In the UITest, the ButtonLogin can be now used to interact with the button and validate so the login screen appears:

[Test]
public void OpenLoginScreen()
{
  app.Screenshot("App Launches");
  app.Tap("ButtonLogin");
  app.Screenshot("When I tap Login");
  Assert.IsNotNull(app.Query("EntryUserName").Single());
  app.Screenshot("Login Page is Visible");
}

Learn More

To learn more about Xamarin.UITest and Xamarin Test Cloud, be sure to dive through the developer documentation and see our advanced guide for using Xamarin.UITest with Xamarin.Forms. You can also download the full source code and Xamarin.UITest for Meetup Manager, which I demoed here, on my GitHub.

The post Easily Automate Your Xamarin.Forms Apps appeared first on Xamarin Blog.

August 27, 2015 1:43 GMT

Back To School! Adding A Custom Bindable Property To Xamarin Forms

So how did you spend your summer vacation?

One thing is for sure, I did not spend my month of August blogging! I presented two sessions at That Conference in mid-August and then in late August gave another session at Xamarin Dev Days – Madison. Not exactly resting on the shores of beautiful Lake Mendota here in Madison … but a lot of fun nonetheless.

Anyway – I’m back with a Back To School Blog! This time we’re going to take a look at how to create a custom binding to a ContentView within Xamarin Forms.

What’s A Custom Bindable Property?

Have you ever found yourself wanting to create a control or a view that inherited from ContentView and you needed to implement data binding on a property that that control/view exposed – so you could tie the property to a view model?

The good news is we can do this … We can fully customize the way it binds to the view model – one way, two way, one way to source. The even better news – it’s pretty easy once you see it the first time!

So let’s take a look at the steps necessary to create a bindable property.

Creating A Bindable Property

In this example, the ContentView we’re going to add a bindable property to is a control which allows you rate cheeses. (Wow – I talk about cheese a lot!) It displays 5 cheese wedges, and by tapping on a wedge, it updates the view model behind it. Also on initial display, the number of wedges highlighted corresponds to the “rating” in the view model. The control looks like this:

Cheese Rating Control

Cheese Rating Control

So, here are the steps to add a “WedgeRating” property and make it bindable within this CheeseRatingView control ….

  1. Create a regular property in the class.

    public int WedgeRating { get; set; }

  2. Create a static read only field of a BindableProperty type. Name it the same as the property name from step 1, but with the word “Property” at the end.

    public static readonly BindableProperty WedgeRatingProperty // there will be more here

  3. Create the bindable property using
    BindableProperty.Create<T, V>

    First off … what are the T and the V parameters? The T will be the type of the view the property is a part of. So, in our case it’s a CheeseRatingView.

    The V is the property’s type we’re going to bind to. So, in this case, an int.

    Then the Create function takes several parameters, many of which can be null (all of the delegates). So let’s break them down one by one so we can see what we’re setting … and why.

    Field Name Signature Description
    getter: Expression<Func<T,V>> An expression that should be used for the "getter". To continue our example from above, the expression will be along the lines of rv => rv.WedgeRating;
    defaultValue: V Plain and simply a value to use when none has been supplied. Of course, it will be the type of the property.
    defaultBindingMode: BindingMode An enumeration to specify what type of binding mode our property should have.
    validateValue: ValidateValueDelegate<V> When specified inline, the delegate will accept 2 parameters, the bindable (or the current class) and the value the property is being changed to. The delegate needs to return a boolean as to whether the new value passes validation or not. If it does not pass validation, then an ArgumentException is thrown in the backing property.
    propertyChanged: BindingPropertyChangedDelegate<V> Fired AFTER the property has changed. Here is a good place to update the UI (i.e. change the number of wedges). When specified inline, this will receive 3 parameters: bindable (the current class), the old value of the property, and the new value of the property.
    propertyChanging: BindingPropertyChangingDelegate<V> Fired BEFORE the property has changed. When specified inline, this will receive 3 parameters: bindable (the current class), the old value of the property, and the new value of the property.
    coerceValue: CoerceValueDelegate<V> Here is a place where we can change the value of the property before it gets set. Why? Who knows, maybe we're rating a cheese that should always be a 5 no matter what the user says! When specified inline, this delegate will receive the current class as the bindable and the value the property is being changed to. It needs to return the value it should change the value to.
    defaultValueCreator: CreateDefaultValueDelegate<T,V> A delegate that will get fired for the default value setting. When specified inline, it just receives a current instance of the class. It needs to return the value to set the property to.

    The order in which the delegates get called are as follows:

    Order In Which Invoked Delegate
    1 ValidateValueDelegate
    2 CoerceValueDelegate
    3 CreateDefaultValueDelegate
    4 BindingPropertyChangingDelegate
    5 BindingPropertyChangedDelegate

    So … when all put together – an implementation might look like this (except with a lot more functionality instead of just comments and return values!):

    public static readonly BindableProperty WedgeRatingProperty = 
        BindableProperty.Create<CheeseRatingView, int> (
            rv => rv.WedgeRating,
            1,
            BindingMode.TwoWay,
            (bindable, value) => {
                // Here we would validate the new value against
                // whatever criteria we choose.
                // Note: "bindable" in this case is an object with a "RatingView" type.
                return true;
            },
            (bindable, oldValue, newValue) => {
                // Property has changed
    
                // We can call something here to update the UI
                var thisView = (RatingView)bindable;
    
                // Update the UI to display
                // the correct number of highlighted
                // cheeses
                thisView.UpdateRatings();
    
            },
            (bindable, oldValue, newValue) => {
                // Property is changing
            },
            (bindable, value) => {
                // Coerce the property
                // Here we would override what the passed in value is
                // And return something else - if we wanted to
                return value;
            }, (bindable) => {                   
                // This is the default creator
                return 1;
        });

  4. Flush out the backing property from step 1 to make use of the new bindable property.

    public int WedgeRating {
        get {
            return (int)GetValue (WedgeRatingProperty);
        }
        set {
            try {
                SetValue (WedgeRatingProperty, value);
            } catch (ArgumentException ex) {
                // We need to do something here to let the user know
                // the value passed in failed databinding validation
            }                   
        }
    }

  5. Use the control – setting the binding as one normally would. (Here we’re doing it in code, you could easily do it from XAML as well).

    var ratingView = new CheeseRatingView (true);
    ratingView.SetBinding (RatingView.WedgeRatingProperty, "CheeseToAdd.WedgeRating");

    Here the instance of the view model is called “CheeseToAdd” and the property we’re binding to is called “WedgeRating”.

That’s It!

That’s all there is to it. The key thing to remember is the

BindableProperty
and then creating it appropriately.

School is back in session!

Science Hall Photo: Dori

August 26, 2015 10:07 GMT

Securing Your App with Touch ID

One of my favorite features of the iPhone is Touch ID, introduced by Apple with the release of the iPhone 5s a couple of years ago. touch-id-iconTouch ID adds biometric authentication to your device so users can touch the home button to unlock their device instead of using a pin code.

Since its initial release, Apple has added a few new ways to use Touch ID, including integrating it as an essential part of Apple Pay and adding an API for developers to use Touch ID in their apps. In this blog post we’re going to discuss how you can leverage Touch ID to create secure user authentication. We’ll include a fallback to store the password in Keychain and authenticate our users against that in cases where the device doesn’t support Touch ID.

Xamarin Studio with TouchID Design

Supporting Older Devices

Sign Up

If the device has Touch ID, we won’t need to sign the user up since the device can authenticate them for us. But to ensure we support devices such as iPhone 4, 4S, and the iPhone 5, we’ll want to ensure we’ve got a fallback in place. To do this, we’ll use Keychain to store and validate the user credentials.

I like to use UserDefaults for storing usernames to read back information when the app launches and populate the username UITextField for the user. It’s small touches like this that make an app feel more polished and help achieve higher ratings on the app store.

var hasLoginKey = NSUserDefaults.StandardUserDefaults.BoolForKey("hasLogin");

if (!hasLoginKey)

    NSUserDefaults.StandardUserDefaults.SetValueForKey(new NSString(tbxUsername.Text), new NSString("username"));


Saving the Password

It’s important to note that we don’t want to use UserDefaults here since it’s not a secure approach to saving your data. Instead, we’ll use Keychain, which is iOS’s built-in secure storage service that allows us to store passwords, keys, certificates, and more. My colleague René Ruppert has developed a helpful wrapper for storing passwords on iOS with Keychain that you can grab here and is what I’ll be using.

To save the password, we simply call ‘SetPasswordForUsername’. In this case, I have my serviceId set to ‘MySecureApp’.

Helpers.KeychainHelpers.SetPasswordForUsername(tbxUsername.Text, tbxPassword.Text, serviceId, Security.SecAccessible.Always, true);

Once we’ve done that, it’s time to set ‘hasLogin’ to true and synchronize the UserDefaults.

NSUserDefaults.StandardUserDefaults.SetBool(true, "hasLogin");

NSUserDefaults.StandardUserDefaults.Synchronize();

Validating the User Credentials

We’re now ready to validate the credentials provided by the user. To do this, we get the password from the Keychain and check that it matches the password provided. We then repeat the process with the username. If CheckLogin returns true, then we can continue loading new views.

static bool CheckLogin(string username, string password)
{
    if (password == Helpers.KeychainHelpers.GetPasswordForUsername(username, serviceId, true) &&
        username == NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("username")).ToString())
    {
        return true;
    }
    return false;
}

Adding Touch ID

Implementing user authentication with Touch ID is painless and only involves a tiny amount of code since iOS does most of the heavy lifting for us. Below is all the code required to get started.

//Lets double check the device supports Touch ID
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out error))
{
    var replyHandler = new LAContextReplyHandler((success, error) =>
        {
            InvokeOnMainThread(() =>
                {
                    if (success)
                    {
                        var newVC = new UIViewController();
                        PresentViewController(newVC, true, null);
                    }
                    else
                    {
                        var alert = new UIAlertView("OOPS!", "Something went wrong.", null, "Oops", null);
                        alert.Show();
                    }
                });
        });
    context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Logging in with Touch ID", replyHandler);
}
else
{
    var alert = new UIAlertView("Error", "TouchID not available", null, "BOOO!", null);
    alert.Show();
}

Wrapping Up

Not all apps require a backend service for user authentication, and iOS provides lots of options for authenticating locally. If you wanted to take this one step further you could look at integrating 1Password authentication into your app. I’ve created a completed version of the demo project on GitHub, to which I’ll be adding 1Password support to in a separate branch that you can find here. Additionally, be sure to read through our full documentation on integrating Touch ID.

The post Securing Your App with Touch ID appeared first on Xamarin Blog.

August 26, 2015 1:40 GMT

Episode 28: Behind the Scenes of Xamarin.Forms with Jason Smith

In this episode we’re talking about Xamarin.Forms again, but this time around it’s a bit different. We’re joined once again by Jason Smith, lead developer of Xamarin.Forms, to take a look behind the scenes of Xamarin.Forms. We get into where it came from, inspirations, design decisions, triumps, mistakes, and more. Join us for this peek behind the curtain of creating the Xamarin.Forms framework!

Hosts: Greg Shackles, Jon Dick

Guest: Jason Smith

Links:

Thanks to our Sponsors!

Raygun.io

Raygun.io – Exceptional Error Tracking Raygun.io is the fastest and easiest way to track your application’s errors and get the level of detail you need to fix crashes quickly. Notifications are delivered right to your inbox and presented on a beautiful dashboard.

August 25, 2015 6:51 GMT

Mobile Apps with Visual Basic & Xamarin.Forms

If you are a Visual Basic developer, your options for becoming a mobile developer have historically been limited to targeting Windows Phone; however, with Xamarin.Forms, Portable Class Libraries, and Visual Studio, developing iOS and Android apps entirely in Visual Basic has become a real possibility.

Last year I wrote about how Visual Basic Portable Class Libraries (PCLs) can be used in Xamarin apps. Xamarin.iOS and Xamarin.Android can access business logic written in Visual Basic PCLs, while writing the platform-specific code (including the user interface) in C# (or F#) on the Xamarin platform.

Visual Basic Xamarin.Forms

Since then we’ve released Xamarin.Forms, which makes it possible for an entire app—from business logic to user interface—to be written in a PCL and shared across platforms. This means that it’s become possible to write entire mobile applications in Visual Basic in Visual Studio using Xamarin.Forms. The Xamarin developer portal has instructions on creating a Visual Basic project from the Xamarin.Forms new project template. A “Basic” App class is shown here:

Public Class App
    Inherits Application
    Public Sub New()
        Dim label = New Label With {.XAlign = TextAlignment.Center,
                                    .FontSize = Device.GetNamedSize(NamedSize.Medium, GetType(Label)),
                                    .Text = "Welcome to Xamarin.Forms with Visual Basic.NET"}
        Dim stack = New StackLayout With {
            .VerticalOptions = LayoutOptions.Center
        }
        stack.Children.Add(label)
        Dim page = New ContentPage
        page.Content = stack
        MainPage = page
    End Sub

Once you’ve created a new project and converted it to Visual Basic (or just started with the sample) your entire application can be written in Visual Basic. The code below represents a simple ContentPage written in Visual Basic. You can use this as a basis for new pages in your apps:

Public Class Page2
    Inherits ContentPage
    Public Sub New()
        Dim label = New Label With {.XAlign = TextAlignment.Center,
                                    .FontSize = Device.GetNamedSize(NamedSize.Medium, GetType(Label)),
                                    .Text = "Visual Basic  ContentPage"}
        Dim button = New Button With {.Text = "Click me"}
        AddHandler button.Clicked, Async Sub(sender, e)
                                       Await DisplayAlert("Hello from VB", "Visual Basic.NET is back!", "Thanks")
                                   End Sub
        Dim stack = New StackLayout With {
            .VerticalOptions = LayoutOptions.Center
        }
        stack.Children.Add(label)
        stack.Children.Add(button)
        Content = stack
    End Sub
End Class

Xamarin doesn’t implement support for the Visual Basic language directly, so you can’t use Xamarin Studio for these projects; however, if you’re a Visual Basic programmer, or have existing Visual Basic code you’d like to mobilize, there’s never been a better time to get started with mobile development with Xamarin.Forms! And, of course, if you have published a Windows Phone application written in Visual Basic, there’s still time to take advantage of our free subscriptions for Windows Phone Developers promotion before August 31, 2015.

The post Mobile Apps with Visual Basic & Xamarin.Forms appeared first on Xamarin Blog.

August 25, 2015 11:29 GMT

Using iOS standard icons in Xamarin Forms

Have you ever wished for using the standard iOS icons in the toolbar for Xamarin Forms applications? Then you are reading the correct blog post. If not, then you are in the wrong place.

The problem

We want to utilize the built in icons for iOS in our Xamarin Forms application to create something like the image below.



The solution

The good news is that is isn't really that complicated. Simply create a custom renderer and add some behavior to the NavigationRenderer.

First, the Xaml

The definition of our view looks like this.

xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    Title = "Welcome"
    x:Class="Test.MyPage">

    <ContentPage.ToolbarItems>
        <ToolbarItem Name="Add" />
        <ToolbarItem Name="Camera" />
    </ContentPage.ToolbarItems>

    <ContentPage.Content>
        <Label Text="Wow, that's cool!" HorizontalOptions="Center" VerticalOptions="Center" />
    </ContentPage.Content>

</ContentPage>


The key part here is to name your ToolbarItems to something useful and something that we can reference in the custom renderer. You also might want to make sure that the name works on Android and Windows Phone since those platforms won't be affected by this change.

Then the renderer

Being a swede, I have trouble saying the word Renderer... Rendererrerr... Anyhow, this is what it looks like in code. The key is to look at the title for each UIBarButtonItem and replace the entire button with a new one. So we first define a new list to hold our new buttons and then recreate them, one by one to finally assign the new list to the NavigationItem.

The renderer goes in the iOS project since it's iOS specific.

[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationRenderer))]

namespace ToolbarApp.iOS.Renderers
{
    public class CustomNavigationRenderer : NavigationRenderer
    {

        public override void PushViewController(UIKit.UIViewController viewController, bool animated)
        {
            base.PushViewController(viewController, animated);

            var list = new List<UIBarButtonItem>();

            foreach (var item in TopViewController.NavigationItem.RightBarButtonItems)
            {
                if(string.IsNullOrEmpty(item.Title))
                {
                    continue;
                }

                if (item.Title.ToLower() == "add")
                {
                    var newItem = new UIBarButtonItem(UIBarButtonSystemItem.Add)
                    {
                        Action = item.Action,
                        Target = item.Target
                    };
                    
                    list.Add(newItem);
                }

                if (item.Title.ToLower() == "camera")
                {
                    var newItem = new UIBarButtonItem(UIBarButtonSystemItem.Camera)
                        {
                            Action = item.Action,
                            Target = item.Target
                        };

                    list.Add(newItem);
                }

                TopViewController.NavigationItem.RightBarButtonItems = list.ToArray();
            }
        }
    }
}


Summary

It's pretty simple to utilize platform specific stuff in Forms and you should do that in order keep that native feeling. The key to success is Custom Renderers. Learn to use them and you'll excel in all parts of your life!

Resources

The original post from the Xamarin Forum. Thanks goes to Torben Kruse for initially answering this question.

A sample project for trying it out without coding a line.
August 24, 2015 7:06 GMT

Rapid Mobile App Prototyping with Xamarin.Forms

Creating mobile app prototypes is an important part of the design process. It’s extremely useful for developers and test users to be able to interact with a prototype in order to experience how the app will behave when it’s complete, but building prototypes can be daunting due to the large amount of time it takes. This is especially true when you’re asked to make prototypes for more than just one mobile platform, which happens more often than not. With Xamarin.Forms, though, it’s quick and easy to create user interfaces that are shared across Android, iOS, and Windows Phone.

Wireframes vs. Mockups vs. Prototypes

These terms often get used interchangeably in the mobile world. In order to understand why you might use Xamarin.Forms for prototyping, let’s go over the differences between these design terms.

Login_Wireframe

Wireframes

Wireframes are a static, low-fidelity representation of design. They’re usually in black and white, with blue sometimes used to show links and/or buttons. Wireframes should be created before mockups or prototypes, since they’re the backbone of your mobile app’s design.

Bottom Line: Wireframes are quick to create and are typically used as documentation for your project.
 

MockupsProfile_Mockup

Mockups are a static, high-fidelity representation of designs. These full-color images should look almost exactly like the final product in terms of color, icons, buttons, etc. Mockups represent the structure of information and demonstrate the basic functionalities of your app in a static way.

Bottom Line: Mockups are quicker to create than prototypes and are great for gathering feedback on the design in its entirety.

Prototypes

Prototypes are a middle to high-fidelity representation of the final product that simulates user interaction. It’s more likely that your prototypes will be middle-fidelity, meaning they won’t have to be as accurate as mockups when it comes to the design of your app. Prototypes should allow testers to interact with the app in a way similar to the final product.
Prorotype_Image
Bottom Line: Prototypes are expensive to create but are good for allowing stakeholders to preview the mobile app in its entirety.

Xamarin.Forms for Prototyping

Prototyping can be expensive and time consuming, but Xamarin.Forms lets you create prototypes for all three platforms by writing code in XAML or C# just one time, greatly reducing this pain. Xamarin.Forms also allows you to put real apps onto real devices to show off your prototypes. It empowers you to rapidly create a prototype and then put your prototype onto iOS, Android, and Windows devices so that your client or stakeholder can experience the user interaction of your app. That’s a pretty powerful tool in the design and development process.

So… Let’s code!

We are going to use the Swarm mobile app by Foursquare for our prototyping example. Here are a few screens that we should be able to easily create prototypes for:
Swarm_Screenshots

Initial Setup

Create a new Xamarin.Forms app. I’m going to name mine “SwarmPrototype”. Now, add a new Forms ContentPage XAML file named “LoginPage”.

In your App.cs file, modify the existing App() method so that our LoginPage shows up as soon as the app starts. We will also wrap the LoginPage in a NavigationPage and change some navigation bar properties.

public App ()
{
  // The root page of your application
  MainPage = new NavigationPage(new LoginPage())
  {
    BarBackgroundColor = Color.Transparent,
    BarTextColor = Color.White
  };
}

This gives us a NavigationPage, which provides some simple navigation properties so we can easily move from screen to screen through our prototype. The navigation bar will have white text to represent the screenshots above.

Login

Let’s head over to our LoginPage.xaml now. You can see it has automatically given us a content page in which we will need to add some content. First, add a StackLayout with 200 padding on top and an orange background.

<ContentPage.Content>
  <StackLayout
    Padding="0,200,0,0"
    BackgroundColor="#FFA733"
    VerticalOptions="FillAndExpand"
    Spacing="20">
  </StackLayout>
</ContentPage.Content>

Now, inside of our stacklayout, which is oriented vertically by default, we want to add a label, two entries, and three buttons. The label and the two entries will look like this:

<Label
  Text="Log in with your Foursquare account"
  TextColor="White"
  HorizontalOptions="Center"/>
<StackLayout
  HorizontalOptions="FillAndExpand"
  Spacing="0">
  <Entry
    Placeholder="Username"/>
  <Entry
    Placeholder="Password"/>
</StackLayout>

As you can see, we have a label and then two entries inside of another stacklayout. The reason I put those two entries inside of a new stacklayout is so that I could make sure the Spacing=”20″ in our main stacklayout didn’t apply to those elements. Here’s the rest of the XAML for the LoginPage:

<StackLayout
  Orientation="Horizontal"
  HorizontalOptions="CenterAndExpand"
  Spacing="30">
  <Button
    x:Name="buttonCancel"
    Text="Cancel"
    TextColor="White"
    BackgroundColor="#FFA733"
    BorderRadius="15"
    BorderColor="White"
    BorderWidth="2"
    HeightRequest="40"
    WidthRequest="150"/>
  <Button
    x:Name="buttonLogin"
    Text="Log in"
    TextColor="#FFA733"
    BackgroundColor="White"
    BorderRadius="15"
    HeightRequest="40"
    WidthRequest="150"/>
</StackLayout>
<Button
  x:Name="buttonForgot"
  Text="Forgot your password?"
  TextColor="White"
  BackgroundColor="Transparent"/>

One Last Thing

Now we have a static login page, which is a great start, but prototypes are meant to be interactive; we want the app to navigate when the user clicks the “Log in” button. In the LoginPage.xaml.cs file, we’re going to add an event handler for that button as well as a line of code to hide the navigation bar on the LoginPage.

public LoginPage ()
{
  InitializeComponent ();
  NavigationPage.SetHasNavigationBar (this, false);
  buttonLogin.Clicked += async (object sender, EventArgs e) => {
    await Navigation.PushAsync (new ActivityFeedPage ());
  };
}

In the event handler, we use the Navigation property (given to us by the NavigationPage we set up in our App.cs file) to Push a new ActivityFeedPage. You will have to add a new ContentPage XAML file named “ActivityFeedPage” for this to work.

Our login page is now good to go! If we run the app we can see that, even though we only wrote one XAML file, it looks and feels native on Android and iOS.
Login_Screenshots

Keep on coding!

I urge you to take a look at the Xamarin.Forms guides and to try creating the next two pages on your own. If you’re having trouble, take a look at the completed project on my GitHub. I will also be doing a more extensive guest lecture on this topic through Xamarin University on September 24th. Get your free 30-day trial so you can join me for this awesome rapid prototyping session!

The post Rapid Mobile App Prototyping with Xamarin.Forms appeared first on Xamarin Blog.

August 24, 2015 5:51 GMT

Xamarin Evolve + Open Source Save The Date App

In just under eight months in Orlando, FL thousands of mobile .NET developers will be heading to the next Xamarin Evolve conference. Xamarin Evolve 2014 was one of the most spectacular conferences that I have ever been part of and have ever attended. The most amazing developers came together for five action packed days of training, sessions, hacking, and collaboration. To keep it short, you do NOT want to miss Xamarin Evolve 2016.

I had the joy last year of crafting multiple mobile applications for Evolve including the main conference application and an interactive scavenger hunt based on iBeacons called Evolve Quest.

With Evolve 2014 coming to a close there isn’t much need for the mobile application to hang around on the app stores, which is why I teamed up with Xamarin’s very own Mike James to craft an updated Save the Date application for Evolve. We decided that we wanted something simple but native. It had to be elegant with the latest iOS and Android designed, but still have deep integration into the platforms. The new Save the Date application for Evolve can be installed from both the Apple App Store or Google Play for Android enabling you easily sign up for updates, add Evolve to your calendar, and of course share Evolve with your friends.

Best yet, is that you can see exactly how Mike and I created the application and create your own Save the Date application for your upcoming event. Simply head over to the github repo to download the entire source code and get started today. 

August 24, 2015 2:25 GMT

Create Modern Android Apps with the Design Support Library

With the release of Android 5.0, also known as Lollipop, Google introduced its new material design style.

Material Design is a huge step forward for Android apps, bringing with it a total overhaul of theming, as well as a bunch of new UI components you can use in your apps. To make things even better, Google also released the Android Design Support Library, which allows you to take advantage of material design in versions of Android going all the way back to Android 2.1.

In this article I'll walk-through some of the new components available in this library, and show how easy they are to introduce into an app.


Read the rest of the article over at Visual Studio Magazine.

August 24, 2015 1:54 GMT

Xamarin Dev Days – Madison Recap!

It’s Your Day

That was the mantra that James Montemagno repeated time and time again during his opening remarks yesterday, August 22, for Xamarin Dev Days – Madison. And truly, it was the developers’ day, as there were tons of insightful questions, comments and positive reactions throughout the day as people learned and explored the Xamarin platform.

We have an amazing community of .Net developers here in Wisconsin who came together to make Xamarin Dev Days – Madison a success! We had people drive in from Milwaukee… Stevens Point… Wausau… in other words, we had people driving upwards of 3 hours to attend this event! That really speaks to both the passion of the .Net community here in Wisconsin and the product that Xamarin has developed.

All in all – about 65 people made it to the event … and they just didn’t come for the delicious bagels provided by Code Mill Technologies!

I want to extend a thank you to James Montemagno, Krystin Stutesman, and James White – all from Xamarin. They performed like a well oiled machine! Professional, in-sync, and constantly on their game! Nothing phased them.

James Montemagno gave an outstanding introduction to cross platform development with Xamarin – including Test Cloud.

Then Krystin Stutesman took over to give the crowd an intro to Xamarin Forms. Mitch Muenster – a local developer – followed by speaking on enabling network connectivity for your apps with Xamarin.

Then it was my turn – I talked about cheese – and Azure integration with Xamarin.

The afternoon was a ton of fun as James Montemagno led the attendees through creating a Xamarin Forms project from scratch. It wasn’t just somebody standing at a podium typing away and people trying to follow however … James would explain what we were trying to do – then stop if anybody had any difficulties, while Team Xamarin helped anybody who needed it.

Nobody left the day without having created a fully functioning Xamarin Forms app.

All in all – a very successful day!

A Funny Story …

My company, Code Mill Technologies, sponsored the breakfast for Dev Days. And as such, I had arranged to have the bagels and coffee delivered to the venue. However – there was an issue with the delivery…

The City of Madison’s Engineering Department picked the summer of 2015 to have 92.7% of the streets under construction in the city. Obviously that’s a made up number, but there are a ton of streets closed due to construction … so many closed that only one street remained construction free to the venue.

So of course that street was closed the morning of the event for … are you ready for this? … a mini-marathon!!

Right on schedule I received a phone call from the delivery guy saying that he couldn’t get to the venue and was wondering what to do. I said I’d meet him around the corner & we’d figure something out. When I arrived (in somewhat of a panic), I saw a Toyota Prius parked half on the sidewalk, half on the street (barely a street – more like a gravel path), with two people talking to the driver … and that was my introduction to James Montemagno and Krystin Stutesman … (nothing like making a good first impression)!

Delivery guys being the resourceful fellas they are – suggested that instead of having us carry all the bagels and coffee the one block to the event – he just drive on the sidewalk and follow us. So with that – I led Krystin & James to the venue … making idle smalltalk about their travels and hotel … while the bagel delivery guy followed us on the sidewalk in his Toyota Prius.

Somehow this didn’t phase Krystin & James in the least. In fact it seemed perfectly normal to them! Not only are they talented developers, but also complete and total professionals… even with a car following them down the sidewalk!

August 21, 2015 3:13 GMT

Genetics for Xamarin.Android

As with all my development, I try to do as little as possible :) The more code you type, the more you have to maintain and bugfix.

Now, being that I enjoy working on libraries/backends rather than on UI/frontends, I like my code to be neat and clean. Sure, the final app must be good, but I read the code.

So, I looked around and found a simple way to reduce the overall boilerplate code, as well as improve the final code. Although good code doesn't mean a good app, bad code often results in a poor app.

A Practical Example

This library is focused around only one small things, but that one small thing is done over and over again everywhere... boilerplate! This one thing is getting hold of an Android View or Resource based on the ID.

For example, if we have an Activity with X amount of UI widgets that we need to access:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:padding="8dp">
  <TextView
    android:id="@+id/myLabel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="50sp" />
  <Button
    android:id="@+id/myButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp" />
  <ListView
    android:id="@+id/myListView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_margin="10dp" />
</LinearLayout>

Then, usually we would have X number of FindViewById method calls and X fields:

private TextView myLabel;
private Button myButton;
private ListView myListView;

protected override void OnCreate(Bundle savedInstanceState)
{
  base.OnCreate(savedInstanceState);

  SetContentView(Resource.Layout.MyActivityLayout);

  myLabel = this.FindViewById<TextView>(Resource.Id.myLabel);
  myButton = this.FindViewById<Button>(Resource.Id.myButton);
  myListView = this.FindViewById<ListView>(Resource.Id.myListView);
}

This is not much code as it stands, but it is a bit monotonic if you ask me... especially if you have a good few widgets on the screen.

Now, this is where Genetics comes in. We can replace all those FindViewById methods with a single Splice method call, and annotate the fields, or properties, with the [Splice] attribute:

[Splice(Resource.Id.myLabel)]
private TextView myLabel;
[Splice(Resource.Id.myButton)]
private Button myButton;
[Splice(Resource.Id.myListView)]
private ListView myListView;

protected override void OnCreate(Bundle state)
{
  base.OnCreate(state);

  SetContentView(Resource.Layout.MyActivityLayout);

  Geneticist.Splice(this);
}

And that's all there is to it!

Resources

Not only can we avoid all the FindViewById method calls, but we can also avoid querying the Resources object for the various values. Given the resource file:

<resources> 
  <string name="titleText">Genetics</string> 
</resources>

We can automatically populate the field or property in the same way as with the views.

[Splice(Resource.String.loginError)]
private string loginErrorMessage;

protected override void OnCreate(Bundle state)
{
  // ...

  Geneticist.Splice(this);
}

Fragments

A special case exists when the target object instance that contains the widgets is not an Activity, Dialog or View. This is most commonly used when inflating views, as when using a Fragment:

public class MyFragment : Fragment
{
  [Splice(Resource.Id.textView)]
  private TextView textView;

  public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle state)
  {
    var view = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);

    Geneticist.Splice(this, view);

    return view;
  }
}

List Views

Another popular case is when working with a ListView and the view holder pattern for the list items:

public class SimpleAdapter : BaseAdapter
{ 
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder;
        if (convertView != null)
        {
            holder = (ViewHolder)convertView.Tag;
        }
        else
        {
            convertView = inflater.Inflate(Resource.Layout.SimpleListItem, parent, false);
            holder = new ViewHolder(convertView);
            convertView.Tag = holder;
        }

        holder.word.Text = ...;
        holder.length.Text = ...;
        holder.position.Text = ...;

        return convertView;
    }

    private class ViewHolder : Java.Lang.Object
    {
        [Splice(Resource.Id.word)] 
        public TextView word;
        [Splice(Resource.Id.length)] 
        public TextView length;
        [Splice(Resource.Id.position)] 
        public TextView position;

        public ViewHolder(View view)
        {
            Geneticist.Splice(this, view);
        }
    }
}

Downloading & Using

There is lots more that can be done, or rather, not done, using Genetics. The best way to get hold of this library is either through the Xamarin Components Store or from NuGet.

This library is really tiny, and has no dependencies other than Android...

Lots more information can be found on the Getting Started guide as well as in the source on GitHub.

August 21, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #54

Free Xamarin Subscriptions for Windows Phone Developers
Joseph Hill, from Xamarin Inc., made all Windows Phone developers day.

Accessing Azure AD information from .Net Azure Mobile Services and the Xamarin Client
Kevin Ford digs deep into Azure AD and comes up with a winner.

Xamarin Helps Launch AWS APN Mobile Competency Program
Lacey Butler, from Xamarin Inc., announces Xamarin becoming an Amazon competency partner.

Xamarin.Forms Freelance Style
I (Adam) show off a little Xamarin.Forms side project of mine.

Motz Codes Live!
James Montemagno, from Xamarin Inc., has a new series out. Watch him code.

The Road to Xamarin Certification
Chris Swain gives it to you straight about Xamarin certification and Xamarin University.

Using Auto Layouts for iOS 9 SplitView
Mike James, from Xamarin Inc., gets us ready for some new features in iOS 9.

31 Days of Xamarin.Android
Venkata Koppaka, from Falafel Software, continues his 31 days of Xamarin.Android series.

  • Day 14 Controls: Spinner
  • Day 15 Controls: Date Time Controls
  • Day 16 Controls: Media Controls
  • Day 17 Fragments
  • Day 18 Listview and Adapters P1
  • Day 19 Listview and Adapters P2
  • Day 20 Card View

Invoking Methods From Xamarin Test Cloud UITests
Mark Arteaga, from RedBit Development shows off their IApp.Invoke workaround for Test Cloud.

Mars Petcare Improves Engagement 10x with Xamarin
Jo Ann Buckner, from Xamarin Inc., shows off an app from Mars Petcare.

Xamarin Podcast: MVVM Frameworks with James Montemagno
Mike James and James Montemagno talk about Frameworks and MVVM on this Xamarin.Podcasts.

The post Weekly Xamarin Newsletter Issue #54 appeared first on Syntax is my UI.

August 21, 2015 6:49 GMT

Roboto Condensed Bold in Forms (iOS)

The last few days have been spent in pixel perfect land. I've done some fine tuning of a clients forms layouts that of course includes a bunch of custom fonts. I've started out with making sure that the iOS design is correct and we'll move on to Android and WP in another post perhaps.

This post is about a specific issue and that issue is how the naming of the font isn't all that matters.

Short version

Ttf-files only contain one weight. If you bold a regular version of a font it will be calculated bold and not the true bold since that one is contained in another file. To get the real bold, you need to reference the ttf-file containing the bold weight.

Start off here for the longer version

To get a grip of how to use custom fonts, please check out the Xamarin documentation at http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/fonts/ and also a post from Mike James that can be found here: https://blog.xamarin.com/custom-fonts-in-ios/

So what's the problem?

To summarize the usage of custom fonts loaded from a ttf-file on iOS, all described in the links above.

  • Add the ttf-file to the Resource folder - make it a Bundled Resource and Copy Always
  • Edit the info.plist to include the font
And then to use the font we do something like

<Label FontFamily="Roboto Condensed" Text="Very custom" />

To find out the FontFamily name to use, you open up the ttf-file in Windows by simply double clicking it and you'll find it. Since my client is a client, they wanted to use a different typeface for the bold text. No problem, I shouted and downloaded the bolder typeface perfectly named Roboto Condensed Bold.

I then opened the ttf file in windows to check out the name and it was named exactly the same. Wait what? How do I then distinguish between them?

It turns out that the Bold font has the same name and will be used if you set FontAttributes="Bold".

<Label FontFamily="Roboto Condensed" Text="Very custom" FontAttributes="Bold" />

And if you use the above without importing the "Roboto Condensed Bold" font it will Bold the regular font.

Still, what's the problem?

Really, nothing when I come to think of it. TrueType only supports one weight per file from what I understand and that's what I've missed in the past. I just thought that a font is a font and all is included within. :)

Also, if you only supply the regular weight and bold it, it would be some kind of calculated boldness instead of the real bold font that is meant to be used.

Extra material

Instead of using the FontAttributes that only supports Bold, Normal and Italic you can specify what font you'd like to us in the Font-attribute. For example, If I want to use Roboto Condensed Light I must specify the font name like this:

<Label FontFamily="Roboto Condensed" Text="Very custom" Font="RobotoCondensed-Light" />


How would I know what font names that are available for a font family? I use the following line of code on iOS to find out. 

var f =  UIFont.FontNamesForFamilyName("Roboto Condensed");

Summary

Make sure you reference all the weights you want and if they have the same name you only have to change the FontAttributes to select the font you wish for. But be careful and check that you actually get the weight you want since it would still bold a regular font instead of picking the correct one if you miss something along the way.

Resources


August 20, 2015 12:00 GMT

Xamarin.Forms Freelance Style

I don’t freelance! Well, almost never. Sometimes I do when things are slow. Ok, when it came to styling a Xamarin.Forms app for some good folks in Brazil, I had to say yes. Just one catch. The UI had to be in Xaml. I know, it’s like a Xaml conspiracy to get me to actually like Xaml.

They may be winning

For my friends in Brazil, I wrote all the UI that I could in Xaml but kept the style resource in a static file. Referencing the static file from Xaml was easy. I just added a namespace to the Xaml file and referenced the name of the color, font or style needed. To be completely honest it wasn’t that bad using Xaml. On another project I am writing, everything will be in Xaml, including the styles. More on that to come.

iOS and Android

TrackStyle

The Challenge

The most challenging thing on this project was following the designer’s/customer’s mockups. There are subtle and not so subtle differences between the two operating systems. My OnPlatform kungfu got a workout especially with the MasterDetail menu.

Some other challenges I had were in styling non Xamarin.Forms things like the Android splash screen and Android themes. I learned a lot about Android and 9-patch images on this project. Styling a single page is pretty easy; keeping a theme going across a whole app and two operating systems is much harder.

I have to admit the project was a lot of fun even with the Xaml. For my next project, I’m going full Xaml and, you dear reader, will get a look under the covers soon.

The post Xamarin.Forms Freelance Style appeared first on Syntax is my UI.

August 19, 2015 10:45 GMT

Motz Codes Live!

When I am not traveling around presenting at conferences, dev days, user groups, and code camps you will probably find me doing one of three things: Riding my bike, drinking coffee, and most likely coding. The elusive Motz can be found coding usually from home or in a coffee shop drinking said coffe, but I have finally decided to unleash my coding to the world in a new web series I am calling “Motz Codes Live”.

Each week I will be covering a topic of mobile development and for about 30-60 mintues I will be coding live, answer questions, and showing you exactly how I code on a daily basis.

Last week I kicked things off by covering how to create your very first Xamarin.UITest test and ship your app to Xamarin Test Cloud all in under 60 minutes. If you weren’t able to see it live the best part is all Motz Codes Live episodes are recorded! Here is the first one:



This Friday I will be covering the topic of using local storage with SQLite-net PCL in your apps. You can subsribe to my Youtube station for the latest updates. Be sure to register here on google hangouts.



Be sure to follow my Google+ or Twitter account for new episodes.
August 19, 2015 9:22 GMT

Different images for selected and unselected using Xamarin Forms Tab Bar

This is just a simple hack for iOS using Xamarin Forms and icons for a TabbedPage.

Problem definition

In Xamarin Forms, the icon of the tab bar is fetched from what ever image you reference in the Icon property of the page added to the TabbedPage. This image is grayed out if unselected and filled in with the defined color when selected.
However, sometimes you want to display a different image if unselected or selected and there is no build in way to specify this nicely.

Solution

The solution is a small hack. Simply add event handlers to the Appearing and Disappearing events and reset the images to your liking.

         var activeImage = "active";
            var inactiveImage = "inactive";

            var tab1 = new AnotherPage();
            tab1.Title = "Check in";
            tab1.Icon = new FileImageSource() { File = activeImage };
            tab1.Appearing += (s, a) => tab1.Icon = new FileImageSource() { File = activeImage };
            tab1.Disappearing += (s, a) => tab1.Icon = new FileImageSource() { File = inactiveImage };



Summary

Should it be done? Probably not, but if your out of options (that is your customer insist of doing it in such way) then this is an option.

Also worth noting is that the images will flicker if the debugger is attached. There is no visible delay when running it in release.
August 14, 2015 1:30 GMT

Weekly Xamarin Newsletter Issue #53

Contest: Test Your Way to Xamarin Evolve
Jayme Singleton, from Xamarin Inc., announces a new contest that can win you a trip to Evolve 2016.

Xamarin.UITest Reaches 1.0 Release
Steven Yi, from Xamarin Inc., announces the 1.0 release milestone of Xamarin.UITest.

Cross Platform Compositional Gestures 
George Cook, from Twin Technologies, puts together an epic post on Xamarin.Forms gestures. Check it out!

Xaml Reference for Xamarin.Forms
I (Adam) get tired of searching the internet for Xamarin.Forms Xaml samples.

Xamarin.Forms and Data Pluralsight course
Jesse Liberty released another Pluralsight course. This time on Xamarin.Forms and Data.

Visualize Your Data with Charts, Graphs, and Xamarin.Forms
James Montemagno, from Xamarin Inc., shows off some sexy chart for Xamarin.Forms.

31 Days of Xamarin.Android
Venkata Koppaka, from Falafel Software, is adding to his 31 Days of Xamarin.Android series.

  • Day 7: Relative Layout
  • Day 8: Grid and Table Layout
  • Day 9: Android Main Concepts: Intents
  • Day 10: Android Main Concepts: Activities
  • Day 11: Android Main Concepts: Services
  • Day 12: Controls: Input Controls, Part 1
  • Day 13: Controls: Input Controls, Part 2

Adding a Disclosure Indicator Accessory to Xamarin.Forms ViewCells
James Montemagno, from Xamarin Inc., fixes part of Xamarin.Forms with a custom renderer.

Xamarin.Forms SearchBar with Mvvm
Alec Tucker highlights some gotchas with the SearchBar and Xamarin.Forms.

Understanding Native Image Sizing in Xamarin Forms Apps
Keith Rome, from Wintellect Inc., writes about his least favorite part of mobile dev, Image Sizing.

Pearson is at the Top of the Class with Xamarin
Jo Ann Buckner, from Xamarin Inc., highlights a Xamarin win with Pearson.

Emacs key mappings for Xamarin Studio on Mac
Kym Phillpotts, from Xamarin Inc. and Richard get crazy with Emacs key mappings.

52 Weeks of Xamarin – Week 1
Jesse Liberty kicks off week 1 of 52 of his new series with an introduction of Xamarin.Forms.

Azure ApplicationsInsights for Xamarin iOS
Has Altaiar, from Kloud.com, shows off the new Azure Application Insights for Xamarin.Forms.

The post Weekly Xamarin Newsletter Issue #53 appeared first on Syntax is my UI.

August 14, 2015 12:00 GMT

How to disable Xamarin Forms XAML Intellisense in VS 2015

Straight answer first just in case you’re in a hurry:

  1. Download devenv.pkgundef to C:\Program Files (x86)\Microsoft Visual Studio [VSVERSION]\Common7\IDE\
  2. Run devenv /updateconfiguration from a developer command prompt (for the relevant VS versions).

In addition to this manual workaround, we’ll post an updated Xamarin.Forms pre-release nuget package that won’t provide the design assemblies to XAML and will stop the crash from happening. But that won’t turn off XAML intellisense, which will be all red (as it is without the 1.5-pre nuget).

Now the long answer if you’re interested :)

XML vs XAML intellisense

For Visual Studio 2012 and 2013, we provide Xamarin.Forms intellisense by extending the core text editor using the same extensibility APIs you use to extend any other text-based editor. Besides being able to use some XML-editor provided APIs to access the current document, we basically have to keep track of keystrokes, completion sessions, dismissal on Esc and so on. In addition to also discovering types and members available for completion.

In Visual Studio 2015, the XAML editor became extensible so we could take advantage of all the work already done by Microsoft for WPF by just providing some metadata via the NuGet package itself, and registering our Xamarin.Forms namespace to opt-in XAML intellisense instead. This was the result of close collaboration with the XAML team, since XF is pretty much the first non-WPF flavor of XAML around.

In addition to being a solid editor for many years, opting in for XAML intellisense also means we will get all new features they add to WPF for free. In particular around the data binding expressions and markup extensions.

Unfortunately, when we enabled XAML intellisense for our XML namespace, we triggered a bug that causes the XAML editor to crash VS. Microsoft is aware of the issue, has identified the issue and is actively looking for ways to ship this to users. Worst case, it should be available in VS2015 Update 1, november-ish.

How to get XML intellisense back

We will soon release an update to the current stable release that will re-enable the XML-based intellisense for Xamarin.Forms. Stay tunned on the Release Blog for news.

August 12, 2015 1:40 GMT

Understanding Native Image Sizing in Xamarin Forms Apps

This post is about probably my least favorite part of mobile app development – figuring out and assembling all of the various images needed to build an application and publish it into the stores. Each platform has its own requirements for this, and often you will need to provide multiple resolution versions within each platform in order to handle varying pixel density ratios. Xamarin supports all of the necessary resource types of course, but it is still up to us as developers to include the right images in our projects.

For very simply apps this isn’t quite as big of a problem – but it becomes a huge headache for medium-size and large-size apps. To help make my life easier, I like to use a spreadsheet to identify all of the images needed along with the final image resolutions and preferred file names. This works great because I can give this spreadsheet to the UX designer and have them provide all of the assets – already sized and named appropriately so that I can just drop them right into my project. So let’s cover all of the various image types that an app might need – including both the minimum required images as well as optional ones.… Read more

August 12, 2015 12:00 GMT

Xaml Reference for Xamarin.Forms

XamlReference3Last month I took a little side project with a development group down in Brazil. This group was looking for help making their Xamarin.Forms app look nice. There was only one problem, they wanted it in Xaml!

Even after making the price 25% more for Xaml over code, they still insisted on Xaml. So what’s a developer that likes code to do? He rolls up his sleeves and dives into the world of Xamarin.Forms and Xaml.

Google Captcha

One of the first things I noticed when looking up samples on Google was the lack of Xaml sample. You know you’re Googling too hard when Google thinks you’re a bot and asks you to solve a captcha. This was a first for me. Have you ever seen that before? No, well I need to apologize to you dear reader.

Regularly readers email me or leave comments about my lack of Xaml in my blog post. I had no idea it was so hard to find good Xaml sample for Xamarin.Forms. One thing that was surprising is the lack of Xaml samples in the Xamarin developers’ documentation.

As a Silverlight and WPF developer, I know how Xaml works and the difference between property elements and properties attributes but sometimes you want and need to see sample code xml.

Xaml Reference

To fix this lack of Xaml samples I have started my own Xamarin.Forms Xaml Reference. This reference will be my source and hopefully your source for Xaml samples. The reference will start small and it will grow over time. Each Xamarin.Froms control will have its own page. Each page will have a simple sample and will outline the public settable properties. Things like OnPlatform and Styles will also get pages as time permits.

If you have some sample Xaml code or are looking for a sample of Xaml, please email me or tweet me. I would love to fill out the reference with as much Xaml as I can get my hands on. Yes, I said that. I want more Xaml. Times are changing.

The post Xaml Reference for Xamarin.Forms appeared first on Syntax is my UI.

August 10, 2015 7:08 GMT

Xamarin.Forms SearchBar with Mvvm

Wow - it's been a long time since my last post. I've been very busy with something that I hope to chat about before too long...

In the meantime, here are some thoughts on using the Xamarin.Forms SearchBar control with Mvvm.

Firstly, there's a great, simple explanation of the control itself here: https://www.syntaxismyui.com/xamarin-forms-searchbar-recipe/

This shows how to get up and running without Mvvm, applying a search filter form the TextChanged event of the SearchBar. When you put this into an Mvvm structured app there are a couple of gotchas to look out for. You can bind the Text property of the SearchBar to an Mvvm compatible string property in your ViewModel, and the setter replaces the TextChanged event on the above link, like this:

    <SearchBar Text="{Binding SearchText}"

               SearchCommand="{Binding SearchCommand}"

    />


Where your SearchText definition in your associated view model would look something like this:

        private string _searchText;

        public string SearchText

        {

            get { return _searchText; }

            set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(() => SearchText); } }

        }


You can now set up the ObservableCollection property in your viewmodel which you have bound your list to looks something like this:

        public ObservableCollection<YourEntity> YourList

        {

            get

            {

                ObservableCollection<YourEntity> theCollection = new ObservableCollection<YourEntity>();


                if (_yourList != null)

                {

                    List<YourEntity> entities = (from e in _yourList

                        where e.dealerDisplayName.Contains(_searchText)

                        select e).ToList<YourEntity>();

                    if (entities != null && entities.Any())

                    {

                        theCollection = new ObservableCollection<YourEntity>(entities);

                    }

                }


                return theCollection;

            }

        }


(This assumes that you have other code to populate _yourList in the first place, by reading from a DB or perhaps calling a web service.)

The SearchBar also supports command binding (as you can see from the xaml above), so we can define our search command like this:

        #region Command and associated methods for SearchCommand

        private Xamarin.Forms.Command _searchCommand;

        public System.Windows.Input.ICommand SearchCommand

        {

            get

            {

                _searchCommand = _searchCommand ?? new Xamarin.Forms.Command(DoSearchCommand, CanExecuteSearchCommand);

                return _searchCommand;

            }

        }

        private void DoSearchCommand()

        {

            // Refresh the list, which will automatically apply the search text

            RaisePropertyChanged(() => YourList);

        }

        private bool CanExecuteSearchCommand()

        {

            return true;

        }

        #endregion


Now let's embellish our property a little to get it to execute the command each time the text is changed. (This is effectively the Mvvm equivalent of the TextChanged event in the blog post referenced above.)

        public string SearchText

        {

            get { return _searchText; }

            set

            {

                if (_searchText != value)

                {

                    _searchText = value;

                    RaisePropertyChanged(() => SearchText);


                    // Perform the search

                    if (SearchCommand.CanExecute(null))

                    {

                        SearchCommand.Execute(null);

                    }

                }

            }

        }


All well and good. However, there are two gotchas here. This code, as it stands, will fail. The problem is that the first time in, _searchText is not an empty string - it's null. This upsets our Linq statement. We can remedy this by changing:

        private string _searchText;

to:

        private string _searchText = string.Empty;


First time in things now work fine. You should also be able to apply filtering to your list and watch it in action. However, there's one more gotcha waiting in the wings. The SearchBar comes with a built in 'Cancel' button, which you can use to clear your search text. Your users will expect this to remove all filtering and display the entire list again. However, clicking the 'Cancel' button does not set the Text property of the SearchBar to an empty string - you guessed it, it sets it to null. This upsets our Linq statement all over again.

We can remedy this by changing the setter of our property slightly, to ensure that if an attempt is made to set it to null, it will simply set it to an empty string instead. We'll change this:

_searchText = value ;


to this:

_searchText = value ?? string.Empty;


It should now be happy again, and ready to roll.

August 10, 2015 12:00 GMT

1 Year Anivresary of the Weekly Xamarin Newsletter

That’s right, over 365 days, or 52 weeks, or 12 months ago, the first Weekly Xamarin newsletter rolled off the MailChimp presses. To be honest, I’m surprised I made it.

Like a lot of you, I like starting something new. The newsletter was no different. I’m not sure what it is about Xamarin but working on the newsletter and reading everything I can about Xamarin, Xamarin.Forms and mobile development never gets old or boring.

In the beginning, the newsletter was a lot of work. Now that it’s 1 year old and I am a little wiser, it takes up much less of my time. Reading all the posts take the majority of my time but I would be doing that anyway.

Subscribers

The growth of the newsletter has slowed a bit because I am actively unsubscribing people who are no longer interested in the newsletter. How you can no longer be interested in all things Xamarin is beyond me but it does happen.

This unsubscribing has an added benefit. The newsletter’s open and click rates are very healthy and active. It also keeps me under the 2,000 subscriber limit. Above 2,000 and yours truly would have to take on a sponsor or pay for the email service out of pocket.

1YearTrend

Overview

As you can see from the graph, our open and click rates are well above industry norms. Our open and click rates are more than two times the average for this type of newsletter.

1YearSubs

The data for the latest issue of the Xamarin Weekly newsletter is not complete yet but you can see the trend. 60+ for open rate and 30+ for click rate.

1YearDetail

The Future

Like I said in the 9 month update to the newsletter, I do not see any changes now or in the future for the newsletter. I will be continuing as the scribe of the newsletter. More Weekly Xamarin newsletters will be sent every week, every month and now every year for the foreseeable future.

I want to thank all of the subscribers and especially all of the bloggers who have taken their time and energy to contribute to Xamarin and mobile development for the .Net developer.

Thank you, Adam

 

Don't miss out! Subscribe Today

Do you blog about Xamarin? Get your blog in the newsletter. Email me at adam [at] adamjwolf.com.

The post 1 Year Anivresary of the Weekly Xamarin Newsletter appeared first on Syntax is my UI.

August 09, 2015 2:00 GMT

TypeScript Addin 0.6 Released

A new version of the TypeScript addin for Xamarin Studio and MonoDevelop has been released. The addin is available from MonoDevelop’s Add-in Repository in the alpha channel. More details on how to install the addin can be found in the TypeScript support in Xamarin Studio post.

Changes

  • Updated to support TypeScript 1.5.
  • Linux 32 bit and 64 bit are now supported with a single addin. Thanks to Christian Bernasko.
  • Allow UMD and System modules to be selected in project options.

The separate TypeScript Linux 32 bit addin is now deprecated since the TypeScript addin can now be used on 32 bit and 64 bit versions of Linux.

Bug Fixes

  • TypeScript language service host not updated when the project options are changed

For example, switching from ES3 to ES6 in the project options could cause the code completion to be incorrect since the language service host compiler settings were not being updated.

  • TypeScript options shown when viewing solution options

The TypeScript options are now only available when the project options are selected.

August 07, 2015 1:30 GMT

WeeklyXamarin Newsletter Issue #52

Hello and welcome to the 1 year anniversary edition of the Weekly Xamarin newsletter. Thank you for subscribing and a special thank you to all the authors who are blogging about Xamarin and Xamarin.Forms.

This edition of the newsletter comes to you from my Mt. Rainier vacation where wifi and cell service is intermittent or absent. The newsletter is a little shorter this week but next week you can expect me and the newsletter back to full strength.

Adam

What is Xamarin.UITest?
Rasmus Kromann-Larsen, from Xamarin Inc., shares his thoughts and advice for using Xamarin Test Cloud.

31 Days of Xamarin.Android
Venkata Koppaka, from Falafel Software, is putting together a whole month of Xamarin.Android articles. Love this!

Put Some Azure Active Directory in Xamarin.Forms
Mayur Tendulkar, from Xamarin Inc., puts a twist on using ADAL with the dependency service.

iOS Tip: Force UIWebView to Display Mobile Sites on iPad
James Montemagno, from Xamarin Inc., gets specific and wrestles web view to do the right thing.

Building Apps for a Connected World
Pierce Boggan, from Xamarin Inc., lights up the Xamarin Podcast with the connected world.

Webinar Recording: Mobile Enterprise Success with Xamarin and Oracle
Courtney Witmer, from Xamarin Inc., adds the Oracle webinar recording and slides to Xamarin.com.

The post WeeklyXamarin Newsletter Issue #52 appeared first on Syntax is my UI.

August 06, 2015 10:54 GMT

Adding a Disclosure Indicator Accessory to Xamarin.Forms ViewCells

Xamarin.Forms has a super powerful ListView. You can easily add custom cells, pull to refresh, headers, footers, and even sections with just a few lines of code. A while ago I talked about how to easily group items to display section headers in the ListView. You get a great native styling of section headers with just a few simple lines of code. One thing I have noticed and has bothered me specifically with iOS is the lack of the Disclosure Indicator on cells. A Disclosure Indicator you say? What is that you may be asking? A Disclosure Indicator is a special Accessory on a Cell that has an arrow pointing to the right, normally indicating you can navigate another level deep. It looks like this:

This is just one of the 3 types of Accessories that you can have on a UITableViewCell. You can read all about them on the Xamarin documentation recipe and when you should use each of them. 

So what’s the issue?

The reason I am writing this blog is because out of the box Android and Windows have no concept of Accessories on cells. Users of these platforms simply expect that when you tap on an item you navigate, but on iOS you should really have the Disclosure Indicator or other accessory. Since there is no way to actually abstract this Xamarin.Forms simply leaves out the accessories of ListView cells, which is sad, but makes complete sense.

We can fix it! 

Xamarin.Forms has the concept of custom renderers that can be used to customize controls, add custom controls, and even completely replace how a control is rendered! This is crazy and amazing as we can use a custom renderer to replace the default ViewCell implementation with our own that adds in the accessories. Instead of creating our own custom cell we will simply tell Xamarin.Forms to use our ViewCellRenderer for iOS. We can then leverage the fact that the “StyleId” property doesn’t do much besides providing the ability to do awesome things with Xamarin.UITest and Test Cloud. We can use the StyleId property to set what type of indicator we want. In your iOS project simply add a new class called ViewCellRenderer and copy in this code:

Now, all of your ViewCells will automatically be updated with an indicator by default or you can set the StyleId to anything you want in XAML or C#. 

Since I am am creating this renderer explicitly for a “ViewCell” with a “ViewCellRenderer” this means that only my custom ViewCell’s will have this new fancy indicator, but you could apply this same exact concept to TextCell with a TextCellRender or a ImageCell and ImageCellRenderer. It is amazing and really easy to implement without creating custom Xamarin.Forms controls. Enjoy and happy ViewCell Accessorizing!.

August 06, 2015 8:20 GMT

GameplayKit path-finding in iOS 9 with Xamarin.iOS

Easy-peasy, lemon-squeazy:

var a = GKGraphNode2D.FromPoint (new Vector2 (0, 5));
var b = GKGraphNode2D.FromPoint (new Vector2 (3, 0));
var c = GKGraphNode2D.FromPoint (new Vector2 (2, 6));
var d = GKGraphNode2D.FromPoint (new Vector2 (4, 6));
var e = GKGraphNode2D.FromPoint (new Vector2 (6, 5));
var f = GKGraphNode2D.FromPoint (new Vector2 (6, 0));

a.AddConnections (new [] { b, c }, false);
b.AddConnections (new [] { e, f }, false);
c.AddConnections (new [] { d }, false);
d.AddConnections (new [] { e, f }, false);

var graph = GKGraph.FromNodes(new [] { a, b, c, d, e, f });

var a2e = graph.FindPath (a, e); // [ a, c, d, e ]
var a2f = graph.FindPath (a, f); // [ a, b, f ]

GKPathFindPath

August 06, 2015 12:19 GMT

Using the symbol enumeration for icons/symbols in Windows 10 universal app

If you are developer and not a graphic artist it is always a challange to find/create icons. Windows 10 has a symbol enumeration that you can use that contains the most common icons/symbols (you find the complete list of symbols here: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.symbol.aspx).

The not only look good they are easy to use to, just use the SymbolIcon element. The code below shows a settings icon.

<SymbolIcon Symbol="Setting" />

If you want to change color on the icon just use the Foreground attribute.

<SymbolIcon Foreground="Gold" Symbol="Favorite" />

The symbols is based on the “Segoe MDL2 Assets” font (You can read more about it here: https://msdn.microsoft.com/en-us/library/windows/apps/jj841126.aspx).

Symbols in a Windows 10 app

Symbols in a Windows 10 app

If you want to read more about Windows 10 development I have created a list with all my Windows 10 blog posts, http://danielhindrikes.se/windows-10/, more will be added.

August 05, 2015 5:05 GMT

Code Mill Minute: Adding npm Modules to Azure Mobile Services

I recently had to add some npm modules to a “classic” Azure Mobile Service instance built on node.js.

(I say classic, which is accessed through the old portal, as opposed to the new Azure Mobile Apps, which is managed through the new portal. But the process to add npm modules will be more or less the same.)

As I was doing so, I thought to myself … “this would be a great idea for a Code Mill Minute”!

Mainly because the first time I had to add npm modules to an Azure Mobile Service I was stumped for a bit. (For a while, I really liked editing my JavaScript through the built in editor in Azure.) But it turns out it’s really an easy process.

So here we go with a step by step process:

  1. Log into, or create, an AMS instance.
  2. Once there, head on over to the “Configure” tab.
  3. There you will see a “Git Url” text box. Copy the contents of that guy.Azure Git Get
  4. Head on over to your favorite git manager and clone that repo. (I prefer using Visual Studio with Node Tools for Visual Studio installed. In fact, I’m giving a talk on introducing Node.js to .Net developers at That Conference, Monday August 10. You should go! End of shameless plug.)
  5. Once you have the repo cloned, you are now free to issue
    npm install
    commands, and have it grab your modules, update the node_module folder & package.json file.
  6. Start developing using the new goodness downloaded from npm!
  7. Commit and push your repo back to Azure

Please note … you do not … and I repeat, do not push the node_modules folder to Azure. Azure will take care of downloading all of the modules and dependencies for you… just like a good friend should!

As an extra bonus – if you don’t trust that Azure downloaded all the node modules, or if you just need to do some debugging for other reasons, you can always head over to the Kudo console. To get to Kudo – you just put “scm” to your mobile service’s domain name. For example: <your-service-name>.scm.azure-mobile.net. Hit the Debug tab in the header (doesn’t matter if you CMD or PowerShell for this), and then you’ll be able to browse your site’s directory and inspect the node_modules folder for yourself. Yay for cool tools!

Screen Shot 2015-08-05 at 11.31.57 AM

Adding npm modules to other node instances/sites/services in Azure is as simple as cloning the git repo (you may need to setup continuous deployment in order to enable git within your Azure site). Once there, clone it, edit it, push it. Simple!