Advertisement
tuomasvaltanen

Untitled

Apr 13th, 2021 (edited)
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.63 KB | None | 0 0
  1. XAML:
  2.  
  3. <StackPanel Margin="20">
  4. <TextBlock Margin="10" FontSize="32" FontWeight="Bold" Name="ResultText">TESTI</TextBlock>
  5. <Button Margin="10" Click="Button_Click">Lataa videot</Button>
  6. <Button Margin="10">TESTINAPPI</Button>
  7. </StackPanel>
  8.  
  9. <ListView.Resources>
  10. <MenuFlyout x:Name="allContactsMenuFlyout">
  11. <MenuFlyout.Items>
  12. <MenuFlyoutItem x:Name="Edit" Text="Edit" />
  13. <MenuFlyoutItem x:Name="Remove" Text="Remove" Click="Remove_Click" />
  14. </MenuFlyout.Items>
  15. </MenuFlyout>
  16. </ListView.Resources>
  17.  
  18. C#:
  19. // ilman threadaamista tulee ongelma käyttöliittymän kanssa
  20. private void Button_Click(object sender, RoutedEventArgs e)
  21. {
  22. DownloadVideoAsync();
  23. }
  24.  
  25. public async System.Threading.Tasks.Task DownloadVideoAsync()
  26. {
  27. // testivideot otettu täältä: https://gist.github.com/jsturgis/3b19447b304616f18657
  28. List<String> videos = new List<String>();
  29. videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4");
  30. videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4");
  31.  
  32. // haetaan sovelluksen tallenuspaikka, ja luodaan uusi kansio videoille
  33. Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
  34. StorageFolder newFolder = await storageFolder.CreateFolderAsync("myvideos", CreationCollisionOption.ReplaceExisting);
  35.  
  36. // tulostetaan konsoliin testaamista varten kansion polku
  37. Debug.WriteLine(storageFolder.Path.ToString());
  38.  
  39. ResultText.Text = "Aloitetaan lataus.";
  40.  
  41. // ensimmäinen tiedosto alkaa numerosta 1
  42. int fileNumber = 1;
  43.  
  44. // luodaan web client
  45. var client = new WebClient();
  46.  
  47. // ladataan yksitellen videot
  48. foreach (String video in videos)
  49. {
  50. ResultText.Text = "Ladataan videota " + fileNumber;
  51.  
  52. Debug.WriteLine("Downloading video " + fileNumber);
  53.  
  54. // jos käytössä BackgroundWorker, tämä pitää olla päällä
  55. //workerThread.ReportProgress(fileNumber);
  56.  
  57. // lataa tiedosto ja tallenna se tallennustilaan
  58. client.DownloadFile(new Uri(video), storageFolder.Path.ToString() + @"\myvideos\video" + fileNumber + ".mp4");
  59. Debug.WriteLine(storageFolder.Path.ToString() + @"\myvideos\video" + fileNumber + ".mp4");
  60.  
  61. // kasvata numeroa seuraavaa tiedostoa varten
  62. fileNumber += 1;
  63.  
  64. }
  65.  
  66. ResultText.Text = "Kaikki videot on ladattu.";
  67. }
  68.  
  69. // säikeistäminen BackgroundWorkerilla (vanhentunut, valitettavasti
  70. public async System.Threading.Tasks.Task BigWorkBackground()
  71. {
  72. // luodaan worker
  73. BackgroundWorker workerThread = new BackgroundWorker();
  74.  
  75. // tässä tapauksessa emme mahdollista säikeen peruuttamista
  76. workerThread.WorkerSupportsCancellation = false;
  77.  
  78. // haluamme kuitenkin antaa välitietoja miten työ etenee
  79. workerThread.WorkerReportsProgress = true;
  80.  
  81. // tässä määritetään koodi mikä ajetaan taustasäikeessä
  82. workerThread.DoWork += delegate (object s, DoWorkEventArgs args)
  83. {
  84.  
  85. // simuloidaan hidasta koodia Thread.Sleepin avulla
  86. Debug.WriteLine("Vaihe 1");
  87. workerThread.ReportProgress(1);
  88. System.Threading.Thread.Sleep(4000);
  89. Debug.WriteLine("Vaihe 2");
  90. workerThread.ReportProgress(2);
  91. System.Threading.Thread.Sleep(4000);
  92. Debug.WriteLine("Vaihe 3");
  93. workerThread.ReportProgress(3);
  94. System.Threading.Thread.Sleep(4000);
  95.  
  96.  
  97. };
  98.  
  99. // päivitetään tieto myös käyttöliittymään (XAML)
  100. workerThread.ProgressChanged += delegate (object s, ProgressChangedEventArgs e)
  101. {
  102. ResultText.Text = "Vaihe " + e.ProgressPercentage;
  103. };
  104.  
  105. // kun DoWork on suoritettu loppuun
  106. workerThread.RunWorkerCompleted += delegate (object s, RunWorkerCompletedEventArgs args)
  107. {
  108. ResultText.Text = "Kaikki työt suoritettu!";
  109. };
  110.  
  111. // käynnistä säie!
  112. workerThread.RunWorkerAsync();
  113.  
  114. }
  115.  
  116. public async Task TaskWorkBackground()
  117. {
  118. Debug.WriteLine("Aloitetaan työ");
  119. // jos haluamme Taskin sisällä päästä käsiksi UI Threadiin, eli käyttöliittymään, tarvitsemme Dispatcheria:
  120. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
  121. ResultText.Text = "Aloitetaan työ.";
  122. });
  123.  
  124. // simuloidaan kolme vaihetta, await-versio Thread.Sleepistä
  125. await Task.Delay(4000);
  126. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
  127. ResultText.Text = "Vaihe 1";
  128. });
  129.  
  130. await Task.Delay(2000);
  131. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
  132. ResultText.Text = "Vaihe 2";
  133. });
  134. await Task.Delay(5000);
  135.  
  136. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
  137. ResultText.Text = "Vaihe 3";
  138. });
  139.  
  140. await Task.Delay(1000);
  141.  
  142. Debug.WriteLine("Kaikki työ tehty.");
  143. // jos haluamme Taskin sisällä päästä käsiksi UI Threadiin, eli käyttöliittymään, tarvitsemme Dispatcheria:
  144. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
  145. ResultText.Text = "Kaikki työ tehty!";
  146. });
  147.  
  148. }
  149.  
  150. // event handlerissa, esim:
  151. var t = Task.Run(() => TaskWorkBackground());
  152.  
  153. // suositeltavin tapa tiedon lataamisessa (tiedostosta toiseen, internetistä tiedostoon jne, input/output)
  154.  
  155. private void Button_Click(object sender, RoutedEventArgs e)
  156. {
  157. // käynnistäminen esim. event handlerissa:
  158. //var t = Task.Run(() => TaskWorkBackground());
  159.  
  160. // alaviiva tarkoittaa "discardia" C#:ssa, eli tämä metodikutsu laitetaan pois muistista kun se on valmis
  161. _ = LaunchDownloadAsync();
  162. }
  163.  
  164. public async Task LaunchDownloadAsync()
  165. {
  166. await AwaitBackgroundWork();
  167. }
  168.  
  169. private async Task AwaitBackgroundWork()
  170. {
  171. Debug.WriteLine("Vaihe 1");
  172. ResultText.Text = "Vaihe 1...";
  173.  
  174. await Task.Delay(3000);
  175. Debug.WriteLine("Vaihe 2");
  176. ResultText.Text = "Vaihe 2...";
  177. await Task.Delay(3000);
  178. Debug.WriteLine("Vaihe 3");
  179. ResultText.Text = "Vaihe 3...";
  180. await Task.Delay(3000);
  181.  
  182. ResultText.Text = "Kaikki työ tehty!";
  183. }
  184.  
  185.  
  186. // tiedoston lataaminen netistä, await/async versio
  187.  
  188. public async Task LaunchDownloadAsync()
  189. {
  190. await DownloadVideosAsync();
  191. }
  192.  
  193. private async Task DownloadVideosAsync()
  194. {
  195. // haetaan ohjelman tallennuskansio Windowsista
  196. Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
  197.  
  198. // luodaan apukansio "myvideos"
  199. // korvataan vanha kansio, jos se löytyy entuudestaan
  200. StorageFolder newFolder = await storageFolder.CreateFolderAsync("myvideos", CreationCollisionOption.ReplaceExisting);
  201.  
  202. // tulostetaan testimielessä kansion sijainti konsoliin
  203. Debug.WriteLine(storageFolder.Path.ToString());
  204.  
  205. // lisätään pari testivideota ladattavaksi listaan
  206. List<string> videos = new List<string>();
  207. videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4");
  208. videos.Add("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4");
  209.  
  210. // pidetään muuttujassa yllä seuraavaksi tallennettavan videon numero
  211. int fileNumber = 1;
  212.  
  213. // luodaan http-client, jolla voimme ladata internetistä dataa
  214. // joudumme awaitin vuoksi käyttämään tätä, sillä WebClient ei toimi awaitin kanssa
  215. // tämä johtuu siitä, että WebClient on itse toteuttanut säikeistämisen eri tavalla
  216. HttpClient httpc = new HttpClient();
  217.  
  218. // käydään videot silmukassa läpi
  219. foreach (String video in videos)
  220. {
  221. // päivitetään tilanneviestit
  222. Debug.WriteLine("Start download: " + video);
  223. ResultText.Text = "Ladataan videota " + fileNumber;
  224.  
  225. // ladataan videon sisältö tavutaulukkoon
  226. byte[] stringData = await httpc.GetByteArrayAsync(video);
  227.  
  228. // tehdään uudelle videolle uusi tiedosto apukansioon (myvideos)
  229. Windows.Storage.StorageFile file = await storageFolder.CreateFileAsync(@"\myvideos\video" + fileNumber + ".mp4",
  230. Windows.Storage.CreationCollisionOption.ReplaceExisting);
  231.  
  232. // kirjoitetaan videon sisältö uuteen tiedostoon
  233. await Windows.Storage.FileIO.WriteBytesAsync(file, stringData);
  234.  
  235. // kasvatetaan numeroa seuraavaa tiedostoa varten
  236. fileNumber += 1;
  237. Debug.WriteLine("Download finished.");
  238. }
  239.  
  240. ResultText.Text = "Kaikki videot on ladattu!";
  241. }
  242.  
  243.  
  244. // kielen vaihtaminen lennosta ohjelmassa
  245. private void Button_Click_1(object sender, RoutedEventArgs e)
  246. {
  247. // vaihdetaan kieli, ja ladataan Page uudestaan
  248. ApplicationLanguages.PrimaryLanguageOverride = "en-US";
  249. this.Frame.Navigate(typeof(MainPage));
  250. }
  251.  
  252. // DATA ACCESS LUOKKA SQLITEÄ VARTEN
  253. // muista asentaa NuGetillä Microsoft.Data.Sqlite -kirjasto
  254.  
  255. public static class DataAccess
  256. {
  257. // luodaan SQLite tietokanta tarvittaessa, jos sitä ei ole olemassa entuudestaan
  258. public async static void InitializeDatabase()
  259. {
  260. await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db", CreationCollisionOption.OpenIfExists);
  261. string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
  262. using (SqliteConnection db =
  263. new SqliteConnection($"Filename={dbpath}"))
  264. {
  265. db.Open();
  266.  
  267. String tableCommand = "CREATE TABLE IF NOT " +
  268. "EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +
  269. "Text_Entry NVARCHAR(2048) NULL)";
  270.  
  271. SqliteCommand createTable = new SqliteCommand(tableCommand, db);
  272.  
  273. createTable.ExecuteReader();
  274. }
  275. }
  276.  
  277. public static void AddData(string inputText)
  278. {
  279. string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
  280. using (SqliteConnection db =
  281. new SqliteConnection($"Filename={dbpath}"))
  282. {
  283. db.Open();
  284.  
  285. SqliteCommand insertCommand = new SqliteCommand();
  286. insertCommand.Connection = db;
  287.  
  288. // Use parameterized query to prevent SQL injection attacks
  289. insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Entry);";
  290. insertCommand.Parameters.AddWithValue("@Entry", inputText);
  291.  
  292. insertCommand.ExecuteReader();
  293.  
  294. db.Close();
  295. }
  296.  
  297. }
  298.  
  299. public static List<String> GetData()
  300. {
  301. List<String> entries = new List<string>();
  302.  
  303. string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
  304. using (SqliteConnection db =
  305. new SqliteConnection($"Filename={dbpath}"))
  306. {
  307. db.Open();
  308.  
  309. SqliteCommand selectCommand = new SqliteCommand
  310. ("SELECT Text_Entry from MyTable", db);
  311.  
  312. SqliteDataReader query = selectCommand.ExecuteReader();
  313.  
  314. while (query.Read())
  315. {
  316. entries.Add(query.GetString(0));
  317. }
  318.  
  319. db.Close();
  320. }
  321.  
  322. return entries;
  323. }
  324.  
  325.  
  326. }
  327.  
  328. // esim. SecondPage.xaml.cs:
  329.  
  330. public SecondPage()
  331. {
  332. this.InitializeComponent();
  333. // haetaan uusimmat tiedot tietokannasta
  334. Output.ItemsSource = DataAccess.GetData();
  335.  
  336. // jos tavallinen luokka, metodia kutsutaan olion kautta:
  337. //DataAccess da = new DataAccess();
  338. //da.ReadData();
  339.  
  340. // jos staattinen luokka, oliota ei ole, ja kutsutaan suoraan luokan kautta
  341. //DataAccess.ReadData();
  342. }
  343.  
  344.  
  345. private void AddData(object sender, RoutedEventArgs e)
  346. {
  347. // lisätään uusi rivi tietokantaan ja haetaan tiedot uusiksi käyttöliittymään
  348. DataAccess.AddData(Input_Box.Text);
  349.  
  350. Output.ItemsSource = DataAccess.GetData();
  351. }
  352.  
  353.  
  354. // muista myös muuttaa App.xaml.cs -luokkaa:
  355.  
  356. public App()
  357. {
  358. this.InitializeComponent();
  359. this.Suspending += OnSuspending;
  360. // alustetaan tietokantayhteys
  361. DataAccess.InitializeDatabase();
  362. }
  363.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement