示例#1
0
        async void Instance_CollectionLoaded(object sender)
        {
            await ProgresIndicator.HideAsync();

            SetViewModel.Instance.CollectionLoaded -= Instance_CollectionLoaded;
            SetData();
        }
示例#2
0
        private async void Compile(object sender, RoutedEventArgs e)
        {
            progressbar.Text = "Compiling code";
            progressbar.ShowAsync();

            var edContent = await webv.InvokeScriptAsync("getContent", new List <string>());

            var bytes  = Encoding.UTF8.GetBytes(edContent);
            var base64 = System.Uri.EscapeUriString(Convert.ToBase64String(bytes)).Replace("+", "%2B").Replace("=", "%3D");

            Debug.WriteLine(base64);

            var cts    = new CancellationTokenSource();
            var client = new HttpClient();

            try
            {
                cts.CancelAfter(7500);
                var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/api/compile?Content=" + base64));

                var result = await response.Content.ReadAsStringAsync();

                outbox.Text = result;
            }
            catch
            {
                outbox.Text = "Timeout";
            }
            progressbar.HideAsync();
            CodeHub.ScrollToSection(HubInOut);
        }
示例#3
0
        private async void semesterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            scheduleGrid.Children.Clear();
            searchResultLabelTextBlock.Text = name;
            if (semesterComboBox.SelectedItem is Semester)
            {
                await progressbar.ShowAsync();
                await GetSchedule(semesterComboBox.SelectedItem as Semester);

                await progressbar.HideAsync();
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            _progressbar = StatusBar.GetForCurrentView().ProgressIndicator;

            await _progressbar.ShowAsync();

            if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(DeviceInformation)))
            {
                try
                {
                    _idDevice = ((DeviceInformation)e.Parameter).Id;
                    _device   = await BluetoothLEDevice.FromIdAsync(((DeviceInformation)e.Parameter).Id);

                    this.lblDeviceName.Text = ((DeviceInformation)e.Parameter).Name + " " + BLEHelper.AddressToString(_device.BluetoothAddress);
                    if (_device == null)
                    {
                        new MessageDialog("Could not connect to the selected device!", "Error").ShowAsync();
                    }

                    _services = _device.GattServices;
                    lstServices.ItemsSource = _services;
                }
                catch (Exception ex)
                {
                    new MessageDialog("Device enumeration error: " + ex.Message, "Error").ShowAsync();
                }
            }
            this.navigationHelper.OnNavigatedTo(e);
            await _progressbar.HideAsync();

            _dataTransferManager = DataTransferManager.GetForCurrentView();
            _dataTransferManager.DataRequested += OnDataRequested;
        }
        async private void GetDataFromWeb()
        {
            progressbar.Text = "Fetching new data";
            progressbar.ShowAsync();

            var client = new HttpClient();

            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            if (!localSettings.Containers.ContainsKey("userInfo"))
            {
                MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu.");
                await msgbox.ShowAsync();

                return;
            }

            var lastcheck = localSettings.Containers["userInfo"].Values["lastcheckexamples"].ToString();

            Debug.WriteLine(System.Uri.EscapeUriString(lastcheck));
            var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/query/data?Timestamp=" + System.Uri.EscapeUriString(lastcheck) + "&Table=Examples"));

            var result = await response.Content.ReadAsStringAsync();

            result = result.Trim(new Char[] { '"' });
            Debug.WriteLine(result);

            DatabaseExample Db_Helper = new DatabaseExample();

            try
            {
                List <Examples> newex = JsonConvert.DeserializeObject <List <Examples> >(result);
                foreach (Examples ex in newex)
                {
                    try
                    {
                        Db_Helper.InsertExample(ex);
                    }
                    catch
                    {
                        Debug.WriteLine("DB error for item of id: " + ex.Id);
                    }
                }

                localSettings.Containers["userInfo"].Values["lastcheckexamples"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                progressbar.Text = "New items";
            }
            catch
            {
                Debug.WriteLine("No new items");
                progressbar.Text = "No New items";
            }
            finally
            {
                ReadExamples dbproblems = new ReadExamples();
                DB_ExampleList      = dbproblems.GetAllExamples();
                listBox.ItemsSource = DB_ExampleList.OrderByDescending(i => i.Id).ToList();
            }
            progressbar.HideAsync();
        }
示例#6
0
        private async void Login()
        {
            //Send GA Event
            App.Current.GATracker.SendEvent("Session", "Attempt Login", null, 0);

            string id = idTextBox.Text, password = passwordTextBox.Password;

            passwordTextBox.IsEnabled = loginAppBarButton.IsEnabled = false;
            idTextBox.IsReadOnly      = true;

            await progressbar.ShowAsync();

            var loginResult = await NPAPI.LoginNPortal(id, password);

            await progressbar.HideAsync();

            if (loginResult.Success)
            {
                //Store logged id, password
                var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

                if (roamingSettings.Values.ContainsKey("id"))
                {
                    roamingSettings.Values["id"] = id;
                }
                else
                {
                    roamingSettings.Values.Add("id", id);
                }

                if (roamingSettings.Values.ContainsKey("password"))
                {
                    roamingSettings.Values["password"] = password;
                }
                else
                {
                    roamingSettings.Values.Add("password", password);
                }

                //Login Aps

                await NPAPI.LoginAps();

                //Go to previous page
                if (Frame.CanGoBack)
                {
                    Frame.GoBack();
                }
            }
            else
            {
                await new MessageDialog(loginResult.Message).ShowAsync();
            }

            passwordTextBox.IsEnabled = loginAppBarButton.IsEnabled = true;
            idTextBox.IsReadOnly      = false;
        }
示例#7
0
 private async void LoginButton_Click(object sender, RoutedEventArgs e)
 {
     progressIndicator = StatusBar.GetForCurrentView().ProgressIndicator;
     progressIndicator.Text = "Daxil olunur";
     await progressIndicator.ShowAsync();
     await Authentication.Current.Login(EmailBox.Text, PasswordBox.Password);
     await NavigateToHome();
     await progressIndicator.HideAsync();
 }
        async private void GetDataFromWeb()
        {
            progressbar.Text = "Fetching new data";
            progressbar.ShowAsync();

            var client = new HttpClient();

            if (!localSettings.Containers.ContainsKey("userInfo"))
            {
                MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu.");
                await msgbox.ShowAsync();

                Frame.Navigate(typeof(Settings));
                return;
            }

            var lastcheck = localSettings.Containers["userInfo"].Values["lastcheckproblems"].ToString();

            Debug.WriteLine(System.Uri.EscapeUriString(lastcheck));
            var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/query/data?Timestamp=" + System.Uri.EscapeUriString(lastcheck) + "&Table=Problems"));

            var result = await response.Content.ReadAsStringAsync();

            result = result.Trim(new Char[] { '"' });
            Debug.WriteLine(result);

            DatabaseProblem Db_Helper = new DatabaseProblem();

            try
            {
                List <Problems> newprobs = JsonConvert.DeserializeObject <List <Problems> >(result);
                foreach (Problems prob in newprobs)
                {
                    try
                    {
                        Db_Helper.InsertProblem(prob);
                    }
                    catch
                    {
                        Debug.WriteLine("DB error for item of id: " + prob.Id);
                    }
                }
                localSettings.Containers["userInfo"].Values["lastcheckproblems"] = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
                progressbar.Text = "New items";
            }
            catch
            {
                Debug.WriteLine("No new items");
                progressbar.Text = "No New items";
            }
            finally
            {
                assignToListBox();
            }
            progressbar.HideAsync();
        }
示例#9
0
 private static async Task SetVisibility(StatusBarProgressIndicator progressIndicator, bool isVisible)
 {
     if (isVisible)
     {
         await progressIndicator.ShowAsync();
     }
     else
     {
         await progressIndicator.HideAsync();
     }
 }
示例#10
0
        private async Task populateSolvedData()
        {
            progressbar.Text = "Fetching data";
            progressbar.ShowAsync();

            var client   = new HttpClient();
            var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/users/getuserdata?Username="******"")
                    {
                        values.Add(Convert.ToInt32(value));
                        Debug.WriteLine("Adding " + value + " to list");
                    }
                }
                string serialized = JsonConvert.SerializeObject(values);
                localSettings.Containers["userInfo"].Values["PPsolved"] = serialized;
                localSettings.Containers["userInfo"].Values["Points"]   = udata[0].Points;

                Debug.WriteLine("Points: " + (int)localSettings.Containers["userInfo"].Values["Points"]);

                var ubox = FindChildControl <TextBlock>(LayoutRoot, "username_box") as TextBlock;
                Debug.WriteLine("u");
                var pbox = FindChildControl <TextBlock>(LayoutRoot, "points_box") as TextBlock;
                Debug.WriteLine("p");
                var sbox = FindChildControl <TextBlock>(LayoutRoot, "pp_box") as TextBlock;
                Debug.WriteLine("s");
                var tbox = FindChildControl <TextBlock>(LayoutRoot, "time_box") as TextBlock;
                Debug.WriteLine("t");
                ubox.Text = username;
                Debug.WriteLine("xu");
                pbox.Text = "Points: " + udata[0].Points.ToString();
                Debug.WriteLine("xp");
                tbox.Text = "Time spent coding: " + time;
                Debug.WriteLine("xt");
                sbox.Text = "Practice problems solved: " + count.ToString();
                Debug.WriteLine("xs");
            }
            catch
            {
                Debug.WriteLine("error");
            }
            progressbar.HideAsync();
        }
