Thursday, April 14, 2016

Are you Ready to Bring in a Partner to Help Create a Mobile App?

This is a question that organizations should ask themselves when engaging a partner to help with their mobile initiative. As a consulting company Magenic does our best to help the clients understand if they are ready to start the app creation process but we will never fully know until we engage with them. In cases where we engage and find the client isn’t ready, we try to steer them into a soft landing through continued communication of project difficulties which may cause a re-evaluation of the current path. However, it is always better if the client is ready before we engage. A false start can be a source of significant lost time, capital and frustration for all parties.

This leads to the important question, how do you know you are ready? At Magenic, we generally look at the following areas.


Do you understand if you have a project or a product?

Understanding this is key to knowing how the app will be built and setting expectations around the long term financial investment. Projects tend to involve a set amount of scope and have fixed delivery timelines, with a clear start and end date Many B2E applications that are not in a “bring your own device” environment may potentially be viewed as projects. A key expectation for a project type app is that it will be built once and only have minor maintenance over time. A project may also be suitable for either a waterfall approach or agile.

A product, on the under hand, describes an app that will continually change and evolve as time goes on. Most apps that are externally facing should be considered as products. The mobile environment and user expectations and competitive market are continually changing and your app will have to evolve with it as devices, capabilities and desire for features change over time. A key feature of a product is the expectation that there will be a team continually working on improving and evolving the app through its entire lifetime. Products are well suited for an agile methodology and usually falter in Waterfall environments. For more information, see Mobile Project vs. Mobile Product.

Do you understand the vision for your product and is it shared organizationally?

This may seem like an unusual problem problem but it is not. Many organizations have groups with different or incomplete vision and understanding for what the product should do. Sometimes we given guidance “to  make it work like System X”, but no one is able to articulate exactly what system X does or how it does it, because the people who knew are no longer available.  The technologies behind System X may also be considered legacy and reproducing features identically in a new technology may not be feasible. This leads to incomplete requirements and dissatisfaction as it is inevitably realized that something is missing, or that it will cost even more to create. If you are not able to articulate what your product needs are, your partners won’t know them either. Problems manifest themselves in different ways in this situation but the end result is the same: unclear requirements with no way to prioritize the backlog or successfully complete the product.  In many cases, you may have a release which does not align with stakeholder expectations or deliver expected features,

We help our clients reconcile their emerging points of view, and reach consensus on the business needs.  We help  define key application features and it’s into their overall business strategy.  We also help our client understand critical strategies to leverage mobile transformation into a strategic advantage. However, in some cases, we still find it difficult to broker internal reconciliation and shared understanding due to cultural realities. Partners like Magenic can help facilitate the process of defining strategy and how they app supports it but it is clear that understanding and agreement has to come internally. Partners are not going to be able to change, or in many cases overcome, a client’s internal culture or ability to come to consensus.

Have you defined Key Performance Indicators and know how they will be measured?

Like the definition of “done”, the definition of success can be similarly murky. Successful mobile initiatives have defined key performance indicators to track and measure success and have defined the metrics needed to evaluate success.  Without fully understanding how success will be measured, it becomes challenging to prioritize features or adjust the product after initial release to further business goals. The lack of a good definition of success can be an insidious problem because the symptoms associated with it are not always readily apparent. It usually manifests itself in difficulty creating requirements or general dissatisfaction over the perceived value of the product being created.

Do you have a product owner who is empowered to make decisions?

Someone needs to own the business requirements and be empowered to make decisions, at least on a tactical basis. No matter how well planned out a feature is, questions will come up as changes are being made to the application. Additionally, disagreements over direction will arise that need timely resolution. Questions that can’t be answered quickly will lead to a disruption in the development process. This can be particularly hard for organizations used to making decisions by committee or when other organizational stakeholders are allowed to enforce changes or alter decisions made by the backlog owner.  . When there is no clear product owner or the product owner is unable to decide or enforce decisions, at least on a short term basis, then the app development process will almost certainly start to falter as the delivery team becomes idled waiting for decisions to be made or re-working changes to decisions that have already been implemented.

Are you willing to commit to the project lifecycle and understand what it is?

Most mobile projects are better suited for using an Agile methodology, which goes beyond a solid a technical delivery team; it requires a team that includes representatives of the business that have the time and capacity to be involved in the requirements and delivery process, who can commit to the meetings/ceremonies and are willing to abide by other agile rules.  A cardinal rule here is to respect the Sprint commit once it has been made, and not change Sprint deliverables midstream.  If some of these terms seem foreign to a Client, then the Client is not ready to start an agile process. Good partners will be able to help you understand the process but they can’t force you to commit to it. That will need to happen internally and requires full support from all stakeholders.

Can your internal technical team deliver their pieces on time?

Many mobile projects integrate with internal systems that are already in place. Access to these systems can be critical to fulfilling the business requirements of the product. While in many cases integrations can be delayed and worked around for a short period of time, they usually represent a significant source of technical risk and should be addressed as early as possible. Delays in critical integrations will eventually cause project failure as the delivery team becomes delayed and costs mount to an unacceptable level without project completion.

Do you understand that the world of mobility is continually changing?

A source of product dissatisfaction can be around a misunderstanding that a product is never done and that changes to the underlying platforms can interfere with the fulfillment of business objectives. Apps, particularly ones visible to the public, your customers or business partners, need to change and evolve as the platforms change or there is a significant risk of application invalidity. The constant updating of the app to handle platform, expectation and device changes  must be anticipated and accepted.

Can you control scope and expectations internally?

