Showing posts with label Xamarin. Show all posts
Showing posts with label Xamarin. Show all posts

Thursday, November 6, 2014

Authentication with third party Auth providers in new era of Mobile Apps

When you are developing app, to increase security and manipulate users without taking user details is use authentication providers help such like Live, Google, Facebook, twitter , linked in, flickers etc.

With the newer versions of mobile BCL is not supported the olde way of authenticating with third party SDK's. All the BCL are updated with 8.1 and Universal apps.

With this post I'm gonna explain how to implement those authentication (ex: facebook)

1. you need to have facebook app. (http:\\developer.facebook.com)

To implement the Authentication you need to create separate class and interface that can handle Continuation events. Once authentication done it will redirect to the app using these Continuation objects.

Here is ContinuationManager Class that I used

using System.Text;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
 
#if WINDOWS_PHONE_APP
    /// <summary>
    /// ContinuationManager is used to detect if the most recent activation was due
    /// to a continuation such as the FileOpenPicker or WebAuthenticationBroker
    /// </summary>
    public class ContinuationManager
    {
        IContinuationActivatedEventArgs args = null;
        bool handled = false;
        Guid id = Guid.Empty;
 
        /// <summary>
        /// Sets the ContinuationArgs for this instance. Using default Frame of current Window
        /// Should be called by the main activation handling code in App.xaml.cs
        /// </summary>
        /// <param name="args">The activation args</param>
        internal void Continue(IContinuationActivatedEventArgs args)
        {
            Continue(args, Window.Current.Content as Frame);
        }
 
        /// <summary>
        /// Sets the ContinuationArgs for this instance. Should be called by the main activation
        /// handling code in App.xaml.cs
        /// </summary>
        /// <param name="args">The activation args</param>
        /// <param name="rootFrame">The frame control that contains the current page</param>
        internal void Continue(IContinuationActivatedEventArgs args, Frame rootFrame)
        {
            if (args == null)
                throw new ArgumentNullException("args");
 
            if (this.args != null && !handled)
                throw new InvalidOperationException("Can't set args more than once");
 
            this.args = args;
            this.handled = false;
            this.id = Guid.NewGuid();
 
            if (rootFrame == null)
                return;
 
            switch (args.Kind)
            {
               
 
                case ActivationKind.WebAuthenticationBrokerContinuation:
                    var wabPage = rootFrame.Content as IWebAuthenticationContinuable;
                    if (wabPage != null)
                    {
                        wabPage.ContinueWebAuthentication(args as WebAuthenticationBrokerContinuationEventArgs);
                    }
                    break;
            }
        }
 
        /// <summary>
        /// Marks the contination data as 'stale', meaning that it is probably no longer of
        /// any use. Called when the app is suspended (to ensure future activations don't appear
        /// to be for the same continuation) and whenever the continuation data is retrieved 
        /// (so that it isn't retrieved on subsequent navigations)
        /// </summary>
        internal void MarkAsStale()
        {
            this.handled = true;
        }
 
        /// <summary>
        /// Retrieves the continuation args, if they have not already been retrieved, and 
        /// prevents further retrieval via this property (to avoid accidentla double-usage)
        /// </summary>
        public IContinuationActivatedEventArgs ContinuationArgs
        {
            get
            {
                if (handled)
                    return null;
                MarkAsStale();
                return args;
            }
        }
 
        /// <summary>
        /// Unique identifier for this particular continuation. Most useful for components that 
        /// retrieve the continuation data via <see cref="GetContinuationArgs"/> and need
        /// to perform their own replay check
        /// </summary>
        public Guid Id { get { return id; } }
 
        /// <summary>
        /// Retrieves the continuation args, optionally retrieving them even if they have already
        /// been retrieved
        /// </summary>
        /// <param name="includeStaleArgs">Set to true to return args even if they have previously been returned</param>
        /// <returns>The continuation args, or null if there aren't any</returns>
        public IContinuationActivatedEventArgs GetContinuationArgs(bool includeStaleArgs)
        {
            if (!includeStaleArgs && handled)
                return null;
            MarkAsStale();
            return args;
        }
    }
 
    /// <summary>
    /// Implement this interface if your page invokes the web authentication
    /// broker
    /// </summary>
    interface IWebAuthenticationContinuable
    {
        /// <summary>
        /// This method is invoked when the web authentication broker returns
        /// with the authentication result
        /// </summary>
        /// <param name="args">Activated event args object that contains returned authentication token</param>
        void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args);
    }

