c# - Making a prettier Facebook Login Screen for Parse.com Server with Xamarin.Android -


im trying create login system xamarin.android used on parse server. want login user facebook , save real name , small user photo. current code of displaying login system this:

using xamarin.auth;  loginfacebookbutton.click += (sender, e) =>         {              if (crossconnectivity.current.isconnected)                 logintofacebook();             else             {                 displaynoconnectivitymessage();             }          };          logintwitterbutton.click += (sender, e) =>         {             logintotwitter();         };     }      void displaynoconnectivitymessage()     {         alertdialog.builder alert2 = new alertdialog.builder(this);         alert2.settitle("network error");         alert2.setmessage("connection internet required. please check connectivity , try again.");         alert2.show();      }      void displayloadingmessage(bool dismiss)     {         runonuithread(() =>         {             if (!dismiss)             {                 builder = new alertdialog.builder(this);                  builder.settitle("signing in");                 builder.setmessage("please wait...");                 builder.setcancelable(false);                 alert = builder.create();                 alert.show();              } else {                 if (alert != null)                     if (alert.isshowing)                     {                          alert.dismiss();                         alert.dispose();                     }             }         });      }      async void logintofacebook()     {         var auth = new oauth2authenticator(             clientid: "809804315805408",             scope: "user_about_me",             authorizeurl: new uri("https://m.facebook.com/dialog/oauth/"),             redirecturl: new uri("http://www.facebook.com/connect/login_success.html")         );          auth.allowcancel = false;          // if authorization succeeds or canceled, .completed fired.         auth.completed += logincomplete;          var intent = auth.getui(this);         startactivity(intent);     }      public async void logincomplete(object sender, authenticatorcompletedeventargs e)     {         string id = "";         string name = "";         jsonvalue obj;         if (!e.isauthenticated)         {             var builder = new alertdialog.builder(this);             builder.setmessage("not authenticated");             builder.setpositivebutton("ok", (o, c) => { });             builder.create().show();             return;         }         else {              displayloadingmessage(false);             accountstore.create(this) .save(e.account, "facebook");             // we're logged in, make oauth2 request user's info.             var request = new oauth2request("get", new uri("https://graph.facebook.com/me"), null, e.account);             await request.getresponseasync().continuewith(t =>             {                 var builder2 = new alertdialog.builder(this);                 if (t.isfaulted)                 {                     builder2.settitle("error");                     builder2.setmessage(t.exception.flatten().innerexception.tostring());                     builder2.show();                 }                 else if (t.iscanceled)                 {                     builder2.settitle("task canceled");                     builder2.show();                 }                 else {                     obj = jsonvalue.parse(t.result.getresponsetext());                     id = obj["id"];                     name = obj["name"];                 }                  builder.setpositivebutton("ok", (o, c) => { });                 builder.create();             }, uischeduler);              var accesstoken = e.account.properties["access_token"];             var expiresin = convert.todouble(e.account.properties["expires_in"]);             var expirydate = datetime.now + timespan.fromseconds(expiresin);             var user = await parsefacebookutils.loginasync(id, accesstoken, expirydate);              try             {                 user.add("name", name);             }             catch (exception ex)             {                 console.writeline("loginfragment.cs | logincomplete() :: user.add (\"name\",name); :: " + ex.message);             }              var webclient = new webclient();             //var httpclient = new httpclient(new nativemessagehandler());             var url = new uri("http://graph.facebook.com/" + id + "/picture?type=small");             application.currentuserimageurl = url.tostring();             application.currentusername = name;             byte[] bytes = null;             //bytes = await httpclient.getbytearrayasync(url);             bytes = await webclient.downloaddatataskasync(url);              parsefile saveimagefile = new parsefile("profileimage.jpg", bytes);             try             {                 user.add("profile_pic", saveimagefile);             }             catch (exception ex)             {                 console.writeline("loginfragment.cs | logincomplete() :: user.add (\"profile_pic\",saveimagefile); :: " + ex.message);             }              application.currentuser = user;             await user.saveasync();             displayloadingmessage(true);             changescreen();         }     } 

the problem code this:

  1. after login success message displayed (a simple success message on white page) must facebook , dont wnat displayed on user.
  2. while logincompete code running app working on background , user doesn't see anyhting, app closes , after login opens again. have try display alertdialog function displaynoconnectivitymessage doesnt shown in user dont know way.

the easiest way login facebook on parse official parse sdk in combination offical facebook android sdk handle single-sign on scenario.

with small steps achieve expected result:

  1. follow small guide setup app facebook sdk: https://components.xamarin.com/gettingstarted/facebookandroid

  2. setup parse sdk

    public app() {     // app.xaml initialization     parseclient.initialize("your application id", "your .net key");     parsefacebookutils.initialize("your facebook app id");     // other initialization } 
  3. add fb login button view.

    <com.facebook.login.widget.loginbutton   android:id="@+id/login_button"   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:layout_gravity="center_horizontal"   android:layout_margintop="30dp"   android:layout_marginbottom="30dp" />    
  4. get callback , use token signin user parse.

    public class mainactivity : activity, ifacebookcallback {     protected override void oncreate(bundle bundle)     {         base.oncreate(bundle);          // set our view "main" layout resource         // setcontentview (resource.layout.main);          var callbackmanager = callbackmanagerfactory.create();          var loginbutton = findviewbyid<loginbutton>(resource.id.login_button);         loginbutton.registercallback(callbackmanager, this);     }      #region ifacebookcallback      public void oncancel()     {         // handle cancel     }      public void onerror(facebookexception error)     {         // handle error     }      public async void onsuccess(object result)     {         // know loginresult         var loginresult = (loginresult) result;          // convert java.util.date datetime         var epoch = new datetime(1970, 1, 1, 0, 0, 0, datetimekind.utc);         var expiredate = epoch.addmilliseconds(loginresult.accesstoken.expires.time);          // fb user accesstoken         var accesstoken = loginresult.accesstoken.token;          parseuser user = await parsefacebookutils.loginasync("your facebook app id", accesstoken, expiredate);     }      #endregion ...  } 
  5. (optional) interact facebook sdk & parseuser

    // can pass acquired accesstoken graphrequest var parameters = new bundle(); parameters.putstring("fields", "id,email,gender,cover,picture.type(small)"); var request = new graphrequest(loginresult.accesstoken, "me", parameters, httpmethod.get);  // execute request , handle response (see fb android sdk guide) // image byte[] graphresponse byte[] data;  // store image parseuser user["image"] = new parsefile("image.jpg", data); 

instead of using graphrequest can fallback httpclient / webclient , pass accesstoken url parameter. docs

additional

here link official docs: http://parseplatform.github.io/docs/dotnet/guide/#facebook-users

pick sdk nuget: https://www.nuget.org/packages/xamarin.facebook.android/

the xamarin facebook android sdk works java sdk docs worth at: https://developers.facebook.com/docs/facebook-login/android#addbutton


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -