Exemplo n.º 1
0
        private async void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (InfoFlyout.IsOpen)
            {
                InfoFlyout.Hide();
            }
            if (Movies.Any(x => x.HasErrors))
            {
                InfoText.Text = "Пожалуйста, сначала исправьте ошибки в таблице";
                InfoFlyout.ShowAt(dgv);
                return;
            }
            SaveBtn.IsEnabled = false;
            MoviesController controller = MoviesController.GetInstance();
            int result = await controller.SaveMovies(Movies.Select(x => x.Movie).ToList());

            int userId   = UAC.GetInstance().UserId;
            int viewings = await controller.SaveViewings(Movies.Select(
                                                             x => new ViewingData(x.Movie.ID, userId, DateTime.Parse(x.Date), x.Rate)).ToList());

            InfoText.Text = string.Format("Сохранено {0}/{1} фильмов{2}Добавлено {3}/{1} просмотров",
                                          result, Movies.Count, Environment.NewLine, viewings);
            InfoFlyout.ShowAt(dgv);
            Movies          = new List <MovieDisplay>();
            dgv.ItemsSource = Movies;
        }
Exemplo n.º 2
0
 private void ParamTB_KeyUp(object sender, KeyRoutedEventArgs e)
 {
     if (e.Key != Windows.System.VirtualKey.Enter)
     {
         return;
     }
     if ((filterCB.SelectedItem as FilterOption).Filter == Filters.GetByYearPeriod)
     {
         string[] vs = (sender as TextBox).Text.Split(new char[] { ' ', '-' }, StringSplitOptions.RemoveEmptyEntries);
         if (vs != null && vs.Length == 2 &&
             short.TryParse(vs[0], out short start) && short.TryParse(vs[1], out short end) &&
             end > start)
         {
             filterParam = new Tuple <short, short>(start, end);
             UpdateDG(1);
         }
         else
         {
             if (!InfoFlyout.IsOpen)
             {
                 InfoText.Text = "Пожалуйста, введите правильный диапазон" + Environment.NewLine +
                                 "Например: 1989-2007";
                 InfoFlyout.ShowAt(sender as TextBox);
             }
         }
     }
     else
     {
         if (!string.IsNullOrWhiteSpace((sender as TextBox).Text))
         {
             filterParam = (sender as TextBox).Text;
             UpdateDG(1);
         }
     }
 }
 private void AppBarButton_Click(object sender, RoutedEventArgs e)
 {
     if (isInfoFlyoutOpen)
     {
         InfoFlyout.Hide();
     }
     else
     {
         Uri targetUri = new Uri(@"https://developers.arcgis.com/en/features/geocoding/");
         MyWebView.Navigate(targetUri);
     }
 }
Exemplo n.º 4
0
 private void AddUser_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(userName.Text))
     {
         InfoText.Text = "Поле не должно быть пустым";
         InfoFlyout.ShowAt(userName);
         return;
     }
     if (!MoviesController.GetInstance().AddUser(userName.Text))
     {
         InfoText.Text = "Логин уже занят";
     }
     else
     {
         InfoText.Text = "Пользователь создан с пустым паролем";
     }
     InfoFlyout.ShowAt(userName);
 }
Exemplo n.º 5
0
        private async void ActionButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            ActionButton.IsEnabled = false;
            DateTime      date   = DateTime.Now.Date;
            ContentDialog dialog = new ContentDialog()
            {
                Title             = "Подтвердите действие",
                Content           = string.Format("Добавить просмотр за {0} с оценкой {1}?", date.ToShortDateString(), Rate.Text),
                PrimaryButtonText = "Да",
                CloseButtonText   = "Нет"
            };
            var result = await dialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                ViewingData viewing = new ViewingData(id, UAC.GetInstance().UserId, date, float.Parse(Rate.Text));
                int         z       = await MoviesController.GetInstance().SaveViewings(new List <ViewingData>()
                {
                    viewing
                });

                if (z > 0)
                {
                    InfoText.Text = "Просмотр добавлен";
                    List <ViewingData> viewings = MoviesController.GetInstance().GetViewings(id, UAC.GetInstance().UserId);
                    tViewings.Text = string.Join(
                        ", ", viewings.Select(x => string.Format("{0} ({1:F1})", x.Date.ToShortDateString(), x.Rating)));
                }
                else
                {
                    InfoText.Text = "Что-то пошло не так";
                }
                InfoFlyout.ShowAt(Rate);
                Rate.Text = "";
            }
            else
            {
                ActionButton.IsEnabled = true;
            }
        }
Exemplo n.º 6
0
 private void ChangePwd_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(newPass.Password))
     {
         InfoText.Text = "Поле не должно быть пустым";
         InfoFlyout.ShowAt(newPass);
         return;
     }
     if (!MoviesController.GetInstance().ChangeUserPwd(oldPass.Password, newPass.Password))
     {
         InfoText.Text = "Неверный старый пароль";
         InfoFlyout.ShowAt(oldPass);
         oldPass.Password = "";
     }
     else
     {
         InfoText.Text = "Установлен новый пароль";
         InfoFlyout.ShowAt(newPass);
         oldPass.Password = "";
         newPass.Password = "";
     }
 }