Everyone wants the magic app that will do everything, solve all problems and catapult a client into the Number 1rank in the industry; sometimes, this is expected immediately and without a huge spend.  Apps can take a lot of time to build correctly; in the mobile world, applications are normally created through a long cycle of trial and error. This means that it is critical to control scope to create a minimum viable product (Does an MVP Release Make Sense for your Mobile Initiative?) and set internal expectations that not all features will need to get into the app’s first release. The app will continue to evolve and grow as you organizationally gain more insights into actual usage of the application and validate desired additional features before implementation.  It should be expected that this is “normal” and a significant source of dissatisfaction and eventual project failure is caused either by a “big bang” approach to development and/or a failure to recognize and commit to the level on ongoing investment required.

If all else fails, know when to stop

Sometimes these problems will manifest despite our best efforts or intentions. Project rarely fail due to technical reasons. There are generally 3 main themes behind every project failure: inability to define requirements;  dependencies not being met in a timely matter; and  improper expectations setting. A sign of a great collaborative relationships is when extreme problems are recognized and the group is willing to stop and pause the process so course corrections can be made.

Problems will always occur, but not all problems can be solved merely through by force of will. Knowing the difference and having the courage to call a “stop” can be the difference between long term success or burning through budget, until the project is eventually considered a failure. Good consulting partners will give you ample warning that a stop may be required. An early alert to this eventuality will be in consistent progress warnings on status reports and conversations consistently pointing out missed dependencies and commitments.

Creating a good mobile application is an expensive process and not one you can just throw over the fence and have a partner throw the result back at you. It is an iterative and collaborative process where everyone works as a team to identify and create value, are willing to commit to a shared process and where responsibility for success is likewise shared. Many of our clients cannot afford major misses on mobile initiatives. The questions listed above should be discussed internally and a readiness evaluation should be conducted before making a significant financial investment and engaging a partner. 

Wednesday, February 24, 2016

MS Buys Xamarin - Analysis # 248

As you probably heard Microsoft announced that they are acquiring Xamarin. I see there are a ton of these posts asking the fundamental question, what does this mean? For myself I'm thinking through a bunch of issues.

Will the pricing model for licensing change?
I would guess almost certainly. Microsoft generally handles licensing for development tools through Visual Studio editions and MSDN licensing. Already the "free" version of the Xamarin platform is available as part of the VS install. I expect this will now become the full version that is baked into Visual Studio. What level of Visual Studio will be required for Xamarin? I'm actually not sure. However I expect MS will want most developers to be able to use the Xamairn tools so they will likely set the bar pretty low.

What about Xamarin Studio?
If  you love Xamarin Studio, I'm not hopeful, at least in the long run. Microsoft already has Visual Studio and Visual Studio Code. I would expect them to double down on these IDEs and in that world Xamarin Studio largely becomes redundant. In the short term I expect it will be around for a bit.  What this means is that development will done on a PC with a remote build server unless and if Microsoft builds the Xamarin technology into Visual Studio Code to run on OSX. This may or may not happen, it is always possible that if it is part of the roadmap that Xamarin Studio will be kept around until then. But at some point I guess that it will almost certainly be retired.

What about Mono?
Mono is open source, will remain so, and so isn't overly impacted by this. The new MS loves open source anyway.

Xamarin University?
Microsoft does not have a training program or certification program as in depth and extensive as Xamarin University and its associated certification. I'm not sure this is an area where Microsoft will invest in changing how they do things. The Xamarin University program will likely be rolled into Microsoft's current certification scheme.

How about Xamarin's Partner Program?
Microsoft, I hate to say this but Xamarin's partner program has your's beat, hands down. I am not hopeful that Microsoft will change its partner program to meet Xamarin's but I do at least have some small hope that they will examine it closely for things that really work there. That may just be wishful thinking on my part.

What is the future of Xamarin Forms?
I expect it to be pulled in more closely to the UWP structure so it can be used without extensively altering UWP development. For example the XAML may change to meet the UWP structure. Having said that the match will not be exact. Part of the reason why the UWP structure works is because MS is in control of the UI components and sits on top of a unified OS. This is not true for iOS and Android. I expect some changes here, but the concepts won't (and likely can't) be completely abandoned. Jason Smith's work is still relevant.

How about their relationship with Apple?
There will be some degradation in the relationship because MS will be seen as less of a neutral party than Xamarin is.  Having said that, the relationship between Apple and Microsoft has fundamentally changed and improved over the past year or two. This will likely continue.

Can we still expect day one support for API changes?
As I understand how Xamarin wraps the iOS APIs it is largely automated so in cases where there will be no fundamental underlying change in the ability to get day one support for most XCode version and API changes. However, more fundamental changes like moving from 32-to-64 bit or the Apple Watch structure may require a closer relationship. I suspect Microsoft will try and continue to partner with Apple across a wide variety of initiatives and keep improving the relationship. Let's be honest here, Apple and Android have the phone space and Microsoft isn't a viable competitor here. Tablets are a different story but one where the advantages of cooperation for both firms, given the current conditions, outweigh the desire to freeze each other out.

How about product stability?
This is one the huge pluses that I see. Xamarin was a smaller company that was very ambitious in the breadth of their offerings and what they are trying to do. The stability of the products from release to release is, well, not always where it should be. I've stated this before, Xamarin has a lot to learn in really getting a fully stable product to market and they are solving an extremely complex problem. I suspect that the Microsoft control over process and quality assurance will only have a long term positive impact on the product. Having said that, it may take a while to play out.

What about the Android Player?
Microsoft has their own player that sits on top of Hyper-V, Microsoft's virtualization technology. The real advantage of the Xamarin Android Player is that it works with Oracle's Virtualbox and can run on a Mac. With recent improvements in Google's version of the Android player I'm not sure if they will need to keep the increasingly redundant Xamarin Android player. One of them will likely go and it probably won't be the one that runs on Hyper-V.

