Пример #1
0
        private async void Logout(object param)
        {
            try
            {
                var task   = AsyncServiceClient.Logout();
                var result = await task;

                Result = MessageBoxResult.No;
                RequestClose(this, EventArgs.Empty);

                // need to clear out the logged in username/pw
                // refresh awesomium
                OnPropertyChanged("Logout");
            }
            catch (Exception e)
            {
                Result = MessageBoxResult.No;
                RequestClose(this, EventArgs.Empty);

                // need to clear out the logged in username/pw
                // refresh awesomium
                OnPropertyChanged("Logout");
                MessageBox.Show("There was an error logging you out from OSBLE+. If this issue persists, please contact [email protected] with the following error message.\n\nError: " + e.InnerException.ToString(), "Log Into OSBLE+", MessageBoxButton.OK);
            }
        }
        private async void GetLibraryVersion()
        {
            var task   = AsyncServiceClient.LibraryVersionNumber();
            var result = await task;

            InitStepThree_CheckServiceVersionComplete(result);
        }
Пример #3
0
        /// <summary>
        /// Asynchronous web api call to update the array of courses.
        /// </summary>
        /// <param name="c"></param>
        public void UpdateCourses()
        {
            List <ProfileCourse> c = null;

            //web api call to collect courses
            try
            {
                var task = AsyncServiceClient.GetCoursesForUser(m_authtoken);
                c = task.Result;
            }

            catch (Exception e)
            {
                //TODO: Handle unknown exception
            }


            //set courses to the web api result converted to an array
            if (c == null)
            {
                m_courses = null;
            }
            else
            {
                m_courses = c.ToArray();
            }
        }
Пример #4
0
        /// <summary>
        /// Asynchronous web api call to update the array of submission assignments.
        /// </summary>
        /// <param name="c"></param>
        public void UpdateAssignments(ProfileCourse c)
        {
            List <SubmisionAssignment> a = null;

            //web api call to collect assignments
            try
            {
                var task = AsyncServiceClient.GetAssignmentsForCourse(c.Id, m_authtoken);
                a = task.Result;
            }

            catch (Exception e)
            {
                //TODO: Handle unknown exception
            }


            //set assignments to the web api result converted to an array
            if (a == null)
            {
                m_assignments = null;
            }
            else
            {
                m_assignments = a.ToArray();
            }
        }
Пример #5
0
        private async void SubmitAssignmentAsync()
        {
            _submitEvent.CreateSolutionBinary(_submitEvent.GetSolutionBinary());
            _submitEvent.AssignmentId = SelectedAssignment;
            _submitEvent.CourseId     = SelectedCourse;

            var task         = AsyncServiceClient.SubmitAssignment(_submitEvent, _authToken);
            var confirmation = await task;

            SubmitAssignmentCompleted(confirmation);
        }
        /// <summary>
        /// Saves the active word document and zips the file in the local directory.
        /// </summary>
        /// <param name="state"></param>
        /// <param name="course"></param>
        /// <param name="assignment"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static SaveResult Save(OSBLEState state, int courseId, int assignmentId, Document doc)
        {
            //if the document doesn't exist or contains changes then request the user to save
            if (!File.Exists(doc.FullName) || !doc.Saved)
            {
                return(new SaveResult(false, "Please save the current document before submitting."));
            }

            string zipPath = null;

            byte[] zipData = null;

            //zip document
            try
            {
                zipPath = SaveFileToZip(state.FullName, doc);
                zipData = File.ReadAllBytes(zipPath);
            }

            catch (Exception e)
            {
                return(new SaveResult(true, "Failed to package document before sending to the server."));
            }

            //package assignment information
            var submitevent = new SubmitEvent();

            submitevent.AssignmentId = assignmentId;
            submitevent.CourseId     = courseId;
            submitevent.SolutionData = zipData;

            HttpResponseMessage response = null;

            //call asynchronous web api helper function
            try
            {
                response = AsyncServiceClient.SubmitAssignment(submitevent, state.AuthToken).Result;
            }

            catch (Exception e)
            {
                return(new SaveResult(false, "Failed to submit document to the server."));
            }

            if (response.IsSuccessStatusCode)
            {
                return(new SaveResult(true, null));
            }
            else
            {
                return(new SaveResult(false, "The server failed to process the submission."));
            }
        }
Пример #7
0
 public override void SynchronizeCookies(AsyncServiceClient client)
 {
     if (client.StoreCookies && client.ShareCookiesWithBrowser && !client.EmulateHttpViaPost)
     {
         // browser cookies must be set on the ui thread
         System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
         {
             var cookieHeader = client.CookieContainer.GetCookieHeader(new Uri(client.BaseUri));
             System.Windows.Browser.HtmlPage.Document.Cookies = cookieHeader;
         });
     }
 }
        private async void InitStepThree_CheckServiceVersionComplete(string version)
        {
            var isOsbideUpToDate = true;

            if (string.IsNullOrWhiteSpace(version))
            {
                _errorLogger.WriteToLog("Web service error", LogPriority.HighPriority);
                _hasStartupErrors = true;
                return;
            }

            //if we have a version mismatch, stop sending data to the server & delete localDb
            if (string.Compare(StringConstants.LibraryVersion, version, StringComparison.OrdinalIgnoreCase) != 0)
            {
                isOsbideUpToDate = false;

                //download updated library version
                var web = new WebClient();
                web.DownloadFileCompleted += web_DownloadFileCompleted;
                web.Headers.Add(HttpRequestHeader.UserAgent, "OSBIDE");
                if (File.Exists(StringConstants.LocalUpdatePath))
                {
                    try
                    {
                        File.Delete(StringConstants.LocalUpdatePath);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }
                try
                {
                    web.DownloadFileAsync(new Uri(StringConstants.UpdateUrl), StringConstants.LocalUpdatePath);
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            //if we're all up to date and had no startup errors, then we can start sending logs to the server
            if (isOsbideUpToDate && _hasStartupErrors == false)
            {
                _client.StartSending();
                ShowActivityFeedTool(this, EventArgs.Empty);

                var task       = AsyncServiceClient.GetMostRecentWhatsNewItem();
                var recentNews = await task;
                GetRecentNewsItemDateComplete(recentNews);
            }
        }
Пример #9
0
        private async void GetCoursesForUserAsync(string authToken)
        {
            var task    = AsyncServiceClient.GetCoursesForUser(authToken);
            var courses = await task;

            Courses.Clear();
            foreach (var course in courses.OfType <ICourse>())
            {
                Courses.Add(course);
            }

            IsLoading = false;
        }
Пример #10
0
        public override void SetCookieContainer(HttpWebRequest webRequest, AsyncServiceClient client)
        {
            if (!client.EmulateHttpViaPost)
            {
                if (client.ShareCookiesWithBrowser)
                {
                    if (client.CookieContainer == null)
                        client.CookieContainer = new CookieContainer();
                    client.CookieContainer.SetCookies(webRequest.RequestUri, System.Windows.Browser.HtmlPage.Document.Cookies);
                }
            }

            webRequest.CookieContainer = client.CookieContainer;
        }
Пример #11
0
        private async void GetAssignmentsForCourseAsync(int courseId, string authToken)
        {
            var   task = AsyncServiceClient.GetAssignmentsForCourse(courseId, authToken);
            await task;
            var   assignments = task.Result;

            Assignments.Clear();
            foreach (var assignment in assignments)
            {
                Assignments.Add(assignment);
            }

            IsLoading = false;
        }
Пример #12
0
        private async void GetLastAssignmentSubmitDateAsync(int assignmentId, string authToken)
        {
            var task           = AsyncServiceClient.GetLastAssignmentSubmitDate(assignmentId, authToken);
            var submissionDate = await task;

            if (!submissionDate.HasValue || submissionDate.Value == DateTime.MinValue)
            {
                LastSubmitted = "N/A";
            }
            else
            {
                //convert from UTC to local time
                var utc = new DateTime(submissionDate.Value.Ticks, DateTimeKind.Utc);
                LastSubmitted = utc.ToLocalTime().ToString("MM/dd @ hh:mm tt");
            }
        }
Пример #13
0
        /// <summary>
        /// Verifies the username and password submitted by the login form.
        /// If the information is valid then the user's course will be
        /// populated and the ribbon will be updated to a logged in state.
        /// Otherwise an error message will appear.
        /// </summary>
        private void RefreshProc()
        {
            //validate login information
            try
            {
                m_authtoken = AuthenticationClient.Login(m_user, m_pass);
                m_name      = AsyncServiceClient.GetName(m_authtoken).Result;

                if (m_name == null)
                {
                    m_name = "";
                }
            }

            //connection error
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                m_onComplete(this, new OSBLEStateEventArgs(false,
                                                           "Could not connect to the OSBLE server. " +
                                                           "Please contact support if this problem persists."));
                return;
            }

            //credentials error
            if (string.IsNullOrEmpty(m_authtoken))
            {
                m_onComplete(this, new OSBLEStateEventArgs(false,
                                                           "Could not log into OSBLE. " +
                                                           "Please check your user name and password."));
                return;
            }

            //login was successful so update collection of the user's courses
            UpdateCourses();

            //don't bother continuing to login if no courses found
            if (null == m_courses || 0 == m_courses.Length)
            {
                m_onComplete(this, new OSBLEStateEventArgs(false,
                                                           "No courses were found for this user."));
                return;
            }

            //TODO: consider filtering courses by the user's role

            m_onComplete(this, new OSBLEStateEventArgs(true, string.Empty));
        }
        public void Can_download_movies_in_Csv()
        {
            var asyncClient = new AsyncServiceClient
            {
                ContentType        = MimeTypes.Csv,
                StreamSerializer   = (r, o, s) => CsvSerializer.SerializeToStream(o, s),
                StreamDeserializer = CsvSerializer.DeserializeFromStream,
            };

            MoviesResponse response = null;

            asyncClient.SendAsync <MoviesResponse>(HttpMethods.Get, ServiceClientBaseUri + "/movies", null,
                                                   r => response = r, FailOnAsyncError);

            Thread.Sleep(1000);

            Assert.That(response, Is.Not.Null, "No response received");
        }
        private async void Login(string userName, string password)
        {
            try
            {
                var task   = AsyncServiceClient.Login(userName, password);
                var result = await task;

                //setup intervention window cache
                bool showInterventionWindow = false;

                try                                                                              //we don't want this to cause any issue if it fails...
                {
                    var settingsTask   = AsyncServiceClient.GetUserInterventionSettings(result); //result is the authkey
                    var settingsResult = await settingsTask;
                    showInterventionWindow = settingsResult.ShowInIDE;
                    //setup cache for intervention settings
                    _cache["ShowSuggestionsWindow"] = showInterventionWindow.ToString();
                    //refresh threshold
                    _cache["InterventionRefreshThresholdInMinutes"] = settingsResult.RefreshThreshold;
                    //set last refresh time as now since we will open the window now if they are seeing interventions
                    _cache["LastRefreshTime"] = DateTime.Now.ToString();
                }
                catch (Exception e)
                {
                    _errorLogger.WriteToLog(string.Format("Open Suggestions window error: {0}", e.Message), LogPriority.HighPriority);
                }

                Init_BrowserLogin(result, showInterventionWindow);
                InitStepTwo_LoginCompleted(result);
            }
            catch (Exception e)
            {
                try
                {
                    //this may crash visual studio, we'll catch it just in case...
                    _manager.CloseAllWindows();
                    var result = MessageBox.Show("The OSBLE+ Visual Studio Plugin is unable to connect to the OSBLE+ server.  If this issue persists, please contact [email protected] with the error message.\n\nError: " + e.InnerException.ToString(), "Log Into OSBLE+", MessageBoxButton.OK);
                }
                catch (Exception ex)
                {
                    ShowAwesomiumError(ex); // if this crashes it must be missing awesomium
                }
            }
        }
Пример #16
0
        private void SendLocalErrorLogs()
        {
            var dataRoot     = StringConstants.DataRoot;
            var logExtension = StringConstants.LocalErrorLogExtension;
            var today        = StringConstants.LocalErrorLogFileName;

            //find all log files
            var files = Directory.GetFiles(dataRoot);

            foreach (var file in files)
            {
                if (Path.GetExtension(file) != logExtension ||
                    Path.GetFileNameWithoutExtension(file) == today)
                {
                    continue;
                }

                var  log = LocalErrorLog.FromFile(file);
                bool result;
                lock (_cache)
                {
                    var webServiceKey = _cache[StringConstants.AuthenticationCacheKey] as string;

                    var task = AsyncServiceClient.SubmitLocalErrorLog(new LocalErrorLogRequest {
                        Log = log, AuthToken = webServiceKey
                    });
                    result = task.Result;
                }

                //remove if file successfully sent
                if (!result)
                {
                    continue;
                }
                try
                {
                    File.Delete(file);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Пример #17
0
        void saveHandler_AfterSaveEvent(Word.Document doc, bool isClosed)
        {
            //if (!isClosed)
            //    MessageBox.Show("After Save Event");
            //else
            //    MessageBox.Show("After Close and Save Event. The filname was: " + saveHandler.ClosedFilename);

            string authToken = null;

            try
            {
                authToken = Globals.Ribbons.OSBLE_Ribbon.mState.AuthToken;
                var response = AsyncServiceClient.SubmitStatistics(authToken, doc);
            }

            catch (Exception e)
            {
            }
        }
Пример #18
0
        private async void Login(object param)
        {
            //begin login attempt
            LoadingIconVisible = true;
            ButtonsEnabled     = false;
            ErrorText          = string.Empty;

            //TODO: handle the try catch exception
            try
            {
                var task   = AsyncServiceClient.Login(Email, Password);
                var result = await task;

                LoginCompleted(result);
            }
            catch (Exception e)
            {
                ErrorText = "Unable to connect to OSBLE+";
                LoginCompleted("exception");
            }
        }
Пример #19
0
        private async void SendLogToServer(IActivityEvent data)
        {
            SendStatus.IsActive = true;

            List <IActivityEvent> logsToBeSaved;
            string webServiceKey;

            //request exclusive access to our cache of existing logs
            lock (_cache)
            {
                //get pending records
                logsToBeSaved = GetLogsFromCache();

                //add new log to list
                logsToBeSaved.Add(data);

                //clear out cache
                SaveLogsToCache(new List <IActivityEvent>());

                webServiceKey = (string)_cache[StringConstants.AuthenticationCacheKey];
            }

            //send logs to the server
            for (var idx = 0; idx < logsToBeSaved.Count; idx++)
            {
                var log = logsToBeSaved[idx];

                //reset the log's sending user just to be safe
                _logger.WriteToLog(string.Format("Sending {0}th of {1} log(s) to the server", idx + 1, logsToBeSaved.Count), LogPriority.LowPriority);
                SendStatus.CurrentTransmission = log;

                //update send status with the number of logs that need to submit
                SendStatus.NumberOfTransmissions = logsToBeSaved.Count;

                try
                {
                    //compose web request and send to the server
                    var eventPostRequest = GetEventPostWebRequest(log, webServiceKey);
                    var task             = AsyncServiceClient.SubmitLog(eventPostRequest);
                    var result           = await task;

                    //log status
                    _logger.WriteToLog(string.Format("The return code of the batch is {0}", result), LogPriority.LowPriority);
                    log.EventLogId = result;

                    //update batch status
                    SendStatus.LastTransmissionTime = DateTime.UtcNow;
                    SendStatus.LastTransmission     = log;
                    SendStatus.CompletedTransmissions++;
                }
                catch (Exception ex)
                {
                    SendError(ex);
                    break;
                }
            }

            lock (_cache)
            {
                SaveLogsToCache(logsToBeSaved.Where(x => !(x.EventLogId > 0)).ToList());
            }
            SendStatus.IsActive = false;
        }
Пример #20
0
        /// <summary>
        /// This function is responsible for continually asking for status updates from OSBIDE
        /// </summary>
        private void CheckStatus()
        {
            while (IsSendingData)
            {
                //this block checks to make sure that our authentication key is up to date
                string webServiceKey;
                lock (_cache)
                {
                    webServiceKey = _cache[StringConstants.AuthenticationCacheKey] as string;

                    var result = false;
                    try
                    {
                        var task = AsyncServiceClient.IsValidKey(webServiceKey);
                        result = task.Result;
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    //if result is false, our key has gone stale.  Try to login again
                    if (result == false)
                    {
                        var userName      = _cache[StringConstants.UserNameCacheKey] as string;
                        var passwordBytes = _cache[StringConstants.PasswordCacheKey] as byte[];
                        var encoderKey    = _cache[StringConstants.AesKeyCacheKey] as byte[];
                        var encoderVector = _cache[StringConstants.AesVectorCacheKey] as byte[];
                        var password      = string.Empty;
                        try
                        {
                            password = AesEncryption.DecryptStringFromBytes_Aes(passwordBytes, encoderKey, encoderVector);
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                        if (userName != null && password != null)
                        {
                            var task = AsyncServiceClient.Login(userName, password);
                            webServiceKey = task.Result;
                            _cache[StringConstants.AuthenticationCacheKey] = webServiceKey;
                        }
                        else
                        {
                            IsSendingData = false;
                        }
                    }
                }

                //this block checks for recent user profile activity
                DateTime     lastLocalProfileUpdate;
                const string lastProfileActivityKey = "LastProfileActivity";

                //get last cached value
                lock (_cache)
                {
                    if (_cache.Contains(lastProfileActivityKey) == false)
                    {
                        _cache[lastProfileActivityKey] = DateTime.MinValue;
                    }
                    try
                    {
                        lastLocalProfileUpdate = (DateTime)_cache[lastProfileActivityKey];
                    }
                    catch (Exception)
                    {
                        lastLocalProfileUpdate = DateTime.MinValue;
                        _cache.Remove(lastProfileActivityKey);
                    }
                }

                //get last server value
                if (IsSendingData)
                {
                    DateTime lastServerProfileUpdate;
                    try
                    {
                        var task = AsyncServiceClient.GetMostRecentSocialActivity(webServiceKey);
                        lastServerProfileUpdate = task.Result;
                    }
                    catch (Exception)
                    {
                        lastServerProfileUpdate = DateTime.MinValue;
                    }

                    if (lastLocalProfileUpdate < lastServerProfileUpdate)
                    {
                        //notify client of new social activity
                        if (ReceivedNewSocialActivity != null)
                        {
                            ReceivedNewSocialActivity(this, EventArgs.Empty);
                        }

                        lock (_cache)
                        {
                            _cache[lastProfileActivityKey] = lastServerProfileUpdate;
                        }
                    }
                }

                Thread.Sleep(new TimeSpan(0, 0, 3, 0, 0));
            }
        }