async partial void SignUpButton_TouchUpInside(UIButton sender)
        {
            string userPassword       = userPasswordTextField.Text;
            string userRepeatPassword = userRepeatPasswordTextField.Text;

            // Check for empty fields
            if (string.IsNullOrWhiteSpace(userPassword) || string.IsNullOrWhiteSpace(userRepeatPassword))
            {
                // Display an alert message
                DisplayAlertMessage("All fields are required to fill in");
                return;
            }
            // If password do not meet requirements
            else if (!Validation.ValidationResult(userPassword, "password"))
            {
                DisplayAlertMessage(Validation.Message);
                return;
            }

            // Check if passwords match
            if (!userPassword.Equals(userRepeatPassword))
            {
                // Display an alert message
                DisplayAlertMessage("Passwords do not match");
                return;
            }

            // Show the loading overlay on the UI
            LoadingOverlay.ShowOverlay(View);

            // Add user
            // Create instance of table Users
            user = new UsersModel()
            {
                FirstName     = RegisterUserSharedData.UserFirstName,
                LastName      = RegisterUserSharedData.UserLastName,
                Email         = RegisterUserSharedData.UserEmail.ToLower(),
                Password      = userPassword,
                LoginProvider = "Email"
            };

            // Call REST service to send Json data
            RestService rs = new RestService();

            // Get Json data from server in JsonResponseModel format
            Task <UsersModel> jsonResponeTask = rs.UserLoginAndRegisterJson(user, "register");

            // If there was an error in PostJsonDataAsync class, display message
            if (jsonResponeTask == null)
            {
                DisplayAlertMessage(rs.Message);
                return;
            }

            // Create instance of JsonResponseModel and pass jsonResponeTask there
            var jsonResponse = await jsonResponeTask;

            // Get user status (Success/Error)
            string statusUser   = jsonResponse.Status;
            string alertMessage = jsonResponse.Message;

            // Excecutes the given code in the background
            var alert    = UIAlertController.Create(title: "", message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert);
            var okAction = UIAlertAction.Create("Ok", UIAlertActionStyle.Cancel, (obj) =>
            {
                // If user has been added successfully, dismiss view controller
                if (statusUser == "Success")
                {
                    var loginController = this.Storyboard.InstantiateViewController("LoginUserViewController") as LoginUserViewController;
                    if (loginController != null)
                    {
                        this.PresentViewController(loginController, true, null);
                    }
                }
                else if (statusUser == "Error" && alertMessage == "Email already exists")
                {
                    //var registerController = this.Storyboard.InstantiateViewController("EnterEmailRegisterUser") as RegisterUserViewController;
                    //if (registerController != null)
                    this.NavigationController.PopViewController(true);
                }
            });

            alert.AddAction(okAction);
            this.PresentViewController(alert, true, null);

            // Remove overlay
            LoadingOverlay.RemoveOverlay();
        }
