コード例 #1
0
        /// <summary>
        /// Ricostruisce le informazioni di accesso al Cloud da una precedente
        /// serializzazione
        /// </summary>
        private void DeSerialize()
        {
            try
            {
                Account = null;
                string       data         = File.ReadAllText(SerializationFileName, Encoding.UTF8);
                EncDecHelper encDecHelper = new EncDecHelper
                {
                    PasswordString = SerializationPassword
                };

                Xamarin.Auth.Account account = Xamarin.Auth.Account.Deserialize(encDecHelper.AESDecrypt(data, out bool warning));
                if (warning)
                {
                    Debug.Write(string.Format("Google Drive serialize file {0}. File seems to be corrupted. I have tried to recover the data.",
                                              SerializationFileName));
                }
                if (account != null)
                {
                    Account    = new OAuthAccountWrapper(account);
                    RememberMe = true;
                }
            }
            catch (FileNotFoundException)
            {
                // Accettabile
                Debug.WriteLine(string.Format("Deserialize: file {0} not found", SerializationFileName));
            }
            catch (Exception Ex)
            {
                Debug.WriteLine("Deserialize error: " + Ex.Message);
            }
        }
コード例 #2
0
        private static void Init()
        {
            if (Account == null)
            {
                if (AccountStore == null)
                {
                    AccountStore = Xamarin.Auth.AccountStore.Create();
                }

                if (AccountStore == null)
                {
                    throw new Exception("Account Store not Supported");
                }

                try
                {
                    Account = AccountStore.FindAccountsForService(APP_NAME_KEY).FirstOrDefault();
                }
                catch
                {
                    Account = null;
                }

                if (Account == null)
                {
                    Account = new Xamarin.Auth.Account
                    {
                        Username = USERNAME_FOR_SS
                    };

                    AccountStore.Save(Account, APP_NAME_KEY);
                }
            }
        }
コード例 #3
0
 private Xamarin.Auth.Account getFacebookToken()
 {
     Xamarin.Auth.Account a = new Xamarin.Auth.Account();
     foreach (String key in Application.Current.Properties.Keys)
     {
         a.Properties.Add(key, Application.Current.Properties[key] as string);
     }
     return(a);
 }
コード例 #4
0
        public async static void Logout()
        {
            _fbaccount = null;
            _Token     = null;

            SettingsService.IsLoggedIn        = false;
            SettingsService.LoggedInUserEmail = string.Empty;
            await App.AppNavigationService.NavigateAsync($"/{nameof(NavigationPage)}/{nameof(LoginPage)}");
        }
コード例 #5
0
 internal string getToken()
 {
     Xamarin.Auth.Account account = getFacebookToken();
     if (account == null)
     {
         return(null);
     }
     return(account.Properties["access_token"]);
 }
コード例 #6
0
        async protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            if (MainActivity.Activities.ContainsKey("SearchTwitter"))
            {
                MainActivity.Activities["SearchTwitter"].Finish();
                MainActivity.Activities.Remove("SearchTwitter");
                MainActivity.Activities.Add("SearchTwitter", this);
            }
            else
            {
                MainActivity.Activities.Add("SearchTwitter", this);
            }
            //has the user already authenticated from a previous session? see AccountStore.Create().Save() later
            IEnumerable <Xamarin.Auth.Account> accounts = Xamarin.Auth.AccountStore.Create(this).FindAccountsForService("UndertheShopTwitApp");

            SearchTerm = Intent.GetStringExtra("keyword");
            shopID     = Intent.GetStringExtra("SHOP_ID_NUMBER");
            local      = Intent.GetStringExtra("Local");

            //check the account store for a valid account marked as "Twitter" and then hold on to it for future requests
            foreach (Xamarin.Auth.Account account in accounts)
            {
                loggedInAccount = account;
                break;
            }
            if (loggedInAccount == null)
            {
                Toast.MakeText(this, GetString(Resource.String.authfail), ToastLength.Short).Show();
                var next = new Intent(this.ApplicationContext, typeof(ShopInfoActivity));
                next.PutExtra("SHOP_ID_NUMBER", shopID);
                next.PutExtra("Local", local);
                StartActivity(next);
                Finish();
            }

            else
            {
                var cred = new LinqToTwitter.InMemoryCredentialStore();
                cred.ConsumerKey      = loggedInAccount.Properties["oauth_consumer_key"];
                cred.ConsumerSecret   = loggedInAccount.Properties["oauth_consumer_secret"];
                cred.OAuthToken       = loggedInAccount.Properties["oauth_token"];
                cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"];
                var auth0 = new LinqToTwitter.PinAuthorizer()
                {
                    CredentialStore = cred,
                };
                var TwitterCtx = new LinqToTwitter.TwitterContext(auth0);
                Console.WriteLine(TwitterCtx.User);
                _searches = await(from tweet in TwitterCtx.Search
                                  where (tweet.Type == SearchType.Search) &&
                                  (tweet.Query == SearchTerm)
                                  select tweet).ToListAsync();
                this.ListAdapter = new SearchAdapter(this, _searches[0].Statuses);
            }
        }
コード例 #7
0
        public TokenStorage(IAccountStorage accountStorage)
        {
            AccountStorage = accountStorage;

            _account     = null;
            AccessToken  = null;
            RefreshToken = null;
            UserToken    = null;
            XToken       = null;
        }
コード例 #8
0
        public void UpdateTokensFromAccount(Xamarin.Auth.Account account)
        {
            // Set new account
            Account = account;

            // Initialize access/refresh tokens
            var wlResponse = CreateResponseFromAccount(account);

            AccessToken  = new AccessToken(wlResponse);
            RefreshToken = new RefreshToken(wlResponse);
        }
コード例 #9
0
 protected override void OnAppearing()
 {
     pinAccount = App.Current.Properties["Pin"] as Xamarin.Auth.Account;
     if (pinAccount.Properties["FingerPrint"].Equals("True"))
     {
         FPswitch.IsToggled = true;
     }
     else
     {
         FPswitch.IsToggled = false;
     }
 }
コード例 #10
0
 public static WindowsLiveResponse CreateResponseFromAccount(Xamarin.Auth.Account account)
 {
     return(new WindowsLiveResponse()
     {
         CreationTime = account.GetCreationDateTime(),
         ExpiresIn = account.GetAccessTokenExpirationSeconds(),
         AccessToken = account.GetAccessTokenJwt(),
         RefreshToken = account.GetRefreshTokenJwt(),
         TokenType = account.GetTokenType(),
         Scope = account.GetScope(),
         UserId = account.GetUserId()
     });
 }
コード例 #11
0
        public static Xamarin.Auth.Account CreateAccountFromResponse(WindowsLiveResponse response)
        {
            var account = new Xamarin.Auth.Account();

            account.SetCreationDateTime(response.CreationTime);
            account.SetAccessTokenExpirationSeconds(response.ExpiresIn);
            account.SetAccessTokenJwt(response.AccessToken);
            account.SetRefreshTokenJwt(response.RefreshToken);
            account.SetTokenType(response.TokenType);
            account.SetScope(response.Scope);
            account.SetUserId(response.UserId);
            return(account);
        }
コード例 #12
0
        private void setFacebookToken(Xamarin.Auth.Account token)
        {
            if (token == null)
            {
                Application.Current.Properties.Remove("access_token");
                Application.Current.SavePropertiesAsync();
                return;
            }

            foreach (String key in token.Properties.Keys)
            {
                Application.Current.Properties[key] = token.Properties.GetValueOrDefault(key);
            }

            Application.Current.SavePropertiesAsync();
        }
コード例 #13
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> >();

            // 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.
                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.
                    this.FinishActivity(99);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sender, 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();
                        this.FinishActivity(99);
                    }
                }
            };

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

            this.StartActivityForResult(intent, 99);

            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
コード例 #14
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 Xamarin.Auth.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
                {
                    // Dismiss the OAuth login
                    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: dismiss the OAuth login
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        FinishActivity(99);
                    }
                }

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

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

            StartActivityForResult(intent, 99);
            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
コード例 #15
0
 public AuthenticatorEventArgs(Xamarin.Auth.Account account)
 {
     Account = account;
 }
コード例 #16
0
 public static void SaveFBAccount(Xamarin.Auth.Account account)
 {
     _fbaccount = account;
     _Token     = account.Properties["access_token"];
     GetFacebookLoginDetail();
 }
コード例 #17
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> >();

            // 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
                {
                    // 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
                {
                    // Dismiss the OAuth login
                    this.DismissViewController(true, null);
                }
            };

            // 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: dismiss the OAuth login
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        this.DismissViewController(true, null);
                    }
                }
            };

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

            // Return completion source task so the caller can await completion
            return(_taskCompletionSource != null ? _taskCompletionSource.Task : null);
        }
コード例 #18
0
ファイル: Passphrase.cs プロジェクト: Sandy4321/XamarinClient
        public Passphrase()
        {
            pinAccount = App.Current.Properties["Pin"] as Xamarin.Auth.Account;
            passphrase = new Editor
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                HeightRequest     = 100,
            };
            if (App.Current.Properties.ContainsKey("Account"))
            {
                Account acc        = App.Current.Properties["Account"] as Account;
                string  encoded_pk = encoder.EncodeData(acc.privateKey);
                passphrase.Text = encoded_pk;
                Content         = new StackLayout
                {
                    Margin            = 5,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    Children          =
                    {
                        new Label       {
                            Text = "Your Passphrase"
                        },
                        new StackLayout {
                            BackgroundColor = Color.Gray,
                            Padding         = 1,
                            Children        =
                            {
                                passphrase,
                            }
                        },
                    }
                };
            }
            else
            {
                Button save = new Button
                {
                    Text = "Save"
                };
                save.Clicked += SaveKeys;

                Content = new StackLayout
                {
                    Margin            = 5,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    Children          =
                    {
                        new Label       {
                            Text = "Enter Passphrase"
                        },
                        new StackLayout {
                            BackgroundColor = Color.Gray,
                            Padding         = 1,
                            Children        =
                            {
                                passphrase,
                            }
                        },
                        save,
                    }
                };
            }
        }
コード例 #19
0
 public static void DeleteAccount()
 {
     Init();
     AccountStore.Delete(Account, APP_NAME_KEY);
     Account = null;
 }
コード例 #20
0
        public AccountPage()
        {
            Title = "Red Belly Blockchain";

            pinAccount = App.Current.Properties["Pin"] as Xamarin.Auth.Account;

            PrivKey = new Entry
            {
                IsPassword        = true,
                Text              = "",
                HorizontalOptions = LayoutOptions.FillAndExpand,
            };

            ShowPrivKey = new Button
            {
                HorizontalOptions = LayoutOptions.End,
                Image             = "hide.png",
            };
            ShowPrivKey.Clicked += ShowPrivateKey;

            Save = new Button
            {
                ContentLayout = new Button.ButtonContentLayout(Button.ButtonContentLayout.ImagePosition.Top, 0),
                Text          = "Save",
                Image         = "adduser.png",
            };
            Save.Clicked += SaveKeys;

            CreateAccount = new Button
            {
                ContentLayout = new Button.ButtonContentLayout(Button.ButtonContentLayout.ImagePosition.Top, 0),
                Text          = "Create",
                Image         = "newuser.png"
            };
            CreateAccount.Clicked += CreateNewAccount;

            Remove = new Button
            {
                ContentLayout = new Button.ButtonContentLayout(Button.ButtonContentLayout.ImagePosition.Top, 0),
                Text          = "Remove",
                Image         = "trash.png",
            };
            Remove.Clicked += RemoveKeys;

            Grid passwordGrid = new Grid
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                RowSpacing        = 0.5,
            };

            passwordGrid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(30, GridUnitType.Absolute)
            });
            passwordGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(9, GridUnitType.Star)
            });
            passwordGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });
            passwordGrid.Children.Add(PrivKey, 0, 0);
            passwordGrid.Children.Add(ShowPrivKey, 1, 0);

            Grid buttonsGrid = new Grid
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
            };

            buttonsGrid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(60, GridUnitType.Absolute)
            });
            buttonsGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });
            buttonsGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });
            buttonsGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });
            buttonsGrid.Children.Add(CreateAccount, 0, 0);
            buttonsGrid.Children.Add(Save, 1, 0);
            buttonsGrid.Children.Add(Remove, 2, 0);

            AccountList = new ObservableCollection <AccountDisplay>();
            if (Application.Current.Properties.ContainsKey("Accounts"))
            {
                AccountList = Application.Current.Properties["Accounts"] as ObservableCollection <AccountDisplay>;
            }
            else
            {
                Application.Current.Properties.Add("Accounts", AccountList);
            }

            if (App.Current.Properties.ContainsKey("Account"))
            {
                Account acc = App.Current.Properties["Account"] as Account;
                PrivKey.Text = Convert.ToBase64String(acc.privateKey);
                AccountDisplay accdisplay = new AccountDisplay(Convert.ToBase64String(acc.privateKey), Convert.ToBase64String(acc.address));
                if (!AccountList.Contains(accdisplay))
                {
                    AccountList.Add(accdisplay);
                }
            }

            listView                     = new ListView();
            listView.ItemsSource         = AccountList;
            listView.ItemTapped         += OnItemTapped;
            listView.SeparatorVisibility = SeparatorVisibility.None;

            StackLayout stack = new StackLayout
            {
                Spacing         = 10,
                VerticalOptions = LayoutOptions.Fill,

                Children =
                {
                    new Label {
                        Text = "Private Key",
                        HorizontalOptions = LayoutOptions.Center,
                        FontSize          = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                    },
                    passwordGrid,
                    buttonsGrid,
                    new Label {
                        Text = ""
                    },
                    listView,
                }
            };

            ScrollView scroll = new ScrollView
            {
                Margin = 5,
            };

            scroll.Content = stack;

            Content = scroll;
        }
