Beispiel #1
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = new UserManager();
            var user    = new ApplicationUser()
            {
                UserName = UserName.Text
            };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                ApplicationUser newUser = manager.Find(UserName.Text, Password.Text);
                var             sa      = new StoredAccount();
                sa.CreateNewAccount(newUser.Id, Email.Text);
                var returnUrl = Request.QueryString["ReturnUrl"];
                IdentityHelper.SignIn(manager, user, isPersistent: false);
                if (returnUrl == null)
                {
                    IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response);
                }
                else
                {
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        private void StoredAccount_AccountDelete(object sender, RoutedEventArgs e)
        {
            StoredAccount storedAccount = sender as StoredAccount;

            if (storedAccount == null)
            {
                return;
            }

            lstStoredAccounts.Items.Remove(storedAccount);

            SettingsManager.PersistentSettings.RemoveUser(
                storedAccount.Account.Login);
        }
        /**
         * This asynchronous function check our credentials and store them in our database.
         * We also store some user information such as tweets numbers.
         */
        public async void success(PinAuthorizer auth)
        {
            //We use the data, check that is correct and store it. Finally, we navigate to other frame.
            //We create a twitter account handler
            var twitterCtx = new TwitterContext(auth);

            //Selection of our account
            var accounts =
                from acct in twitterCtx.Account
                where acct.Type == AccountType.VerifyCredentials
                select acct;

            //Current user
            User currentUser = accounts.SingleOrDefault().User;

            //Open the database and store this data
            var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + @"\" + Constants.getDbName();

            db = new SQLiteAsyncConnection(path);

            //We store all the data in the new account
            var newUser = new StoredAccount()
            {
                TwOAuthToken     = auth.OAuthTwitter.OAuthToken,
                TwAccessToken    = auth.OAuthTwitter.OAuthTokenSecret,
                TwId             = currentUser.Identifier.UserID,
                TwUsername       = currentUser.Identifier.ScreenName,
                TwName           = currentUser.Name,
                TwFollowingCount = currentUser.FriendsCount,
                TwFollowersCount = currentUser.FollowersCount,
                TwTweetCount     = currentUser.StatusesCount,
                TwAvatarURL      = currentUser.ProfileImageUrl,
                DefaultAccount   = true
            };

            //Finally, we store the data in the DB
            await db.InsertAsync(newUser);

            //And we change the page to the timeline page
            SuspensionManager.SessionState["MyUser"]         = newUser;
            SuspensionManager.SessionState["TwitterContext"] = twitterCtx;
            Frame.Navigate(typeof(TimeLinePage));
        }
        private async void StoredAccount_AccountClick(object sender, RoutedEventArgs e)
        {
            lstStoredAccounts.IsEnabled     = false;
            btnOpenStoredAccounts.IsEnabled = false;

            StoredAccount storedAccount = sender as StoredAccount;

            if (storedAccount == null)
            {
                return;
            }

            try
            {
                if (!SettingsManager.PersistentSettings.SetCurrentUser(
                        storedAccount.Account.Login))
                {
                    return;
                }

                if (NavigationController.Instance.HistoryIsEmpty())
                {
                    NavigationController.Instance.RequestPage <FeedPage>();
                }
                else
                {
                    NavigationController.Instance.GoBack();
                }

                btnOpenStoredAccounts.IsChecked = false;
            }
            catch (Exception ex)
            {
                await DialogManager.ShowErrorDialog(ex.Message)
                .ConfigureAwait(true);
            }
            finally
            {
                lstStoredAccounts.IsEnabled     = true;
                btnOpenStoredAccounts.IsEnabled = true;
            }
        }
        public IActionResult Create(OutputAccount newAccount)
        {
            if (ModelState.IsValid)
            {
                StoredAccount storedAccount = new StoredAccount
                {
                    UserId = int.Parse(UserManager.GetUserId(User))
                };

                DbContext.StoredAccounts.Add(storedAccount);
                DbContext.SaveChanges();

                int currentAccountId = storedAccount.AccountId;

                StoredAccountDetails storedAccountDetails = newAccount.StoredAccountDetails;
                storedAccountDetails.AccountId = currentAccountId;


                string encryptedPassword = (newAccount.Password != null) && (newAccount.Password != "") && (newAccount.Password != " ") ?
                                           CredentialsProcessor.Encrypt(newAccount.Password, User.Identity.Name) : " ";

                StoredAccountPassword storedAccountPassword = new StoredAccountPassword
                {
                    AccountId = currentAccountId,
                    Password  = encryptedPassword
                };

                DbContext.StoredPasswords.Add(storedAccountPassword);
                DbContext.StoredAccountsDetails.Add(storedAccountDetails);
                DbContext.SaveChanges();

                return(RedirectToAction("Index"));
            }

            return(View());
        }
        public async Task ReloadStoredAccounts()
        {
            _autoUpdateStatusTimer.Stop();

            await Dispatcher.Invoke(() =>
            {
                return(ShowLoadingGrid(true));
            }).ConfigureAwait(false);

            try
            {
                Interlocked.Increment(ref _accountsUpdateWaitingCount);

                await _accountsUpdateLock.WaitAsync()
                .ConfigureAwait(true);
            }
            finally
            {
                Interlocked.Decrement(ref _accountsUpdateWaitingCount);
            }

            try
            {
                Dispatcher.Invoke(() =>
                {
                    lstStoredAccounts.Items.Clear();
                });

                if (SettingsManager.PersistentSettings.AvailableUsers.Values.Count == 0)
                {
                    return;
                }

                foreach (var user in SettingsManager.PersistentSettings.AvailableUsers.Values)
                {
                    Dispatcher.Invoke(() =>
                    {
                        var storedAccountWidget = new StoredAccount
                        {
                            Account = user
                        };
                        storedAccountWidget.AccountClick  += StoredAccount_AccountClick;
                        storedAccountWidget.AccountDelete += StoredAccount_AccountDelete;

                        lstStoredAccounts.Items.Add(storedAccountWidget);
                    });
                }

                ItemCollection items = null;

                Dispatcher.Invoke(() =>
                {
                    lstStoredAccounts.GetChildOfType <ScrollViewer>()?
                    .ScrollToVerticalOffset(0);

                    items = lstStoredAccounts.Items;
                });

                await Task.Delay(500)
                .ConfigureAwait(true);

                if (_accountsUpdateWaitingCount == 0)
                {
                    await Dispatcher.Invoke(() =>
                    {
                        return(ShowLoadingGrid(false));
                    }).ConfigureAwait(false);
                }

                foreach (var item in items)
                {
                    var storedAccountWidget = item as StoredAccount;

                    if (storedAccountWidget == null)
                    {
                        continue;
                    }

                    await Dispatcher.Invoke(() =>
                    {
                        return(storedAccountWidget.UpdateAccount());
                    }).ConfigureAwait(false);
                }
            }
            finally
            {
                await Task.Delay(500)
                .ConfigureAwait(true);

                if (_accountsUpdateWaitingCount == 0)
                {
                    await Dispatcher.Invoke(() =>
                    {
                        return(ShowLoadingGrid(false));
                    }).ConfigureAwait(false);

                    _autoUpdateStatusTimer.Start();
                }

                _accountsUpdateLock.Release();
            }
        }
 public bool findDefaultUser(StoredAccount storedAccount)
 {
     return(storedAccount.DefaultAccount);
 }
        /**
         * Check if the database exists. In that case, we need to know if there is some content there or not.
         * If there is no content, we must create the tables and look forward to request tokens to the user (loggin).
         * If there is content, we must retrieve and use it to loggin.
         */
        public async void checkDatabaseExists()
        {
            var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + @"\" + Constants.getDbName();

            db = new SQLiteAsyncConnection(path);
            List <StoredAccount> allAccounts = null;
            //await db.DropTableAsync<StoredAccount>();
            //await db.DropTableAsync<StoredStatus>();

            //QUITAR ESTA MIERDA
            await db.CreateTableAsync <StoredAccount>();

            await db.CreateTableAsync <StoredStatus>();

            //await db.CreateTableAsync<StoredMention>();

            //Look if there is something on storedaccounts

            allAccounts = await db.QueryAsync <StoredAccount>("SELECT * FROM StoredAccounts");

            if (allAccounts == null || allAccounts.ToArray().Length == 0)
            {
                //Obtains the translator
                translator = SuspensionManager.SessionState["Translator"] as Translator;

                //Translates some texts
                steps.Text                    = translator.getCadena("steps:");
                instructions.Text             = translator.getCadena("instructions");
                notstoringcredentials.Text    = translator.getCadena("notstoringcredentials");
                AuthenticatePinButton.Content = translator.getCadena("authenticate");
            }
            else
            {
                //Get the default user
                var defaultAccount = allAccounts.FindAll(findDefaultUser);

                //The first situation should be the correct one
                switch (defaultAccount.ToArray().Length)
                {
                case 1:     //There is one default user, so I'll take it
                    myDefaultAccount = defaultAccount.ToArray()[0];
                    break;

                case 0:     //There is no default user, so I'll set up the first userAccount as default
                    var singleAccount = allAccounts.First();
                    singleAccount.DefaultAccount = true;
                    await db.UpdateAsync(singleAccount);

                    myDefaultAccount = singleAccount;
                    break;

                default:     //Too many defaults users, so I'll set up the first user Account as default
                    //Firstly, I'll set up all default detected accounts as false
                    foreach (StoredAccount singleTemporalAccount in defaultAccount)
                    {
                        var tmp = singleTemporalAccount;
                        tmp.DefaultAccount = false;
                        await db.UpdateAsync(tmp);
                    }

                    var singleAccount2 = allAccounts.First();
                    singleAccount2.DefaultAccount = true;
                    await db.UpdateAsync(singleAccount2);

                    myDefaultAccount = singleAccount2;
                    break;
                } //switch

                //After that, we must check the credentials from myDefaultAccount variable
                SingleUserAuthorizer auth = new SingleUserAuthorizer
                {
                    Credentials = new InMemoryCredentials
                    {
                        ConsumerKey    = Constants.getConsumerKey(),
                        ConsumerSecret = Constants.getConsumerSecret(),
                        OAuthToken     = myDefaultAccount.TwOAuthToken,
                        AccessToken    = myDefaultAccount.TwAccessToken
                    }
                };

                var twitterCtx = new TwitterContext(auth);

                if (NetworkInformation.GetInternetConnectionProfile() == null)
                {
                    SuspensionManager.SessionState["MyUser"] = myDefaultAccount;
                }
                else
                {
                    //Selection of our account
                    //var accounts =
                    //    from acct in twitterCtx.Account
                    //    where acct.Type == AccountType.VerifyCredentials
                    //    select acct;

                    //Current user
                    //currentUser = accounts.SingleOrDefault().User;
                    currentUser = (from acct in twitterCtx.Account
                                   where acct.Type == AccountType.VerifyCredentials
                                   select acct).SingleOrDefault().User;



                    var newUser = new StoredAccount()
                    {
                        TwOAuthToken     = auth.OAuthTwitter.OAuthToken,
                        TwAccessToken    = auth.OAuthTwitter.OAuthTokenSecret,
                        TwId             = currentUser.Identifier.UserID,
                        TwUsername       = currentUser.Identifier.ScreenName,
                        TwName           = currentUser.Name,
                        TwFollowingCount = currentUser.FriendsCount,
                        TwFollowersCount = currentUser.FollowersCount,
                        TwTweetCount     = currentUser.StatusesCount,
                        TwAvatarURL      = currentUser.ProfileImageUrl,
                        DefaultAccount   = true
                    };

                    SuspensionManager.SessionState["MyUser"] = newUser;
                }


                //Finally, we transfer the credentials

                SuspensionManager.SessionState["TwitterContext"] = twitterCtx;
                Frame.Navigate(typeof(TimeLinePage));
            }
        }
        /**
         * This asynchronous function check our credentials and store them in our database.
         * We also store some user information such as tweets numbers.
         */ 
        public async void success(PinAuthorizer auth)
        {
            //We use the data, check that is correct and store it. Finally, we navigate to other frame.
            //We create a twitter account handler
            var twitterCtx = new TwitterContext(auth);

            //Selection of our account
            var accounts =
                from acct in twitterCtx.Account
                where acct.Type == AccountType.VerifyCredentials
                select acct;

            //Current user
            User currentUser = accounts.SingleOrDefault().User;

            //Open the database and store this data
            var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + @"\" + Constants.getDbName();
            db = new SQLiteAsyncConnection(path);

            //We store all the data in the new account
            var newUser = new StoredAccount()
            {
                TwOAuthToken = auth.OAuthTwitter.OAuthToken,
                TwAccessToken = auth.OAuthTwitter.OAuthTokenSecret,
                TwId = currentUser.Identifier.UserID,
                TwUsername = currentUser.Identifier.ScreenName,
                TwName = currentUser.Name,
                TwFollowingCount = currentUser.FriendsCount,
                TwFollowersCount = currentUser.FollowersCount,
                TwTweetCount = currentUser.StatusesCount,
                TwAvatarURL = currentUser.ProfileImageUrl,
                DefaultAccount = true
            };

            //Finally, we store the data in the DB
            await db.InsertAsync(newUser);

            //And we change the page to the timeline page
            SuspensionManager.SessionState["MyUser"] = newUser;
            SuspensionManager.SessionState["TwitterContext"] = twitterCtx;
            Frame.Navigate(typeof(TimeLinePage));
        }
Beispiel #10
0
        /**
         * Main method:
         * -Varaibles initialization.
         * -Context variables obtention.
         * -Establishment of some events.
         * -Get last tweets and mentions.
         *
         * Every minute (timer) the program recovers last tweets and mentions. Throught the
         * "Connect" and "Mention" buttons it iterates between our TimeLine and Mention
         * tweets.
         */

        public TimeLinePage()
        {
            this.InitializeComponent();
            loadingring.IsActive = true;

            //Obtains the translator
            translator = SuspensionManager.SessionState["Translator"] as Translator;

            //Translates some texts
            //loadingtext.Text = translator.getCadena("loading...");
            //tweetsendingstatus.Text = translator.getCadena("sending...");
            whatshappening.Text    = translator.getCadena("whatshappening");
            multipletweets.Content = translator.getCadena("multipletweets");
            orientationtext.Text   = translator.getCadena("verticalorientation");


            //Timer to start the application
            firstloadtimer = new DispatcherTimer {
                Interval = new TimeSpan(0, 0, 1)
            };

            //Timer to reload tweets
            loadtweetstimer = new DispatcherTimer {
                Interval = new TimeSpan(0, 0, 1, 0)
            };

            //Timer to blink "tweet sent"
            tweetsenttimer = new DispatcherTimer {
                Interval = new TimeSpan(0, 0, 2)
            };

            //We must recive always the twitter context, and there should be impossible not to recive it
            if (SuspensionManager.SessionState.ContainsKey("TwitterContext"))
            {
                twitterCtx = SuspensionManager.SessionState["TwitterContext"] as TwitterContext;
            }
            else
            {  //Look for it in the database, but this shouldn't happen.
               //At this moment, this is not necessary
            }

            //It must recive always the user, and there should be impossible not to recive it
            if (SuspensionManager.SessionState.ContainsKey("MyUser"))
            {
                currentUser = SuspensionManager.SessionState["MyUser"] as StoredAccount;
            }
            else
            {  //Look for it in the database, but this shouldn't happen.
               //At this moment, this is not necessary
            }

            //Establishment of some events
            firstloadtimer.Tick         += firstloadtimer_Tick;
            tweetsenttimer.Tick         += tweetsenttimer_Tick;
            loadtweetstimer.Tick        += loadtweetstimer_Tick;
            connectImage.PointerPressed += connect_Click;
            homeImage.PointerPressed    += home_Click;

            firstloadtimer.Start();

            abouttext.Text = "JMTwitter has been developed by Juan Miguel Valverde Martinez (lipman). " +
                             "I have many thoughts for the next version in mind, and I hope continue with this project.\n\n" +
                             "Credits:\n-Joe Mayo and his team, who made this possible (LinqToTwitter)\n" +
                             "-Frank Krueger (sqlite-net)\n-@rNiubo and #OlimpiadAPPs to encourage me to learn C# and about W8 development.\n\n" +
                             "Contact: @jmlipman\nWebsite: delanover.com/ajsdbasdhas dhas dahs dajhs dha sdha s";

            /*var account = (from acct in twitterCtx.Account
             *                         where acct.Type == AccountType.Settings
             *                         select acct).SingleOrDefault();
             *
             *
             *      Debug.WriteLine("lalalal: "+account.Settings.Language);*/
        }
        public async Task ReloadStoredAccounts()
        {
            _autoUpdateStatusesTimer.Stop();

            await Dispatcher.Invoke(() =>
            {
                return(ShowLoadingGrid());
            }).ConfigureAwait(false);

            try
            {
                Interlocked.Increment(
                    ref _accountsUpdateWaitingCount);

                await _accountsUpdateLock.WaitAsync()
                .ConfigureAwait(true);
            }
            finally
            {
                Interlocked.Decrement(
                    ref _accountsUpdateWaitingCount);
            }

            try
            {
                Dispatcher.Invoke(() =>
                {
                    StoredAccountsListBox.Items.Clear();
                });

                if (SettingsManager.PersistentSettings.AvailableUsers.Values.Count == 0)
                {
                    return;
                }

                foreach (var user in SettingsManager.PersistentSettings.AvailableUsers.Values)
                {
                    Dispatcher.Invoke(() =>
                    {
                        var storedAccount = new StoredAccount
                        {
                            UserAccount = user,
                            Margin      = new Thickness(5)
                        };
                        storedAccount.Click         += StoredAccount_Click;
                        storedAccount.AccountDelete += StoredAccount_AccountDelete;

                        StoredAccountsListBox.Items.Add(
                            storedAccount);
                    });
                }

                ItemCollection items = null;

                Dispatcher.Invoke(() =>
                {
                    StoredAccountsListBox
                    .GetChildOfType <ScrollViewer>()?
                    .ScrollToVerticalOffset(0);

                    items = StoredAccountsListBox.Items;
                });

                await Task.Delay(
                    TimeSpan.FromSeconds(0.5))
                .ConfigureAwait(true);

                if (_accountsUpdateWaitingCount == 0)
                {
                    await Dispatcher.Invoke(() =>
                    {
                        return(HideLoadingGrid());
                    }).ConfigureAwait(false);
                }

                foreach (var item in items)
                {
                    if (!(item is StoredAccount storedAccount))
                    {
                        continue;
                    }

                    await Dispatcher.Invoke(() =>
                    {
                        return(storedAccount
                               .UpdateAccount());
                    }).ConfigureAwait(false);
                }
            }
            finally
            {
                await Task.Delay(
                    TimeSpan.FromSeconds(0.5))
                .ConfigureAwait(true);

                if (_accountsUpdateWaitingCount == 0)
                {
                    await Dispatcher.Invoke(() =>
                    {
                        return(HideLoadingGrid());
                    }).ConfigureAwait(false);

                    _autoUpdateStatusesTimer.Start();
                }

                _accountsUpdateLock.Release();
            }
        }