public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			var auth = new OAuth1Authenticator ("Ywun66NxYNMXgjzNRdIG12q4k",
				"XQAQ5djSlMOiXfMhn5rl4fdPahqw0wNPW6nBS5I9aRCajbxMvJ",
				new Uri("https://api.twitter.com/oauth/request_token"),
				new Uri("https://api.twitter.com/oauth/authorize"),
				new Uri("https://api.twitter.com/oauth/access_token"),
				new Uri("http://mobile.twitter.com"));

			auth.Completed += (sender, e) => {
				DismissViewController (true, null);
				if (e.IsAuthenticated) {

					loggedInAccount = e.Account;
					GetUserData ();
					var mList =   GetTwitterData();
					mList.ContinueWith(async (Task<List<Status>> arg) =>{
						myList = arg.Result;
						//twitterHomeTableView.Source = new TwitterHomeSource(arg.Result.ToArray());
					});


				}

			};

			var ui = auth.GetUI();
			PresentViewController(ui, true, null);
		}
		public override  void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			var auth = new OAuth1Authenticator ("Ywun66NxYNMXgjzNRdIG12q4k",
				"XQAQ5djSlMOiXfMhn5rl4fdPahqw0wNPW6nBS5I9aRCajbxMvJ",
				new Uri("https://api.twitter.com/oauth/request_token"),
				new Uri("https://api.twitter.com/oauth/authorize"),
				new Uri("https://api.twitter.com/oauth/access_token"),
				new Uri("http://mobile.twitter.com"));

			auth.Completed += (sender, e) => {
				DismissViewController (true, null);
				if (e.IsAuthenticated) {

					loggedInAccount = e.Account;
					GetUserData ();
					var mList = GetTwitterData().ToString();
					PresentViewController(new TwitterTimelineTabController(mList), true, null);
				}

			};

			var ui = auth.GetUI();
			PresentViewController(ui, true, null);



		}
Esempio n. 3
0
		public override  void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			this.NavigationItem.Title = "Home";
			var auth = new OAuth1Authenticator ("Ywun66NxYNMXgjzNRdIG12q4k",
				"XQAQ5djSlMOiXfMhn5rl4fdPahqw0wNPW6nBS5I9aRCajbxMvJ",
				new Uri("https://api.twitter.com/oauth/request_token"),
				new Uri("https://api.twitter.com/oauth/authorize"),
				new Uri("https://api.twitter.com/oauth/access_token"),
				new Uri("http://mobile.twitter.com"));

			auth.Completed += (sender, e) => {
				DismissViewController (true, null);
				if (e.IsAuthenticated) {
					

					loggedInAccount = e.Account;
					GetUserData ();
					var mList =   GetTwitterData();

					TableView.RowHeight = UITableView.AutomaticDimension;
					TableView.EstimatedRowHeight = 160;

					TableView.Source = new TwitterHomeSource(mList.ToArray());
					//twitterHomeTableView.ReloadData();




				}

			};

			var ui = auth.GetUI();
			PresentViewController(ui, true, null);



		}
Esempio n. 4
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task.
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();
#if __ANDROID__ || __IOS__
#if __ANDROID__
            // Get the current Android Activity
            Activity activity = (Activity)Android.App.Application.Context;
#endif
#if __IOS__
            // Get the current iOS ViewController.
            UIViewController viewController = null;
            Device.BeginInvokeOnMainThread(() =>
            {
                viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            });
#endif
            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
#if __IOS__
                    // Dismiss the OAuth UI when complete.
                    viewController.DismissViewController(true, null);
#endif

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    authenticator.OnCancelled();
                }
                finally
                {
                    // Dismiss the OAuth login.
#if __ANDROID__
                    activity.FinishActivity(99);
#endif
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
#if __ANDROID__
                        activity.FinishActivity(99);
#endif
                    }
                }

                // Cancel authentication.
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password.
#if __ANDROID__
            var intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);
#endif
#if __IOS__
            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            Device.BeginInvokeOnMainThread(() =>
            {
                viewController.PresentViewController(authenticator.GetUI(), true, null);
            });
