Thursday, June 2, 2016

Web Services made easy with HttpClient & JSON.NET

I have intended to write this for a while. As a Sales Engineer for Xamarin, and now Microsoft, I go through a lot of the same scenarios when working with companies to get up and running with Xamarin and mobile development. As one example, there is almost a 99% guarantee that the first apps these companies plan to build will communicate with an external data source in some way, almost always using web services.

Now, there is a high likelihood this is not a new topic to those who read this blog, but as a believer in the "Lucky 10,000" from xkcd, I figure this information is still worth sharing. To those of you who were unaware of today's content, congrats as you are one of the lucky 10,000 today! What I have to share should make your mobile journey all the easier.

Now it should be noted that I recognize web services are a broad topic, lots of solutions out there. One quick hop over to the Xamarin documentation alone lists a few:

https://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/

The main three built into the Xamarin tooling are on consuming RESTful, SOAP and WCF services. For the remainder of this post I will focus on REST as I find it to be the most straightforward to consume.

Consuming REST services really falls down to two main parts. Consumption of the service itself, and then consumption of the data received. As you likely have guessed, there are two tools available to help make this process much more straightforward. For the service, Microsoft's HTTP Client libraries and for the data, JSON.NET. When combined, it can be as simple as three lines of code to communicate with an external service and acquire data. Below is a sample of what that code would look like:

var httpClient = new HttpClient ();
var json = await httpClient.GetStringAsync ($"http://mywebservice.com");
var result = JsonConvert.DeserializeObject (json);


What you see above is both parts. Line one creates the HttpClient followed by actually making a REST call to grab you data. The third line is part two, parsing the resulting json into something more C# readable. If you have not used JSON.NET before, it really is something of magic under the hood. Basically, all you need to do is provide it a valid json file, and then pass a constructed C# object for it to parse into. In the above example, it will try to parse your json into the class "MY_DATA_OBJECT". 

To use a more "practical" example, I am a big fan of Blizzard games and recently wrote an app to play with some of the community API's available, found here https://dev.battle.net/. The main goal was to just do a bit of poking and write a simple Warcraft character display app. Nothing complex, make some calls to load character data, item sets, etc. In  order to grab the basic character profile in my app, I have the following code:

var httpClient = new HttpClient (new NativeMessageHandler ());
var json = await httpClient.GetStringAsync ($"https://us.api.battle.net/wow/character/Muradin/Deaus?locale=en_US&apikey={
Constants.APIKEY}" );

var res = JsonConvert.DeserializeObject (json); 

In this case, I am pulling the data for my Paladin, Deaus, from the Muradin server. The resulting JSON looked like this:

{
     "lastModified": 1426370270000,
     "name": "Deaus",
     "realm": "Muradin",
     "battlegroup": "Vengeance",
     "class": 2,
     "race": 3,
     "gender": 0,
     "level": 100,
     "achievementPoints": 7620,
     "thumbnail": "muradin/10/119640842-avatar.jpg",
     "calcClass": "b",
     "faction": 0,
     "totalHonorableKills": 1961
}

On the C# side, I would create a class called CharData which would look something like this:

public class CharData
{
    public long lastModified { get; set; }
    public string name { get; set; }
    public string realm { get; set; }
    public string battlegroup { get; set; }
    public int class { get; set; }
    public int race { get; set; }
    public int gender { get; set; }
    public int level { get; set; }
    public int achievementPoints { get; set; }
    public string thumbnail { get; set; }
    public string calcClass { get; set; }
    public int faction { get; set; }
    public int totalHonorableKills { get; set; }
}


JSON.NET does the rest of the work, taking advantage of the json tags and matching them to the appropriate C# properties, and instantiates/populates my data for me. The best part of all of this? All of this is PCL compliant so it is located 100% inside my shared code!

One useful tool to expedite the process even more is the website  json2csharp.com. This website will take json data and auto generate the resulting C# class for you, at least at a base level.

As a note, not all REST end points are so easily configured, but HttpClient is actually quite flexible. I was also recently poking around a community made Hearthstone API, https://market.mashape.com/omgvamp/hearthstone, and their .NET API's are powered through unirest (http://unirest.io/net). To get this to work I had to add a couple of DefaultRequestHeader paramters to match the documentation there. Still, rather straight forward to communicate with.

That is about it. While this does put some requirement to set up good REST endpoints for your mobile applications, it tends to be worth the effort. Even if you have legacy WCF systems or complicated back ends, I have found that companies that have made exposed REST front ends to facilitate the communication can help streamline the entire process and, as you see above, can really make consumption on the mobile side quite easy. Until next time!

Monday, May 16, 2016

Complete Mobile Dev Ops with Visual Studio Team Services and Xamarin Test Cloud

Wow it has been over six months. Sorry! As you can imagine, things have been busy in 2016. There has been an acquisition, Xamarin tools made available for free in Visual Studio, and then Xamarin Evolve. Now that things have settled down, and integration into Microsoft underway, I wanted to take this as an opportunity to get back to making semi-regular posts once more.

When I joined Xamarin in December of 2013, it was still largely a one product company. Xamarin enabled you to develop apps for Android, iOS, or Mac using C#. (OK, technically three products but to a degree you can look at them as different facets of the same tool).

Since that point Xamarin has grown to help assist in the full mobile development lifecycle. This included the launch of Xamarin University for training, Xamarin Test Cloud for better testing and Xamarin Inisghts for crash reporting, messaging and analytics. With Xamarin now under the Microsoft umbrella, a few new tools are available to even further complete that picture. The focus of this entry will be on how to leverage Visual Studio Team Services with Xamarin, both development and Xamarin Test Cloud, to create a full Dev-Test-Publish lifecycle.

Getting setup with Visual Studio Team Services
I won't spend a whole lot of time on this. The basic checklist can be found below.

1. Create your VSTS account
2. Create your Project
3. Connect to Visual Studio
4. Set up your repo and code

The main setup guide hub can be found here: https://www.visualstudio.com/get-started/setup/set-up-vs

For my scenario, I ended up using git as my repository, which would also be my recommendation if you don't have a previous requirement or preference.

Integrating Xamarin Test Cloud
Now that you have your code integrated with VSTS, and uploaded, the next step is to create a build process that confirms your build and also calls to Xamarin Test Cloud for regression testing. That way, any time a developer on your team submits their code, you can confirm everything is still working. Please note, this will require having created a UITest project and at least one step to run. If you have not ever done this, you can find more details here:
https://developer.xamarin.com/guides/testcloud/uitest/intro-to-uitest/

Now, the final piece of this puzzle is to integrate this as part of your VSTS build chain. Microsoft actually made this process quite straight forward, once I had my head wrapped around the tooling. A full general doc, found after I got it sorted myself, can be found here:

https://msdn.microsoft.com/library/vs/alm/build/apps/xamarin

This is what I wanted to break down and guide in more detail. First, select the Build tab in the VSTS portal and hit the green "+" button:

This will create a new dialog window. This is where you will select your build type. For our example we will use Xamarin.Android template. If you need iOS, you would match this process with iOS.

So many options
From here you can use the default settings, you want to select your Repository in question so that it uses this code for the build. If you notice in my example, I have "Continuous integration" selected. I recommend this if possible as it will allow you to run these tests whenever code is submitted to the branch.

Once you hit create, you are then resented with a dialog to configure the specific build settings. There are a three steps that require input:





But it can be boiled down to
1. Your license login (user name and password) information to activate\deactivate your Xamarin credentials
2. Xamarin Test Cloud API Key, Device ID, Test Cloud email

As a pro-tip for the password, the password field defaults to a plain text entry. What I would recommend is select the variables tab, and add your password as a variable, with the lock icon selected to flag it as "Secret".
MyPassword is the variable I have created.
Then in the password field you just use that variable with the syntax $(_VARNAME_). Much more secure than plain text usage.

