Exemplo n.º 1
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            this.methodComboBox.SelectedIndex = 0;

            try
            {
                LiveLoginResult loginResult = await this.AuthClient.IntializeAsync();

                if (loginResult.Session != null)
                {
                    this.liveConnectClient = new LiveConnectClient(loginResult.Session);
                }
            }
            catch (Exception ex)
            {
                this.LogOutput("Received an error during initializing. " + ex.Message);
            }
        }
Exemplo n.º 2
0
        private static LiveLoginResult RequestAccessToken(string postContent)
        {
            string          url         = LiveAuthUtility.BuildTokenUrl();
            HttpWebRequest  request     = WebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response    = null;
            LiveLoginResult loginResult = null;

            request.Method      = ApiMethod.Post.ToString().ToUpperInvariant();
            request.ContentType = TokenRequestContentType;

            try
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(postContent);
                }

                response    = request.GetResponse() as HttpWebResponse;
                loginResult = ReadResponse(response);
            }
            catch (WebException e)
            {
                response    = e.Response as HttpWebResponse;
                loginResult = ReadResponse(response);
            }
            catch (IOException ioe)
            {
                loginResult = new LiveLoginResult(new LiveAuthException(AuthErrorCodes.ClientError, ioe.Message));
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            if (loginResult == null)
            {
                loginResult = new LiveLoginResult(new LiveAuthException(AuthErrorCodes.ClientError, ErrorText.RetrieveTokenError));
            }

            return(loginResult);
        }
Exemplo n.º 3
0
        public async Task <bool> SignInSkydrive()
        {
            try
            {
                _authClient = new LiveAuthClient();
                LiveLoginResult loginResult = await this._authClient.LoginAsync(scopes);

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    _liveClient = new LiveConnectClient(loginResult.Session);
                    _session    = loginResult.Session;
                    return(true);
                }
            }
            catch (LiveAuthException authExp)
            {
            }
            return(false);
        }
Exemplo n.º 4
0
        public async Task <ActionResult> AuthHandler()
        {
            string redirectPath;

            try
            {
                LiveLoginResult result = await this.AuthClient.ExchangeAuthCodeAsync(this.HttpContext, this.CurrentPath);

                redirectPath = result.State;
            }
            catch (LiveAuthException ex)
            {
                redirectPath = ex.State;
            }

            this.Response.Redirect(redirectPath);

            return(null);
        }
Exemplo n.º 5
0
        public async Task <ActionResult> AjaxCallback()
        {
            try
            {
                LiveLoginResult loginStatus = await this.AuthClient.InitializeWebSessionAsync(this.HttpContext, this.CurrentPath);

                if (loginStatus.Status == LiveConnectSessionStatus.Expired)
                {
                    string reAuthUrl = this.AuthClient.GetLoginUrl(new string[] { "wl.signin" }, this.CurrentPath);
                    this.Response.Redirect(reAuthUrl);
                    return(null);
                }
            }
            catch (LiveAuthException)
            {
            }

            return(View("AjaxCallback", this.JSClientModel));
        }
Exemplo n.º 6
0
        private async void SignIn(object sender, RoutedEventArgs e)
        {
            try
            {
                LiveAuthClient  auth        = new LiveAuthClient();
                LiveLoginResult loginResult =
                    await auth.LoginAsync(new string[] { "wl.basic" });

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    this.infoTextBlock.Text = "Signed in.";
                }
            }
            catch (LiveAuthException exception)
            {
                this.infoTextBlock.Text = "Error signing in: "
                                          + exception.Message;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Upload a file to OneDrive
        /// </summary>
        /// <param name="Filename"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        public static async Task <int> UploadFileAsync(String Foldername, String Filename)
        {
            try
            {
                //  create OneDrive auth client
                var authClient = new LiveAuthClient();

                //  ask for both read and write access to the OneDrive
                LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.skydrive", "wl.skydrive_update" });

                //  if login successful
                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    //  create a OneDrive client
                    liveClient = new LiveConnectClient(result.Session);

                    //  create a local file
                    StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(Filename);

                    //  create a folder
                    string folderID = await GetFolderIDAsync(Foldername, true);

                    if (string.IsNullOrEmpty(folderID))
                    {
                        //  return error
                        return(0);
                    }

                    //  upload local file to OneDrive
                    await liveClient.BackgroundUploadAsync(folderID, file.Name, file, OverwriteOption.Overwrite);

                    return(1);
                }
            }
            catch (Exception e)
            {
                return(e.Message.Length);
            }

            //  return error
            return(0);
        }