#endif
#endif // (If Android or iOS)
            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization is in progress
            if (_taskCompletionSource != null)
            {
                // Allow only one authorization process at a time
                throw new Exception();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            Xamarin.Auth.OAuth2Authenticator auth = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: new Uri(AuthorizeUrl),
                redirectUrl: new Uri(OAuthRedirectUrl));

            // Allow the user to cancel the OAuth attempt
            auth.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            auth.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete
                    this.DismissViewController(true, null);

                    // Throw an exception if the user could not be authenticated
                    if (!authArgs.IsAuthenticated)
                    {
                        throw new Exception("Unable to authenticate user.");
                    }

                    // If authorization was successful, get the user's account
                    Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                    // Set the result (Credential) for the TaskCompletionSource
                    _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.SetException(ex);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            auth.Error += (sndr, errArgs) =>
            {
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    _taskCompletionSource.TrySetException(new Exception(errArgs.Message));
                }
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password
            InvokeOnMainThread(() =>
            {
                this.PresentViewController(auth.GetUI(), true, null);
            });

            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
Esempio n. 6
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be cancelled
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            Xamarin.Auth.OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: _appClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false
            };

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Check if the user is authenticated
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication
                    authenticator.OnCancelled();
                }
                finally
                {
                    // End the OAuth login activity
                    FinishActivity(99);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: end the OAuth login activity
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        FinishActivity(99);
                    }
                }

                // Cancel authentication
                authenticator.OnCancelled();
            };

            // Present the OAuth UI (Activity) so the user can enter user name and password
            Android.Content.Intent intent = authenticator.GetUI(this);
            StartActivityForResult(intent, 99);

            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
Esempio n. 7
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            // Try to cancel any existing authentication process.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            _auth = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: new Uri(OAuthRedirectUrl))
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            _auth.Completed += (o, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete.
                    InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); });

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    _auth.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            _auth.Error += (o, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    _taskCompletionSource?.TrySetCanceled();
                }

                // Cancel authentication.
                _auth.OnCancelled();
                _auth = null;
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_auth.GetUI(), true, null); });

            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);

			SetContentView (Resource.Layout.layout_iniciar_sesion);

			Typeface font = Typeface.CreateFromAsset (Application.Context.Assets, "Fonts/HelveticaNeue-Thin.otf");
			var btnIniciar = FindViewById<Button> (Resource.Id.btnIniciar);
			var txtContraseña = FindViewById<TextView> (Resource.Id.txtContraseñaSesion);
			var txtEmail = FindViewById<TextView> (Resource.Id.txtEmailSesion);

			btnIniciar.SetTypeface (font, TypefaceStyle.Normal);

			_supporttoolbar = FindViewById<Android.Support.V7.Widget.Toolbar> (Resource.Id.ToolBarSesion);
			var ToolbarTitle = FindViewById<TextView> (Resource.Id.toolbar_sesion);
			ToolbarTitle.SetText (Resource.String.Sesion);
			SetSupportActionBar(_supporttoolbar);
			SupportActionBar.SetDisplayHomeAsUpEnabled(false);


			btnIniciar.Click += (object sender, EventArgs e) => {
				btnIniciar.SetBackgroundColor (Color.White);
				btnIniciar.SetTextColor (Color.Orange);
				string string_key = "41f579fc-1445-4065-ab10-c06d50e724d3";
				string UserEmail = txtEmail.Text.Trim ();
				string Password = txtContraseña.Text.Trim ();

				try {

					services_911consumidor_com.COCOService cliente = new Navigation_View.services_911consumidor_com.COCOService ();
					services_911consumidor_com.UserDTO Usuario = new Navigation_View.services_911consumidor_com.UserDTO ();

					Usuario = cliente.AccountLogin (new Navigation_View.services_911consumidor_com.UserDTO {
						Email = UserEmail,
						Password = Password
					}, string_key);

					Xamarin.Auth.Account account = new Xamarin.Auth.Account (Usuario.Email, AccountCore.Dictionary (Usuario.FirstName, Usuario.Email, Password));
					AccountStore.Create (this).Save (account, "consumidor");
					new Android.Support.V7.App.AlertDialog.Builder (this)
						.SetMessage ("Conexión Satisfactoria")
						.SetPositiveButton ("OK", delegate {
						Console.WriteLine ("OK");
					})
						.SetTitle ("ATENCIÓN")
						.Show ();

					StartActivity (typeof(MainActivity));

				} catch (Exception ex) {
					var MensajeError = ex.Message.Remove (0, 43);
					new Android.Support.V7.App.AlertDialog.Builder (this)
						.SetMessage ("Error en la conexión: " + MensajeError)
						.SetPositiveButton ("OK", delegate {
						Console.WriteLine ("OK");
					})
						.SetTitle ("ATENCIÓN")
						.Show ();
				}

			};

			// Create your application here
		}