For that matter Xamarin Insights?
Microsoft has their own Insight's product. I expect the Xamarin version to be rolled into the Microsoft one, using the Microsoft back end and pricing schemes.

Test Cloud?
This type of cloud service is right up Microsoft's alley. Perhaps rebranded as part of Azure, I think good things will happen here if you use this product. Also this will likely continue to use more standard testing formats.

Profiler?
This tool is very specific to the mobile platforms and Microsoft will likely (hopefully) complete it.

The upshot of all this? I believe it will be a net positive impact. There are two major benefits I see; first since Microsoft gets its revenue in other ways the licensing scheme will change making the Xamarin platform a bigger player because it will lower the bar to learning the platform. The second has to do with the size of Microsoft and maturity of their development processes, the products will only get stronger and more stable.

I look forward to seeing how this plays out.

Wednesday, January 20, 2016

Best in Class Consultants or Learning on Your Dime

If the consulting company you are looking at says "yes, we do that" to whatever technology you throw at them, they are probably learning on your dime. If you work for such a consulting company, you probably have a lot of sleepless nights and unhappy customers. A common truism is that no one can be an expert in everything and that extends to organizations as well. Highly sales focused organizations, in particular, can fall prey to this if the pressure to keep selling overwhelms the desire for quality delivery.

When I became the mobile practice lead early last year one of the first things my boss shared with me is that he wanted us to become a best in class provider for mobile services. In order to achieve that goal we had to decide what it is we actually do, and by extension what we don't do as well. Different companies may come to different conclusions but for our mobile practice we looked at our internal competencies, the spectrum of client needs and settled on native iOS/Android, Xamarin and Cordova, with responsive web applications being covered by other groups in the company. If a client needs Appcelerator of Kony development expertise we let them know that we may not be the best partner. This is in their best interest and in ours.

By deciding what we actually did in the mobile space we solved many problems. We now knew where to focus our training efforts and in so doing alleviated many delivery issues associated with resources that learn on the job. The impact of this keeps spreading. By reducing delivery issues our thought leadership becomes free to put more formalization around our technical delivery and ALM process, adding to our existing overall delivery process and in turn further reducing delivery issues associated with these processes. This again frees up management to work on other issues, including growing and scaling the business.

This idea isn't anything new. People can't be experts in everything and if they perpetually stay at the start of the learning curve of an overly wide variety of disciplines they will constantly be making the mistakes associated with that part of the curve; with management dealing with the fallout. As good consultants we don't do our clients any favors when we just blindly reply, "Yes, we do that" when we know it is far outside our our capabilities.

That's not to say you shouldn't move into new skill sets and product offerings as a person or as an organization. Indeed you likely need to do that to continue to thrive. But every new skill learned or product offered comes with a learning curve and a cost in terms of focus that is redirected into learning that skill set or creating that new product. With that in mind it should be a deliberate process, one where you understand and are prepared for the cost and with that understanding knowing that there is limited capability to do it all, know it all and learn it all at once.

To be best in class you need to limit the scope of that class to something that can be viably achieved and understand exactly what it is are best in class at. If you are on the other side and looking to hire a consulting company with best in class talent, just remember if they keep saying,"Yes we do that" to an overly wide variety of things, they probably are not best in class at anything and likely you will be paying them to learn.

Wednesday, October 28, 2015

Choosing a Mobile Development Platform

I've written a lot about the subject of choosing a mobile development platform; how to compare mobile development platforms, which ones perform better and it what circumstance. A lot of what choosing the right mobile development platform comes down to is mitigating the risk of choosing the wrong platform for your organization's needs and having to engage in expensive refactoring or rewrites later in the process.

In my mind, the need for this decision normally comes into play when you have to create applications for more than one mobile platform. Quite frankly, I you have the luxury of only needing to develop for one platform use the native tool set; it will give you the platform vendor's vision on how apps should be developed in a no compromise fashion. Unless you have some existing preference for different development languages or eco-systems, the best choice for single mobile platform scenarios is usually to use the vendor's tool set.

However, for the vast majority of us that just isn't reality. Even within enterprises, the rise of bring your own device has created a situation where needing to develop for multiple platforms is extremely likely. With this in mind I've been increasingly trying to work out a more formulaic approach to thinking about and choosing the right mobile development platform for different situations. The approach I've come up with is STANCE.

STANCE is a system that looks at several pertinent factors in the requirements for a mobile application and then forces you to rank those factors. With this ranking, different development platforms are given a rating on the STANCE factors. With this in mind, you have the ability to measure how different mobile development platforms rate on the stance factors, and you should pay particular attention to the factors you rank the highest.

First let's take a look at those factors and what they mean:

Speed / performance - how important is it that your application perform CPU intensive tasks, rendering, external applications calls with the best performance possible? Do you really have a CPU intensive application that will push the bounds of the mobile platform or do you just need good enough?

Time to complete / Cost - Is the time and cost a significant factor? I would not underestimate or under-rank this metric.

Always working with the newest standards / APIs - Will your application always be using the latest technologies of the mobile platforms. For example, will you start using 3D Touch or the newest design standards shortly after they are released or will those types of changes not be a significant factor in your application until sometime after they are released?

Native user experience - How sensitive are your users to having a true native experience in your application? Will your users be put off if your Android application isn't using Material design or will they be OK if it's close enough or potentially even uses web design standards?

Complex hardware / platform API interactions - Will your application need different or very specific interactions with the device's hardware or APIs? For example, does your application need to have a check scanning algorithm utilizing the camera, direct access to Health Kit or precise control over the format and bit rate audio and video are being recorded at?

Enterprise Services and Tools - Are there some particular enterprise services or tool sets that have already been decided on or your organization has decided should be used. If the development technology doesn't work with one of these, will it mean that your app is a non starter for meeting corporate standards or communicating with corporate services?

Each of these factors should be rated against the others. This is done instead of a straight ordering to get a relative weight on each of the factors; just how more important is one compared to the others? To do the ranking you can use a chart like the following:


To use this chart look at each of the green cells and ask yourself which is more important, the one on the Y axis or the item on the X axis. For example, the first cell compares T(ime/cost) to S(peed/performance). If cost of the application is more important to the application draw a symbol pointing to the T, otherwise one pointing to the S. It may even be useful to have several different stakeholders fill this out to make sure there is agreement on what the priorities and requirements of the solution are. A filled out chart may look like the following:


To use this simply assign one point to each metric where it has been selected as the more important. In the above example we find the following rankings:

S - 2
T - 5
A - 2
N - 2
C - 1
E - 3

(Note: The total of all the ranking should always be 15)

In the above example, far and away the most important factor of making this application would seem to be keeping the cost low. It is more important to anything else; scoring a full five points. It would also appear that integrating with some enterprise services and tools is also reasonably important while complex hardware interactions do not appear to be particularly important to this application at all.

With this understanding we can now look at how they compare to some of the development platforms that are available. I have scored some of the ones we use at Magenic, but with a little research you could score other mobile development platforms as well (I have scored on a scale of 1-8 with the higher number being that the platform is better at delivering that metric).

Cordova:
The Cordova platform has many compromises but it also has one particular area where it shines. If you can work within the bounds of its plugins, don't have complex hardware interactions, are not overly concerned with it fully looking native and performance isn't a huge issue then Cordova will create cross platform applications faster and cheaper than any other mobile development technology on this list.

Xamarin Platform:
The Xamarin Platform has very few compromises. The largest compromise it does have is in Time / cost. It certainly does better than the native technologies but in our experience only 40-60% of code is shared, depending on the business logic of the application. The user interface is written once on each platform and mobile applications then to have a lot of user interface code and potentially platform specific API calls.

Some of you may notice that the Xamarin Platform didn't get a full score for always working with the newest standards / APIs. This would seem to be somewhat at odds with their day one support of new APIs that Xamarin is known for. The reason why I didn't score them fully here is that occasionally a change to an ecosystem is so fundamental that it takes Xamarin a while to implement. An example of this is when iOS started supporting 64 bit applications. It took the Xamarin Platform quite a while to re-architect for this change, only releasing a stable version within a month of when Apple stopped accepting new apps to the store that were not on the 64 bit standard. You can be reasonably confident that Xamarin will fulfill your needs for always working with the newest standards / APIs and also should be prepared for the off chance of a fundamental change happening where day one support does not appear.

Xamarin.Forms:
Xamarin.Forms is much more of a compromise than the Xamarin Platform. There is a slight Speed / performance penalty, it isn't as good as always using the latest standards / APIs (for example, it didn't implement elements of Android Material design for quite some time after it was released), there is not as much flexibility in the design and complex hardware interactions require writing platform specific code. But those penalties compared to the Xamarin Platform are offset by a better Time / Cost score. If your app can work with the limitations of forms then you can write cross platform applications at a cost advantage over the Xamarin Platform. The cost advantage isn't quite as good as it is for Cordova, but then again the other trade offs are not quite so severe.

Native:
When it comes to using the platform's native development technology  and creating cross platform applications there is one primary trade off that is being made, it is usually the most expensive way to do it. You will have to create and maintain two or more completely separate code bases. But in every other way the native development platform gets full marks. Even in Enterprise Services and Tools that all tend to tread the native development technologies as first class citizens, which is usually not the case with other mobile application development technologies. It is for this reason why when there is only one platform I usually starting thinking about native.

Now you might notice even though I scored the rankings of the factors that are required for the application I don't then take it the next step and formulaicly compare it to the ratings of the development platforms. I don't do this because it usually isn't a formulaic answer. For example, if you find it critical that your app work with some enterprise service or tool, then really what is required is some research to find out which mobile development platforms work with your selected enterprise services and that's what will matter.

In many cases there are usually other more subjective factors that come into play or ones that are very context sensitive. For example, if your entire development team is familiar with .Net, in which technology would they be more likely to create well architected, stable and maintainable applications? Another factor that may complicate these ratings are the design of the UI itself. I have seen many digital agencies create mobile application designs that are more akin to websites than native mobile applications. In such cases HTML based technologies such as Cordova really start becoming more attractive.

The STANCE metrics do not lead you to the absolute, in all circumstance,s correct mobile development platform based on your needs. There are just too many situational and subjective factors involved to make a completely formulaic approach. Instead, it gives you a tool to start thinking about what factors are more and less relevant to your mobile efforts and from that what tools are more and less likely to fulfill those needs. STANCE won't, in and of itself, clearly identify the one and only mobile development platform for your problem, but it will help you mitigate risk so you are more likely to choose the one that best fits your needs.

Monday, August 17, 2015

Accessing Azure AD information from .Net Azure Mobile Services and the Xamarin Client

I've been busy, really busy of late but recently I encountered an interesting problem while working on a while paper comparing Xamarin with PhoneGap. I wanted to back this all by Azure Mobile Services and also use Azure AD for authentication. There are lots of articles out there that explain exactly how to tie the two together and it worked great. This is one such article that is very useful: Authenticate your app with Active Directory Authentication Library Single Sign-On.