For the "Test" step, you need to provide a few pieces of information.

First is your Test Cloud API Key, which is found under Teams and Organizations on your Test Cloud account. You can find details on obtaining that here: https://developer.xamarin.com/guides/testcloud/organizations-and-teams/#Obtaining_the_Team_API_Key
 
If you are not currently using Xamarin Test Cloud, fear not! We have a free trial that you can try out. More details can be found here: https://testcloud.xamarin.com/register

Again, you need to provide an email, this time the email of registered/added to the Test Cloud account. This may or may not differ from your Xamarin license details.

The devices ID you can acquire when you create an upload on Xamarin Test Cloud. The final step will give you a command line prompt that can be used for Windows or OSX and included is a --devices (#########) flag. This id is the final piece of information as it tells Test Cloud what devices the test needs to be run on, and can be reused from run to run. I would recommend recording these ID's as currently there is not another way to retrieve them to my knowledge.

Once you have entered all this information you have everything you need. At this point I would recommend selecting "Queue build" to do a test run with what you have uploaded, troubleshoot issues as needed. Ideally you should see this:
Green is good!
That's it! You have made your first step into a larger world of end to end mobile development and more efficient DevOps! Now, any time you submit code from git, this build step will be executed and you are on your way to writing higher quality code. Use this to make sure you are keeping your app at a high quality, and catch bugs and regressions before your users do!

Friday, November 13, 2015

How to Preview your Xamarin.Forms XAML in Xamarin Studio

In my work as a Customer Success Engineer at Xamarin, I demo the tools we provide daily. One that has gained immense popularity since launch has been, without a doubt, Xamarin.Forms. For those of you new to Xamarin development, Xamarin.Forms is a framework that enables you to write your mobile UI for Android, iOS and Windows phone in a shared code layer using either C# or XAML. Many developers see this as a real asset as greater code share suggests shorter development times and getting your app faster to market. XAML based UI development is also something that WPF and C# developers are already familiar with so that means their experience will help them get up and running with mobile sooner.

With that in mind, one thing that developers desire is rapid feedback and development. At the time of this writing Xamarin.Forms currently is a programmatic solution only. That means, no visual designer or previewer to view your UI in progress. That means that the only way to ensure your UI looks good is to build and deploy your app to either an emulator or physical device. While certainly a possibility, this is not the fastest process, especially if you are trying to make minute changes and get immediate feedback.


One solution to this that has been made available is a tool call the Xamarin.Forms Player, written by Daniel Cazzulino, who also happens to be a developer at Xamarin. What this tool does is installs a plugin to Visual Studio that allows you to pair your Visual Studio instance to either an emulator or device. Then, while you are writing the XAML portion of your application, you can actually quickly preview the results live without doing a full build and deployment of the application. This serves as a great solution to many developers. While the Visual Studio add-in has been available for a while, I was recently made aware of this also being published as an Add-In for Xamarin Studio and wanted to write a quick guide on how to get it set up.

From what I understand about the tool, the Forms Player works as a pub/sub application where multiple devices will subscribe to an IDE through a paired code between your IDE and an configured application running on device. Then, as you are developing your XAML you can quickly do a compile and publish. When the IDE publishes an update, each subscriber running will update and display the result. Really cool.

There are two main parts to getting this set up

I. Install the Add-In within Xamarin Studio (On Mac)

Select Xamarin Studio -> Add-In Manager -> Gallery Tab. From there search for Forms Player, it should appear under Mobile Development

II. Create and Install a Forms Player application on device.

Here is where we set up the subscriber side of things. There are a few ways you could do this, including compiling the code from GitHub and installing it, but this approach is pretty simple.

1) Create a new cross platform Xamarin.Forms application. I would name it something like "Forms Player" or maybe equally memorable. PCL or Shared Project should be fine.

2) Add the Xamarin.Forms Player NuGet to your Android and iOS Targets. Right click both Android and iOS Projects-> Add-> Add NuGet Packages. Make sure in the bottom right you check the "Show pre-release" box.


3) Update  new App () in MainActivity.cs and AppDelegate.cs to be new Xamarin.Forms.Player.App ()






As a side note, you may need to modify some of the built references on the iOS project. When I set this up, it complained, initially, about duplicate references to System.Runtime, System.Threading and System.IO. Removing them from the References-> From Packages folder got it running fine.

4) Deploy this application to the devices/emulators you want to support. You will see a Home screen like this:

  
iOS on left, Android on Right
III) Start debugging your app

Now that you have these installed, what you will do is pair them. You do this by selecting the Forms Player menu and select Connect. This will create a running Session ID, which you will input in the running application you have previously installed above.

Open up the Forms application you want to work on. When you open the .xaml file, you will notice that the "Publish" option from the Forms Player menu will no longer be greyed out. Each time you select publish, or hit the hotkey, while you have a .xaml file loaded in your IDE, it will load that current XAML to any device with the app running and session paired, and then preview it.

And there you go! Hopefully you found this useful and it will help you build and ship higher quality Xamarin.Forms apps faster.

Tuesday, October 6, 2015

Getting started with iOS Development- No more XML

Well, I finally am making the plunge. After weeks of postponing, delays, justification and just general laziness I pulled myself together and started the iOS side of development. For those that don't know me I have always had a preference to Android (or an irrational dislike of Apple and its products) so my desire to work on iOS definitely came with a bias against it.

That being said, as a developer with a background in .NET, C#, WPF and Android moving to iOS can be TOUGH. It is a very different paradigm shift to move from xml based UI development, which I have really grown to love, to iOS Storyboards, which still confuse me. Storyboards are built with a visual flow to them, this gives you a nice ability to get a good overview of the app and how it navigates but the individual details are not as easy to manage. Additionally, coming from a world of Layout Controls, moving to the paradigm of Auto-Layout and Constraints can also be a unique challenge. Overall the shift for me hearkens back to a day of WinForms development. It is definitely something new for me.

Much as before, this will likely see a few iterations as my knowledge grows. I decided to follow a similar pattern to how I built my Android UI, first loading the main character overview page, then start building it out from there. So after setting up my initial UI I found myself with this general starting point:

I'll deal with layout later.
The first challenge I ran into was a new paradigm for my drop down selection boxes. Where android has a spinner control that provides a drop down list for you to interact with, that is not something available on iOS.

They have a picker control instead, which is described as using "a spinning-wheel or slot-machine metaphor to show one or more sets of values". If you notice, I am using Text Field's for my data display since there was no "combo box". After some research I learned that iOS actaully has a pretty cool solution set up for something like this. What i needed to do was wire the Text Field input option to be a Picker control instead of the default keyboard input. iOS, in this regard, actually makes this quite simple to do. Text Fields, and many other controls, have a property called InputView which defines what control is the selected input. Keyboard is the default when nothing is set, so instead I set it to a created Picker Control, like so:

var racePicker = new UIPickerView (CGRect.Empty);
racePickerText.InputView = racePicker;

Then a picker control is displayed when we click the Text Field like so:


Overall this is a good start. Different from what we had before, but it works. This does bring up a couple more questions however, populating our data, binding it to the Text Field itself, and then dismissing our Picker when we are done.

1. Setting up the Data.
This is an area that is actually not as documented in Xamarin, but is something that needs to be learned. In Objective-C/Swift world the UIPickerView has two main sources for data and interaction. The Delegate and DataSource. The DataSource is, as you can guess, the data that is tied to the control. You can think of Delegates kind of like the controller layer, defining interaction. 

In Xamarin, both of these properties are exposed, as well as a hybrid Object called the UIPickerViewModel. This is something specific to Xamarin, but basically serves as a hybrid of the two previously mentioned properties and is more C# styled. I learned, over time, that this is a paradigm we do quite frequently but it is something we admittedly do not have as much documentation on. For the case of my application it served my needs. Knowing I had at least four different scenarios I wanted a data source for my object, I created a general PickerModel and overrode the defined methods to use my data, and then set my model in my picker control:

var model = new MyPickerModel (RaceHelper.GetAllRaces (), info.Race.Name);
model.OnPropertySelected += (object sender, EventArgs args) =>  

{
    racePickerText.Text = model.SelectedItem;
};
racePicker.Model = model;


The constructor is how I set my initial conditions, and then if you notice I have a defined PropertySelected event so that I can feedback to my UI when items are updated. Then I was able to get my data populating within my UIPickerView:
The final piece to the puzzle was dismissing the view. This took a bit of hunting and research and then I finally found the final piece. Along with an InputView, there is also an InputAccessoryView. This gives you the ability to add a toolbar to your InputView, giving additional functionality and methods of interaction, including a "Done" button in my case. Setup was actually pretty simple:

var toolbar = new UIToolbar (new RectangleF (0.0f, 0.0f, 50.0f, 44.0f));
var myButton = new UIBarButtonItem (UIBarButtonSystemItem.Done,

     delegate {
          this.racePickerText.ResignFirstResponder (); 

     });

toolbar.Items = new UIBarButtonItem[] {

     new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace), myButton };

racePickerText.InputAccessoryView = toolbar;

And what this gives us is the final product here:


Next step will be to organize the code to be more clean/refactored but that will be for another time.


Again I apologize for lack of diligence in getting things posted, lots going on but hopefully I will get updates on a more regular pace once more as I dig into the world of iOS.

Monday, September 21, 2015

Android Code Review- BaseAdapters are your Friend

Well, I am finally forcing myself to make the jump to iOS, but that is taking more time than I anticipated. More on that in the first iOS blog post. I did spend a little time doing some code review, bug fixing and refactoring. In that process I had a great conversation with one of the other Success Engineers at Xamarin, Colby Williams, who gave me some good feedback and reviewed some of my code. I learned one really great nuget that is worth sharing as it is not immediately apparent when getting started with Xamarin from Android.

When using collection views, it is almost always best to subclass BaseAdapter rather than use any of the out of the box adapters provided by Android (ArrayAdapter comes to mind). I was using the default ArrayAdapter for all of my drop down spinner controls and what I learned is most of the default Adapters provided by Android will give a potential performance hit because for each object in the list, an equal java object has to be created and maintained. This is due to how Xamarin and Android communicate with each other. For an in depth review, this document covers it well:

http://developer.xamarin.com/guides/android/under_the_hood/architecture

So what was happening was for every spinner I created using an Array Adapter, a general C# and Java object were being created and maintained, creating overhead. Instead, creating a BaseAdapter, the under the hood creates a single Java object that has a C# implementation within. Much better performance wise, fewer objects to maintain in memory.

My final code for the adapter is actually pretty simple:

public class SpinnerAdapter : BaseAdapter<string>
    {
        List<string> _items;
        Activity _context;
        public SpinnerAdapter (Activity context, List<string> items)
        {
            _items = items;
            _context = context;
        }

        public override long GetItemId (int position)
        {
            return position;
        }

        public int GetPosition(string selected)
        {
            return _items.IndexOf (selected);
        }

        public override string this[int index] {  
            get { return _items[index]; }
        }

        public override Android.Views.View GetView (int position, Android.Views.View convertView, Android.Views.ViewGroup parent)
        {
            var view = convertView;
            if(view == null)
            {
                view = _context.LayoutInflater.Inflate (Resource.Layout.spinner_item, null);
            }

            view.FindViewById<TextView> (Resource.Id.text).Text = _items[position];

            return view;
        }

        public override int Count {
            get {
                return _items.Count;
            }
        }
    }


Once I made that update, I noticed my views loaded much quicker.

Next time I am going to dig into iOS development, and why it can be a challenge. Given that iOS 9 just came out this past week, I am also using this as an "excuse" to learn iOS 9.

Monday, August 31, 2015

