Showing posts with label Windows Phone. Show all posts
Showing posts with label Windows Phone. Show all posts

Wednesday, November 19, 2014

Universal Apps using the .NET client library for Google APIs

Hi all,

In the last couple weeks, Jesse and I improved the samples repository of the Google APIs client library for .NET with new samples for Windows and Windows Phone.
Jesse authored Translate.WP.TranslateText - a Windows Phone sample for the Google Translate API.
A week ago, I submitted a Blogger.Sample for Universal Store apps using the Google Blogger API.
These are the first samples in our repository that target Windows Phone 8.1 and Windows 8.1 apps using the .NET client library for Google APIs.

In this blog post I'll focus on the Universal Windows sample I created. The sample shares code between the Windows Store and Windows Phone versions, and uses MVVM best practices.

I must admit, the last time I wrote MVVM was back in 2011, back then I worked on a huge WPF project and while working on MVVM again I saw that nothing really has changed since then.

For those of you who don’t know, Universal Windows apps help you develop and share code between all Windows devices. You can read more about it in building-universal-windows-apps.
It's important to mention that I already had a hacky sample for Windows Phone 8.0 that I used to test a new release of the client library with it. I just thought that it is going to be easy to upgrade it to Windows Phone 8.1.

I WAS WRONG

I didn't find a right meme... any suggestion will be appreciated :)


Microsoft introduced significant breaking API changes when upgrading from 8.0 to 8.1. The WebAuthenticationBroker.AuthenticateAsync which I used in Windows Phone 8.0 isn't supported anymore. Starting with Windows 8.1, Microsoft supports several AndContinue methods (one of them is WebAuthenticationBroker.AuthenticateAndContinue). When you call an AndContinue method, the app is deactivated until the operation completes. You can read more in How to continue your Windows Phone Store app after calling an AndContinue method.

So, in order to support the OAuth 2.0 protocol for Windows Phone Store apps, I had to do the following:


Step 1

Create core classes that I’m going to move shortly to Google.Apis and Google.Apis.Auth new projects that will target Windows Phone 8.1. Those classes include the following:

  1. PasswordVaultDataStore
A Windows Phone implementation of IDataStore. It uses the platform PasswordVault. PasswordVault represents a credential locker and its content is private for each app and can’t be used by other apps or services in the phone.

  1. AuthorizationCodeBroker
An implementation of ICodeReceiver. The important method is ReceiveCodeAsync which should be called twice.
In the 1st time, the method calls WebAuthenticationBroker.AuthenticateAndContinue so that users would be able to authorize this app to access their personal resources.
In the 2nd time, it should be called after the app had already received the authorization code. The implementation counts on the developer to store the code response in the PasswordVaultDataStore using WebAuthResult.Name. (see changes in MainPage.xaml.cs later on…)

  1. AuthorizationCodeWPInstalledApp
An implementation of IAuthorizationCodeInstalledApp, that uses the standard AuthorizationCodeInstalledApp with the AuthorizationCodeBroker mentioned above.

  1. GoogleWebAuthorizationBroker
A helper class that puts everything together - the installed app and the password vault data store.


* All those classes are very similar to classes that we already have for supporting Windows Store applications or Windows Phone 8.0.


Step 2

In addition, each Windows Phone app that wants to support continuation should implement the following:

ContinuationManager

A custom and a very short implementation that targets authentication ONLY. The full implementation is available here: http://msdn.microsoft.com/en-us/library/dn631755.aspx. Take a look in this short version:
App.xaml.cs
The application starting point. The important method is OnActivated, which might be called after the authorization code was received. The implementation looks like the following:
MainPage.xaml.cs
The first time the users log in to the app, the app should be suspended and the users must authorizes the app in order to access their private resources. When the app is activated again, it calls the continuation manager which in turn calls the ContinueWebAuthentication method. I think that the method is self documented, so without any words, take a look:

The only piece that is still missing to you now, is the BlogsViewModel and the BloggerRepository. Those two classes (and several others) are shared between the Windows and Windows Phone projects.
BlogsViewModel is just the ViewModel of the MainPage. When the users request to get all their blogs, the GetBlogsCommand is called. Then GetBlogsAsync will be executed and in turn it will call the repository to retrieve all blogs.
And the BloggerRepository looks like the following:
* Note that the implementation of GoogleWebAuthorizationBroker is different for Windows and Windows Phone apps.
Take a look in the code sample at Blogger.Sample. You will find all the missing pieces there, like IBloggerRepository, BlogViewModel, PostViewModel, MainPage and other classes. Just remember to follow the README file in order to setup and run the app.


Upstate NY, Oct 2014


Stay tuned for further documentation - the Windows Phone 8.1 section is going to be refreshed soon.



We hope you find our new sample useful when writing Windows Phone 8.1 apps with Google Apis. Let us know if you have any questions in the comments of this post, on the client issue tracker or in Stack Overflow using the google-api-dotnet-client tag (Preferred).



Enjoy!
Eyal (upside down)