Exemplo n.º 8
0
        public async static Task <bool> SilentLoginAsync()
        {
            try
            {
                _auth = new LiveAuthClient(ClientId);
                LiveLoginResult result = await _auth.InitializeAsync(Scopes);

                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    _client         = new LiveConnectClient(result.Session);
                    CurrentUserName = await GetUserNameAsync();

                    return(true);
                }
            }
            catch (Exception) { }
            _client = null;
            _auth   = null;
            return(false);
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Calls LiveAuthClient.Initialize to get the user login status.
        ///     Retrieves user profile information if user is already signed in.
        /// </summary>
        private async void InitializePage()
        {
            try
            {
                this.authClient = new LiveAuthClient("0000000048087CFD");
                LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    this.btnLogin.Content = "Sign Out";

                    this.liveClient = new LiveConnectClient(loginResult.Session);
                    this.GetMe();
                }
            }
            catch (LiveAuthException authExp)
            {
                this.tbResponse.Text = authExp.ToString();
            }
        }
        private void OnInitCompleted(LiveLoginResult authResult)
        {
            authResult = this.ValidateSessionInitScopes(authResult);
            this.UpdateSession(authResult);

            Debug.Assert(this.loginStatus != null);
            this.publicAuthClient.FirePendingPropertyChangedEvents();


            if (authResult != null && authResult.Error != null)
            {
                this.initTask.SetException(authResult.Error);
            }
            else
            {
                this.initTask.SetResult(this.loginStatus);
            }

            this.initTask = null;
        }
Exemplo n.º 11
0
        private async void signInButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LiveLoginResult loginResult = await _liveAuthClient.LoginAsync(_scopes);

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    _liveConnectClient = new LiveConnectClient(loginResult.Session);

                    responseTextBlock.Text = "signed in";

                    createPageButton.IsEnabled = true;
                }
            }
            catch (LiveAuthException ex)
            {
                responseTextBlock.Text = ex.ToString();
            }
        }
Exemplo n.º 12
0
        private async void btnGreetUser_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LiveAuthClient  auth             = new LiveAuthClient();
                LiveLoginResult initializeResult = await auth.InitializeAsync();

                try
                {
                    LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });

                    if (loginResult.Status == LiveConnectSessionStatus.Connected)
                    {
                        LiveConnectClient   connect         = new LiveConnectClient(auth.Session);
                        LiveOperationResult operationResult = await connect.GetAsync("me");

                        dynamic result = operationResult.Result;
                        if (result != null)
                        {
                            this.infoTextBlock.Text = string.Join(" ", "Hello", result.name, "!");
                        }
                        else
                        {
                            this.infoTextBlock.Text = "Error getting name.";
                        }
                    }
                }
                catch (LiveAuthException exception)
                {
                    this.infoTextBlock.Text = "Error signing in: " + exception.Message;
                }
                catch (LiveConnectException exception)
                {
                    this.infoTextBlock.Text = "Error calling API: " + exception.Message;
                }
            }
            catch (LiveAuthException exception)
            {
                this.infoTextBlock.Text = "Error initializing: " + exception.Message;
            }
        }
Exemplo n.º 13
0
        public async Task <ActionResult> ShowContacts()
        {
            try
            {
                var             scopes      = new string[] { "wl.signin", "wl.basic" };
                LiveLoginResult loginStatus = await this.AuthClient.InitializeWebSessionAsync(
                    this.HttpContext,
                    this.CurrentPath,
                    scopes);

                switch (loginStatus.Status)
                {
                case LiveConnectSessionStatus.Expired:
                {
                    string reAuthUrl = this.GetLoginUrl(scopes, this.CurrentPath);
                    this.Response.Redirect(reAuthUrl);
                    return(null);
                }

                case LiveConnectSessionStatus.Connected:
                {
                    return(await this.GetAccountDataView(AccountDataContent.Basic | AccountDataContent.Contacts));
                }

                default:
                {
                    string authorizeUrl = this.GetLoginUrl(
                        scopes,
                        ShowContactsUrl);
                    this.Response.Redirect(authorizeUrl);
                    return(null);
                }
                }
            }
            catch (LiveAuthException ex)
            {
                // Log errors
            }

            return(this.GetLoggedOutView());
        }
Exemplo n.º 14
0
        private async System.Threading.Tasks.Task Authenticate()
        {
            LiveAuthClient liveIdClient = new LiveAuthClient("https://idb.azure-mobile.net/");

            while (session == null)
            {
                // Force a logout to make it easier to test with multiple Microsoft Accounts
                if (liveIdClient.CanLogout)
                {
                    liveIdClient.Logout();
                }

                LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });

                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    session = result.Session;
                    LiveConnectClient   client   = new LiveConnectClient(result.Session);
                    LiveOperationResult meResult = await client.GetAsync("me");

                    MobileServiceUser loginResult = await App.MobileService.LoginAsync(result.Session.AuthenticationToken);

                    //string title = string.Format("Welcome {0}!", meResult.Result["first_name"]);
                    App.LoginName = string.Format("{0}", meResult.Result["name"]);
                    App.Gender    = string.Format("{0}", meResult.Result["gender"]);
                    App.UserID    = string.Format("{0}", loginResult.UserId);

                    //var message = string.Format("You are now logged in - {0}", loginResult.UserId);
                    //var dialog = new MessageDialog(message, title);
                    //dialog.Commands.Add(new UICommand("OK"));
                    //await dialog.ShowAsync();
                }
                else
                {
                    session = null;
                    var dialog = new MessageDialog("You must log in.", "Login Required");
                    dialog.Commands.Add(new UICommand("OK"));
                    await dialog.ShowAsync();
                }
            }
        }
        private async Task Authenticate()
        {
            try
            {
                var liveIdClient = new LiveAuthClient("000000004810306D");
                var initResult   = await liveIdClient.InitializeAsync(scopes);

                _session = initResult.Session;

                if (null == _session)
                {
                    LiveLoginResult result = await liveIdClient.LoginAsync(scopes);

                    if (result.Status == LiveConnectSessionStatus.Connected)
                    {
                        _session = result.Session;
                        if (AuthenticationSuccessful != null)
                        {
                            AuthenticationSuccessful();
                        }
                    }
                    else
                    {
                        _session = null;
                        if (AuthenticationFailed != null)
                        {
                            AuthenticationFailed();
                        }
                        //MessageBox.Show("Unable to authenticate with Windows Live.", "Login failed :(", MessageBoxButton.OK);
                    }
                }

                if (AuthenticationSuccessful != null)
                {
                    AuthenticationSuccessful();
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Handles the refresh token completed event.  Restarts the operation.
        /// </summary>
        private void OnRefreshTokenOperationCompleted(LiveLoginResult result)
        {
            switch (result.Status)
            {
            case LiveConnectSessionStatus.Connected:
                this.LiveClient.Session = result.Session;
                break;

            case LiveConnectSessionStatus.Unknown:
                // Once we know the user is unknown, we clear the session and fail the operation.
                // On Windows Blue, the user may disconnect the Microsoft account.
                // We ensure we are not allowing app to continue to access user's data after the user disconnects the account.
                this.LiveClient.Session = null;
                var error = new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn"));
                this.OnOperationCompleted(new LiveOperationResult(error, false));
                return;
            }

            // We will attempt to perform the operation even if refresh fails.
            this.InternalExecute();
        }
Exemplo n.º 17
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            getGpsLocation();
            try
            {
                LiveAuthClient  auth             = new LiveAuthClient();
                LiveLoginResult initializeResult = await auth.InitializeAsync();

                try
                {
                    LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic", "wl.emails" });

                    if (loginResult.Status == LiveConnectSessionStatus.Connected)
                    {
                        LiveConnectClient   connect         = new LiveConnectClient(auth.Session);
                        LiveOperationResult operationResult = await connect.GetAsync("me");

                        dynamic result = operationResult.Result;
                        if (result != null)
                        {
                            User u = new User();
                            u.FirstName = result.first_name;
                            u.LastName  = result.last_name;
                            u.Email     = result.emails.account;
                            _vm.SaveUser(u);
                            _vm.ActiveUser = u;
                        }
                    }
                }
                catch (LiveAuthException exception)
                {
                }
                catch (LiveConnectException exception)
                {
                }
            }
            catch (LiveAuthException exception)
            {
            }
        }
Exemplo n.º 18
0
        private async Task AuthenticateUser(bool silent)
        {
            string text      = null;
            string firstName = string.Empty;
            bool   connected = false;

            try
            {
                var             authClient = new LiveAuthClient();
                LiveLoginResult result     = silent ? await authClient.InitializeAsync(_defaultAuthScopes) : await authClient.LoginAsync(_defaultAuthScopes);

                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    connected = true;
                    var connectClient = new LiveConnectClient(result.Session);
                    var meResult      = await connectClient.GetAsync("me");

                    dynamic meData = meResult.Result;
                    firstName = meData.first_name;

                    await LoadProfileImage(connectClient);
                }
            }
            catch (LiveAuthException ex)
            {
                text = "Error: " + ex.Message;
            }
            catch (LiveConnectException ex)
            {
                text = "Error: " + ex.Message;
            }

            if (text != null)
            {
                var dialog = new Windows.UI.Popups.MessageDialog(text);
                await dialog.ShowAsync();
            }

            UpdateUI(connected, firstName);
        }
Exemplo n.º 19
0
        private async Task getAuthResult()
        {
            try
            {
                LiveLoginResult result = await liveAuthClient.ExchangeAuthCodeAsync(new HttpContextWrapper(Context));

                session = result.Session;
                new JITAD.UserStats().SendMessage("WebAuth", "jitad", "Inside getAuthResult()");
                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    var liveClient = new LiveConnectClient(session);
                    var myData     = await liveClient.GetAsync("me");

                    string user_id = myData.Result["id"].ToString();
                    new JITAD.UserStats().SendMessage("WbAuth", "jitad", "Successfully connected");
                    getSession(user_id);
                }
            }
            catch (LiveAuthException)
            {
            }
        }