示例#11
0
#pragma warning disable 1998
        public static async void HideProgressBar()
        {
#if WINDOWS_PHONE_APP
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                          async() =>
            {
                StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
                await progressbar.HideAsync();
            }
                                                                          );
#endif
        }
示例#12
0
        private async void send(object sender, RoutedEventArgs e)
        {
            progressbar.Text = "Sending contribution";
            progressbar.ShowAsync();

            var client = new Windows.Web.Http.HttpClient();

            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            if (!localSettings.Containers.ContainsKey("userInfo"))
            {
                MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu.");
                await msgbox.ShowAsync();

                progressbar.HideAsync();
                Frame.Navigate(typeof(Settings));
                return;
            }

            var username = localSettings.Containers["userInfo"].Values["userName"].ToString();

            HttpStringContent content = new HttpStringContent(
                "{ \"Username\": \"" + username + "\", \"Category\": \"" + category_box.Text + "\", \"Title\": \"" + title_box.Text + "\", \"Content\": \"" + content_box.Text + "\", \"AdditionalContent\": \"" + add_box.Text + "\" }",
                UnicodeEncoding.Utf8,
                "application/json");

            Debug.WriteLine(content);

            var uri = new Uri("http://codeinn-acecoders.rhcloud.com:8000/contribute");

            var response = await client.PostAsync(uri, content);

            var result = await response.Content.ReadAsStringAsync();

            MessageDialog msgbox1 = new MessageDialog(result + " Thanks a lot!");
            await msgbox1.ShowAsync();

            progressbar.HideAsync();
        }
示例#13
0
        static partial void OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool isVisible = (bool)e.NewValue;

            if (isVisible)
            {
                AsyncHelpers.RunSync(async() => await _progressIndicator.ShowAsync());
            }
            else
            {
                AsyncHelpers.RunSync(async() => await _progressIndicator.HideAsync());
            }
        }
示例#14
0
        async private void GetDataFromWeb()
        {
            progressbar.Text = "Fetching new data";
            progressbar.ShowAsync();

            var client = new HttpClient();

            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            if (!localSettings.Containers.ContainsKey("userInfo"))
            {
                MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu.");
                await msgbox.ShowAsync();

                progressbar.HideAsync();
                Frame.Navigate(typeof(Settings));
                return;
            }

            var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/leaderboard"));

            var result = await response.Content.ReadAsStringAsync();

            result = result.Trim(new Char[] { '"' });
            Debug.WriteLine(result);

            try
            {
                List <LeaderboardItem> leaders = JsonConvert.DeserializeObject <List <LeaderboardItem> >(result);
                progressbar.Text    = "New items";
                listBox.ItemsSource = leaders.OrderByDescending(i => i.Points).ToList();
            }
            catch
            {
                progressbar.Text = "Error";
            }
            progressbar.HideAsync();
        }
        /// <summary>
        /// Rellena la página con el contenido pasado durante la navegación.  Cualquier estado guardado se
        /// proporciona también al crear de nuevo una página a partir de una sesión anterior.
        /// </summary>
        /// <param name="sender">
        /// El origen del evento; suele ser <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Datos de evento que proporcionan tanto el parámetro de navegación pasado a
        /// <see cref="Frame.Navigate(Type, Object)"/> cuando se solicitó inicialmente esta página y
        /// un diccionario del estado mantenido por esta página durante una sesión
        /// anterior. El estado será null la primera vez que se visite una página.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var sb = StatusBar.GetForCurrentView();
            StatusBarProgressIndicator progress = sb.ProgressIndicator;

            progress.Text = "Downloading Processes...";
            progress.ShowAsync();
            if (!App.ViewModel.IsDataLoaded)
            {
                await App.ViewModel.LoadData();
            }
            DataContext = App.ViewModel;
            progress.HideAsync();
        }
        private async void ToggleProgressBar(bool toggle, string message = "")
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;

            if (toggle)
            {
                progressbar.Text = message;
                await progressbar.ShowAsync();
            }
            else
            {
                await progressbar.HideAsync();
            }
        }
        private static async Task ToggleProgressBar(bool show)
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;

            if (show)
            {
                progressbar.Text = "Loading...";
                await progressbar.ShowAsync();
            }
            else
            {
                progressbar.Text = string.Empty;
                await progressbar.HideAsync();
            }
        }
