Beispiel #1
0
        public OAuth2Request ToOAuth2Request (ISalesforceUser user)
        {
            if (!(Resource is SObject))
                throw new InvalidOperationException ("Only SObjects can have changes. Searches and Queries not elibible.");

            if (Since > Until)
                throw new InvalidOperationException ("Since must preceed Until.");

//            var path = user.Properties ["instance_url"] + SalesforceClient.RestApiPath;
//            var baseUri = new Uri (path);
//            var queryString = String.Format("?start={0:O}&end={1:O}", Since.ToUniversalTime(), Until.ToUniversalTime());
//            var changesPath = Path.Combine(Resource.AbsoluteUri.AbsolutePath, ChangeType.ToString(), queryString);
//            var changesUri = new Uri(changesPath);
//            var uri = new Uri (baseUri, changesUri);
            var path = user.Properties ["instance_url"] + SalesforceClient.RestApiPath;
            var baseUri = new Uri (path);
            var uri = new UriBuilder(new Uri (baseUri, Resource.AbsoluteUri));
            // Custom ISO format:
            var since = Since.ToUniversalTime();
            var sinceString = String.Format("{0}T{1}Z", since.ToString("yyyy-MM-dd"), since.ToString("HH:mm:ss"));
            var until = Until.ToUniversalTime();
            var untilString = String.Format("{0}T{1}Z", until.ToString("yyyy-MM-dd"), until.ToString("HH:mm:ss"));
            uri.Query = String.Format("start={0}&end={1}", sinceString, untilString);
            var oauthRequest = new OAuth2Request (Method, uri.Uri, Resource.Options.Where (kvp => kvp.Value.JsonType == JsonType.String).ToDictionary (k => k.Key, v => (string) v.Value), user);
            return oauthRequest;
        }
		public LoginPageRenderer()
		{
			var activity = this.Context as Activity;

			var auth = new OAuth2Authenticator (
				clientId: "1500267916942625", // your OAuth2 client id
				scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
				authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
				redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));

			auth.Completed += async (sender, eventArgs) => {
				if (eventArgs.IsAuthenticated) {
					var accessToken = eventArgs.Account.Properties ["access_token"].ToString ();
					var expiresIn = Convert.ToDouble (eventArgs.Account.Properties ["expires_in"]);
					var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);

					var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, eventArgs.Account);
					var response = await request.GetResponseAsync ();
					var obj = JObject.Parse (response.GetResponseText ());

					var id = obj ["id"].ToString ().Replace ("\"", ""); 
					var name = obj ["name"].ToString ().Replace ("\"", "");

					App.NavigateToProfile(string.Format("Olá {0}", name));
				} else {
					App.NavigateToProfile("Usuário Cancelou o login");
				}
			};

			activity.StartActivity (auth.GetUI(activity));	
		}
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            System.Diagnostics.Debug.WriteLine ("======>Login Page OAuth");
            base.OnElementChanged (e);
            var activity = this.Context as Activity;
            var auth = new OAuth2Authenticator (
                clientId: "621549137987350", // your OAuth2 client id
                scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service
                redirectUrl: new Uri ("http://ihbiproject.azurewebsites.net/api/Users")); // the redirect URL for the service
            auth.Completed += async (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated) {
                    try {
                        var accessToken = eventArgs.Account.Properties ["access_token"].ToString ();
                        App.Instance.SaveToken(accessToken);
                        AccountStore.Create (activity).Save (eventArgs.Account, "WellnessFB");
                        var expiresIn = Convert.ToDouble (eventArgs.Account.Properties ["expires_in"]);
                        var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);
                        var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, eventArgs.Account);
                        var response = await request.GetResponseAsync ();
                        var obj = JObject.Parse (response.GetResponseText ());
                        var id = obj ["id"].ToString ().Replace ("\"", "");
                        var name = obj ["name"].ToString ().Replace ("\"","");
                        App.Instance.SuccessfulLoginAction.Invoke();
                    } catch (Exception ex) {
                        System.Diagnostics.Debug.WriteLine("========> Error getting from GraphAPI" +ex);
                    }
                } else {

                }
            };
            System.Diagnostics.Debug.WriteLine ("======>after OAuth");
            activity.StartActivity(auth.GetUI(activity));
        }
        public FacebookPageRenderer()
        {
            var activity = this.Context as Activity;
            var auth = new OAuth2Authenticator(
            clientId: "476292725915235",
            scope: "",
            authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
            redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));

            auth.Completed += async (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated)
                {
                    var accessToken = eventArgs.Account.Properties["access_token"].ToString();
                    var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
                    var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);

                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
                    var response = await request.GetResponseAsync();
                    var obj = JObject.Parse(response.GetResponseText());

                    var id = obj["id"].ToString().Replace("\"", "");
                    var name = obj["name"].ToString().Replace("\"", "");

                    App app = new App();
                   await app.NavigateToProfile(string.Format("Olá {0}", name));

                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Alerta", "lOGIN CANCELADO", " OK");

                }
            };
            activity.StartActivity(auth.GetUI(activity));
        }
        void LoginToFacebook(object sender, EventArgs e)
        {
            var auth = new OAuth2Authenticator (
                clientId: "597442676937621",
                scope: "email,user_about_me",
                authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));

            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += (s, ee) => {
                if (!ee.IsAuthenticated) {
                    _facebookStatusView.Text = "Not Authenticated";
                    return;
                }

                // Now that we're logged in, make a OAuth2 request to get the user's info.
                var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, ee.Account);
                request.GetResponseAsync().ContinueWith (t => {
                    if (t.IsFaulted)
                        _facebookStatusView.Text = "Error: " + t.Exception.InnerException.Message;
                    else if (t.IsCanceled)
                        _facebookStatusView.Text = "Canceled";
                    else
                    {
                        var obj = JsonValue.Parse (t.Result.GetResponseText());
                        _facebookStatusView.Text = "Logged in as " + obj["name"];
                        _emailView.Text = obj["email"];
                        _genderView.Text = obj["gender"];
                    }
                }, uiScheduler);
            };

            var intent = auth.GetUI (this);
            StartActivityForResult (intent, 42);
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            var auth = new OAuth2Authenticator(
                 clientId: LoginOathPage.SocialInfo.clientId, // your OAuth2 client id
                scope: LoginOathPage.SocialInfo.scope, // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: LoginOathPage.SocialInfo.authorizeUrl, // the auth URL for the service
                redirectUrl: LoginOathPage.SocialInfo.redirectUrl); // the redirect URL for the service
            auth.ClearCookiesBeforeLogin = false;
            auth.Completed += async (sender, eventArgs) =>
            {
                // We presented the UI, so it's up to us to dimiss it on iOS.
                App.SuccessfulLoginAction.Invoke();

                if (eventArgs.IsAuthenticated)
                {
                    // Use eventArgs.Account to do wonderful things

                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
                    try
                    {
                        Response response = await request.GetResponseAsync();
                        var json = (response.GetResponseText());

                        //Debug.WriteLine("Name: " + obj["name"]);

                        if (eventArgs.IsAuthenticated)
                        {
                            // Use eventArgs.Account to do wonderful things
                            Remind.App.ParseSocial(json, Remind.View.LoginOathPage.SocialInfo);
                            Remind.App.SuccessfulLoginAction.Invoke();

                        }
                        else
                        {
                            // The user cancelled

                        }
                    }

                    catch (OperationCanceledException)
                    {
                        System.Diagnostics.Debug.WriteLine("Canceled");
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
                    }

                }
                else
                {
                    // The user cancelled
                }
            };

            PresentViewController(auth.GetUI(), true, null);
        }
Beispiel #7
0
		public OAuth2Request ToOAuth2Request (ISalesforceUser user)
		{
			var path = user.Properties ["instance_url"] + SalesforceClient.RestApiPath;
			var baseUri = new Uri (path);
			var uri = new Uri (baseUri, Resource.AbsoluteUri);
			var oauthRequest = new OAuth2Request (Method, uri, Resource.Options.Where (kvp => kvp.Value.JsonType == JsonType.String).ToDictionary (k => k.Key, v => (string) v.Value), user);
			return oauthRequest;
		}
Beispiel #8
0
        public void Show(SocialInfo socialInfo)
        {
            // IEnumerable<Account> accounts = AccountStore.Create().FindAccountsForService("Facebook");

            var auth = new OAuth2Authenticator(
                clientId: socialInfo.clientId, // your OAuth2 client id
                scope: socialInfo.scope, // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: socialInfo.authorizeUrl, // the auth URL for the service
                redirectUrl: socialInfo.redirectUrl); // the redirect URL for the service
            auth.ClearCookiesBeforeLogin = false;
            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += async (sender, eventArgs) =>
            {
                if (!eventArgs.IsAuthenticated)
                {
                    Debug.WriteLine("Not Authenticated");
                    return;
                }
                else
                {
                    // Now that we're logged in, make a OAuth2 request to get the user's info.
                    var request = new OAuth2Request("GET", new Uri(socialInfo.userInfoAPI), null, eventArgs.Account);
                    try
                    {
                        Response response = await request.GetResponseAsync();
                        var json = (await response.GetResponseTextAsync());

                        //Debug.WriteLine("Name: " + obj["name"]);

                        if (eventArgs.IsAuthenticated)
                        {
                            // Use eventArgs.Account to do wonderful things
                            //dynamic foo = JsonObject.Parse(json);
                            Remind.App.ParseSocial(json, socialInfo);
                            Remind.App.SuccessfulLoginAction.Invoke();

                        }
                        else
                        {
                            // The user cancelled

                        }
                    }

                    catch (OperationCanceledException)
                    {
                        Debug.WriteLine("Canceled");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error: " + ex.Message);
                    }
                }
            };

            Uri uri = auth.GetUI() as Uri;
            App.RootFrame.Navigate(uri);
        }