Exemplo n.º 20
0
        private async void login()
        {
            try
            {
                string          clientId         = "000000004C10C962";
                LiveAuthClient  auth             = new LiveAuthClient(clientId);
                LiveLoginResult initializeResult = await auth.InitializeAsync();

                try
                {
                    LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic", "wl.emails" });

                    if (loginResult.Status == LiveConnectSessionStatus.Connected)
                    {
                        LiveConnectClient   connect         = new LiveConnectClient(auth.Session);
                        LiveOperationResult operationResult = await connect.GetAsync("me");

                        dynamic result = operationResult.Result;
                        if (result != null)
                        {
                            u.FirstName = result.first_name;
                            u.LastName  = result.last_name;
                            u.Email     = result.emails.account;
                            _vm.SaveUser(u);
                            _vm.ActiveUser = u;
                        }
                    }
                }
                catch (LiveAuthException exception)
                {
                }
                catch (LiveConnectException exception)
                {
                }
            }
            catch (LiveAuthException exception)
            {
            }
        }
Exemplo n.º 21
0
        private async Task InitializeAuthClient(string[] scopes)
        {
            LiveLoginResult loginResult = await this.authClient.Initialize();

            if (loginResult.Status == LiveConnectSessionStatus.Connected)
            {
                this.apiClient = new LiveConnectClient(loginResult.Session);
            }
            else
            {
                loginResult = await this.authClient.Login(scopes);

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    this.apiClient = new LiveConnectClient(loginResult.Session);
                }
                else
                {
                    throw new InvalidOperationException("LiveAuthClient failed to login. The status is " + loginResult.Status.ToString());
                }
            }
        }
Exemplo n.º 22
0
        public async Task<LiveLoginResult> AuthenticateAsync(string redirectUrl, bool silent)
        {
            this.redirectUrl = redirectUrl;

            LiveLoginResult result;
            if (silent)
            {
                result = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null);
            }
            else
            {
                LiveConnectSession session = new LiveConnectSession();
                session.AccessToken = TestAuthClient.FakeAccessToken;
                session.AuthenticationToken = TestAuthClient.FakeAuthenticationToken;
                result = new LiveLoginResult(LiveConnectSessionStatus.Connected, session);
            }

            return await Task.Factory.StartNew<LiveLoginResult>(() =>
            {
                return result;
            });
        }