Esempio n. 9
0
		private static async Task<DataIUser> LoginToVk()
		{
			IUser user = null;
			try
			{
				TaskCompletionSource<int> ts = new TaskCompletionSource<int>();

				var auth = new OAuth2Authenticator(
				clientId: "5042701",
				scope: "offline,messages,friends",
				authorizeUrl: new Uri("https://oauth.vk.com/authorize"),
				redirectUrl: new Uri("https://oauth.vk.com/blank.html"));

				auth.AllowCancel = true;

				auth.Completed += (s, ee) =>
				{
					if (!ee.IsAuthenticated)
					{
						ts.SetResult(0);
						return;
					}

					var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/users.get"), null, ee.Account);
					request.GetResponseAsync().ContinueWith(t =>
					{
						if (t.IsCompleted)
						{
							Token = ee.Account.Properties["access_token"].ToString();
							string account = ee.Account.Serialize();
							Account = ee.Account;

							var response = t.Result.GetResponseText();
							var users = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkUsers>(response);

							string uid = users.response[0].uid;
							string firstName = users.response[0].first_name;
							string lastName = users.response[0].last_name;

							user = new User()
							{
								FirstName = firstName,
								LastName = lastName,
								Uid = uid,
								SerializeInfo = Account.Serialize(),
								SocialNetwork = enSocialNetwork.VK
							};

							ts.SetResult(0);
						}
						else
						{
							ts.SetResult(0);
							return;
						}
					}, UIScheduler);
				};

				var intent = auth.GetUI(Forms.Context);
				Forms.Context.StartActivity(intent);
				await ts.Task;
			}
			catch (Exception)
			{
			}
			return user;
		}
Esempio n. 10
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization is in progress
            if (_taskCompletionSource != null)
            {
                // Allow only one authorization process at a time
                throw new Exception();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();
#if __ANDROID__ || __IOS__
#if __ANDROID__
            // Get the current Android Activity
            var activity = Xamarin.Forms.Forms.Context as Activity;
#endif
#if __IOS__
            // Get the current iOS ViewController
            var viewController = Platform.GetRenderer(this).ViewController;
#endif
            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            Xamarin.Auth.OAuth2Authenticator authenticator = new Xamarin.Auth.OAuth2Authenticator(
                clientId: _appClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri);

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
#if __IOS__
                    // Dismiss the OAuth UI when complete
                    viewController.DismissViewController(true, null);
#endif

                    // Check if the user is authenticated
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.SetException(ex);
                }
                finally
                {
                    // Dismiss the OAuth login
#if __ANDROID__
                    activity.FinishActivity(99);
#endif
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
#if __ANDROID__
                        activity.FinishActivity(99);
#endif
                    }
                }
            };

            // Present the OAuth UI so the user can enter user name and password
#if __ANDROID__
            var intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);
#endif
#if __IOS__
            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password
            Device.BeginInvokeOnMainThread(() =>
            {
                viewController.PresentViewController(authenticator.GetUI(), true, null);
            });
#endif
#endif
            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