예제 #2
0
        // Login user and register using Facebook
        public async Task <UsersModel> UserLoginAndRegisterJson(UsersModel user, string action)
        {
            try
            {
                if (!CrossConnectivity.Current.IsConnected || !await CrossConnectivity.Current.IsReachable(serverUri.Host.ToString(), 3000))
                {
                    Message = "There was a network problem. Please, try again later";
                    return(new UsersModel()
                    {
                        Status = "Error", Message = this.Message
                    });
                }

                var user_tmp = new UsersModel();
                // Disable sending Facebook's avatar to server
                if (user.LoginProvider == "Facebook")
                {
                    user_tmp.Id            = user.Id;
                    user_tmp.FirstName     = user.FirstName;
                    user_tmp.LastName      = user.LastName;
                    user_tmp.Email         = user.Email.ToLower();
                    user_tmp.Password      = user.Password;
                    user_tmp.Avatar        = null;
                    user_tmp.LoginProvider = user.LoginProvider;
                    user_tmp.CreatedAt     = user.CreatedAt;
                }
                else
                {
                    user_tmp = user;
                }

                // Serialize UserModel class into a JSON String
                var jsonUserSerialize = await Task.Run(() => JsonConvert.SerializeObject(user_tmp));

                // Wrap JSON inside a StringContent which then can be used by the HttpClient class
                var httpContent = new StringContent(jsonUserSerialize, Encoding.UTF8, "application/json");

                Console.WriteLine("INPUT content:" + jsonUserSerialize);

                using (httpClient = new HttpClient())
                {
                    if (action == "login")
                    {
                        phpFileUri = new Uri(serverUri, "userlogin.php");
                    }
                    else if (action == "register")
                    {
                        phpFileUri = new Uri(serverUri, "userregister.php");
                    }
                    else if (action == "update")
                    {
                        phpFileUri = new Uri(serverUri, "userupdate.php");
                    }

                    // Send JSON using HTTP request and receiving HTTP response
                    HttpResponseMessage response = await httpClient.PostAsync(phpFileUri, httpContent);

                    if (response.IsSuccessStatusCode)
                    {
                        // If the response contains content, read it
                        if (response.Content != null)
                        {
                            var responseContent = await response.Content.ReadAsStringAsync();

                            Console.WriteLine("OUTPUT content:" + responseContent);

                            // Deserialize JSON
                            var jsonUserDeserialize = await Task.Run(() => JsonConvert.DeserializeObject <UsersModel>(responseContent));

                            return(jsonUserDeserialize);
                        }
                        else
                        {
                            Message = "HTTP Content is empty";
                            return(new UsersModel()
                            {
                                Status = "Error", Message = this.Message
                            });
                        }
                    }
                    else
                    {
                        Message = "HTTP Response Error\n" + new HttpResponseMessage(HttpStatusCode.NotModified);
                        return(new UsersModel()
                        {
                            Status = "Error", Message = this.Message
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                return(new UsersModel()
                {
                    Status = "Error", Message = this.Message
                });
            }
        }
예제 #3
0
        // Facebook Authentification
        void FacebookAuthentication()
        {
            flag = false;
            // If was send true to Profile.EnableUpdatesOnAccessTokenChange method
            // this notification will be called after the user is logged in and
            // after the AccessToken is gotten
            Profile.Notifications.ObserveDidChange((sender, e) =>
            {
                if (e.NewProfile == null)
                {
                    return;
                }

                var accessToken = AccessToken.CurrentAccessToken.TokenString;
                var request     = new GraphRequest("/" + e.NewProfile.UserID, new NSDictionary("fields", "email,first_name,last_name,picture.type(large)"), accessToken, null, "GET");
                request.Start((connection, result, error) =>
                {
                    // Show the loading overlay on the UI
                    LoadingOverlay.ShowOverlay(View);

                    var userInfo = result as NSDictionary;

                    // Get Facebook avatar image from url
                    var avatarUrl = new NSUrl(userInfo["picture"].ValueForKey(new NSString("data")).ValueForKey(new NSString("url")).ToString());
                    var data      = NSData.FromUrl(avatarUrl);

                    facebookImageData = data;

                    // string facebookAvatar = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
                    // facebookAvatar = new NSString(eefacebookAvatar, NSStringEncoding.UTF8); //Encoding.ASCII.GetString(ToByteArray(data));

                    // Add Facebook user to database
                    var user = new UsersModel()
                    {
                        FirstName     = userInfo["first_name"].ToString(),
                        LastName      = userInfo["last_name"].ToString(),
                        Email         = userInfo["email"].ToString().ToLower(),
                        LoginProvider = "Facebook"
                    };

                    // Call REST service to send Json data
                    RestService rs = new RestService();

                    // Get Json data from server in JsonResponseModel format
                    Task <UsersModel> jsonResponeTask = rs.UserLoginAndRegisterJson(user, "register");

                    // If there was an error in PostJsonDataAsync class, display message
                    if (jsonResponeTask == null)
                    {
                        LoadingOverlay.RemoveOverlay();
                        return;
                    }

                    // Get user id from Json after login or display an error
                    GetUserIdFromJson(jsonResponeTask, user);

                    if (error != null)
                    {
                        LoadingOverlay.RemoveOverlay();
                        Console.WriteLine("Error in request. Start Facebook login");
                        return;
                    }
                });
            });

            // Set the Read and Publish permissions you want to get
            loginView = new LoginButton(fbAuthButton.Frame)
            {
                LoginBehavior   = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };

            // Handle actions once the user is logged in
            loginView.Completed += LoginView_Completed;

            // Handle actions once the user is logged out
            loginView.LoggedOut += (sender, e) =>
            {
                // Set logout User Defaults
                var plist = NSUserDefaults.StandardUserDefaults;
                plist.SetBool(false, "isUserLoggedIn"); // set flag that user logged out
                plist.SetString("", "userId");
                plist.Synchronize();
            };

            // Use your System Account of Settings
            //loginButton.LoginBehavior = LoginBehavior.SystemAccount;

            // Add views to main view
            View.AddSubview(loginView);
        }