コード例 #21
0
        public SettingsPage()
        {
            Title = "Red Belly Blockchain";
            Icon  = "settings.png";

            pinAccount = App.Current.Properties["Pin"] as Xamarin.Auth.Account;

            accountPage = new Button
            {
                Text              = "Account",
                FontSize          = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                HorizontalOptions = LayoutOptions.Start,
                TextColor         = Color.Black,
            };
            accountPage.Clicked += account_page;

            passPhrase = new Button
            {
                Text              = "Passphrase",
                FontSize          = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                HorizontalOptions = LayoutOptions.Start,
                TextColor         = Color.Black,
            };
            passPhrase.Clicked += pass_phrase;

            changePin = new Button
            {
                Text              = "Change Pin",
                FontSize          = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                HorizontalOptions = LayoutOptions.Start,
                TextColor         = Color.Black,
            };
            changePin.Clicked += ChangePin_Clicked;

            FPswitch = new Switch
            {
                HorizontalOptions = LayoutOptions.EndAndExpand,
                IsToggled         = false,
            };
            if (pinAccount.Properties["FingerPrint"].Equals("True"))
            {
                FPswitch.IsToggled = true;
            }
            FPswitch.Toggled += FPswitch_Toggled;

            ServerHost = new Entry
            {
                Text = "129.78.10.53",
            };
            ServerHost.HorizontalOptions = LayoutOptions.FillAndExpand;
            ServerPort = new Entry
            {
                Text = "7822",
            };
            ServerPort.HorizontalOptions = LayoutOptions.FillAndExpand;
            AddServer = new Button
            {
                Text = "Add Server"
            };
            AddServer.Clicked += AddServerClicked;

            ServerList = new ObservableCollection <ServerDisplay>();
            if (Application.Current.Properties.ContainsKey("Servers"))
            {
                ServerList = Application.Current.Properties["Servers"] as ObservableCollection <ServerDisplay>;
            }

            listView                     = new ListView();
            listView.ItemsSource         = ServerList;
            listView.ItemTapped         += OnItemTapped;
            listView.SeparatorVisibility = SeparatorVisibility.None;

            StackLayout stack = new StackLayout
            {
                Spacing         = 10,
                VerticalOptions = LayoutOptions.Fill,
                Children        =
                {
                    accountPage,

                    passPhrase,

                    changePin,

                    new Label {
                        Text = ""
                    },

                    new StackLayout {
                        Orientation       = StackOrientation.Horizontal,
                        HorizontalOptions = LayoutOptions.StartAndExpand,
                        Children          =
                        {
                            new Label {
                                Text = "Built-in Unlock",
                                HorizontalTextAlignment = TextAlignment.Start,
                            },
                            FPswitch,
                        }
                    },

                    new Label {
                        Text = ""
                    },

                    new Label
                    {
                        Text              = "Server Configuration",
                        FontSize          = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                        HorizontalOptions = LayoutOptions.Center
                    },
                    new StackLayout
                    {
                        Orientation = StackOrientation.Horizontal,
                        Children    =
                        {
                            new Label {
                                Text = "Host",
                            },
                            ServerHost,
                        }
                    },
                    new StackLayout
                    {
                        Orientation = StackOrientation.Horizontal,
                        Children    =
                        {
                            new Label {
                                Text = "Port",
                            },
                            ServerPort,
                        }
                    },
                    AddServer,
                    listView,
                }
            };
            ScrollView scroll = new ScrollView {
                Margin = 5,
            };

            scroll.Content = stack;

            Content = scroll;
        }