Esempio n. 11
0
        public async Task RegisterInLongPoolServer(IUser user)
        {
            try
            {
                if (user.SocialNetwork == enSocialNetwork.Twitter)
                {
                    return;
                }


                this.StartRequest();

                Account acc = Account.Deserialize(user.SerializeInfo.ToString());

                var request =
                    new OAuth2Request("GET",
                                      new Uri("https://api.vk.com/method/messages.getLongPollServer?access_token=" + Token),
                                      null, acc);

                request.Parameters.Add("use_ssl", "1");
                request.Parameters.Add("need_pts", "0");

                var res1 = await request.GetResponseAsync();

                var responseText = res1.GetResponseText();

                var settings = JsonConvert.DeserializeObject <XamarinSocialApp.Droid.Data.VkData.VkLongPoolServerResponse>(responseText);

                this.StopRequest();

                this.StartRequest();

                while (true)
                {
                    request = new OAuth2Request("GET",
                                                new Uri(String.Format("http://{0}?act=a_check&key={1}&ts={2}&wait=25&mode=2",
                                                                      settings.Response.ServerUrl, settings.Response.Key, settings.Response.Ts
                                                                      )), null, acc);
                    res1 = await request.GetResponseAsync();

                    responseText = res1.GetResponseText();
                    var updates =
                        JsonConvert.DeserializeObject <XamarinSocialApp.Droid.Data.VkData.VkLongPoolServerUpdates>
                            (responseText);
                    settings.Response.Ts = updates.Ts;

                    foreach (var updateArray in updates.Updates)
                    {
                        JToken token0    = updateArray[0];
                        int    operation = (int)token0;
                        if (operation != 4)
                        {
                            continue;
                        }

                        int    uidSender            = (int)updateArray[3];
                        int    messageId            = (int)updateArray[1];
                        int    dialogParticipientId = (int)updateArray[2];
                        string messageString        = (string)updateArray[6];

                        await SendRecievedMessage(user, acc, uidSender, messageId, dialogParticipientId, messageString);
                    }
                }

                this.StopRequest();
            }
            catch (Exception ex)
            {
                RegisterInLongPoolServer(user);
            }
        }
Esempio n. 12
0
        private static async Task <DataIUser> LoginToVk()
        {
            IUser user = null;

            try
            {
                TaskCompletionSource <int> ts = new TaskCompletionSource <int>();

                var auth = new OAuth2Authenticator(
                    clientId: "5042701",
                    scope: "offline,messages,friends",
                    authorizeUrl: new Uri("https://oauth.vk.com/authorize"),
                    redirectUrl: new Uri("https://oauth.vk.com/blank.html"));

                auth.AllowCancel = true;

                auth.Completed += (s, ee) =>
                {
                    if (!ee.IsAuthenticated)
                    {
                        ts.SetResult(0);
                        return;
                    }

                    var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/users.get"), null, ee.Account);
                    request.GetResponseAsync().ContinueWith(t =>
                    {
                        if (t.IsCompleted)
                        {
                            Token          = ee.Account.Properties["access_token"].ToString();
                            string account = ee.Account.Serialize();
                            Account        = ee.Account;

                            var response = t.Result.GetResponseText();
                            var users    = JsonConvert.DeserializeObject <XamarinSocialApp.Droid.Data.VkData.VkUsers>(response);

                            string uid       = users.response[0].uid;
                            string firstName = users.response[0].first_name;
                            string lastName  = users.response[0].last_name;

                            user = new User()
                            {
                                FirstName     = firstName,
                                LastName      = lastName,
                                Uid           = uid,
                                SerializeInfo = Account.Serialize(),
                                SocialNetwork = enSocialNetwork.VK
                            };

                            ts.SetResult(0);
                        }
                        else
                        {
                            ts.SetResult(0);
                            return;
                        }
                    }, UIScheduler);
                };

                var intent = auth.GetUI(Forms.Context);
                Forms.Context.StartActivity(intent);
                await ts.Task;
            }
            catch (Exception)
            {
            }
            return(user);
        }
        public virtual void SaveAccountInSecureStore(TAccount account)
        {
            var authAccount = new Xamarin.Auth.Account(account.Id, account);

            this.AccountStore.Save(authAccount, AccountServiceName);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.layout_iniciar_sesion);

            Typeface font          = Typeface.CreateFromAsset(Application.Context.Assets, "Fonts/HelveticaNeue-Thin.otf");
            var      btnIniciar    = FindViewById <Button> (Resource.Id.btnIniciar);
            var      txtContraseña = FindViewById <TextView> (Resource.Id.txtContraseñaSesion);
            var      txtEmail      = FindViewById <TextView> (Resource.Id.txtEmailSesion);

            btnIniciar.SetTypeface(font, TypefaceStyle.Normal);

            _supporttoolbar = FindViewById <Android.Support.V7.Widget.Toolbar> (Resource.Id.ToolBarSesion);
            var ToolbarTitle = FindViewById <TextView> (Resource.Id.toolbar_sesion);

            ToolbarTitle.SetText(Resource.String.Sesion);
            SetSupportActionBar(_supporttoolbar);
            SupportActionBar.SetDisplayHomeAsUpEnabled(false);


            btnIniciar.Click += (object sender, EventArgs e) => {
                btnIniciar.SetBackgroundColor(Color.White);
                btnIniciar.SetTextColor(Color.Orange);
                string string_key = "41f579fc-1445-4065-ab10-c06d50e724d3";
                string UserEmail  = txtEmail.Text.Trim();
                string Password   = txtContraseña.Text.Trim();

                try {
                    services_911consumidor_com.COCOService cliente = new Navigation_View.services_911consumidor_com.COCOService();
                    services_911consumidor_com.UserDTO     Usuario = new Navigation_View.services_911consumidor_com.UserDTO();

                    Usuario = cliente.AccountLogin(new Navigation_View.services_911consumidor_com.UserDTO {
                        Email    = UserEmail,
                        Password = Password
                    }, string_key);

                    Xamarin.Auth.Account account = new Xamarin.Auth.Account(Usuario.Email, AccountCore.Dictionary(Usuario.FirstName, Usuario.Email, Password));
                    AccountStore.Create(this).Save(account, "consumidor");
                    new Android.Support.V7.App.AlertDialog.Builder(this)
                    .SetMessage("Conexión Satisfactoria")
                    .SetPositiveButton("OK", delegate {
                        Console.WriteLine("OK");
                    })
                    .SetTitle("ATENCIÓN")
                    .Show();

                    StartActivity(typeof(MainActivity));
                } catch (Exception ex) {
                    var MensajeError = ex.Message.Remove(0, 43);
                    new Android.Support.V7.App.AlertDialog.Builder(this)
                    .SetMessage("Error en la conexión: " + MensajeError)
                    .SetPositiveButton("OK", delegate {
                        Console.WriteLine("OK");
                    })
                    .SetTitle("ATENCIÓN")
                    .Show();
                }
            };

            // Create your application here
        }