Sunday, June 1, 2014

1.8.2 is here :)

Hi all,
Several days ago I released a new version of the core Google APIs client library for .NET (version 1.8.2)

This release includes several bug fixes, such as fixing MaxUrlLengthInterceptor to not delete the last character of a URL and improving FileDataStore to support an absolute path folder.

The full issues list is available in the library's latest blogpost.

In addition, from this release we support token revocationUserCredential now contains a new RevokeTokenAsync method which revokes the current token.

Later on, you can reauthorize the user again by calling GoogleWebAuthorizationBroker's ReauthorizeAsync. By doing so, the user will have to reauthorize your application to use his or her private resources.

Take a look in the following snippet:

Note the following:
  1. You should already be familiar with lines 1-20. Those lines contain the creation of user credentials and a book service, and a sample request to this service.
  2. In line 23 there is a call to the new RovokeTokenAsync method. From this point the access token is invalid and it is removed form the data store.
  3. Then, any request using the current credentials will fail, because the access token was revoked (lines 25-33).
  4. In this point, the user can reauthorize the application again to access his or her private resources, by calling to ReauthorizeAsync (line 37).

While working on this release I encountered the following error over and over again while trying to compile a Windows Phone sample using the new 1.8.2 library:


Error 3 Cannot resolve reference assemblies. Please check the reference assemblies. Cannot resolve dependency to assembly 'Google.Apis, Version=1.8.1.31687, Culture=neutral, PublicKeyToken=null' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.

It took me a lot of time to understand what is the exact problem, and I finally found a solution in this blogpost: http://www.ideatoappster.com/how-to-overcome-windows-phone-8-xaml-compilation-errors/.
Thanks Mr. Gill :) 
All I had to do is to change the following line in the Windows Phone project file:
<ValidateXaml>true</ValidateXaml>
And set the validate XAML tag to false.
That's all.


SF view from the Golden Gate Bridge, May 2014

The countdown continues... In 10 days I'm going to arrive in Brazil and in 12 days I'm going to watch my first world cup game ever. And... what an amazing game to start with: Spain-Holland.
Bom dia amigos!

Friday, October 25, 2013

1.6.0-beta is available!

Hi all, happy 1.6.0-beta everyone!

We just announced a new release of the .NET client library for Google APIs as you can find in this announcement post. The blogpost contains all the release highlights, so you should take a look at it before you upgrade.

This release introduced a new Google.Apis.Auth NuGet package for making authenticated calls to Google services. It supports .NET 4 applications as well as Windows Phone, Windows Store applications and Portable Class Libraries.
For supporting ASP.NET MVC applications we also provide the Google.Apis.Auth.MVC package.

The old Google.Apis.Authentication package, which depends on DotNetOpenAuth, is now obsolete and we are not going to support this package any more.
Feel free to read more in our OAuth2 wiki page for instructions how to use this package on different Windows platforms with different OAuth2 flows.

The following lines of code present how easy it is to use a Google service from WP:

           UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
               new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read),
               new[] { DriveService.Scope.Drive },
               "user", CancellationToken.None);


           var service = new DriveService(new BaseClientService.Initializer
               {
                   HttpClientInitializer = credential,
                   ApplicationName = "WP Drive Sample Application”
               });


           // DO YOUR MAGIC HERE… Sample code could look like the following:
           var list = await service.Files.List().ExecuteAsync();

And in a Windows Store applications your code should look something like the following:

           UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
               new Uri("ms-appx:///Assets/client_secrets.json"),
               new[] { Uri.EscapeUriString(CalendarService.Scope.Calendar) },
               "user", CancellationToken.None);

           var service = new CalendarService(new BaseClientService.Initializer
               {
                   HttpClientInitializer = credential,
                   ApplicationName = "Store sample",
               });
            
           // DO YOUR MAGIC HERE… Sample code could look like the following:
           var calendarListResource = await service.CalendarList.List().ExecuteAsync();

It looks like it's the exact same code, but of course that's our intention - having one user experience for every platform. You can imagine what sample code for .NET 4 applications would look like.

Things you should be aware of:
  1. GoogleWebAuthorizationBroker is a utility class which exists in the WP and WinRT extensions. You will get it from NuGet when you target the appropriate platform. It manages all the OAuth2 "dance" for you, including redirecting the user to Google authorization server for first login and saving the user's access token and refresh token (for future use) in a specific data store for WP or WinRT applications, etc.
  2. UserCredential, the output of the AuthorizeAsync method, implements IConfigurableHttpClientInitializer, IHttpExecuteInterceptor and IHttpUnsuccessfulResponseHandler. It implements the initializer so it will be able to add itself as an unsuccessful response handler (for refreshing the token on 401 responses) and as an execute interceptor (to add the authorization header for every request). Read more here.
  3. Plugging this OAuth2 solution into your service is done by adding the UserCredential as HttpClientInitializer. That's all!

Indian Summer, Upstate NY 2013














Happy 1.6.0-beta!

Happy Halloween!

Enjoy,


Eyal