To handle the continuation after authentication you nee to modify your app.xaml.cs as well. Because Once you redirect to auth providers screen you are exit (deactivate) your app. then once auth provider redirect back your app gets activate .

Create object of ContinuationManager  in App.xml.cs

public static ContinuationManager continuationManager { getprivate set; }

Then OnActivated event of the app add the continuation handle

protected async override void OnActivated(IActivatedEventArgs e)
{
   continuationManager = new ContinuationManager();
 
   //Check if this is a continuation 
   var continuationEventArgs = e as IContinuationActivatedEventArgs;
   if (continuationEventArgs != null)
   {
	continuationManager.Continue(continuationEventArgs);
   }
 
  Window.Current.Activate(); 
}



Then you are free to go with any kind of authentication that provide from auth provider 

    internal async Task FacebookLoginMethod()
        {
            String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString("Your app Id") + "&redirect_uri=" + Uri.EscapeDataString("https://m.facebook.com/dialog/return/ms") + "&scope=read_stream&display=popup&response_type=token";
 
            System.Uri StartUri = new Uri(FacebookURL);
//To use windows phone or windows app with Fb authentication user this end uri and redirect uri. Both are working 
             System.Uri EndUri = new Uri("https://m.facebook.com/dialog/return/ms");
 
#if WINDOWS_PHONE_APP
            try
            {
                WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
            }
            catch
            {
 
            }
#endif
        }


and use this ContinueWeb authentication method inside the page that you call authentication. otherwise it will not working. Inherit the IWebAuthnticationContinuable interface to the page and add this method

public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
       {
           WebAuthenticationResult result = args.WebAuthenticationResult;
           if (result.ResponseStatus == WebAuthenticationStatus.Success)
           {
               token = await FilterToken(result.ResponseData.ToString());
 
           }
           else
           {
               MessageDialog Msg = new MessageDialog("Login failed");
               Msg.ShowAsync();
           }
 
       }


This WebAuthentication result wil contains the Authprovider's access token. Filterout it and do what ever graph is available with authentication provider. 


Enjoy ..








HttpClient Caching

Is any one of you have an experience on when send http request through http client the response become the same (no change) even your source of the response (server) is updated.

It is the way that default http protocol behaves

By default HttpClient use a cache to store responses that come up with response headers without Cache-Control header. ( Ref: HTTP Header fields)

In a scenario you need to change the cache behavior with HttpClient you can have two options

1. Edit the service (server) to response with relevant cache headers
2. Modify your request headers

Edit the service (server) to response with relevant cache headers

In this model it give two benefits to you
  • A content you will not use again is not stored in the client machine.
  • Other requests can benefit from the cache (when using the same instance of HttpClient).
In your web service go to web.config file and in-side the system.serviceModel add following tag with relevant headers you need


     <client>
      <endpoint address="http://localhost/..." >
        <headers>
          <Cache-Control>no-cache</Cache-Control>
        </headers>
      </endpoint>
    </client>


Modify your request headers

if you don't have the access to the server you can go with this option. Just ad additional header with HttpClient and send the request then response automatically include these headers

HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Cache-Control""no-cache");


Now your HttpClient is ready to handle http request with no cache .


here is Cache contol values that provide from W3 with Http headers.

    cache-directive = cache-request-directive
         | cache-response-directive
    cache-request-directive =
           "no-cache"                          
         | "no-store"                          
         | "max-age" "=" delta-seconds         
         | "max-stale" [ "=" delta-seconds ]   
         | "min-fresh" "=" delta-seconds       
         | "no-transform"                      
         | "only-if-cached"                    
         | cache-extension                     
     cache-response-directive =
           "public"                               
         | "private" [ "=" <"> 1#field-name <"> ] 
         | "no-cache" [ "=" <"> 1#field-name <"> ]
         | "no-store"                             
         | "no-transform"                         
         | "must-revalidate"                      
         | "proxy-revalidate"                     
         | "max-age" "=" delta-seconds            
         | "s-maxage" "=" delta-seconds           
         | cache-extension 
 
 
 
 Enjoy the code .. 
 
 




Saturday, October 11, 2014

Windows Azure Mobile Authentication Service

Magic with Azure mobile services is easy handling in Authentication for users. It allows you to authenticate users
1. Microsoft Account
2. Facebook Account
3. Twitter Account
4. Google Account
5. Azure Active Directory

What else developer need..

To enable all of those authentications you need to have apps running on those platforms. Url's for creating apps on each service provider is given below (Creating app on your hand *Get the developer manual help according to each technology)