Beispiel #9
0
		public OAuth2Request ToOAuth2Request (ISalesforceUser user)
		{
			var path = user.Properties ["instance_url"] + SalesforceClient.RestApiPath;
			var baseUri = new Uri (path);
			var uri = new Uri (baseUri, Resource.AbsoluteUri);

			var oauthRequest = new OAuth2Request (this.Method, uri, null, Headers, user);
			return oauthRequest;
		}
Beispiel #10
0
        void LoginToFacebook(bool allowCancel)
        {
            var auth = new OAuth2Authenticator(
                clientId: "635793476502695",
                scope: "",
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));

            auth.AllowCancel = allowCancel;

            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += (s, ee) =>
            {
                if (!ee.IsAuthenticated)
                {
                    var builder = new AlertDialog.Builder(this);
                    builder.SetMessage("Not Authenticated");
                    builder.SetPositiveButton("Ok", (o, e) => { });
                    builder.Create().Show();
                    return;
                }

                // Now that we're logged in, make a OAuth2 request to get the user's info.
                var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, ee.Account);
                request.GetResponseAsync().ContinueWith(t =>
                {
                    var builder = new AlertDialog.Builder(this);
                    if (t.IsFaulted)
                    {
                        builder.SetTitle("Error");
                        builder.SetMessage(t.Exception.Flatten().InnerException.ToString());
                    }
                    else if (t.IsCanceled)
                        builder.SetTitle("Task Canceled");
                    else
                    {
                        var obj = JsonValue.Parse(t.Result.GetResponseText());

                        builder.SetTitle("Logged in");
                        builder.SetMessage("Name: " + obj["name"]);

                        //Store the account
                        AccountStore.Create(this).Save(ee.Account, "Facebook");

                        StartActivity(typeof(NewA));
                    }

                    builder.SetPositiveButton("Ok", (o, e) => { });
                    builder.Create().Show();
                }, UIScheduler);
            };

            var intent = auth.GetUI(this);
            StartActivity(intent);
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);
            var activity = this.Context as Activity;

            var auth = new OAuth2Authenticator(
                clientId: LoginOathPage.SocialInfo.clientId, // your OAuth2 client id
                scope: LoginOathPage.SocialInfo.scope, // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: LoginOathPage.SocialInfo.authorizeUrl, // the auth URL for the service
                redirectUrl: LoginOathPage.SocialInfo.redirectUrl); // the redirect URL for the service
            auth.ClearCookiesBeforeLogin = false;
            auth.Completed += async (sender, eventArgs) =>
            {
                if (eventArgs.IsAuthenticated)
                {
                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
                    try
                    {
                        Response response = await request.GetResponseAsync();
                        var json = (response.GetResponseText());

                        //Debug.WriteLine("Name: " + obj["name"]);

                        if (eventArgs.IsAuthenticated)
                        {
                            // Use eventArgs.Account to do wonderful things
                            Remind.App.ParseSocial(json, LoginOathPage.SocialInfo);
                            Remind.App.SuccessfulLoginAction.Invoke();
                        }
                        else
                        {
                            // The user cancelled

                        }
                    }

                    catch (OperationCanceledException)
                    {
                        System.Diagnostics.Debug.WriteLine("Canceled");
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
                    }
                }
                else
                {
                    // The user cancelled
                }
            };

            activity.StartActivity(auth.GetUI(activity));
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            // Fixed the issue that on iOS 8, the modal wouldn't be popped.
            // url : http://stackoverflow.com/questions/24105390/how-to-login-to-facebook-in-xamarin-forms
            if(	! IsShown ) {

                IsShown = true;

                var auth = new OAuth2Authenticator (
                    clientId: App.Instance.OAuthSettings.ClientId, // your OAuth2 client id
                    scope: App.Instance.OAuthSettings.Scope, // The scopes for the particular API you're accessing. The format for this will vary by API.
                    authorizeUrl: new Uri (App.Instance.OAuthSettings.AuthorizeUrl), // the auth URL for the service
                    redirectUrl: new Uri (App.Instance.OAuthSettings.RedirectUrl)); // the redirect URL for the service

                auth.Completed += async(sender, eventArgs) => {
                    DismissViewController (true, null);

                    if (eventArgs.IsAuthenticated) {

                        var accessToken = eventArgs.Account.Properties ["access_token"].ToString ();
                        var expiresIn = Convert.ToDouble (eventArgs.Account.Properties ["expires_in"]);
                        var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);
                        var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, eventArgs.Account);
                        var response = await request.GetResponseAsync ();
                        System.Diagnostics.Debug.WriteLine (response);

                        var obj = JObject.Parse (response.GetResponseText ());
                        var id = obj ["id"].ToString ().Replace ("\"", "");
                        var name = obj ["name"].ToString ().Replace ("\"", "");

                        App.Instance.SaveToken(accessToken);
                        AccountStore.Create ().Save (eventArgs.Account, "WellnessFB");

                        //fb(accessToken);

                        //Once the login is successful,
                        //fire off a Xamarin.Forms navigation via App.SuccessfulLoginAction.Invoke();.
                        App.Instance.SuccessfulLoginAction.Invoke();

                    } else {
                        // The user cancelled
                    }
                };

                PresentViewController (auth.GetUI (), true, null);
            }
        }
        async partial void BtnConnectWithFacebook_TouchUpInside(UIButton sender)
        {
            try
            {
                string facebookToken;
                var auth = new OAuth2Authenticator(
                               clientId: BeerDrinkin.Core.Helpers.Keys.FacebookClientId,
                               scope: "",
                               authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                               redirectUrl: new Uri("https://beerdrinkin.azure-mobile.net/signin-facebook"));
    
                auth.AllowCancel = true;
                auth.Completed += (s, e) =>
                {
                    if (!e.IsAuthenticated)
                    {
                        Acr.UserDialogs.UserDialogs.Instance.ShowError("Not authorized");
                        return;
                    }
    
                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, e.Account);
                    var response = request.GetResponseAsync().ContinueWith(t =>
                        {
                            if (!t.IsFaulted && !t.IsCanceled)
                            {
                                var stri = t.Result.GetResponseText();
                                var profile = JsonConvert.DeserializeObject<FacebookUser>(stri);

                                var userItem = new UserItem();
                                userItem.FirstName = profile.FirstName;
                                userItem.LastName = profile.LastName;
                                userItem.Email = profile.Email;
                            }
                        });
    
                };
    
                await PresentViewControllerAsync(auth.GetUI(), true);
    
                // Client.Instance.BeerDrinkinClient.CurrenMobileServicetUser = await Client.Instance.BeerDrinkinClient.ServiceClient.LoginAsync()
                var userService = new UserService();
                await userService.SaveUser(Client.Instance.BeerDrinkinClient.CurrenMobileServicetUser);
            }
            catch (Exception ex)
            {
                Acr.UserDialogs.UserDialogs.Instance.ShowError($"ERROR - AUTHENTICATION FAILED {ex.Message}");
            }
        }