The instructions in there are simple enough to follow and getting this to work in my Android application is similarly simple. But when I authenticate, what exactly is it that I get back? Take the following code called in my mobile application:

var token = await service.LoginAsync(this, MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);

When I look at the token object I find that it contains two properties; MobileServiceAuthenticationToken and UserId. Neither of these looks like anything but binary goo. That's fine, but I want to show the user of the application things like their name stored in AD, AD id, find out what roles they are in and do things like find all the users in a role. How do I do this with .Net Azure Mobile Service backed by Azure AD?

First I found some articles that gave me some clues. Nick's .Net Travels talked about doing this with the Azure AD Graph API. and this is fine but he used the ActiveDirectoryClient class. This worked great for me but I noticed that some of the versions of the required dependencies of Microsoft Azure Active Directory (Microsoft.Azure.ActiveDirectory.GraphClient) Nuget package were of a different version than is required by Microsoft Azure Mobile Services .NET (WindowsAzure.MobileServices.Backend.Entity) version 1.0.470. As of the time of this writing Microsoft Azure Mobile Services .NET, which I needed for my .Net Azure Mobile Service backend, had some dependencies such as one on System.spacial version 5.6.2 and only version 5.6.2. The current version of Microsoft.Azure.ActiveDirectory.GraphClient uses a minimum version of 5.6.4. I tried updating the version that the .Net Azure Mobile Services project used under the hood to 5.6.4 but eventually my Azure Mobile Service stopped working with an error complaining about the version 5.6.2 not being installed. I then found this article on Nick's .Net Travels that illustrated the same problem.

The upshot of the deal, You cannot use any version of the Microsoft.Azure.ActiveDirectory.GraphClient library that uses the ActiveDirectoryClient class introduced in version 2.0.0. Instead you must use version 1.0.3 or earlier of the Nuget package. I ended up editing the Packages.config and project files manually to point to this older version. Since I can't use the ActiveDirectoryClient class, I'm stuck using the older GraphConnection class. With all that in mind, let's look at how I solved two common scenarios using a .Net back end of Azure Mobile Services authenticating with Azure AD.

Problem 1: I want to get information about the logged in user other than the binary parts of the token I get back from the login request.

I want to show the user their AD id or their full names after having logged in, but none of that is returned from the Azure Mobile Services client in Xamarin Android or iOS. I don't want the client trying to hit Azure AD directly so in my .Net Windows Azure Mobile service project I create a new ProfileController that inherits from ApiController to get the currently logged in user's profile information from Active Directory:

[AuthorizeLevel(AuthorizationLevel.User)]
[RoutePrefix("api/Profile")]
public class ProfileController : ApiController
{
    // GET api/Profile
    public async Task<UserProfile> Get()
    {
        var authenticationResult = await Utils.AdIntegration.GetAuthenticationTokenAsync();
        var credentials = await Utils.AdIntegration.GetCredentialsAsync(User);
        var graphConnection = new GraphConnection(authenticationResult.AccessToken);
        var adUser = graphConnection.Get<User>(credentials.ObjectId);
        var groups = graphConnection.GetLinkedObjects(adUser, LinkProperty.MemberOf, null, -1);

       var returnValue = new UserProfile
       {
            FullName = adUser.DisplayName,
            FirstName = adUser.GivenName,
            LastName = adUser.Surname,
            UserId = adUser.UserPrincipalName,
            Manager = groups.Results.ToList().Any(g => g.ObjectId == CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.ManagerAdGroup))
        };
        return returnValue;
    }
}

Some things to notice off the top, the line [AuthorizeLevel(AuthorizationLevel.User)] decorating the class locks this class down so only logged in users can call the get method. It is marked async because I'm about to make asynchronous I/O calls out to get information from Azure AD.

First thing I did was get the Authentication token for the currently logged on user.  To do this I implemented the following GetAuthenticationTokenAsync method:

public async static Task<AuthenticationResult> GetAuthenticationTokenAsync()
{
    ClientCredential clientCred = new ClientCredential(CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.ClientId), CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.ClientSecret));
    AuthenticationContext authenticationContext = new AuthenticationContext(string.Format(CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.Authority), CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.AdSite)), false);
    return await authenticationContext.AcquireTokenAsync(Constants.AdIntegration.Graph, clientCred);
}

The Azure AZ class's ClientCredential takes as constructors the client id and client secret you created when connecting your Azure Mobile Services Account to Azure AD. In my example I'm storing these in the Azure Mobile Service's configuration. With that I get the authentication context using the Authority and AD site name setup for Azure AD. In my case it was: https://login.windows.net/{0} and testincidentqueue.onMicrosoft.com. Finally I returned the token from the AcquireTokenAsync method on the authentication context.

With my token in hand, I now needed to get my credentials. To do that I called the GetCredientalsAsync Method I created. This method appears as the following:

public async static Task<AzureActiveDirectoryCredentials> GetCredentialsAsync(IPrincipal user)
{
    var serviceUser = (ServiceUser)user;
    var identities = await serviceUser.GetIdentitiesAsync();
    return (identities != null && identities.Count > 0) ? (AzureActiveDirectoryCredentials)identities[0] : null;
}


This method takes the ApiController's User object for the currently logged in user as a property and casts it into a ServiceUser. If the user is logged into Azure Mobile Services using Azure AD, this should always be a valid cast. With this object I return the first identity found in the GetIdentitiesAsync method, there should only be one.

With the credentials I now have the access token of the current user and with the identity I have the user's AD object Id that I can query against. I use these to tell the AD graph that I want the user with the Id I returned from the identity.  I also query the linked objects of that returned AD user to find out what AD groups this user is a member of. The rest is just returning the results to the caller.

From my client I can now make the following call to my mobile services to get information about the logged in user in Azure AD:

var profile = await service.InvokeApiAsync<UserProfile>("Profile", HttpMethod.Get, null);

Problem 2: I want to get information about all the users in the system who belong to a particular AD group.

This is a similar problem to what I solved before. However, in this case I need to know the AD object Id of the group I'm querying for. In my case it was always the same group so I stored the group Id in the mobile service's configuration. My class looked like this:

[AuthorizeLevel(AuthorizationLevel.User)]
[RoutePrefix("api/WorkerList")]
public class WorkerListController : ApiController
{
    // GET api/WorkerList
    public async Task<IList<UserProfile>> Get()
    {
        var authenticationResult = await AdIntegration.GetAuthenticationTokenAsync();
        var graphConnection = new GraphConnection(authenticationResult.AccessToken);
        var adWorkers = graphConnection.Get<Group>(CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.WorkerAdGroup));
        var members = graphConnection.GetLinkedObjects(adWorkers, LinkProperty.Members, null, -1);

        var returnValue = new List<UserProfile>();
        foreach (var member in members.Results)
        {
            var user = member as User;
            if (user != null && (!user.AccountEnabled.HasValue || user.AccountEnabled.Value))
            {
                var groups = graphConnection.GetLinkedObjects(user, LinkProperty.MemberOf, null, -1);
                returnValue.Add(new UserProfile
                    {
                        FullName = user.DisplayName,
                        FirstName = user.GivenName,
                        LastName = user.Surname,
                        UserId = user.UserPrincipalName,
                        Manager = groups.Results.ToList().Any(g => g.ObjectId == CloudConfigurationManager.GetSetting(Constants.ConfigurationKeys.ManagerAdGroup))
                    });                    
            }
        }
        return returnValue;
    }
}

I started the same way as last time, I ensured there was a user logged in to access the Get method and then got the authentication token for the currently logged on user that I can use to connect to Azure AD. Like last time I query AD but instead of querying the User objects with a user's object Id, I query the groups with the group Id stored in the service's configuration. Calling GetLinkedObjects on a group gets me the members of a group, which is exactly what I want. With this it is simply a matter of enumerating through the group members and sending the results back to the caller.

To use this I make a similar call from the client as last time:

var workers = await service.InvokeApiAsync<IList<UserProfile>>("WorkerList", HttpMethod.Get, null);

That's it. Making simple queries against Azure AD is possible as long as you use the correct version of the libraries and know how to call into the old API.

All code and a working Azure Mobile Service .Net project can be found in the development branch under the Azure folder of the following repository:

https://github.com/Magenic/WhitepaperPerformance/tree/develop

Wednesday, April 29, 2015

Microsoft's Windows 10 Allows You to Run Android and iOS Apps

Today Microsoft made an announcement that Windows 10 will allow Android applications to run in an Android AOSP subsystem. Additionally, Objective-C applications can be compiled and run on Windows 10 as well as universal applications. These announcements, particularly the later, surprised and excited many of us. I've been speaking with a lot of people both inside and outside of Magenic on what all of this means, or could possibly mean, given our limited understanding. (For details See Kevin McLaughlin's article and Mary Jo Foley's article)

First there are some pretty important technical questions raised by this:
- What will the applications look like in Windows 10? If the Android applications are just running in a ASOP subsystem then presumably you would have a bunch of applications looking and navigating like native Android applications on your Windows 10 device. That may be OK for some applications but probably not others.

- How about access to system services and 3D rendering? If I need access to the hardware GPS can one application running in the Android subsystem do that while a Windows 10 application tries to get at it at the same time. This could be handled but I'm curious as to the level to which it is handled or if there be dragons.

- For Objective-C what if my application is accessing HealthKit? I assume HealthKit is not available in Windows 10 when I port my code. When running an Android application how about Google services, can I install them in the subsystem?

- It seems Apple is putting a huge effort behind Swift but MS only mentioned Objective-C; will there be Swift support some time in the future? I just finished writing a white paper on when to use Objective-C vs. Swift. Until and unless MS also supports doing this with Swift, this could change the equation for applications that ever may be expected to run on Windows 10. For that concern, Objective-C would be the one that could work.

- I've heard that Objective-C apps may support porting over Xibs but not Storyboards. If true that could limit the applications that can be ported over without refactoring.

I look forward to learning more and getting some answers to some of these questions. Early days! :)

Even with all those questions, there are a few conclusions that we can come to with what we currently know today.

- One question I've seen floating around is do we still need solutions like Xamarin or NativeScript. The answer is absolutely yes. These new capabilities allow us to more easily run Android applications written in Java to our Windows 10 devices and compile Objective-C code into unified applications for Windows 10. What they don't do is allow you to run your applications written in Objective-C on an Android device or in Java on iOS. For this type of cross platform work you need a different cross platform tool. Then there is the question of will it look right on the platform? Technologies like Xamarin and NativeScript solve that problem, this will not.

- I've heard a comparison with when OS/2 was designed to run Windows applications to help capture the market from Windows and it did it poorly with the conclusion that Microsoft should expect the same result with Android and iOS apps running on Windows 10. Does this argument have any legs? Maybe in some ways, but not too much of a worry. OS/2 failed for many reasons, many of which had nothing to do with having Windows compatibility. But there is one area in particular where the analogy partially seems to hold true, handheld mobile devices. Like OS/2, Windows is not the dominant player in this space and is fighting entrenched leaders. But even then I don't give the argument too many legs. Like OS/2, Windows 10 will will likely stand or fall based on its strengths in the tablet space and will have an uphill battle in the mobile space just because there is so much momentum behind the leaders. If there is any detrimental impact of Android or Objective-C code on Windows 10 will be small next to that. Given the potential upside of additional applications, certainly a viable and likely small risk.