Exemplo n.º 23
0
        private void OnAuthClientInitializeCompleted(System.Threading.Tasks.Task <LiveLoginResult> task)
        {
            if (!CheckTaskCompleted(task, "Not connected. Failed to initialize client."))
            {
                RaiseLinkAbort(task.Exception);
                return;
            }

            LiveLoginResult result = task.Result;

            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                Log("Connected. Moving on with client.");

                // We're online, get the client.
                MakeClientFromSession(result.Session);
            }
            else
            {
                // Checks if we need to auto login.
                bool shouldAutoLogin = false;
                lock (_syncRoot)
                {
                    shouldAutoLogin = _autoLoginOnInitFail;
                }

                // If we need to auto-login, do it.
                if (shouldAutoLogin)
                {
                    Log("Not connected. Starts LoginAsync (auto-login)");
                    StartTaskAndContinueWith(() => _authClient.LoginAsync(_Scopes), OnAuthClientLoginCompleted);
                }
                else
                {
                    Log("Not connected. Auto-login not requested.");
                }
            }
        }
Exemplo n.º 24
0
        public async Task <LiveLoginResult> AuthenticateAsync(string redirectUrl, bool silent)
        {
            this.redirectUrl = redirectUrl;

            LiveLoginResult result;

            if (silent)
            {
                result = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null);
            }
            else
            {
                LiveConnectSession session = new LiveConnectSession();
                session.AccessToken         = TestAuthClient.FakeAccessToken;
                session.AuthenticationToken = TestAuthClient.FakeAuthenticationToken;
                result = new LiveLoginResult(LiveConnectSessionStatus.Connected, session);
            }

            return(await Task.Factory.StartNew <LiveLoginResult>(() =>
            {
                return result;
            }));
        }
Exemplo n.º 25
0
        private async void initialize()
        {
            try
            {
                authClient = new LiveAuthClient();
                LiveLoginResult authLogResult = await authClient.LoginAsync(new List <string>() { "wl.signin", "wl.basic", "wl.skydrive_update" });

                if (authLogResult.Status == LiveConnectSessionStatus.Connected)
                {
                    client = new Microsoft.Live.LiveConnectClient(authClient.Session);

                    LiveOperationResult opResult = await client.GetAsync("me");

                    dynamic result = opResult.Result;

                    //tblUserName.Text = result.name;
                }
            }
            catch (Exception e)
            {
                //tblUserName.Text = "Error";
            }
        }
Exemplo n.º 26
0
        public override async Task <AuthenticationResult> AuthenticateAsync()
        {
            var result = await _authClient.LoginAsync(this.AuthorizationScopesList.ToArray());

            if (result != null && result.Status == LiveConnectSessionStatus.Connected)
            {
                _result = result;
                return(AuthenticationResult.Success);
            }
            if (result.Status == LiveConnectSessionStatus.Unknown)
            {
                return(AuthenticationResult.Unknown);
            }
            else if (result.Status == LiveConnectSessionStatus.NotConnected)
            {
                return(AuthenticationResult.Failed);
            }

            return(AuthenticationResult.Unknown);
            //A really bad status to talk about!
            //var client = new LiveConnectClient(result.Session);
            //dynamic result2 = await client.GetAsync("me/skydrive/files");
        }