示例#18
0
        public static async void ManageSystemTray(bool isActive, string message = "Loading...")
        {
#if WINDOWS_PHONE_APP
            StatusBarProgressIndicator progressIndicator = StatusBar.GetForCurrentView().ProgressIndicator;
            progressIndicator.Text = message;
            if (isActive)
            {
                await progressIndicator.ShowAsync();
            }
            else
            {
                await progressIndicator.HideAsync();
            }
#endif
        }
示例#19
0
        private async void DoRefresh()
        {
            await Task.Delay(300);

            _refreshPending = false;
            if (_token.Count == 0)
            {
                _progressIndicator.ProgressValue = 0;
                await _progressIndicator.HideAsync();
            }
            else
            {
                _progressIndicator.ProgressValue = null;
                await _progressIndicator.ShowAsync();
            }
        }
        protected async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            var request  = e.Request;
            var deferral = request.GetDeferral();

            await _progressbar.ShowAsync();

            e.Request.Data.Properties.Title = _device.Name;
            var txt = await DumpDeviceInfo();

            e.Request.Data.SetText(txt);

            deferral.Complete();

            await _progressbar.HideAsync();
        }
示例#21
0
        private async void _offlineNewsDownloader_OfflineProcessHandler(double process)
        {
            btn_Offline.Text      = "完成:" + (process * 100).ToString("0.0") + "%";
            progInd.ProgressValue = process;
            if (Math.Abs(process) == 1)
            {
                btn_Offline.Text = "离线下载";
                if (process == 1)
                {
                    ToastPrompt.ShowToast("离线下载完成");
                }
                await progInd.HideAsync();

                _offlineNewsDownloader.OfflineProcessHandler -= _offlineNewsDownloader_OfflineProcessHandler;
                _offlineNewsDownloader = null;
            }
        }
示例#22
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
            await progressbar.ShowAsync();

            if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(GattDeviceService)))
            {
                _service = ((GattDeviceService)e.Parameter);
                this.lblDeviceName.Text     = _service.Device.Name;
                this.lblServiceName.Text    = (string)_conv.Convert(_service.Uuid, typeof(string), null, null);
                this.lblServiceAddress.Text = _service.Uuid.ToString();

                _characteristics = new List <CharacteristicWithValue>();
                foreach (var c in _service.GetAllCharacteristics())
                {
                    var val = new CharacteristicWithValue();
                    val.GattCharacteristic = c;


                    if (((int)c.CharacteristicProperties & (int)GattCharacteristicProperties.Read) != 0)
                    {
                        try
                        {
                            GattReadResult readResult = await c.ReadValueAsync();

                            if (readResult.Status == GattCommunicationStatus.Success)
                            {
                                val.Value = new byte[readResult.Value.Length];
                                DataReader.FromBuffer(readResult.Value).ReadBytes(val.Value);
                            }
                        }
                        catch { }
                    }
                    _characteristics.Add(val);
                }

                lstCharacteristics.ItemsSource = _characteristics;
            }

            this.navigationHelper.OnNavigatedTo(e);
            await progressbar.HideAsync();
        }
示例#23
0
        private async void FilterMatches()
        {
            var filteredMatches =
                MatchViewModel.Instance.MatchesCollection.Where(
                    match => match.MatchDate <= EndDate.Date && match.MatchDate >= StartDate.Date);

            await ProgresIndicator.HideAsync();

            if (!filteredMatches.Any())
            {
                var errorDialog = new MessageDialog("Niestety w wybranym okresie nie rozegrano żadnych spotkań")
                {
                    Title = "Błąd Daty"
                };
                await errorDialog.ShowAsync();

                return;
            }

            HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
            Frame.Navigate(typeof(StatisticsWindow), filteredMatches);
        }
        async void RefreshDeviceList()
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
            await progressbar.ShowAsync();

            try
            {
                bleDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess));


                if (bleDevices.Count == 0)
                {
                    await new MessageDialog("No BLE devices were found or bluetooth disabled. Pair the device", "Info").ShowAsync();
                    Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute));
                }
                lstDevices.ItemsSource   = bleDevices;
                lstDevices.SelectedIndex = -1;
                // lstServices.ItemsSource = new List<string>();
            }
            catch { }
            await progressbar.HideAsync();
        }
示例#25
0
        private async Task <ObservableCollection <Song> > GetLibraryCollection()
        {
            SocketClient client = new SocketClient();

            StatusBar statusbar = StatusBar.GetForCurrentView();

            StatusBarProgressIndicator progressIndicator = statusbar.ProgressIndicator;

            progressIndicator.Text = "Loading library...";
            await statusbar.ShowAsync();

            await progressIndicator.ShowAsync();

            // Get all songs in the song library with metadata
            string response = await client.Command("listallinfo");

            ObservableCollection <Song> library = FormatLibrary(response);

            await progressIndicator.HideAsync();

            return(library);
        }
示例#26
0
        private async void RefreshAlarms()
        {
            StatusBarProgressIndicator progressbar = StatusBar.GetForCurrentView().ProgressIndicator;

            progressbar.Text = "Loading Alarms";
            await progressbar.ShowAsync();

            HttpClient client = new HttpClient();

            string response = await client.GetStringAsync(new Uri("https://timeprovider.azurewebsites.net/Api.ashx?action=get-alarms"));

            this.Alarms.Clear();
            var alarms = JsonConvert.DeserializeObject <List <AlarmViewModel> >(response);

            foreach (var alarm in alarms)
            {
                this.Alarms.Add(alarm);
            }

            this.AlarmsListView.ItemsSource = this.Alarms;

            await progressbar.HideAsync();
        }
示例#27
0
        private async Task getNewsFeed()
        {
            progressIndicator = StatusBar.GetForCurrentView().ProgressIndicator;
            progressIndicator.Text = "Yüklənir";
            await progressIndicator.ShowAsync();
            client = new HttpClient();
            try
            {
                response = await client.GetAsync(newsFeedUrl + "?userId=" + Authentication.currentUser + "&token=" + Authentication.token + "&offset=" + offset);
                string msg = await response.Content.ReadAsStringAsync();
                Windows.Data.Json.JsonArray jsonArray = Windows.Data.Json.JsonArray.Parse(msg);

                IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                async (workItem) =>
                {
                    foreach (var postItem in jsonArray)
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                                            CoreDispatcherPriority.High,
                                            new DispatchedHandler(() =>
                                            {
                                                Windows.Data.Json.JsonArray array2 = postItem.GetArray();
                                                string array = array2.Stringify();
                                                string userid = array2.GetNumberAt(0).ToString();
                                                string post = array2.GetStringAt(1);
                                                string posterName = array2.GetStringAt(2);
                                                string url;
                                                try
                                                {
                                                    url = array2.GetStringAt(3);
                                                }
                                                catch (Exception ex)
                                                {
                                                    url = "";
                                                }
                                                double likes = array2.GetNumberAt(4);
                                                double comments = array2.GetNumberAt(5);
                                                PostProfileUpdate prUpdate = new PostProfileUpdate(url, posterName, post, Convert.ToInt32(likes), Convert.ToInt32(comments));
                                                NewsFeedList.Items.Add(prUpdate);
                                            }));
                    }
                });
            }
            catch (HttpRequestException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                client = null;
                response = null;
                await progressIndicator.HideAsync();
                isLoadingNewsFeed = false;
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            _progressbar = StatusBar.GetForCurrentView().ProgressIndicator;
          
            await _progressbar.ShowAsync();
            if ((e.Parameter != null) && (e.Parameter.GetType() == typeof(DeviceInformation)))
            {
                
                try
                {
                    _idDevice=((DeviceInformation)e.Parameter).Id;
                    _device = await BluetoothLEDevice.FromIdAsync(((DeviceInformation)e.Parameter).Id);
                    this.lblDeviceName.Text = ((DeviceInformation)e.Parameter).Name+" " + BLEHelper.AddressToString(_device.BluetoothAddress);
                    if (_device == null)
                        new MessageDialog("Could not connect to the selected device!", "Error").ShowAsync();

                    _services = _device.GattServices;
                    lstServices.ItemsSource = _services;
                }
                catch (Exception ex)
                {
                    new MessageDialog("Device enumeration error: " + ex.Message, "Error").ShowAsync();
                }
            }
            this.navigationHelper.OnNavigatedTo(e);
            await _progressbar.HideAsync();
          
            _dataTransferManager = DataTransferManager.GetForCurrentView();
            _dataTransferManager.DataRequested += OnDataRequested;

        }
        async private void prepareData()
        {
            if (!localSettings.Containers.ContainsKey("userInfo"))
            {
                MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu.");
                await msgbox.ShowAsync();

                Frame.Navigate(typeof(Settings));
                return;
            }

            if (!localSettings.Containers.ContainsKey("dailyChallenge"))
            {
                Debug.WriteLine("needed to create");
                localSettings.CreateContainer("dailyChallenge", Windows.Storage.ApplicationDataCreateDisposition.Always);
                localSettings.Containers["dailyChallenge"].Values["Date"] = "2004-01-01T01:01:01.000Z";
                toRefresh = true;
            }
            else
            {
                string lastDate = localSettings.Containers["dailyChallenge"].Values["Date"].ToString();

                string   format            = "yyyy-MM-ddTHH:mm:ss.fffZ";
                DateTime lastchallengedate = DateTime.ParseExact(lastDate, format, CultureInfo.InvariantCulture);

                if (lastchallengedate.Date < DateTime.Now.Date)
                {
                    toRefresh = true;
                }
            }

            Debug.WriteLine("To refresh = " + toRefresh);

            if (toRefresh)
            {
                progressbar.Text = "Fetching new data";
                progressbar.ShowAsync();

                var client   = new HttpClient();
                var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/query/daily"));

                var result = await response.Content.ReadAsStringAsync();

                Debug.WriteLine(result);

                try
                {
                    // The server sends a single challenge so the list would be singly-occupied.
                    List <Problems> dailychall = JsonConvert.DeserializeObject <List <Problems> >(result);
                    foreach (Problems prob in dailychall)
                    {
                        localSettings.Containers["dailyChallenge"].Values["Date"]        = prob.CreationDate;
                        localSettings.Containers["dailyChallenge"].Values["Content"]     = prob.Content;
                        localSettings.Containers["dailyChallenge"].Values["Name"]        = prob.Name;
                        localSettings.Containers["dailyChallenge"].Values["Description"] = prob.Description;
                        localSettings.Containers["dailyChallenge"].Values["Id"]          = prob.Id;
                        displayedObject = prob;
                    }
                }
                catch
                {
                    Debug.WriteLine("Internal error.");
                    progressbar.Text = "Error";
                }
                progressbar.HideAsync();
            }
            else
            {
                string name        = localSettings.Containers["dailyChallenge"].Values["Name"].ToString();
                string content     = localSettings.Containers["dailyChallenge"].Values["Content"].ToString();
                string description = localSettings.Containers["dailyChallenge"].Values["Description"].ToString();
                displayedObject = new Problems(0, name, description, content, "Admin");
                //await Task.Delay(1000);
            }

            populateContent();
        }
 async void PlayersViewModel_CollectionLoaded(object sender)
 {
     PlayersListBox.ItemsSource = PlayersViewModel.Instance.PlayersCollection;
     await ProgresIndicator.HideAsync();
 }
示例#31
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //Init epub object.

            //bool fileExist = await EpubReader.DoesFileExistAsync(Windows.ApplicationModel.Package.Current.InstalledLocation, "test.epub");
            //if (!fileExist)
            //    throw new Exception(string.Format("File test.epub not found, bitch"));

            progressbar.Text = "Загрузка книги";
            await progressbar.ShowAsync();

            //bookLoadingProgressBar.Visibility = Visibility.Visible;

            // Opening a book
            currentEpubBook = await EpubReader.OpenBookAsync("test.epub");

            if (currentEpubBook != null)
            {
                loadEbookButton.Content   = "Loaded";
                loadEbookButton.IsEnabled = false;
            }
            //// COMMON PROPERTIES
            //// Book's title
            //string title = currentEpubBook.Title;
            //// Book's authors (comma separated list)
            //string author = currentEpubBook.Author;
            //// Book's authors (list of authors names)
            //List<string> authors = currentEpubBook.AuthorList;
            //// Book's cover image (null if there are no cover)
            //BitmapImage coverImage = currentEpubBook.CoverImage;
            //// ShowCoverImage(coverImage); //Only for testing purposes



            // CONTENT

            // Book's content (HTML files, style-sheets, images, fonts, etc.)
            EpubContent bookContent = currentEpubBook.Content;


            // IMAGES

            // All images in the book (file name is the key)
            //Dictionary<string, EpubByteContentFile> images = bookContent.Images;

            //EpubByteContentFile firstImage = images.Values.First();

            //// Content type (e.g. EpubContentType.IMAGE_JPEG, EpubContentType.IMAGE_PNG)
            //EpubContentType contentType = firstImage.ContentType;

            //// MIME type (e.g. "image/jpeg", "image/png")
            //string mimeContentType = firstImage.ContentMimeType;



            // HTML & CSS

            // All XHTML files in the book (file name is the key)
            Dictionary <string, EpubTextContentFile> htmlFiles = bookContent.Html;

            // All CSS files in the book (file name is the key)
            Dictionary <string, EpubTextContentFile> cssFiles = bookContent.Css;
            // All CSS content in the book
            //foreach (EpubTextContentFile cssFile in cssFiles.Values)
            //{
            //    string cssContent = cssFile.Content;
            //}
            // OTHER CONTENT

            // All fonts in the book (file name is the key)
            // Dictionary<string, EpubByteContentFile> fonts = bookContent.Fonts;

            // All files in the book (including HTML, CSS, images, fonts, and other types of files)
            //TO-DO looks like this dictionary not working well at the moment, have to trace
            //Dictionary<string, EpubContentFile> allFiles = bookContent.AllFiles;

            //To-DO:
            //Определить первый файл в книге - через spine или через guide
            //Отслеживать клики по экрану и по краям экрана - чтобы листать вперед и назад.
            //Отслеживать, когда на экране последняя column из файла и нужно подгружать следующую

            await progressbar.HideAsync();

            progressbar.Text = "Форматирование";
            await progressbar.ShowAsync();

            // Entire HTML content of the book should be injected in case we are showing chapter by chapter, and not pretending to load the whole set of chapters
            //foreach (KeyValuePair<string, EpubTextContentFile> htmlItem in htmlFiles)
            //{
            //    string injectedItem = WebViewHelpers.injectMonocle(htmlItem.Value.Content,
            //   (int)bookReaderWebViewControl.ActualWidth, (int)bookReaderWebViewControl.ActualHeight);
            //    htmlItem.Value.Content = injectedItem;
            //}

            IndexFileSceleton index = new IndexFileSceleton();

            index.author     = currentEpubBook.Author;
            index.title      = currentEpubBook.Title;
            index.height     = (int)bookReaderWebViewControl.ActualHeight;
            index.chapters   = currentEpubBook.Chapters;
            index.xhtmlFiles = currentEpubBook.Content.Html;

            // --- Streaming HTML+JS content directly from the memory ---
            //Uri url = bookReaderWebViewControl.BuildLocalStreamUri("MemoryTag", "section4.xhtml");
            CreateIndex();

            Uri url = bookReaderWebViewControl.BuildLocalStreamUri("MemoryTag", "index.html");

            bookReaderWebViewControl.NavigateToLocalStreamUri(url, myMemoryResolver);

            //Now we could have a look at the chapters list
            chaptersMenuButton.IsEnabled = true;
            await progressbar.HideAsync();

            //bookLoadingProgressBar.Visibility = Visibility.Collapsed;

            // ACCESSING RAW SCHEMA INFORMATION

            //// EPUB OPF data
            //EpubPackage package = epubBook.Schema.Package;

            //// Enumerating book's contributors
            //foreach (EpubMetadataContributor contributor in package.Metadata.Contributors)
            //{
            //    string contributorName = contributor.Contributor;
            //    string contributorRole = contributor.Role;
            //}

            //// EPUB NCX data
            //EpubNavigation navigation = epubBook.Schema.Navigation;

            //// Enumerating NCX metadata
            //foreach (EpubNavigationHeadMeta meta in navigation.Head)
            //{
            //    string metadataItemName = meta.Name;
            //    string metadataItemContent = meta.Content;
            //}
        }
 async void TeamsViewModel_CollectionLoaded(object sender)
 {
     ChoseTeamListView.ItemsSource = TeamsViewModel.Instance.TeamsCollection;
     await ProgresIndicator.HideAsync();
 }
示例#33
0
        //Click on Spin it! button
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            progressbar.Text = "Loading...";
            await progressbar.ShowAsync();

            gameToPlay.Visibility = Visibility.Collapsed;

            if (Spin_it.IsEnabled)
            {
                Spin_it.IsEnabled = false;
                if (steamIdTextBox.Text.Equals("") || steamIdTextBox.Text.Equals("enter your community name"))
                {
                    msgPop.Pop("Enter your community name / steamID64.", "Info");
                }
                else
                {
                    try
                    {
                        if (!_user.steamId.Equals(steamIdTextBox.Text))
                        {
                            if (Regex.IsMatch(steamIdTextBox.Text, @"^\d+$") && steamIdTextBox.Text.Length == 17)   //If is all number
                            {
                                _steamID64 = steamIdTextBox.Text;
                            }
                            else
                            {
                                _user.steamId = steamIdTextBox.Text;
                                _steamID64    = await _user.getSteamID64();
                            }
                        }

                        List <object> resultados = await _user.getGame(_steamID64);

                        _game = (Game)resultados[0];

                        TextBlock gtp = new TextBlock();
                        gtp.Text           = _game.name;
                        gtp.TextWrapping   = TextWrapping.Wrap;
                        gameToPlay.Content = gtp;

                        m_Image.Source           = (ImageSource)resultados[1];
                        hyperLinkImg.NavigateUri = new Uri("http://store.steampowered.com/app/" + _game.appid);
                        string time = null;
                        if (_game.playtime_forever < 60)
                        {
                            time = _game.playtime_forever + " mins.";
                        }
                        else
                        {
                            time = String.Format("{0:0.##}", (double)_game.playtime_forever / 60) + " hours.";
                        }

                        gameInfo.Text = "Time played: " + time;

                        RootObject StoreInfo = (RootObject)await _user.gameInfo(_game.appid);

                        if (StoreInfo.success)
                        {
                            HtmlDocument documento = new HtmlDocument();
                            documento.LoadHtml(StoreInfo.data.about_the_game);

                            foreach (HtmlNode child in documento.DocumentNode.ChildNodes)
                            {
                                if (child.Name.Equals("h2"))
                                {
                                    TextBlock txt = new TextBlock();
                                    txt.TextWrapping = TextWrapping.Wrap;
                                    txt.Text         = child.InnerText;
                                    txt.FontSize     = 16;
                                    txt.FontWeight   = Windows.UI.Text.FontWeights.Bold;
                                    txt.Margin       = new Thickness(0, 10, 0, 0);
                                    MyStackPanel_2.Children.Add(txt);
                                }
                                else if (child.Name.Equals("ul"))
                                {
                                    TextBlock txt = new TextBlock();
                                    txt.TextWrapping = TextWrapping.Wrap;
                                    txt.FontSize     = 12;
                                    txt.FontWeight   = Windows.UI.Text.FontWeights.Normal;
                                    foreach (HtmlNode li in child.ChildNodes)
                                    {
                                        txt.Text += "- " + li.InnerText;
                                    }
                                    MyStackPanel_2.Children.Add(txt);
                                }
                                else
                                {
                                    TextBlock txt = new TextBlock();
                                    txt.TextWrapping = TextWrapping.Wrap;
                                    txt.FontSize     = 12;
                                    txt.FontWeight   = Windows.UI.Text.FontWeights.Normal;
                                    txt.Text         = child.InnerText;
                                    MyStackPanel_2.Children.Add(txt);
                                }
                            }
                        }
                    }

                    //Error on the httprequest
                    catch (NullReferenceException)
                    {
                        msgPop.Pop("Could not connect to Steam: An exception ocurred during a http request.", "Error");
                    }
                    //Any other exception
                    catch (Exception ex)
                    {
                        msgPop.Pop(ex.Message, "Error");
                    }
                }

                await progressbar.HideAsync();

                Spin_it.IsEnabled = true;
            }
        }