public async Task<bool> SignIn()
 {
     if (!this.IsSignIn()) return false;
     PtcAccount account = await this.GetPtcAccountAsync();
     if (account == null) return false;
     this.myAccount = account;
     return true;
 }
        public async Task<bool> UpdatePtcAccount(PtcAccount account)
        {
            MSPtcAccount mspa = PtcAccount.ConvertToMSPtcAccount(account);
            List<MSStorageAccount> saList = new List<MSStorageAccount>();
            await App.MobileService.GetTable<MSPtcAccount>().UpdateAsync(mspa);

            this.myAccount = account;
            return true;
        }
        public async Task<bool> DeletePtcAccount(PtcAccount account)
        {
            MSPtcAccount mspa = PtcAccount.ConvertToMSPtcAccount(account);
            await App.MobileService.GetTable<MSPtcAccount>().DeleteAsync(mspa);

            App.ApplicationSettings.Remove(PTCACCOUNT_ID);
            App.ApplicationSettings.Save();
            this.myAccount = null;
            return true;
        }
        public async Task<bool> CreateNewPtcAccountAsync(PtcAccount account)
        {
            MSPtcAccount mspa = PtcAccount.ConvertToMSPtcAccount(account);
            PtcAccount p = await this.GetPtcAccountAsync(account.Email);
            if (p != null) return false;
            await App.MobileService.GetTable<MSPtcAccount>().InsertAsync(mspa);

            this.SavePtcId(account.Email, account.ProfilePassword);
            this.myAccount = account;
            return true;
        }
        //public async Task<bool> CreateStorageAccountAsync(StorageAccount sa)
        //{
        //    MSStorageAccount mssa = StorageAccount.ConvertToMSStorageAccount(sa);
        //    mssa.ptc_account_id = this.Email;
        //    try
        //    {
        //        await App.MobileService.GetTable<MSStorageAccount>().InsertAsync(mssa);
        //        StorageAccounts.Add(sa.StorageName, sa);
        //        return true;
        //    }
        //    catch(Exception ex)
        //    {
        //        Debug.WriteLine(ex.ToString());
        //        return false;
        //    }
        //}
        //private async Task<StorageAccount> GetStorageAccountAsync(string storageAccountId)
        //{
        //    MobileServiceCollection<MSStorageAccount, MSStorageAccount> accounts = null;
        //    try
        //    {
        //        accounts = await App.MobileService.GetTable<MSStorageAccount>()
        //            .Where(a => a.account_platform_id == storageAccountId)
        //            .ToCollectionAsync();
        //    }
        //    catch (MobileServiceInvalidOperationException ex)
        //    {
        //        Debug.WriteLine(ex.ToString());
        //        throw new Exception("AccountManager.GetAccount() ERROR");
        //    }

        //    if (accounts.Count == 1)
        //        return StorageAccount.ConvertToStorageAccount(accounts.First());
        //    else if (accounts.Count > 1)
        //        throw new Exception("AccountManager.GetAccount() ERROR");
        //    else
        //        return null;
        //}

        //public StorageAccount GetStorageAccountById(string storageAccountId)
        //{
        //    if(storageAccountId == null || string.Empty.Equals(storageAccountId)) return null;
        //    using (var itr = StorageAccounts.GetEnumerator())
        //    {
        //        while (itr.MoveNext())
        //        {
        //            if (storageAccountId.Equals(itr.Current.Value.Id))
        //                return itr.Current.Value;
        //        }
        //    }
        //    return null;
        //}

        //public StorageAccount GetStorageAccountByName(string storageName)
        //{
        //    if (StorageAccounts.ContainsKey(storageName))
        //        return StorageAccounts[storageName];
        //    else
        //        return null;
        //}
        //public IEnumerator<KeyValuePair<string, StorageAccount>> GetStorageAccountEnumerator()
        //{
        //    return StorageAccounts.GetEnumerator();
        //}

        public static MSPtcAccount ConvertToMSPtcAccount(PtcAccount pa)
        {
            MSPtcAccount mspa = new MSPtcAccount(pa.Name, pa.Email, pa.PhoneNumber, pa.ProfilePassword, 0.0, pa.AccountType.Id, "for_later_develop");
            return mspa;
        }
 public static PtcAccount ConvertToPtcAccount(MSPtcAccount mspa)
 {
     PtcAccount account = new PtcAccount();
     account.Name = mspa.name;
     account.Email = mspa.email;
     account.PhoneNumber = mspa.phone_number;
     account.ProfilePassword = mspa.profile_password;
     account.UsedSize = mspa.used_size;
     account.AccountType = new StorageAccountType();
     return account;
 }
        public async Task<PtcAccount> GetPtcAccountAsync(string accountId, string password = null)
        {
            Expression<Func<MSPtcAccount, bool>> lamda = (a => a.email == accountId);
            if (password != null)
                lamda = (a => a.email == accountId && a.profile_password == password);

            MobileServiceCollection<MSPtcAccount, MSPtcAccount> list =
                await App.MobileService.GetTable<MSPtcAccount>().Where(lamda).ToCollectionAsync();

            if (list.Count >= 1)
            {
                PtcAccount account = PtcAccount.ConvertToPtcAccount(list.First());
                this.myAccount = account;
                return account;
            }
            else
                return null;
        }
        private async void ui_create_btn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                ui_name.Text = ui_name.Text.Trim();
                ui_email.Text = ui_email.Text.Trim();
                ui_password.Password = ui_password.Password.Trim();

                // Email Check
                if (!Regex.IsMatch(ui_email.Text,
                        @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))"
                        + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,24}))$",
                        RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)))
                {
                    MessageBox.Show(AppResources.BadEmailAddressMessage, AppResources.BadEmailAddressCaption, MessageBoxButton.OK);
                    ui_password.Password = String.Empty;
                    return;
                }


                // Show progress indicator
                // While loading, unable UI instance
                // Set PtcAccount
                base.SetProgressIndicator(true, AppResources.CreateProfile);
                ui_name.IsEnabled = false;
                ui_email.IsEnabled = false;
                ui_password.IsEnabled = false;
                ui_create_btn.IsEnabled = false;
                ui_sign_in_btn.IsEnabled = false;
                PtcAccount ptcAccount = new PtcAccount();
                ptcAccount.Name = ui_name.Text;
                ptcAccount.Email = ui_email.Text;
                ptcAccount.ProfilePassword = ui_password.Password;

                // Make a new account and move to sign in storage page.
                try
                {
                    if (await App.AccountManager.CreateNewPtcAccountAsync(ptcAccount))
                    {
                        NavigationService.Navigate(new Uri(EventHelper.SIGNIN_STORAGE_PAGE, UriKind.Relative));
                    }
                    else  // If there is a duplicated Email address, it fails.
                    {
                        ui_name.IsEnabled = true;
                        ui_email.IsEnabled = true;
                        ui_password.IsEnabled = true;
                        ui_password.Password = String.Empty;
                        MessageBox.Show(AppResources.DuplicateEmailAddressMessage, AppResources.DuplicateEmailAddressCaption, MessageBoxButton.OK);
                    }
                }
                catch
                {
                    ui_name.IsEnabled = true;
                    ui_email.IsEnabled = true;
                    ui_password.IsEnabled = true;
                    ui_password.Password = String.Empty;
                    MessageBox.Show(AppResources.BadCreateProfileMessage, AppResources.BadCreateProfileCaption, MessageBoxButton.OK);
                }
                base.SetProgressIndicator(false);
            }
            else
            {
                MessageBox.Show(AppResources.InternetUnavailableMessage, AppResources.InternetUnavailableCaption, MessageBoxButton.OK);
            }
        }