private async Task AddBookRecense(Session session)
		{
			string message = session.Parameters.GetValue<string>( "message" );
			int bookId = session.Parameters.GetValue<int>( "bookId" );
		    
			await _recensesProvider.AddRecenseForBook( message, bookId, session.Token );
		}
		/// <summary>
		///     Initializes a new instance of the <see cref="SessionAbortedEventArgs" /> class.
		/// </summary>
		/// <param name="session">The session.</param>
		/// <param name="exception">The exception.</param>
		public SessionAbortedEventArgs( Session session, Exception exception )
			: base( session )
		{
			//Contract.Requires<ArgumentNullException>( session != null, "session" );

			_exception = exception;
		}
		private async Task AddPersonRecense( Session session )
		{
			string message = session.Parameters.GetValue<string>( "message" );
			string personUuid = session.Parameters.GetValue<string>( "personUuid" );

			await _recensesProvider.AddRecenseForPerson( message, personUuid, session.Token );
		}
		public async Task AddBookRecense( string message, int bookId )
		{
			Session session = new Session( AddBookRecensePart );
			session.AddParameter( "message", message );
			session.AddParameter( "bookId", bookId );
			await Load( session );
		}
		private async Task RegistrationProceed(Session session)
		{
			var credential = session.Parameters.GetValue<CatalitCredentials>(RegistrationParameter);
            var exitsCredentials =  _credentialsProvider.ProvideCredentials(session.Token);

            var userInfo = await _profileProvider.Register(credential, session.Token, exitsCredentials);

            if (userInfo != null && !string.IsNullOrEmpty(userInfo.SessionId))
			{
				//Merge accounts if exits not user			
                if (toCreateShopAccount || (exitsCredentials != null && !exitsCredentials.IsRealAccount))
				{
				    try
				    {
                        await _profileProvider.MergeAccounts(userInfo.SessionId, exitsCredentials, session.Token);
				    }
                    catch(Exception e) {}
				}

                credential.Sid = userInfo.SessionId;
				_credentialsProvider.RegisterCredentials(credential, session.Token);
				Credential = credential;
                _catalogProvider.CheckBooks();
			}
			//ToDo: What next? Go back?
		}
		public async Task AddPersonRecense( string message, string personUuid )
		{
			var session = new Session( AddPersonRecensePart );
			session.AddParameter( "message", message );
			session.AddParameter( "personUuid", personUuid );
			await Load( session );
		}
		public async Task<bool> SearchBooks( string searchString )
		{
			Session session = new Session( LoadBooksPart );
			session.AddParameter( "search", searchString );
			await Load( session );
			return Founded;
		}
		private async Task ChangePasswordProceed( Session session )
		{
			UserInformation uinfo = session.Parameters.GetValue<UserInformation>( ChangePasswordParameter );
			await _profileProvider.ChangeUserInfo( uinfo, session.Token );
			var creds =  _credentialsProvider.ProvideCredentials( session.Token );
			creds.Password = uinfo.NewPassword;
			_credentialsProvider.RegisterCredentials( creds, session.Token );
			Credentials = creds;
		}
		private async Task LoadCollections( Session session )
		{
			var collections = await _collectionsProvider.ProvideMyCollections(session.Token);

			_loaded = true;

			Collections.BeginUpdate();
			Collections.Clear();
			Collections.AddRange(collections);
			Collections.EndUpdate();
		}
		public async Task LoadCredential(Session session)
		{
			var credential = _credentialsProvider.ProvideCredentials( session.Token );
			if(credential != null)
			{
				Credential = credential;
				if(!credential.IsRealAccount)
				{
					AccountName = credential.Login;
				}
			}
		}
		public async Task LoadNotifications( Session session )
		{
			IXList<Notification> notifications = await _notificationsProvider.GetNotifications( session.Token );

		    if (notifications.Count > 200)
		    {
                notifications =  new XSubRangeCollection<Notification>(notifications, 0, 200);
		    }
            
			Notifications.Update(notifications);

			NotificationsEmpty = Notifications.Count == 0;
		}
		private async Task SearchBooks( Session session )
		{
			string search = session.Parameters.GetValue<string>( "search" );
			var searchBooks = await _catalogProvider.SearchBooks( 0, search, session.Token );

			if(searchBooks != null && searchBooks.Count > 0)
			{
				Founded = true;
			}
			else
			{
				Founded = false;
			}
		}
        private async Task LoadSettings( Session session )
		{
          
           /* var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            //rsModel.LastUpdate = DateTime.Parse(localSettings.Values["LastUpdate"].ToString()); 
            try
            {
                _brightness = (float)localSettings.Values["Brightness"];
                _animate = (bool)localSettings.Values["AnimationMoveToPage"];
            }
            catch (Exception)
            {
                _autorotate = false;
                _brightness = 0;
                _animate = false;
            }*/
        }
		private async Task LoadPersonInfo(Session session, Person person)
		{
			Task loadPersonRecenses = LoadPersonRecenses( session, person );
			Task loadPersonBooks = LoadPersonBooks( session, person );
			Task loadNotificationStatus = LoadNotificationStatus( session, person );
			await Task.WhenAll( loadPersonRecenses, loadPersonBooks, loadNotificationStatus );
		}
		public Task LoadMore()
		{
			Session session = new Session( LoadMorePart );

			return Load( session );
		}
		public Task<Session> LoadById( string id )
		{
			Session session = new Session( LoadMainPart );
			session.AddParameter( "id", id );            
			return Load( session );
		}
		public Task<Session> LoadByName( string personName )
		{
			Session session = new Session( LoadMainPart );
			session.AddParameter( "personName", personName );

			return Load( session );
		}
		private async Task ChangeNotificationStatus(Session session)
		{
			if (AddedToNotifications)
			{
				await DeleteFromNotificationsProceed( session );
			}
			else
			{
				await AddToNotificationsProceed( session );
			}
			
		}
		public async void ChangeNotificationStatus()
		{
			Session session = new Session( ChangeNotificationStatusPart );
			session.AddParameter( "person", Entity );
			await Load( session );
		}
        private async Task BuyBookFromLitres(Session session, Book book)
        {
            UserInformation userInfo = null;
            try
            {
                userInfo = await _profileProvider.GetUserInfo(session.Token, true);
            }
            catch (Exception ex)
            {
                await new MessageDialog("Авторизируйтесь, пожалуйста.").ShowAsync();
            }
            if (userInfo == null) return;
            if (!string.IsNullOrEmpty(book.InGifts) && book.InGifts.Equals("1"))
            {
                await _litresPurchaseService.BuyBookFromLitres(book, session.Token);
            }
            else if (userInfo.Account - book.Price >= 0)
            {
                var dialog = new MessageDialog(string.Format("Подтвердите покупку книги за {0} руб.", book.Price), "Подтвердите покупку");
                dialog.DefaultCommandIndex = 0;
                dialog.CancelCommandIndex = 1;
                dialog.Commands.Add(new UICommand("купить", command => Task.Run(async () => await _litresPurchaseService.BuyBookFromLitres(book, session.Token))));
                dialog.Commands.Add(new UICommand("отмена") { Id = 1 });
                await dialog.ShowAsync();

                //var result = Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
                //"Подтвердите покупку",
                //string.Format("Подтвердите покупку книги за {0} руб.", Entity.Price),
                //new string[] { "купить", "отмена" },
                //0,
                //Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None,
                //null,
                //null);

                //result.AsyncWaitHandle.WaitOne();
                //int? choice = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result);
                //if (choice.HasValue && choice.Value == 0)
                //{
                //    await _litresPurchaseService.BuyBookFromLitres(book, session.Token);              
                //}                
            }
            else
            {
                OnPropertyChanged(new PropertyChangedEventArgs("ChoosePaymentMethod"));
            }
        }
        private async Task CreditCardInfoAsync(Session session)
        {
            var userInfo = await _profileProvider.GetUserInfo(session.Token, true);
            if (userInfo == null) return;
            if (_userInformation == null) _userInformation = userInfo;
            var cred = _credentialsProvider.ProvideCredentials(session.Token);

            if (!userInfo.CanRebill.Equals("0") &&
                cred != null &&
                !string.IsNullOrEmpty(cred.UserId) &&
                userInfo.UserId == cred.UserId &&
                !string.IsNullOrEmpty(cred.CanRebill) &&
                !cred.CanRebill.Equals("0"))
            {
                var box = new Dictionary<string, object>
                {
                    { "isSave", true },
                    { "isAuth", false }
                };
                var param = XParameters.Empty.ToBuilder()
                    .AddValue("Id", Book.Id)
                    .AddValue("Operation", (int)AccountDepositViewModel.AccountDepositOperationType.AccountDepositOperationTypeCreditCard)
                    .AddValue("ParametersDictionary", ModelsUtils.DictionaryToString(box)).ToImmutable();


                _navigationService.Navigate("AccountDeposit", param);
            }
            else
            {
                if (cred != null) _credentialsProvider.ForgetCredentialsRebill(cred, session.Token);
                ShowCreditCardView.Execute(Book);
            }
        }
		private async Task LoadNotificationStatus(Session session, Person person)
		{
			if ( person != null )
			{
				var notification = await _notificationsProvider.GetNotificationByAuthor( person, session.Token );

				AddedToNotifications = notification != null;
			}
		}
		private async Task LoadPerson(Session session)
		{
			AccountExist = (_credentialsProvider.ProvideCredentials(session.Token)) != null;

			Person person = null;

			string name = session.Parameters.GetValue<string>( "personName" );
			if (!string.IsNullOrEmpty( name ))
			{
				person = await _personsProvider.GetPersonByName( name, session.Token );
			}

			string id = session.Parameters.GetValue<string>( "id" );
			if (!string.IsNullOrEmpty( id ))
			{
				person = await _personsProvider.GetPersonById( id, session.Token );
			}

			Entity = person;
		    if (Entity?.TextDescription?.Text == null)
		    {
		        IsBioExists = false;
		    }
		    else
		    {
		        IsBioExists = true;
		    }

			_loaded = true;

			if (person != null)
			{
				await LoadPersonInfo(session, person);
			}
		}
		private async Task AddToNotificationsProceed(Session session)
		{
			Person person = session.Parameters.GetValue<Person>( "person", null );

			var notification = await _notificationsProvider.GetNotificationByAuthor( person, session.Token );

			if (notification == null && person != null)
			{
				await _notificationsProvider.AddNotification( person.Id, session.Token );
			}

			notification = await _notificationsProvider.GetNotificationByAuthor( person, session.Token );
			AddedToNotifications = notification != null;
		}
		private async Task DeleteFromNotificationsProceed(Session session)
		{
			Person person = session.Parameters.GetValue<Person>( "person", null );

			var notification = await _notificationsProvider.GetNotificationByAuthor( person, session.Token );

			if (notification != null)
			{
				await _notificationsProvider.DeleteNotifications( new XCollection<Notification> { notification }, session.Token );
			}

			notification = await _notificationsProvider.GetNotificationByAuthor( person, session.Token );
			AddedToNotifications = notification != null;
		}
		private async Task LoadHistory( Session session )
		{
			var history = await _searchHistoryProvider.GetHistory( session.Token );
			if( history != null )
			{
				SearchQueries.Update( history );
			}
		}
		private async Task LoadPersonRecenses(Session session, Person person)
		{
			if ( person != null )
			{
				var recenses = await _recensesProvider.GetRecensesForPerson(person.Id, session.Token);

				PersonRecenses.Update(recenses);
			}
		}
		private async Task AddToHistory( Session session )
		{
			var query = session.Parameters.GetValue<SearchQuery>( QueryParameter );
			await _searchHistoryProvider.AddToHistory( query, session.Token );
			var history = await _searchHistoryProvider.GetHistory( session.Token );
			if( history != null )
			{
				SearchQueries.Update( history );
			}
		}
		private async Task LoadPersonBooks(Session session, Person person)
		{
			if ( person != null )
			{
				var booksCount = PersonBooks.Count > 0 ? PersonBooks.Count - 1 : 0;

				var authorBooks = await _catalogProvider.GetBooksByAuthor(booksCount, person.Id, session.Token);

				if( authorBooks != null && authorBooks.Count > 0 )
				{
					if( PersonBooks.Count > 0 && PersonBooks[PersonBooks.Count - 1] == null )
					{
						PersonBooks.RemoveAt( PersonBooks.Count - 1 );
					}

					if( authorBooks.Count <= PersonBooks.Count )
					{
						_isEndOfList = true;
					}

					PersonBooks.Update( authorBooks );

					//PersonBooks.Add( new Book { IsEmptyElement = true } );
				}
			}
		}
 private async Task BuyBookAsync(Session session, Book book)
 {
     await _litresPurchaseService.BuyBook(book, CancellationToken.None);
 }