Exemplo n.º 7
0
        private async void AddBtn_Click(object param, RoutedEventArgs e)
        {
            AddBtn.IsEnabled = false;
            FileOpenPicker diag = new FileOpenPicker();

            diag.FileTypeFilter.Add(".zip");
            diag.FileTypeFilter.Add(".html");
            StorageFile file = await diag.PickSingleFileAsync();

            AddBtn.IsEnabled = true;
            if (file == null)
            {
                return;
            }

            StringBuilder builder = new StringBuilder("");
            List <byte[]> html;
            int           count = 0;

            using (Stream stream = await file.OpenStreamForReadAsync())
            {
                if (file.FileType.Equals(".zip"))
                {
                    using (ZipArchive zip = new ZipArchive(stream, ZipArchiveMode.Read, false))
                    {
                        count = zip.Entries.Count;
                        html  = zip.Entries
                                .OrderBy(entry => entry.LastWriteTime.DateTime)
                                .Select(entry =>
                        {
                            byte[] arr = new byte[entry.Length];
                            entry.Open().Read(arr, 0, arr.Length);
                            return(arr);
                        })
                                .ToList();
                    }
                }
                else if (file.FileType.Equals(".html"))
                {
                    html = new List <byte[]>(1)
                    {
                        new byte[stream.Length]
                    };
                    stream.Read(html[0], 0, html[0].Length);
                }
                else
                {
                    html = new List <byte[]>();
                }
            }
            List <MovieData> movies = html
                                      .AsParallel()
                                      .Select(x =>
            {
                string s = Encoding.UTF8.GetString(x);
                int t    = s.IndexOf("charset=") + "charset=".Length;
                int l    = s.IndexOf('"', t) - t;
                if (l > 0)
                {
                    Encoding enc;
                    try
                    {
                        enc = Encoding.GetEncoding(s.Substring(t, l));
                    }
                    catch (Exception)
                    {
                        enc = CodePagesEncodingProvider.Instance.GetEncoding(s.Substring(t, l));
                    }
                    if (enc != Encoding.UTF8)
                    {
                        s = enc.GetString(x);
                    }
                }
                try
                {
                    MovieData temp = KPParser.ParseString(s);
                    return(temp);
                }
                catch (FormatException exc)
                {
                    builder.Append(exc.Message + Environment.NewLine);
                    return(null);
                }
            })
                                      .Where(movie => movie != null)
                                      .ToList();

            builder.AppendFormat("{0}/{1} entries processed{2}", movies.Count(),
                                 count, Environment.NewLine);

            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            if (!(localSettings.Values["picturesFolder"] is string folderToken))
            {
                FolderPicker folderPicker = new FolderPicker();
                folderPicker.FileTypeFilter.Add("*");
                StorageFolder folder = await folderPicker.PickSingleFolderAsync();

                if (folder == null)
                {
                    return;
                }
                folderToken = StorageApplicationPermissions.FutureAccessList.Add(folder);
                localSettings.Values["picturesFolder"] = folderToken;
            }
            StorageFolder nfolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(folderToken);

            var downloads = (await Task.WhenAll(movies
                                                .Select(async movie => new Tuple <string, IStorageItem>(
                                                            movie.PosterLink, await nfolder.TryGetItemAsync(Path.GetFileName(movie.PosterLink)))))
                             )
                            .Where(tuple => tuple.Item2 == null);
            int required = downloads.Count();

            count = (await Task.WhenAll(downloads
                                        .Select(async tuple =>
            {
                try
                {
                    Uri source = new Uri(tuple.Item1);
                    StorageFile destinationFile = await nfolder.CreateFileAsync(Path.GetFileName(tuple.Item1));
                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                    await download.StartAsync();
                    return(true);
                }
                catch (Exception)
                {
                    builder.Append("Download failed: " + tuple.Item1 + Environment.NewLine);
                    return(false);
                }
            })))
                    .Count(x => x);
            builder.AppendFormat("{0}/{1} posters downloaded{2}", count, required, Environment.NewLine);

            if (InfoFlyout.IsOpen)
            {
                InfoFlyout.Hide();
            }
            InfoText.Text = builder.ToString();
            InfoFlyout.ShowAt(dgv);
            Movies = movies
                     .Select(movie => new MovieDisplay(movie, DateTime.Now.Date, movie.RatingIMDB))
                     .ToList();
            dgv.ItemsSource   = Movies;
            SaveBtn.IsEnabled = Movies.Count > 0;
            if (!UpperRibbon.Children.Contains(startDate))
            {
                startDate.DateChanged += Date_DateChanged;
                UpperRibbon.Children.Add(startDate);
                endDate.DateChanged += Date_DateChanged;
                UpperRibbon.Children.Add(endDate);
            }
        }