Exemplo n.º 27
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //if (this.liveClient == null) return;
            if (this.SkySignInBtn.Session == null)
            {
                MessageBox.Show("session is null"); return;
            }
            //this.liveClient = new LiveConnectClient(this.SkySignInBtn.Session);
            try
            {
                LiveAuthClient  auth        = new LiveAuthClient("00000000440FBD35");
                LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    MessageBox.Show("signed in");
                    this.liveClient = new LiveConnectClient(loginResult.Session);
                }
            }
            catch (LiveAuthException exception)
            {
                MessageBox.Show("error: " + exception.Message);
            }
        }
        public async Task SignIn()
        {
            // you should call this from UI thread
            if (_liveSession == null)
            {
                _liveAuth   = new LiveAuthClient(_clientId);
                _liveResult = await _liveAuth.InitializeAsync(_requiredScopes);

                if (_liveResult.Status != LiveConnectSessionStatus.Connected)
                {
                    _liveResult = await _liveAuth.LoginAsync(_requiredScopes);
                }

                _liveSession = _liveResult.Session;
                _liveClient  = new LiveConnectClient(_liveSession);

                _liveClient.BackgroundTransferPreferences = BackgroundTransferPreferences.AllowCellularAndBattery;
            }

            if (_folderId == null)
            {
                await GetSkyDriveFolder();
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Performs login via Live Connect and then via Mobile Services
        /// </summary>
        private async Task Login()
        {
            // Force the user to login on app startup
            LiveLoginResult result = await _liveAuthClient.LoginAsync(new string[] { "wl.signin", "wl.basic", "wl.postal_addresses" });

            if (result.Session == null)
            {
                await _popupService.ShowDialogAsync("You must login to use doto.", "Not logged in");

                SetViewState(ViewState.LoggedOut);
                return;
            }

            await _mobileServiceClient.LoginAsync(result.Session.AuthenticationToken);

            var profiles = await _profilesTable.Where(p => p.UserId == _mobileServiceClient.CurrentUser.UserId).ToListAsync();

            if (profiles.Count == 0)
            {
                LiveConnectClient lcc = new LiveConnectClient(result.Session);
                var me = await lcc.GetAsync("me");

                dynamic pic = await lcc.GetAsync("me/picture");

                RegisterUser(me.Result, pic.Result, _mobileServiceClient.CurrentUser.UserId);
            }
            else
            {
                User = profiles.First();
                RegisterDevice();
                LoadLists(true);
                LoadInvites();
            }

            return;
        }
        public async Task <ActionResult> Process(string code)
        {
            OneNoteViewModel model  = new OneNoteViewModel();
            StringBuilder    status = new StringBuilder();
            Tuple <string, OneNoteNotebook> notebookApiResult = null;
            Tuple <string, OneNoteSection>  sectionApiResult  = null;

            if (code != null)
            {
                LiveLoginResult loginStatus = await liveAuthClient.ExchangeAuthCodeAsync(this.HttpContext);

                // get the selected project
                string projectId            = (string)this.HttpContext.Session["onenote-project"];
                ProjectDetailViewModel data = await GetProjectAndReferencesFromSharePoint(projectId);

                OneNoteRepository repository = new OneNoteRepository(loginStatus.Session);

                status.Append("GetNotebook: ");
                notebookApiResult = await repository.GetNotebook("name eq 'Project Research Tracker'");

                status.Append(notebookApiResult.Item1 + "<br/>");
                OneNoteNotebook notebook = notebookApiResult.Item2;

                if (notebook == null)
                {
                    status.Append("CreateNotebook: ");
                    notebookApiResult = await repository.CreateNotebook();

                    status.Append(notebookApiResult.Item1 + "<br/>");
                    notebook = notebookApiResult.Item2;
                }

                if (notebook != null)
                {
                    model.NewNotebookLink = notebook.links.oneNoteWebUrl.href;

                    string filter = String.Format("name eq '{0}'", data.Project.Title);
                    status.Append("GetSection: ");
                    sectionApiResult = await repository.GetNotebookSection(notebook, filter);

                    status.Append(sectionApiResult.Item1 + "<br/>");
                    OneNoteSection section = sectionApiResult.Item2;

                    if (section == null)
                    {
                        status.Append("CreateSection: ");
                        sectionApiResult = await repository.CreateSection(notebook, data.Project.Title);

                        status.Append(sectionApiResult.Item1 + "<br/>");
                        section = sectionApiResult.Item2;
                    }

                    if (section != null)
                    {
                        foreach (Reference reference in data.References)
                        {
                            status.Append("CreatePage: ");
                            string result = await repository.CreatePageForReference(section.pagesUrl, reference);

                            status.Append(result + "<br/>");
                        }
                    }
                }

                model.ResponseMessage = status.ToString();
                return(View(model));
            }
            else
            {
                RedirectToAction("Index", "Home");
            }

            return(null);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Handles the refresh token completed event.  Restarts the operation.
        /// </summary>
        private void OnRefreshTokenOperationCompleted(LiveLoginResult result)
        {
            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                this.LiveClient.Session = result.Session;
            }

            // We will attempt to perform the operation even if refresh fails.
            this.InternalExecute();
        }
Exemplo n.º 32
0
        // Authenticate the user via Microsoft Account (the default on Windows Phone)
        // Authentication via Facebook, Twitter or Google ID will be added in a future release.
        private async Task Authenticate()
        {
            prgBusy.IsActive = true;
            Exception exception = null;

            try
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    TextUserName.Text = "Please wait while we log you in...";
                });

                LiveAuthClient liveIdClient = new LiveAuthClient(ConfigSecrets.AzureMobileServicesURI);

                while (session == null)
                {
                    // Force a logout to make it easier to test with multiple Microsoft Accounts
                    // This code should be commented for the release build
                    //if (liveIdClient.CanLogout)
                    //    liveIdClient.Logout();

                    // Microsoft Account Login
                    LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });

                    if (result.Status == LiveConnectSessionStatus.Connected)
                    {
                        session = result.Session;
                        LiveConnectClient   client   = new LiveConnectClient(result.Session);
                        LiveOperationResult meResult = await client.GetAsync("me");

                        user = await App.MobileService
                               .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);

                        userfirstname = meResult.Result["first_name"].ToString();
                        userlastname  = meResult.Result["last_name"].ToString();

                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            var message       = string.Format("Logged in as {0} {1}", userfirstname, userlastname);
                            TextUserName.Text = message;
                        });

                        // Debugging dialog, make sure it's commented for publishing
                        //var dialog = new MessageDialog(message, "Welcome!");
                        //dialog.Commands.Add(new UICommand("OK"));
                        //await dialog.ShowAsync();
                        isLoggedin = true;
                        SetUIState(true);
                    }
                    else
                    {
                        session = null;
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            UpdateStatus("You must log in before you can chat in this app.", true);
                            var dialog = new MessageDialog("You must log in.", "Login Required");
                            dialog.Commands.Add(new UICommand("OK"));
                            dialog.ShowAsync();
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                UpdateStatus("Something went wrong when trying to log you in.", true);
                string msg1 = "An error has occurred while trying to sign you in." + Environment.NewLine + Environment.NewLine;

                // TO DO: Dissect the various potential errors and provide a more appropriate
                //        error message in msg2 for each of them.
                string msg2 = "Make sure that you have an active Internet connection and try again.";

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    new MessageDialog(msg1 + msg2, "Authentication Error").ShowAsync();
                });
            }
            prgBusy.IsActive = false;
        }