- Applications that rely on platform specific services like HealthKit or Google Play Services are unlikely to just work. The upshot of the deal, if you are writing an Objective-C or Android Java applications that accesses those services then all of the cross platform concerns come into play, just like they do writing a Xamarin application. Suddenly you have to think clearly about things like inversion of control patterns around platform specific services and writing a different implementation for the Windows platform that may change or even disable functionality.

- Microsoft has made a big deal of giving away Windows 10 and trying to get people to move. Now we see part of the reason as these capabilities are unlikely to be back ported to Windows 8.1 or Windows Phone. So the quicker users move the better. However, the enterprise is notoriously slow to move. How much this lag will carry over to the tablet space remains to be seen but it has been a much faster cycle for mobile phones.

- This move has obviously been made because it is very difficult to attract developers to a platform when there are few users and users to a platform when there are few applications. By lowering the bar to run many existing applications on Windows 10 they have made moves to help solve that equation and completely changed the price point to entry. However, this does have its limits. If I'm currently writing a native Android or iOS app, getting it to work on Windows is still not free. If I'm very lucky all I'm looking at is increased platform testing and perhaps compilation costs in terms of Objective-C. If I'm not lucky I'm re-architecting portions of my application to abstract out capabilities and services I can't access or otherwise don't work on Windows 10. For public facing apps on smart phone devices, software companies will still have to determine if that reduced cost is worth the 3% of US smart phone marketshare. Such investment may be much easier to justify in places like Europe where Windows Phone holds a 10% share.

Final thoughts
If this works well it will undoubtedly increase the attractiveness of the Windows 10 platform, particularly in the tablet space. No matter how you cut it, it is just another example in a long line of examples of how Microsoft has changed and become a very different company than it was a few short years ago. Microsoft continues to show us that it is a fighter and willing to make fundamental changes to stay relevant.

I feel great knowing that I can find enhanced utility in my ability to write Java and Objective-C. However, for my clients that need cross platform applications they almost always are looking at the two big smart phone players; Android and iOS. For that, I will continue to use tools like Xamarin and .Net.

I do wonder if this portends some future movement of MS into Xamarin's space. There were talks of acquisition last year that never materialized. Xamarin is a small player and that can work if they can hide in a niche. I see MS and Xamarin working more an more together so Microsoft is definitely getting interested in that niche. I know a lot of guys at Xamarin and they are a nice and passionate bunch that deserve credit and reward for what they have done to advance the cause and capabilities of X-Platform mobile development. No matter how this turns out I hope they receive the recognition and reward they deserve for their pioneering work.

This move by Microsoft makes a large shift in how I think about the different platforms and their capabilities and I look forward to continuing to evaluate the impact of this as we know more.

Sunday, March 22, 2015

Starting with Microsoft Band and Xamarin

Recently Xamarin released their API for Microsoft Band that works with Android, iOS and Windows Phone. It was a tough choice on what to play with before vacation;  a new Xamarin Forms preview that works with Windows Store and Windows Phone 8.1 was released as well as Xamarin Everywhere that hits Android Wear and Apple Phone. A complete overload of super cool stuff.

But ... last week I got a new Microsoft Band and you know, time to play.  First off, the Band isn't really a Smart Watch.  It's more a like a fitness device on steroids.  You can pull all kinds of sensor information out of it, you can also send notifications to it and play with it's appearance. What you can't really do is input information into the Band and have to do something on the phone. That is to say the band is about collecting sensor information and consuming information but not for inputting information like a "true" smart watch allows.

Xamarin has wrapped the Microsoft platform APIs, pretty much verbatim. One thing they have done which is nice is if the calls are asynchronous on Android, they have Task returning versions. However, like the Microsoft platform specific versions the APIs do not match from platform to platform so making cross platform code will still be challenging unless you wrap them in your own unified interface.  Xamarin has a nice page on the component store that explains the basics of the APIs which are pretty easy to use.  They can be found here:

https://components.xamarin.com/view/microsoft-band-sdk

With that in mind I set out to give this a try.  Since my Band is currently synchronized with an Android device I am working with the Android version of the API.  First I figured I'd try to add and then remove an icon from my Band that could receive notifications and messages.  I created a class to open and close the connection.

public class BandConnection : IDisposable
{
    private IBandClient bandClient;
    private Activity context;

    public BandConnection(Activity context)
    {
        this.context = context;
        var pairedBands = BandClientManager.Instance.GetPairedBands();

        if (pairedBands != null && pairedBands.Length >= 1)
        {
            bandClient = BandClientManager.Instance.Create(context, pairedBands[0]);
        }
    }

    public async Task ConnectAsync()
    {
        if (bandClient == null)
        {
            throw new InvalidOperationException("BandClient is not set");
        }
        await bandClient.ConnectTaskAsync();
    }

    public async void Dispose()
    {
        if (bandClient != null && bandClient.IsConnected)
        {
            await bandClient.DisconnectTaskAsync().ConfigureAwait(false);
        }
    }
}

The class just takes in the current activity and then gets the first band registered with the device. If you were making a "real" application it may be a good idea to make some sort of screen to choose what Band the user wanted to connect to if there were more than one.  The ConnectAsync method opens the connection to the Band.  As you can see I use the ConnectTaskAsync method of the BandClient instead of ConnectAsync.  All the asynchronous Android APIs seem to be wrapped up with Task returning operations with that naming convention.  When the class is disposed, if the bandClient is connected, the connection is closed.