コード例 #22
0
 public Account(Xamarin.Auth.Account account) :
     base(account.Username, account.Properties, account.Cookies)
 {
 }
コード例 #23
0
        public async void Login()
        {
            Animate      = true;
            Instructions = "Validating Identity";
            bool _Failure = false;

            //Diagnostics
            string Message    = string.Empty;
            string StackTrace = string.Empty;

            await Task.Run(() =>
            {
                try
                {
                    //Place base code here
                    //Authenticate Site User here
                    if (string.IsNullOrWhiteSpace(Username))
                    {
                        throw new ArgumentNullException("Username cannot be empty. Please try again");
                    }
                    if (string.IsNullOrWhiteSpace(Password))
                    {
                        throw new ArgumentNullException("Password cannot be empty. Please try again");
                    }

                    if (accountManager != null)
                    {
                        //Apple Test Account
                        var hasher         = new PasswordEncoder();
                        var hashedPassword = hasher.Encode(Password, EncryptType.SHA_512);
                        if (accountManager.AuthenticateSiteUser_ByCredentials(Username, hashedPassword))
                        {
                            var curr = accountManager.GetSiteUser_ByUsername <Account>(Username);
                            Constants.InMemory_ContactID = curr.Contact_ID_Ref;

                            #region Save Credentials to Keychain if Remember me is Enabled
                            var credentialsStore = Xamarin.Auth.AccountStore.Create();
                            var AccountDetails   = new Xamarin.Auth.Account();
                            AccountDetails.Properties.Clear();

                            if (RememberMe)
                            {
                                AccountDetails.Username = Username;
                                AccountDetails.Properties.Add("RememberMe", "true");
                            }
                            else
                            {
                                AccountDetails.Username = Username;
                                AccountDetails.Properties.Add("RememberMe", "false");
                            }

                            credentialsStore.FindAccountsForService(Credentials_Service).ToList().Clear();
                            credentialsStore.Save(AccountDetails, Credentials_Service);
                            #endregion

                            try
                            {
                                var contacts = contactStore.Get_ContactsFromStore <Contact>();
                                if (contacts != null)
                                {
                                    if (contactManager != null)
                                    {
                                        var QueryContacts = contactManager.Get_Contacts_ByUserID <Contact>(curr.Contact_ID_Ref);
                                        contacts.ForEach(w =>
                                        {
                                            //Add Contact to the contact store for the particular account
                                            if (QueryContacts.SingleOrDefault(i => i.Contact_ID == w.Contact_ID && i.User_ID == curr.Contact_ID_Ref) == null)
                                            {
                                                w.Sys_Creation    = DateTime.Now;
                                                w.Sys_Transaction = DateTime.Now;

                                                w.Contact_ID = contactManager.Get_NewContactID();
                                                w.User_ID    = curr.Contact_ID_Ref;
                                                w.Mobile     = curr.Mobile;

                                                //Add Contacts to Table
                                                if (contactManager != null)
                                                {
                                                    contactManager.AddContact_ByDetails(w);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                            catch (Exception eX)
                            {
                                string _Message    = string.Empty;
                                string _StackTrace = string.Empty;
                                if (eX.InnerException != null)
                                {
                                    _Message    = eX.InnerException.Message;
                                    _StackTrace = eX.InnerException.StackTrace;
                                }
                                else
                                {
                                    _Message    = eX.Message;
                                    _StackTrace = eX.StackTrace;
                                }

                                var mEx = new Exceptions(logging, _Message, _StackTrace);
                                if (mEx != null)
                                {
                                    mEx.HandleException(mEx, logging);
                                }
                            }

                            try
                            {
                                ////// Query Contacts and Music
                                var music = musicStore.GetMusic_Collection <Music>();
                                if (music != null)
                                {
                                    if (musicManager != null)
                                    {
                                        var QueryMusic = musicManager.GetMusicCollection_ByContactID <Music>(curr.Contact_ID_Ref);
                                        music.ForEach(w =>
                                        {
                                            if (QueryMusic.SingleOrDefault(i => i.User_ID == curr.Contact_ID_Ref) == null)
                                            {
                                                w.Sys_Creation    = DateTime.Now;
                                                w.Sys_Transaction = DateTime.Now;
                                                w.User_ID         = curr.Contact_ID_Ref;

                                                //Add Music to Table
                                                if (musicManager != null)
                                                {
                                                    musicManager.AddMusic(w);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                            catch (Exception mX)
                            {
                                string _Message    = string.Empty;
                                string _StackTrace = string.Empty;
                                if (mX.InnerException != null)
                                {
                                    _Message    = mX.InnerException.Message;
                                    _StackTrace = mX.InnerException.StackTrace;
                                }
                                else
                                {
                                    _Message    = mX.Message;
                                    _StackTrace = mX.StackTrace;
                                }

                                var mEx = new Exceptions(logging, _Message, _StackTrace);
                                if (mEx != null)
                                {
                                    mEx.HandleException(mEx, logging);
                                }
                            }
                        }
                        else
                        {
                            //Check Cloud Service for the Site user's membership and generate an account locally
                            if (Username.Equals("apple", StringComparison.OrdinalIgnoreCase) && Password.Equals("password", StringComparison.OrdinalIgnoreCase))
                            {
                                //Generate Account
                                Account obj              = new Account();
                                obj.Contact_ID_Ref       = Guid.NewGuid().ToString();
                                obj.FirstName            = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("Apple");
                                obj.LastName             = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("Inc");
                                obj.SiteUser_DisplayName = $"{ obj.FirstName } { obj.LastName }";

                                obj.Sys_Creation    = DateTime.Now;
                                obj.Sys_Transaction = DateTime.Now;

                                //Has the passwords on account generation and on login
                                obj.Username = Username;
                                obj.Password = hashedPassword;

                                obj.Mobile = "";
                                obj.Work   = "";
                                obj.Email  = Username;
                                obj.Home   = "";

                                Constants.InMemory_ContactID = obj.Contact_ID_Ref;
                                accountManager.AddAccount_ByHashedPassword(obj);
                            }
                            else
                            {
                                DataVaultAccountServiceClient accountsClient = new DataVaultAccountServiceClient(ConfigurationManager.InSecurePublicBinding(), new System.ServiceModel.EndpointAddress(Constants.AccountsInSecureUrl));

                                var dataClient = accountsClient._Login_AccountForUserCredentials(Username, Password);
                                if (dataClient.SiteUser != null)
                                {
                                    var curr = dataClient.SiteUser;
                                    Constants.InMemory_ContactID = curr.User_ID;

                                    //Generate Account
                                    Account obj              = new Account();
                                    obj.Contact_ID_Ref       = curr.User_ID;
                                    obj.FirstName            = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(curr.First_Name);
                                    obj.LastName             = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(curr.Last_Name);
                                    obj.SiteUser_DisplayName = $"{ obj.FirstName } { obj.LastName }";

                                    obj.Sys_Creation    = DateTime.Now;
                                    obj.Sys_Transaction = DateTime.Now;

                                    //Has the passwords on account generation and on login
                                    obj.Username = Username;
                                    obj.Password = hashedPassword;

                                    obj.Mobile = curr.Mobile;
                                    obj.Work   = curr.Work;
                                    obj.Email  = Username;
                                    obj.Home   = curr.Home;
                                    obj.Avatar = curr.Avatar;

                                    accountManager.AddAccount_ByHashedPassword(obj); //Add account to local store

                                    #region Save Credentials to Keychain if Remember me is Enabled
                                    var credentialsStore = Xamarin.Auth.AccountStore.Create();
                                    var AccountDetails   = new Xamarin.Auth.Account();
                                    AccountDetails.Properties.Clear();

                                    if (RememberMe)
                                    {
                                        AccountDetails.Username = Username;
                                        AccountDetails.Properties.Add("RememberMe", "true");
                                    }
                                    else
                                    {
                                        AccountDetails.Username = Username;
                                        AccountDetails.Properties.Add("RememberMe", "false");
                                    }

                                    credentialsStore.Save(AccountDetails, Credentials_Service);
                                    #endregion

                                    try
                                    {
                                        var contacts = contactStore.Get_ContactsFromStore <Contact>();
                                        if (contacts != null)
                                        {
                                            if (contactManager != null)
                                            {
                                                var QueryContacts = contactManager.Get_Contacts_ByUserID <Contact>(curr.User_ID);
                                                contacts.ForEach(w =>
                                                {
                                                    //Add Contact to the contact store for the particular account
                                                    if (QueryContacts.SingleOrDefault(i => i.Contact_ID == w.Contact_ID && i.User_ID == curr.User_ID) == null)
                                                    {
                                                        w.Sys_Creation    = DateTime.Now;
                                                        w.Sys_Transaction = DateTime.Now;

                                                        w.Contact_ID = contactManager.Get_NewContactID();
                                                        w.User_ID    = curr.User_ID;

                                                        //Add Contacts to Table
                                                        if (contactManager != null)
                                                        {
                                                            contactManager.AddContact_ByDetails(w);
                                                        }
                                                    }
                                                });
                                            }
                                        }

                                        var music = musicStore.GetMusic_Collection <Music>();

                                        // Query Contacts and Music
                                        if (music != null)
                                        {
                                            if (musicManager != null)
                                            {
                                                var QueryMusic = musicManager.GetMusicCollection_ByContactID <Music>(curr.User_ID);
                                                music.ForEach(w =>
                                                {
                                                    if (QueryMusic.SingleOrDefault(i => i.User_ID == curr.User_ID) == null)
                                                    {
                                                        w.Sys_Creation    = DateTime.Now;
                                                        w.Sys_Transaction = DateTime.Now;
                                                        w.User_ID         = curr.User_ID;

                                                        //Add Music to Table
                                                        if (musicManager != null)
                                                        {
                                                            musicManager.AddMusic(w);
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    }
                                    catch (Exception eX)
                                    {
                                        string oMessage    = string.Empty;
                                        string oStackTrace = string.Empty;

                                        if (eX.InnerException != null)
                                        {
                                            oMessage    = eX.InnerException.Message;
                                            oStackTrace = eX.InnerException.StackTrace;
                                        }
                                        else
                                        {
                                            oMessage    = eX.Message;
                                            oStackTrace = eX.StackTrace;
                                        }

                                        var mEx = new Exceptions(logging, oMessage, oStackTrace);
                                        if (mEx != null)
                                        {
                                            mEx.HandleException(mEx, logging);
                                        }
                                    }
                                }
                                else
                                {
                                    throw new MemberAccessException("Authentication failure. The credentials you have provided are not valid. Please register an account");
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentNullException("iOC Dependency is null. Please contact site administrator for assistance");
                    }
                }
                catch (Exception ex)
                {
                    HasError = true;
                    _Failure = true;

                    if (ex.InnerException != null)
                    {
                        Message    = ex.InnerException.Message;
                        StackTrace = ex.InnerException.StackTrace;
                    }
                    else
                    {
                        Message    = ex.Message;
                        StackTrace = ex.StackTrace;
                    }

                    var mEx = new Exceptions(logging, Message, StackTrace);
                    if (mEx != null)
                    {
                        mEx.HandleException(mEx, logging);
                    }
                }
            }).ContinueWith((e) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Animate = false;

                    if (_Failure)
                    {
                        //Output a dialogue here
                        if (dialogue != null)
                        {
                            dialogue.ShowAlert("mmm...Something went wrong", Message);
                        }
                    }
                    else
                    {
                        if (this.navigation != null)
                        {
                            this.navigation.NavigateToViewModelAsync <HomeViewModel>(true);
                        }
                    }
                });
            });
        }