Exemplo n.º 33
0
        private void OnLogin(LiveLoginResult loginResult)
        {
            this.Session = loginResult.Session;

            var sessionChangedArgs = 
                new LiveConnectSessionChangedEventArgs(loginResult.Status, loginResult.Session);

            this.RaiseSessionChangedEvent(sessionChangedArgs);

            if (loginResult.Status == LiveConnectSessionStatus.Connected)
            {
                this.SetButtonState(ButtonState.LogOut);
            }
        }
 /// <summary>
 /// Raises the OperationCompletedCallback.
 /// </summary>
 protected void OnOperationCompleted(LiveLoginResult opResult)
 {
     Action<LiveLoginResult> callback = this.OperationCompletedCallback;
     if (callback != null)
     {
         callback(opResult);
     }
 }
        /// <summary>
        /// Process the web response from the server.
        /// </summary>
        protected override void OnWebResponseReceived(WebResponse response)
        {
            LiveLoginResult result;

            bool nullResponse = (response == null);
            try
            {
                Stream responseStream = (!nullResponse) ? response.GetResponseStream() : null;
                if (nullResponse || responseStream == null)
                {
                    result = new LiveLoginResult(
                        new LiveAuthException(AuthErrorCodes.ClientError, ResourceHelper.GetString("ConnectionError")));
                }
                else
                {
                    result = this.GenerateLoginResultFrom(responseStream);
                }
            }
            finally
            {
                if (!nullResponse)
                {
                    response.Dispose();
                }
            }

            this.OnOperationCompleted(result);
        }
Exemplo n.º 36
0
        /// <summary>
        /// Handles the refresh token completed event.  Restarts the operation.
        /// </summary>
        private void OnRefreshTokenOperationCompleted(LiveLoginResult result)
        {
            switch (result.Status)
            {
                case LiveConnectSessionStatus.Connected:
                    this.LiveClient.Session = result.Session;
                    break;
                case LiveConnectSessionStatus.Unknown:
                    // Once we know the user is unknown, we clear the session and fail the operation.
                    // On Windows Blue, the user may disconnect the Microsoft account.
                    // We ensure we are not allowing app to continue to access user's data after the user disconnects the account.
                    this.LiveClient.Session = null;
                    var error = new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn"));
                    this.OnOperationCompleted(new LiveOperationResult(error, false));
                    return;
            }

            // We will attempt to perform the operation even if refresh fails.
            this.InternalExecute();
        }