Android ListViews and Updating the Backend Data

I wanted to spend at least one more post to try to put my app in a finished state so there was a lot of time spent on both backend code and getting my skills list to display properly.

My first thought was to use a ListView to display all of my skills, it seemed logical. It was a of items, numbers and a checkbox. Time to brush off what I learned from custom spinner items. Creating adapters for your ListView is actually pretty standard as a lot of the time the default elements are going to not provide what you need.

The first step was to at least get my ListView organized and all my skills displayed. I already had all the hookups in place thanks to my work last week with implementing ViewPager. The first step was to create a new LayoutView, which housed my ListView. I then used a default ArrayAdapter to just grab a placeholder list of strings.


        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var root = inflater.Inflate (Resource.Layout.fragment_charsheet_skills, container, false);
            ListView view = root.FindViewById<ListView> (Resource.Id.skillsList);
            var skills = ((CharacterSheetActivity)this.Activity).CharacterInformation.Skills;
           view.Adapter = new ArrayAdapter<string> (this.Activity,Android.Resource.Layout.SimpleListItem1, skills);

            return root;

        }


 Pretty straight forward, and shows at least a starting point:
 

We have a successful ListView! Now to add the Custom Adapter. In this case, I want to display not only the name, but the ability mod score, whether or not the character is trained, and then the final value. (Mod + Proficiency)

The adapter is set up and in order. The first challenge I ran into was getting my items to not clump together. RelativeLayout was not really an option here, so a little searching I discovered one effective option was to use the "Weight" tag to give each item equal weight within the control. 

 





<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">
    <TextView
        android:id="@+id/skillName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Placeholder"
        android:layout_weight="1" />
    <TextView
        android:id="@+id/modValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="+3" />
    <CheckBox
        android:id="@+id/isTrained"
        android:layout_width="32.0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView
        android:id="@+id/totalValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="+5" />
</LinearLayout>


In theory that worked well, but then I realized I had a problem once I got the final result running.


Looks Perfect
Maybe I need to think this through...
As the weights are row specific, it does not help align each column. Once again, for implementation and times sake I decided to call that "good enough" for now. 

The next step was to work on my back end code. As can be seen in the above, I am hard coding all of my values, and no hookup event for the proficiency checkbox. This actually required a lot of back end work, which was good to revisit and clean up the data.

 Now, I will preface by saying I do not admit this code will be the best. I'm playing more of the functional over proper card here. As a side project it will regularly be a work in progress. 

I created both a Skill and SkillsList class on my back end. The reason for the latter is it gave me a collection that I could house some of the more static concepts like what skills have what ability mods, and a fully populated list of all possible names. Again, not proud of it, but its functional. Then, at launch all possible skills are preloaded based on starting stats. This gives me all my initial conditions that I access as accessor methods. (Loading data I will revisit at a later point).

From an input standpoint the two big changes I needed to make sure happened were 

a) update final values as proficiency was enabled
b) update mods when ability scores are changed.

For the first, I did an inline set of code, pretty straight forward.


proficient.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) =>  
{ 
    CharacterSheet sheet = ((CharacterSheetActivity)_context).CharacterInformation; 
    
sheet.Skills[position].IsProficient = e.IsChecked;
    skillMod.Text = sheet.Skills [position].TotalValue + ""; 
}


On the flip side, with all of my Attribute code, I added this line:

character.UpdateSkills (Attributes.AttributeName.STR);

Which is essentially calling an update method within my SkillsList:

public void UpdateSkillMod (Attributes.AttributeName type, int mod)
{
    foreach(Skill skill in _skills)
    {                
        if(skill.ModType == type)
        {
            skill.ModValue = mod;
        }
    }
}


This is simply an enumeration through all skills that updates the ModValue of the associated type. That gets us to our final version, which we will hold with for now.

On the back end I also did a lot of cleanup for better preparation for when I need to load character data. At this point I am going to call the Android version of the app in a good spot and now move to get an iOS skin running with this.