1. Microsoft - https://account.live.com/developers/applications
2. Facebook - https://developers.facebook.com/ (Click on App's menu)
3. Twitter - https://apps.twitter.com/app/new
4. Google - https://console.developers.google.com/project

** In every instance that you create apps use your Azure Mobile Service Url 
HERE is URL for Microsoft Login
for json backend :https://<mobile_service>.azure-mobile.net/login/microsoftaccount
for .NET backend :https://todolist.azure-mobile.net/signin-microsoft


With later posts you can see how to use Azure Active directory

Start from the beginning

1. First login to your Azure portal and go to Mobile Services



2. Then select your Mobile Service , in here I have already created Mobile Service for the Azure Mobile Services post named as prabathblog. Select it and go inside. Then select IDENTITY  Tab from menu.














3. Fill the values according to the Login provider with details


4. Then go to the dashboard and download the app.

5. Use this code to authenticate in client side

        /// <summary>
        /// Simple authenticate
        /// </summary>
        /// <returns></returns>
        private async Task AuthenticateAsyncSimple()
        {
            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    message =
                        string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
 
                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();
            }
        }


Enjoy your code







Saturday, September 13, 2014

Improve Performance of the Application

As and software producer all of us want to do is software product with correct functionality. Is that enough ? No. We need to give product with correct functionality with optimum resource consumption as well.

Today I'm going to tell you some tips and trikes about resource optimization. basically it is about Memory and CPU resources.

1. Switch for multiple If
 When you are using multiple If conditions ( Most of the time more than 2 ) CPU (Registry level) instructions check as far as use much If with code. It consume more registers in CPU. But with switch it just use check and Jump CPU instruction that far more faster than assignments. Using jump tables makes switches much faster than some if-statements

Use switch when ever possible once you find more than two if statements.

2. Use structures according to the situation
Execution of class is much more consume resources than class.  Whenever you don't need to use functions bind with objects and when you don't go with boxing and unboxing much with code.

3. Chunky calls
Don't let your functions to handle lot of task by itself. use modularity to avoid it.

4. Add Collections
Never try to assign collection items one by one to the another collection. Just try to use simple casting and try to add entire collection directly.

5. Working with strings.
When you are working with string most of the cases we try to concatenate string by '+'operator.(including me ). But sad story is there is more optimal solution than that. use string bulider to concatenate strings.

Here for start.

6. Use bits whenever as possible.
I saw most of the programmers use integers/strings to hold the simple states, flags. Please don't do that there is more than 2 states. Just use bit or bool to store states. It will optimize code and resource as well. ( Simply bit is smaller than more bits)

7. Array as possible
When we use simple basic array it will helpful to maintain machine instructions(registry). Other collections need more than array because most of them are derived form it. Array is basic element in modern machine instructions.

8. ObservableCollection vs List
Use List whenever that your items not binded with the UI. Observation collections are derived from List and it also holds the property changed notifications. If there is no use of property change go for List.  ObservableCollection check the property change when it on use and because of that it consume more.

9. For than foreach
Use while, for and do while loops wherever than foreah. foreach has good performance but basic loops are better than it.

10. ToString
Some  programmers use ToString method wherever elements are already strings. Use ToString wherever the element that con the string. don't use ToString as habit. With integers use
ToStringLookup will optimize memory heap that using with converting integer.

11. Don't sort collections already sorted.
Check collection already sorted or not before sort it.

12. Global variables.
Use global variables when you using same type of object frequently

13. Constant and static
Constants are not assignable memories but they are easy to load.

Static is more faster than instant creations. When load statics no need of run time to check the instance



Hope this is helps...



Friday, June 20, 2014

Cross platform Development With Xamarin

Having a same App on all major platforms and all of them are shared a same  source code is dream. But today it is not. There is several tools to do that  here few of them,

  • Xamarin
  • PhoneGap
  • Rho Mobile
  • Appcelerator
  • Widget Pad
  • Whoop
  • MoSync
  Importance of Xamarin is ,
  • Share code between platforms
  • Using .NET skills
  • C# Language
  • Let developers create UI’s that are unique to each platform.
Xamarin is cross platform development tool that created by Xamarin Studio and it supports to build applications on Windows , iOS and Android platforms.

 Most importantly it have integration with rich IDE , Visual Studio.

You can download Xamarin Trial version here.
https://store.xamarin.com/account/my/subscription/computers

Try it and Enjoy.