I added a simple method to create a new tile on my band if there is room for one.

public async Task AddTileAsync(string tileId, string tileName, BandIcon largeIcon, BandIcon smallIcon)
{
    if (bandClient == null)
    {
        throw new InvalidOperationException("BandClient is not set");
    } 
    var tiles = await bandClient.TileManager.GetTilesTaskAsync().ConfigureAwait(false);
    var id = UUID.FromString(tileId);

    var spacesRemaining = await bandClient.TileManager.GetRemainingTileCapacityTaskAsync().ConfigureAwait(false);
    if (spacesRemaining > 0 && !tiles.Any(t => t.TileId.ToString() == tileId))
    {
        var tileBuilder = new BandTile.Builder(id, tileName, largeIcon);
        if (smallIcon != null)
        {
            tileBuilder.SetTileSmallIcon(smallIcon);
        }
        var tile = tileBuilder.Build();
        await bandClient.TileManager.AddTileTaskAsync(context, tile);
    }
}

I have added two images to my Android project, as per the API specs. One image is 24x24 and the other 48x48.  I create them and convert them into the BandIcon format. The following code is what I used to call the AddTileAsync method.

using (var bandConnection = new BandConnection(this))
{
    if (bandConnection.BandClient != null)
    {
        await bandConnection.ConnectAsync().ConfigureAwait(false);
        var smallIconBitmap = ((BitmapDrawable)Resources.GetDrawable(Resource.Drawable.PhoneFinderSmall)).Bitmap;
        var smallIcon = BandIcon.ToBandIcon(Bitmap.CreateScaledBitmap(smallIconBitmap, 24, 24, false));
        var largeIconBitmap = ((BitmapDrawable)Resources.GetDrawable(Resource.Drawable.PhoneFinderLarge)).Bitmap;
        var largeIcon = BandIcon.ToBandIcon(Bitmap.CreateScaledBitmap(largeIconBitmap, 48, 48, false));

        await bandConnection.AddTileAsync(BandConstants.TileId, "Band Test", largeIcon, smallIcon).ConfigureAwait(true);
    }
}

When using this code it automatically sinks up to the device.  The tile is identified by a unique identifier that I added as a constant to my code. When running it will first ask the user if they want to add the new tile to the Band. You can see my "awesome" abilities as an icon designer:


After choosing allow the band synchronizes the new tile onto the Band.


By scrolling the tiles on the band the newly added tile appears.


I then added a method to remove the tile I just added.

public async Task RemoveTileAsync(string tileId)
{
    if (bandClient == null)
    {
        throw new InvalidOperationException("BandClient is not set");
    } 
    var tiles = await bandClient.TileManager.GetTilesTaskAsync().ConfigureAwait(false);
    var id = UUID.FromString(tileId);
    if (tiles.Any(t => t.TileId.ToString() == tileId))
    {
        await bandClient.TileManager.RemoveTileTaskAsync(id).ConfigureAwait(false);
    }
}

This worked without incident and the tile from my band went away.

Sending a message to the band was also simple. The API reference contains the following description on the difference between a message and a dialog:

App notifications come in two flavors:
- Dialogs – dialog notifications are popups meant to quickly display information to the user. Once the user dismisses the dialog, the information contained therein does not persist on the Band.
- Messages – message notifications are sent and stored in a specific tile, and a tile can keep up to 8 messages at a time. Messages may display a dialog as well.

I added this method to my class to create a message:

public async Task ShowMessageAsync(string tileId, string title, string body, DateTime date, bool showMessage)
{
    if (bandClient == null)
    {
        throw new InvalidOperationException("BandClient is not set");
    }
    var id = UUID.FromString(tileId);
    await bandClient.NotificationManager.SendMessageTaskAsync(id, title, body, date, showMessage);
}

This method calls into my ShowMessageAsync method and gets the device location, converts it to an address and displays it to the user.

using (var bandConnection = new BandConnection(this))
{
    if (bandConnection.BandClient != null)
    {
        await bandConnection.ConnectAsync().ConfigureAwait(false);

        var geocoder = new Geocoder(this);
        var addressList = await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10).ConfigureAwait(false);

        var address = addressList.FirstOrDefault();
        if (address != null)
        {
            var deviceAddress = new StringBuilder();
            for (int i = 0; i < address.MaxAddressLineIndex; i++)
            {
                deviceAddress.Append(address.GetAddressLine(i))
                .AppendLine(",");
            }

            await bandConnection.ShowMessageAsync(BandConstants.TileId, 
                "Test Message", 
                string.Format("Current address: {0}", deviceAddress), 
                DateTime.Now, 
                true).ConfigureAwait(true);
        }
    }       
}

The message comes across to the band as expected.


Additionally, as expected, a message indicator appears with our tile stating that one new message was received.


When selecting the tile the message appears fully (I blocked out my address).


Sending a dialog is similarly easy.  But as this test indicates the amount of text that can be displayed in the dialog is limited and there is no down button (see more) as with the message.  Dialogs should only be used for very short notifications.

public async Task ShowDialogAsync(string tileId, string title, string body)
{
    if (bandClient == null)
    {
        throw new InvalidOperationException("BandClient is not set");
    }
    var id = UUID.FromString(tileId);
    await bandClient.NotificationManager.ShowDialogTaskAsync(id, title, body);
}

When sending this over it shows up as a popup but does not add to the message counter or add to the message history. As the API documentation stated, the dialog is not retained.


That's it for my first go.  Vibrating the band was similarly easy. Next I'll poke around at getting data from the Band and perhaps customizing its appearance.  Generally I was pleased at how easy it was to work with but cross platform applications may want to create a unified interface.