Beispiel #14
0
		public OAuth2Request ToOAuth2Request (ISalesforceUser user)
		{
			// We can't update a query or a search object,
			// so neither of these are appropriate here.
			if (!(Resource is SObject))
				throw new InvalidOperationException ("Only SObjects can be updated. Searches and Queries are read-only.");

			var path = user.Properties ["instance_url"] + SalesforceClient.RestApiPath;
			var baseUri = new Uri (path);
			var uri = new Uri (baseUri, Resource.AbsoluteUri);

            var r = (SObject)Resource;
			var options = r.OnPreparingUpdateRequest ();
			var oauthRequest = new OAuth2Request (this.Method, uri, options,Headers, user);

			return oauthRequest;
		}
		async void OnAuthenticationCompleted (object sender, AuthenticatorCompletedEventArgs e)
		{
			if (e.IsAuthenticated) {
				// If the user is authenticated, request their basic user data from Google
				// UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
				var request = new OAuth2Request ("GET", new Uri (Constants.UserInfoUrl), null, e.Account);
				var response = await request.GetResponseAsync ();
				if (response != null) {
					// Deserialize the data and store it in the account store
					// The users email address will be used to identify data in SimpleDB
					string userJson = response.GetResponseText ();
					App.User = JsonConvert.DeserializeObject<User> (userJson);
					e.Account.Username = App.User.Email;
					AccountStore.Create (Context).Save (e.Account, App.AppName);
				}
			}
			// If the user is logged in navigate to the TodoList page.
			// Otherwise allow another login attempt.
			App.SuccessfulLoginAction.Invoke ();
		}
		public override void ViewDidAppear (bool animated)
		{
			base.ViewDidAppear (animated);

			if (done)
				return;

			var auth = new OAuth2Authenticator (
				clientId: "1500267916942625", // your OAuth2 client id
				scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
				authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
				redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));

			auth.Completed += async (sender, eventArgs) => {
				DismissViewController (true, null);

				App.HideLoginView();

				if (eventArgs.IsAuthenticated) {
					var accessToken = eventArgs.Account.Properties ["access_token"].ToString ();
					var expiresIn = Convert.ToDouble (eventArgs.Account.Properties ["expires_in"]);
					var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);

					var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, eventArgs.Account);
					var response = await request.GetResponseAsync ();
					var obj = JObject.Parse (response.GetResponseText ());

					var id = obj ["id"].ToString ().Replace ("\"", ""); 
					var name = obj ["name"].ToString ().Replace ("\"", "");

					await App.NavigateToProfile(string.Format("Olá {0}", name));
				} else {
					await App.NavigateToProfile("Usuário Cancelou o login");
				}
			};

			done = true;
			PresentViewController (auth.GetUI (), true, null);
		}
		public void LoginButtonClicked(object sender, EventArgs args){

			var activity = this.Context as Activity;
			var loginButton = sender as Button;

			var authenticatorType = (Oauth2AuthenticatorType) Enum.Parse (typeof(Oauth2AuthenticatorType), loginButton.Text);
			var oauthAuthenticationLogin = Oauth2AuthenticatorFactory.CreateAuthenticator(authenticatorType);

			var auth = new OAuth2Authenticator (
				clientId: oauthAuthenticationLogin.ClientId,
				scope: oauthAuthenticationLogin.Scope,
				authorizeUrl: oauthAuthenticationLogin.AuthorizeUrl,
				redirectUrl: oauthAuthenticationLogin.RedirectUrl);

			auth.Completed += async (s, ea) => {
				try{
					if (ea.IsAuthenticated) {
						var token = ea.Account.Properties["access_token"];
						var uri = oauthAuthenticationLogin.InfoUri;
						var request = new OAuth2Request ("GET", uri, null, ea.Account);
						var response = await request.GetResponseAsync();
						var user = JsonConvert.DeserializeObject(response.GetResponseText(), oauthAuthenticationLogin.UserInfoType);
						Pilarometro.App.Portable.App.Instance.SaveUser(user);
						Pilarometro.App.Portable.App.Instance.SuccessfulLoginAction.Invoke();
					} else {
						Console.WriteLine ("Not Authorised");
						return;
					}
				}catch(Exception ex){
					Console.WriteLine(ex.Message);
					throw;
				}
			};

			activity.StartActivity (auth.GetUI(activity));
		}
		private async Task<IDialog> GetVkDialogWithFriend(DataIUser user, IUser friend)
		{
			IDialog dialog = null;
			try
			{
				Account acc = Account.Deserialize(user.SerializeInfo.ToString());

				this.StartRequest();

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

				request.Parameters.Add("user_id", friend.Uid);
				request.Parameters.Add("count", "200");

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

				var msg = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkMessagesResponse>(responseText);
				msg.Response.RemoveAt(0);

				IList<XamarinSocialApp.Droid.Data.VkData.MessageInDialog> msg1
					= new List<XamarinSocialApp.Droid.Data.VkData.MessageInDialog>();
				foreach (var item in msg.Response)
				{
					msg1.Add(JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.MessageInDialog>(item.ToString()));
				}

				IList<IMessage> messages = new List<IMessage>();

				foreach (var item in msg1)
				{
					messages.Add(new DataMessage() { Content = item.Body, Sender = item.UserId == user.Uid ? user : friend });
				}

				dialog = new XamarinSocialApp.UI.Data.Implementations.Entities.Databases.Dialog(user, messages);
			}
			catch (Exception)
			{
			}

			return dialog;
		}
		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);
			}
		}
		private async Task<DataIUser> GetVkUserInfoRequest(IUser user)
		{
			Account accCurrent = Account.Deserialize(user.SerializeInfo.ToString());
			if (accCurrent.HasNotValue())
				return null;

			if (String.IsNullOrWhiteSpace(user.Uid))
				return null;

			this.StartRequest();

			try
			{
				var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/users.get"), null, accCurrent);
				request.Parameters.Add("uids", user.Uid);

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

				var users = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkUsers>(responseText);

				var jsonUser = users.response.First();
				return new DataUser()
				{
					FirstName = jsonUser.first_name,
					LastName = jsonUser.last_name,
					ID = jsonUser.uid,
					Uid = jsonUser.uid
				};
			}
			catch (Exception ex)
			{
			}
			finally
			{
				this.StopRequest();
			}

			return null;
		}
		private static async Task<IEnumerable<DataIUser>> GetUserVkFriends(DataIUser user)
		{
			IList<DataIUser> friends = new List<DataIUser>();
			try
			{
				Account acc = Account.Deserialize(user.SerializeInfo.ToString());
				var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/friends.get"), null, acc);

				request.Parameters.Add("fields", "nickname,photo_200");
				request.Parameters.Add("order", "hints");

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

				var listFriendsIds = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkUsers>(responseText);

				foreach (var friend in listFriendsIds.response)
				{
					friends.Add(new DataUser()
					{
						UserPhoto = friend.photo_200,
						FirstName = friend.first_name,
						LastName = friend.last_name,
						SerializeInfo = user.SerializeInfo,
						Uid = friend.uid
					});
				}
			}
			catch (Exception)
			{
			}
			return friends;
		}
		private static async Task<IEnumerable<IDialog>> GetVkDialogs(DataIUser user)
		{
			IList<IDialog> dialogs = new List<IDialog>();
			try
			{
				Account acc = Account.Deserialize(user.SerializeInfo.ToString());
				var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/messages.getDialogs"), null, acc);

				request.Parameters.Add("count", "200");
				request.Parameters.Add("v", "5.37");

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

				var msg = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkDialogsResponse>(responseText);


				foreach (var item in msg.Response.Messages)
				{
					IUser userDialog = new User()
					{
						Uid = item.Message.UserId,
						SerializeInfo = user.SerializeInfo
					};
					DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);

					string dateMessage = start.AddSeconds(item.Message.DateMessage).ToLocalTime().ToString();				
					//var userDialog = await GetUserInfoRequest(item.Message.UserId, acc, socialNetwork);
					dialogs.Add(new DataDialogs(userDialog, new List<IMessage>() 
				{ 
					new DataMessage() { Content = item.Message.Body, DateMessage = dateMessage } 
				}));
				}
			}
			catch (Exception)
			{
			}

			return dialogs;
		}
		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;
		}
		private async Task<bool> SendVkMessage(DataIUser user, DataIUser friend, string Message)
		{
			try
			{
				Account acc = Account.Deserialize(user.SerializeInfo.ToString());
				var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/messages.send"), null, acc);

				request.Parameters.Add("user_id", friend.Uid);
				request.Parameters.Add("message", Message);

				var res1 = await request.GetResponseAsync();
				var responseText = res1.GetResponseText();
			}
			catch (Exception)
			{
				return false;
			}

			return true;
		}
		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 override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            if (App.IsFacebookLogin && !App.IsLoggedIn)
            {
				
				try {
					var auth = new OAuth2Authenticator (
									clientId: "1064717540213918", //App OAuth2 client id
						           scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
						           authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),//new Uri(""), // the auth URL for the service
						           redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html")); // the redirect URL for the service

					auth.Completed += async (sender, eventArgs) => {
						
						window.Hidden = true;
						dialog.Dispose();
						window.Dispose();

						if (eventArgs.IsAuthenticated) 
						{
							App.SaveToken (eventArgs.Account.Properties ["access_token"]);
					
							var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me?fields=id,name,email"), null, eventArgs.Account);
							await request.GetResponseAsync ().ContinueWith (t => {
								if (t.IsFaulted)
									Console.WriteLine ("Error: " + t.Exception.InnerException.Message);
								else {
									string json = t.Result.GetResponseText ();
									Console.WriteLine (json);
									SerialiseFacebookUserData (json);
								}
							});

							dialog.DismissViewController(false, null);
							App.IsLoggedIn = true;
							App.SuccessfulLoginAction.Invoke();
						}
					};

					dialog.PresentViewController (auth.GetUI (), true, null);
				}
				catch (Exception ex) 
				{
					Console.WriteLine ("ViewDidAppear :: " + ex.Message);
				}


            }
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);

            if (!done)
            {
                // this is a ViewGroup - so should be able to load an AXML file and FindView<>
                activity = this.Context as Activity;
                if (App.IsGoogleLogin && !App.IsLoggedIn)
                {
                    /* ProgressDialog dlg = new ProgressDialog(Context);
                     dlg.SetTitle("Sign In To Google");
                     dlg.Show();*/

                    var myAuth = new GoogleAuthenticator("730990345527-h7r23gcdmdllgke4iud4di76b0bmpnbb.apps.googleusercontent.com",
                                     "https://www.googleapis.com/auth/userinfo.email",
                                     "https://accounts.google.com/o/oauth2/auth",
                                     "https://www.googleapis.com/plus/v1/people/me");
                    // dlg.Hide();

                    myAuth.authenticator.Completed += async (object sender, AuthenticatorCompletedEventArgs eve) =>
                    {

                        /* ProgressDialog dlg2 = new ProgressDialog(Context);
                         dlg2.SetTitle("Sign In To Google");
                         dlg2.Show();*/
                        if (eve.IsAuthenticated)
                        {
                            var user = await myAuth.GetProfileInfoFromGoogle(eve.Account.Properties["access_token"].ToString());
                            
							await App.SaveUserData(user,true);
                            App.IsLoggedIn = true;
							App.SuccessfulLoginAction.Invoke();
                        }
                        //  dlg2.Hide();
                    };

                    //auth.AllowCancel = false;
                    activity.StartActivity(myAuth.authenticator.GetUI(activity));
                    done = true;
                }
                else if (App.IsFacebookLogin && !App.IsLoggedIn)
                {
                    var auth = new OAuth2Authenticator(

						////- purposeColor facebook developer user id - [email protected] // passsword: ultimate.123

						clientId: "1064717540213918",
                        scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
                        authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),//new Uri(""), // the auth URL for the service
                        redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")); // the redirect URL for the service

                    auth.Completed += async (sender, eventArgs) => 
                    {
                        if (eventArgs.IsAuthenticated)
                        {
                            try
                            {
                                App.IsLoggedIn = true;
                                App.SaveToken(eventArgs.Account.Properties["access_token"]);
                                AccountStore.Create(activity).Save(eventArgs.Account, "Facebook");
                                // save user token  - to local DB
                            }
                            catch (System.Exception ex)
                            {
                                Console.WriteLine("auth.Completed ::: " + ex.Message);
                            }
							var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=id,name,email"), null, eventArgs.Account);
                           	await request.GetResponseAsync().ContinueWith(t =>
                            {
                                if (t.IsFaulted)
                                    Console.WriteLine("Error: " + t.Exception.InnerException.Message);
                                else
                                {
                                    string json = t.Result.GetResponseText();
                                    Console.WriteLine(json);
									SerialiseFacebookUserData (json);
                                }
                            });
							App.SuccessfulLoginAction.Invoke();
                        }
                        else
                        {
                            // The user cancelled
                        }
                    };
                    activity.StartActivity(auth.GetUI(activity));
                } // end - else if
            } //end - if (!done)
        }// end - OnElementChanged()
		public async Task<IUser> GetUserInfoRequest(IUser user, enSocialNetwork socialNetwork)
		{
			if (user.HasNotValue())
				return null;

			Account accCurrent = Account.Deserialize(user.SerializeInfo);
			if (accCurrent.HasNotValue())
				return null;

			if (String.IsNullOrWhiteSpace(user.Uid))
				return null;

			var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/users.get"), null, accCurrent);
			request.Parameters.Add("uids", user.Uid);

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

			var users = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkUsers>(responseText);

			var jsonUser = users.response.First();
			return new DataUser() { FirstName = jsonUser.first_name, LastName = jsonUser.last_name, ID = jsonUser.uid, Uid = jsonUser.uid };
		}
		public async Task<IEnumerable<IDialog>> GetDialogWithFriend(DataIUser user, enSocialNetwork socialNetwork)
		{
			IList<IDialog> dialogs = new List<IDialog>();

			try
			{
				Account acc = Account.Deserialize(user.SerializeInfo);
				var request = new OAuth2Request("GET", new Uri("https://api.vk.com/method/messages.getHistory"), null, acc);

				request.Parameters.Add("user_id", user.Uid);

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

				var msg = JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.VkMessagesResponse>(responseText);
				msg.Response.RemoveAt(0);

				IList<XamarinSocialApp.Droid.Data.VkData.MessageInDialog> msg1
					= new List<XamarinSocialApp.Droid.Data.VkData.MessageInDialog>();
				foreach (var item in msg.Response)
				{
					msg1.Add(JsonConvert.DeserializeObject<XamarinSocialApp.Droid.Data.VkData.MessageInDialog>(item.ToString()));
				}

				foreach (var item in msg1)
				{
					dialogs.Add(new DataDialogs(user, new List<IMessage>() 
				{ 
					new DataMessage() { Content = item.Body } 
				}));
				}
			}
			catch (Exception ex)
			{

			}

			return dialogs;
		}
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            var FileManager = new NSFileManager ();
            var appGroupContainer = FileManager.GetContainerUrl ("group.com.conceptdevelopment.watchinsta");
            var appGroupContainerPath = appGroupContainer.Path;
            Console.WriteLine ("agcpath: " + appGroupContainerPath);

            IEnumerable<Account> accounts = AccountStore.Create ().FindAccountsForService ("Instagram");
            string token = "";

            acct = (from a in accounts
                    select a).FirstOrDefault ();

            if (acct != null) {

                token = acct.Properties ["access_token"];

                var request = new OAuth2Request (
                    "GET",
                    new Uri ("https://api.instagram.com/v1/users/self/feed?access_token=" + token)
                    , null
                    , acct);//eventArgs.Account);

                request.GetResponseAsync ().ContinueWith (t => {
                    if (t.IsFaulted)
                        Console.WriteLine ("Error: " + t.Exception.InnerException.Message);
                    else {
                        string json = t.Result.GetResponseText ();
                        Console.WriteLine (json);

                        var root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject> (json);

                        var webClient = new WebClient();

                        var count = Math.Min(5, root.data.Count); var i = 0;

                        var inst = root.data[i];
                        var thumb = inst.images.thumbnail;
                        var url = new Uri(thumb.url);
                        Console.WriteLine(inst.caption.text);
                        Console.WriteLine("download: " + inst.images.thumbnail.url);

                        webClient.DownloadDataCompleted += (s, e) => {
                            Console.WriteLine("download completed");
                            if (e.Error == null) {
                                var bytes = e.Result; // get the downloaded data

                                string documentsPath = appGroupContainerPath; //Environment.GetFolderPath(Environment.SpecialFolder.Personal);

                                string localFilename = "insta-"+DateTime.Now.Ticks+".png";
                                string localPath = Path.Combine (documentsPath, localFilename);
                                File.WriteAllBytes (localPath, bytes); // writes to local storage
                                Console.WriteLine ("saved to: " + localPath);
                                InvokeOnMainThread (() => {
                                    instagramImageView.Image = UIImage.FromFile(localPath);
                                });
                            } else {
                                Console.WriteLine(e.Error);
                            }

                            // other loops
                            if (i < count) {
                                 inst = root.data[i];
                                 thumb = inst.images.thumbnail;
                                 url = new Uri(thumb.url);
                                Console.WriteLine(inst.caption.text);
                                Console.WriteLine(inst.images.thumbnail.url);

                                webClient.DownloadDataAsync(url);

                                i++;
                            }
                        };

                        // first loop
                        webClient.DownloadDataAsync(url);

                    }
                });

            } else {

                //
                //
                // http://instagram.com/developer/clients/manage/
                //
                var auth = new OAuth2Authenticator (
                              clientId: "YOU_NEED_YOUR_INSTAGRAM_DEV_CLIENTID_HERE",
                              scope: "basic",
                              authorizeUrl: new Uri ("https://api.instagram.com/oauth/authorize/"),
                              redirectUrl: new Uri ("http://your-redirect-url.net/"));

                auth.Completed += (sender, eventArgs) => {
                    // We presented the UI, so it's up to us to dimiss it on iOS.
                    DismissViewController (true, null);

                    if (eventArgs.IsAuthenticated) {
                        // Use eventArgs.Account to do wonderful things
                        acct = eventArgs.Account;
                        AccountStore.Create ().Save (eventArgs.Account, "Instagram");

                        token = eventArgs.Account.Properties ["access_token"];

                        var request = new OAuth2Request ("GET",
                                         new Uri ("https://api.instagram.com/v1/users/self/feed?access_token=" + token)
                        , null, acct);//eventArgs.Account);
                        request.GetResponseAsync ().ContinueWith (t => {
                            if (t.IsFaulted)
                                Console.WriteLine ("Error: " + t.Exception.InnerException.Message);
                            else {
                                string json = t.Result.GetResponseText ();
                                Console.WriteLine (json);
                            }
                        });
                    } else {
                        // The user cancelled

                    }
                };
                PresentViewController (auth.GetUI (), true, null);
            }
        }