Esempio n. 15
0
		private async Task SendRecievedMessage(IUser user, Account acc, int uidSender, int messageId, int dialogParticipientId, string messageString)
		{
			string messageType = await GetMessageSenderMessageType(messageId, acc);
			var sender = new DataUser() { Uid = uidSender.ToString() };

			IMessage message = new DataMessage()
			{
				Content = messageString,
				Recipient = messageType == "1" ? sender : user,
				Sender = messageType == "1" ? user : sender,
				ParticipientId = dialogParticipientId.ToString()
			};

			if (messageType == "1")
			{
				GalaSoft.MvvmLight.Messaging.Messenger.Default.Send<MessagesUI.MessageNewMyMessageWasSent>
				(new MessagesUI.MessageNewMyMessageWasSent(message));
			}
			else
			{
				GalaSoft.MvvmLight.Messaging.Messenger.Default.Send<MessagesUI.MessageNewMessageWasSentToMe>
				(new MessagesUI.MessageNewMessageWasSentToMe(message));
			}
		}
Esempio n. 16
0
		private async Task<string> GetMessageSenderMessageType(int messageId, Account acc)
		{
			try
			{
				this.StartRequest();

				var request =
					new OAuth2Request("GET",
						new Uri("https://api.vk.com/method/messages.getById"),
				null, acc);

				request.Parameters.Add("message_ids", messageId.ToString());
				request.Parameters.Add("preview_length", "0");
				request.Parameters.Add("v", "5.37");

				var res1 = await request.GetResponseAsync();
				var responseText = res1.GetResponseText();

				var response = 
					JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkMessageByIdResponse>(responseText);

				return response.Response.Messages.First().Out;
			}
			catch (Exception ex)
			{

			}
			finally
			{
				this.StopRequest();
			}

			return String.Empty;
		}
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be cancelled
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            var authenticator = new OAuth2Authenticator(
                clientId: Samples.AuthorEditSaveMap.AuthorEditSaveMap.AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false
            };

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete
                    DismissViewController(true, null);

                    // Throw an exception if the user could not be authenticated
                    if (!authArgs.IsAuthenticated)
                    {
                        throw new Exception("Unable to authenticate user.");
                    }

                    // If authorization was successful, get the user's account
                    Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                    // Set the result (Credential) for the TaskCompletionSource
                    _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication
                    authenticator.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    _taskCompletionSource.TrySetException(new Exception(errArgs.Message));
                }

                // Cancel authentication
                authenticator.OnCancelled();
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password
            InvokeOnMainThread(() =>
            {
                PresentViewController(authenticator.GetUI(), true, null);
            });

            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.layout_register);

            var btnSave        = FindViewById <Button> (Resource.Id.btnGuardar);
            var txtNombre      = FindViewById <TextView> (Resource.Id.txtNombreCompleto);
            var txtEmail       = FindViewById <TextView> (Resource.Id.txtEmailRegistro);
            var txtPassword    = FindViewById <TextView> (Resource.Id.txtContraseña);
            var txtPassConfirm = FindViewById <TextView> (Resource.Id.txtContraseñaConfirmar);

            var      IniciarSesion = FindViewById <TextView> (Resource.Id.txtIniciarSesion);
            Typeface font          = Typeface.CreateFromAsset(Application.Context.Assets, "Fonts/HelveticaNeue-Thin.otf");

            _supporttoolbar = FindViewById <Android.Support.V7.Widget.Toolbar> (Resource.Id.ToolBarRegistro);
            var ToolbarTitle = FindViewById <TextView> (Resource.Id.toolbar_titleRegister);

            ToolbarTitle.SetText(Resource.String.Registro);
            //_supporttoolbar.SetTitle(Resource.String.Registro);
            SetSupportActionBar(_supporttoolbar);
            SupportActionBar.SetDisplayHomeAsUpEnabled(false);

            btnSave.SetTypeface(font, TypefaceStyle.Normal);

            _supporttoolbar.Click += (object sender, EventArgs e) =>
            {
                StartActivity(typeof(MainActivity));
            };

            IniciarSesion.Click += (object sender, EventArgs e) =>
            {
                StartActivity(typeof(IniciarSesionActivity));
            };

            btnSave.Click += (object sender, EventArgs e) => {
                btnSave.SetBackgroundColor(Color.White);
                btnSave.SetTextColor(Color.Orange);
                string strNombre      = txtNombre.Text.Trim();
                string strEmail       = txtEmail.Text.Trim();
                string strPassword    = txtPassword.Text.Trim();
                string strPassConfirm = txtPassConfirm.Text.Trim();
                string string_key     = "41f579fc-1445-4065-ab10-c06d50e724d3";

                services_911consumidor_com.COCOService cliente = new Navigation_View.services_911consumidor_com.COCOService();

                cliente.AccountRegistration(new Navigation_View.services_911consumidor_com.UserDTO {
                    FirstName = strNombre,
                    Email     = strEmail,
                    Password  = strPassword,
                    Device    = string.Empty
                }, string_key);

                Xamarin.Auth.Account account = new Xamarin.Auth.Account(strEmail, AccountCore.Dictionary(strNombre, strEmail, strPassword));

                AccountStore.Create(this).Save(account, "consumidor");

                new Android.Support.V7.App.AlertDialog.Builder(this)
                .SetMessage("Su cuenta ha sido registrada.")
                .SetTitle("ATENCIÓN")
                .Show();

                StartActivity(typeof(MainActivity));
            };
            // Create your application here
        }
Esempio n. 19
0
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization is in progress
            if (_taskCompletionSource != null)
            {
                // Allow only one authorization process at a time
                throw new Exception();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            var activity = Context as Activity;

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            var authenticator = new OAuth2Authenticator(
                clientId: OAuthPage.AppClientId,
                scope: "",
                authorizeUrl: new Uri(OAuthPage.AuthorizeUrl),
                redirectUrl: new Uri(OAuthPage.OAuthRedirectUrl));

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Check if the user is authenticated
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.SetException(ex);
                }
                finally
                {
                    // End the OAuth login activity
                    activity.FinishActivity(99);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.SetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: end the OAuth login activity
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        activity.FinishActivity(99);
                    }
                }
            };

            // Present the OAuth UI (Activity) so the user can enter user name and password
            var intent = authenticator.GetUI(activity);

            activity.StartActivityForResult(intent, 99);

            return(_taskCompletionSource.Task);
        }