Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- XAML:
- <Page
- x:Class="ExtraFeatures2022.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:ExtraFeatures2022"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel Margin="20">
- <Button Click="Button_Click" Margin="20">Käynnistä raskas operaatio</Button>
- <Button Margin="20">Testipainike</Button>
- <TextBlock Name="ResultText" Margin="20" FontSize="28" FontWeight="Bold"></TextBlock>
- <!-- nappi jolla vaihdetaan aktiivista kieltä -->
- <Button Click="Button_Click_1" Margin="20">FI/EN</Button>
- <!-- x:Uid hakee Strings-kansiosta aktiivisen kielen kansiosta -->
- <!-- Resources-tiedostosta Greeting.Text nimisen kielikäännöksen -->
- <!-- ks. ohje https://docs.microsoft.com/en-us/windows/uwp/app-resources/localize-strings-ui-manifest -->
- <TextBlock x:Uid="Greeting" FontSize="28" FontWeight="Bold" Margin="20"></TextBlock>
- </StackPanel>
- </Page>
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel>
- <TextBox Name="Input_Box"></TextBox>
- <Button Click="AddData">Add</Button>
- <ListView Name="Output">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextBlock Text="{Binding}"/>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackPanel>
- </Grid>
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel>
- <TextBox Name="Input_Box"></TextBox>
- <Button Click="AddData">Add</Button>
- <ListView Name="Output" RightTapped="ListView_RightTapped">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextBlock Text="{Binding}"/>
- </DataTemplate>
- </ListView.ItemTemplate>
- <ListView.Resources>
- <MenuFlyout x:Name="allContactsMenuFlyout">
- <MenuFlyout.Items>
- <MenuFlyoutItem x:Name="Edit" Text="Edit" />
- <MenuFlyoutItem x:Name="Remove" Text="Remove" Click="Remove_Click" />
- </MenuFlyout.Items>
- </MenuFlyout>
- </ListView.Resources>
- </ListView>
- </StackPanel>
- </Grid>
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel>
- <TextBox Name="Input_Box"></TextBox>
- <Button Click="AddData">Add</Button>
- <ListView Name="Output" RightTapped="ListView_RightTapped">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextBlock Text="{Binding}"/>
- </DataTemplate>
- </ListView.ItemTemplate>
- <ListView.Resources>
- <MenuFlyout x:Name="allContactsMenuFlyout">
- <MenuFlyout.Items>
- <MenuFlyoutItem x:Name="Edit" Text="Edit" />
- <MenuFlyoutItem x:Name="Remove" Text="Remove" Click="Remove_Click" />
- </MenuFlyout.Items>
- </MenuFlyout>
- </ListView.Resources>
- </ListView>
- <Button Click="Button_Click">FI/EN</Button>
- </StackPanel>
- </Grid>
- C#:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Threading.Tasks;
- using Windows.Foundation;
- using Windows.Foundation.Collections;
- using Windows.Globalization;
- using Windows.Storage;
- using Windows.UI.Core;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- using Windows.UI.Xaml.Controls.Primitives;
- using Windows.UI.Xaml.Data;
- using Windows.UI.Xaml.Input;
- using Windows.UI.Xaml.Media;
- using Windows.UI.Xaml.Navigation;
- // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
- namespace ExtraFeatures2022
- {
- /// <summary>
- /// An empty page that can be used on its own or navigated to within a Frame.
- /// </summary>
- public sealed partial class MainPage : Page
- {
- public MainPage()
- {
- this.InitializeComponent();
- }
- // jos event handlerissa on await-komento, metodin pitää olla async
- // private void Button_Click(object sender, RoutedEventArgs e)
- private async void Button_Click(object sender, RoutedEventArgs e)
- {
- //SlowCode();
- //_ = BigWorkBackground();
- //var t = Task.Run(() => TaskWorkBackground());
- //await AwaitBackgroundWork();
- //DownloadVideosNoThreadingAsync();
- await DownloadVideosThreaded();
- }
- private async Task AwaitBackgroundWork()
- {
- Debug.WriteLine("Vaihe 1");
- ResultText.Text = "Vaihe 1...";
- await Task.Delay(3000);
- Debug.WriteLine("Vaihe 2");
- ResultText.Text = "Vaihe 2...";
- await Task.Delay(3000);
- Debug.WriteLine("Vaihe 3");
- ResultText.Text = "Vaihe 3...";
- await Task.Delay(3000);
- ResultText.Text = "Kaikki työ tehty!";
- }
- public async Task TaskWorkBackground()
- {
- Debug.WriteLine("Aloitetaan työ");
- // jos haluamme Taskin sisällä päästä käsiksi UI Threadiin, eli käyttöliittymään, tarvitsemme Dispatcheria:
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
- ResultText.Text = "Aloitetaan työ.";
- });
- // simuloidaan kolme vaihetta, await-versio Thread.Sleepistä
- await Task.Delay(3000);
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
- ResultText.Text = "Vaihe 1";
- });
- await Task.Delay(3000);
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
- ResultText.Text = "Vaihe 2";
- });
- await Task.Delay(3000);
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
- ResultText.Text = "Vaihe 3";
- });
- Debug.WriteLine("Kaikki työ tehty.");
- // jos haluamme Taskin sisällä päästä käsiksi UI Threadiin, eli käyttöliittymään, tarvitsemme Dispatcheria:
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
- ResultText.Text = "Kaikki työ tehty!";
- });
- }
- // backgroundworker-versio säikeistämisestä
- // ei suositeltava tapa enää nykyään
- public async System.Threading.Tasks.Task BigWorkBackground()
- {
- // luodaan worker
- BackgroundWorker workerThread = new BackgroundWorker();
- // tässä tapauksessa emme mahdollista säikeen peruuttamista
- workerThread.WorkerSupportsCancellation = false;
- // haluamme kuitenkin antaa välitietoja miten työ etenee
- workerThread.WorkerReportsProgress = true;
- workerThread.DoWork += delegate (object s, DoWorkEventArgs args)
- {
- // simuloidaan hidasta koodia Thread.Sleepin avulla
- Debug.WriteLine("Vaihe 1");
- workerThread.ReportProgress(1);
- System.Threading.Thread.Sleep(3000);
- Debug.WriteLine("Vaihe 2");
- workerThread.ReportProgress(2);
- System.Threading.Thread.Sleep(3000);
- Debug.WriteLine("Vaihe 3");
- workerThread.ReportProgress(3);
- System.Threading.Thread.Sleep(3000);
- };
- workerThread.ProgressChanged += delegate (object s, ProgressChangedEventArgs e)
- {
- ResultText.Text = "Vaihe " + e.ProgressPercentage;
- };
- // kun DoWork on suoritettu loppuun
- workerThread.RunWorkerCompleted += delegate (object s, RunWorkerCompletedEventArgs args)
- {
- ResultText.Text = "Kaikki työt suoritettu!";
- };
- // käynnistä säie!
- workerThread.RunWorkerAsync();
- }
- private void SlowCode()
- {
- // simuloidaan hidasta koodia Thread.Sleepin avulla
- Debug.WriteLine("Vaihe 1");
- ResultText.Text = "Vaihe 1";
- System.Threading.Thread.Sleep(3000);
- Debug.WriteLine("Vaihe 2");
- ResultText.Text = "Vaihe 2";
- System.Threading.Thread.Sleep(3000);
- Debug.WriteLine("Vaihe 3");
- ResultText.Text = "Vaihe 3";
- System.Threading.Thread.Sleep(3000);
- ResultText.Text = "Kaikki tehty.";
- }
- private async Task DownloadVideosThreaded()
- {
- // haetaan ohjelman tallennuskansio Windowsista
- Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
- // luodaan apukansio "myvideos"
- // korvataan vanha kansio, jos se löytyy entuudestaan
- StorageFolder newFolder = await storageFolder.CreateFolderAsync("myvideos", CreationCollisionOption.ReplaceExisting);
- // tulostetaan testimielessä kansion sijainti konsoliin
- Debug.WriteLine(storageFolder.Path.ToString());
- // lisätään pari testivideota ladattavaksi listaan
- List<string> videos = new List<string>();
- videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4");
- videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4");
- videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4");
- // pidetään muuttujassa yllä seuraavaksi tallennettavan videon numero
- int fileNumber = 1;
- // luodaan http-client, jolla voimme ladata internetistä dataa
- // joudumme awaitin vuoksi käyttämään tätä, sillä WebClient ei toimi awaitin kanssa
- // tämä johtuu siitä, että WebClient on itse toteuttanut säikeistämisen eri tavalla
- HttpClient httpc = new HttpClient();
- // käydään videot silmukassa läpi
- foreach (String video in videos)
- {
- // päivitetään tilanneviestit
- Debug.WriteLine("Start download: " + video);
- ResultText.Text = "Downloading video " + fileNumber;
- // ladataan videon sisältö tavutaulukkoon
- byte[] stringData = await httpc.GetByteArrayAsync(video);
- // tehdään uudelle videolle uusi tiedosto apukansioon (myvideos)
- Windows.Storage.StorageFile file = await storageFolder.CreateFileAsync(@"\myvideos\video" + fileNumber + ".mp4",
- Windows.Storage.CreationCollisionOption.ReplaceExisting);
- // tulostetaan testimielessä kansion polku konsoliin,
- // jotta voimme testata helpommin sitä
- Debug.WriteLine(storageFolder.Path.ToString());
- // kirjoitetaan videon sisältö uuteen tiedostoon
- await Windows.Storage.FileIO.WriteBytesAsync(file, stringData);
- // kasvatetaan numeroa seuraavaa tiedostoa varten
- fileNumber += 1;
- Debug.WriteLine("Download finished.");
- }
- ResultText.Text = "All downloads done!";
- }
- private async Task DownloadVideosNoThreadingAsync()
- {
- // testivideot otettu täältä: https://gist.github.com/jsturgis/3b19447b304616f18657
- List<string> videos = new List<string>();
- videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4");
- videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4");
- // haetaan sovelluksen tallenuspaikka, ja luodaan uusi kansio videoille
- Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
- StorageFolder newFolder = await storageFolder.CreateFolderAsync("myvideos", CreationCollisionOption.ReplaceExisting);
- // tulostetaan konsoliin testaamista varten kansion polku
- Debug.WriteLine(storageFolder.Path.ToString());
- // ensimmäinen tiedosto alkaa numerosta 1
- int fileNumber = 1;
- // luodaan web client
- var client = new WebClient();
- // ladataan yksitellen videot
- foreach (String video in videos)
- {
- Debug.WriteLine("Downloading video " + fileNumber);
- // jos käytössä BackgroundWorker, tämä pitää olla päällä
- //workerThread.ReportProgress(fileNumber);
- // lataa tiedosto ja tallenna se tallennustilaan
- client.DownloadFile(new Uri(video), storageFolder.Path.ToString() + @"\myvideos\video" + fileNumber + ".mp4");
- Debug.WriteLine(storageFolder.Path.ToString() + @"\myvideos\video" + fileNumber + ".mp4");
- // kasvata numeroa seuraavaa tiedostoa varten
- fileNumber += 1;
- }
- }
- private void Button_Click_1(object sender, RoutedEventArgs e)
- {
- // vaihdetaan kieleksi joko suomi tai englanti, riippuu
- // kumpi on vaktiivinen
- if(ApplicationLanguages.PrimaryLanguageOverride == "fi")
- {
- ApplicationLanguages.PrimaryLanguageOverride = "en-US";
- }
- else
- {
- ApplicationLanguages.PrimaryLanguageOverride = "fi";
- }
- // navigoidaan sivulle uudestaan jotta vaihdettu kieli näkyy
- Frame.Navigate(this.GetType());
- }
- }
- }
- public App()
- {
- this.InitializeComponent();
- this.Suspending += OnSuspending;
- DataAccess.InitializeDatabase();
- }
- // DataAccess
- public static class DataAccess
- {
- public async static void InitializeDatabase()
- {
- await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db", CreationCollisionOption.OpenIfExists);
- string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
- using (SqliteConnection db =
- new SqliteConnection($"Filename={dbpath}"))
- {
- db.Open();
- String tableCommand = "CREATE TABLE IF NOT " +
- "EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +
- "Text_Entry NVARCHAR(2048) NULL)";
- SqliteCommand createTable = new SqliteCommand(tableCommand, db);
- createTable.ExecuteReader();
- }
- }
- public static void AddData(string inputText)
- {
- string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
- using (SqliteConnection db =
- new SqliteConnection($"Filename={dbpath}"))
- {
- db.Open();
- SqliteCommand insertCommand = new SqliteCommand();
- insertCommand.Connection = db;
- // Use parameterized query to prevent SQL injection attacks
- insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Entry);";
- insertCommand.Parameters.AddWithValue("@Entry", inputText);
- insertCommand.ExecuteReader();
- db.Close();
- }
- }
- public static void RemoveRow(string inputText)
- {
- string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
- using (SqliteConnection db =
- new SqliteConnection($"Filename={dbpath}"))
- {
- db.Open();
- SqliteCommand insertCommand = new SqliteCommand();
- insertCommand.Connection = db;
- // Use parameterized query to prevent SQL injection attacks
- insertCommand.CommandText = "DELETE FROM MyTable WHERE Text_Entry = @Entry;";
- insertCommand.Parameters.AddWithValue("@Entry", inputText);
- insertCommand.ExecuteReader();
- db.Close();
- }
- }
- public static List<String> GetData()
- {
- List<String> entries = new List<string>();
- string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
- using (SqliteConnection db =
- new SqliteConnection($"Filename={dbpath}"))
- {
- db.Open();
- SqliteCommand selectCommand = new SqliteCommand
- ("SELECT Text_Entry from MyTable", db);
- SqliteDataReader query = selectCommand.ExecuteReader();
- while (query.Read())
- {
- entries.Add(query.GetString(0));
- }
- db.Close();
- }
- return entries;
- }
- }
- public sealed partial class MainPage : Page
- {
- public MainPage()
- {
- this.InitializeComponent();
- Output.ItemsSource = DataAccess.GetData();
- }
- private void AddData(object sender, RoutedEventArgs e)
- {
- DataAccess.AddData(Input_Box.Text);
- Output.ItemsSource = DataAccess.GetData();
- }
- private String activeRow = "";
- private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
- {
- ListView listView = (ListView)sender;
- allContactsMenuFlyout.ShowAt(listView, e.GetPosition(listView));
- var a = ((FrameworkElement)e.OriginalSource).DataContext;
- activeRow = a.ToString();
- }
- private void Remove_Click(object sender, RoutedEventArgs e)
- {
- DataAccess.RemoveRow(activeRow);
- Output.ItemsSource = DataAccess.GetData();
- }
- }
- public sealed partial class MainPage : Page
- {
- public MainPage()
- {
- this.InitializeComponent();
- Output.ItemsSource = DataAccess.GetData();
- }
- private void AddData(object sender, RoutedEventArgs e)
- {
- DataAccess.AddData(Input_Box.Text);
- Output.ItemsSource = DataAccess.GetData();
- }
- private String activeRow = "";
- private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
- {
- ListView listView = (ListView)sender;
- allContactsMenuFlyout.ShowAt(listView, e.GetPosition(listView));
- var a = ((FrameworkElement)e.OriginalSource).DataContext;
- activeRow = a.ToString();
- }
- private void Remove_Click(object sender, RoutedEventArgs e)
- {
- // varmistetaan käyttäjältä että hän varmasti haluaa poistaa rivin
- DisplayDeleteRowDialog();
- }
- private async void DisplayDeleteRowDialog()
- {
- ContentDialog deleteFileDialog = new ContentDialog
- {
- Title = "Poistetaanko rivi?",
- Content = "Poistettua riviä ei voi enää palauttaa.",
- PrimaryButtonText = "Kyllä",
- CloseButtonText = "Ei"
- };
- ContentDialogResult result = await deleteFileDialog.ShowAsync();
- // Delete the file if the user clicked the primary button.
- /// Otherwise, do nothing.
- if (result == ContentDialogResult.Primary)
- {
- // Delete the file.
- DataAccess.RemoveRow(activeRow);
- Output.ItemsSource = DataAccess.GetData();
- }
- else
- {
- // The user clicked the CLoseButton, pressed ESC, Gamepad B, or the system back button.
- // Do nothing.
- }
- }
- }
- public sealed partial class MainPage : Page
- {
- public MainPage()
- {
- this.InitializeComponent();
- Output.ItemsSource = DataAccess.GetData();
- }
- private void AddData(object sender, RoutedEventArgs e)
- {
- DataAccess.AddData(Input_Box.Text);
- Output.ItemsSource = DataAccess.GetData();
- }
- private String activeRow = "";
- private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
- {
- ListView listView = (ListView)sender;
- allContactsMenuFlyout.ShowAt(listView, e.GetPosition(listView));
- var a = ((FrameworkElement)e.OriginalSource).DataContext;
- activeRow = a.ToString();
- }
- private void Remove_Click(object sender, RoutedEventArgs e)
- {
- // varmistetaan käyttäjältä että hän varmasti haluaa poistaa rivin
- DisplayDeleteRowDialog();
- }
- private async void DisplayDeleteRowDialog()
- {
- // ladataan kielikäännös resurssitiedostosta
- // tässä tapauksessa projektissa Strings-kansio, jossa en-US ja fi-kansiot. molemmissa Resources.resw
- var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
- ContentDialog deleteFileDialog = new ContentDialog
- {
- // Resourcesissa on DeleteTitle.Text => käytetään / -merkkiä pisteen sijasta
- Title = resourceLoader.GetString("DeleteTitle/Text"),
- Content = "Poistettua riviä ei voi enää palauttaa.",
- PrimaryButtonText = "Kyllä",
- CloseButtonText = "Ei"
- };
- ContentDialogResult result = await deleteFileDialog.ShowAsync();
- // Delete the file if the user clicked the primary button.
- /// Otherwise, do nothing.
- if (result == ContentDialogResult.Primary)
- {
- // Delete the file.
- DataAccess.RemoveRow(activeRow);
- Output.ItemsSource = DataAccess.GetData();
- }
- else
- {
- // The user clicked the CLoseButton, pressed ESC, Gamepad B, or the system back button.
- // Do nothing.
- }
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- // vaihdetaan kieleksi joko suomi tai englanti, riippuu
- // kumpi on vaktiivinen
- if (ApplicationLanguages.PrimaryLanguageOverride == "fi")
- {
- ApplicationLanguages.PrimaryLanguageOverride = "en-US";
- }
- else
- {
- ApplicationLanguages.PrimaryLanguageOverride = "fi";
- }
- // navigoidaan sivulle uudestaan jotta vaihdettu kieli näkyy
- Frame.Navigate(this.GetType());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment