COMO CRIAR UM APP UNIVERSAL WINDOWS PLATFORM COM SQLITE Professor William Yamamoto www.williamyamamoto.com.br 1) Instalar https://marketplace.visualstudio.com/items?itemname=sqlitedevelopmentteam.sqliteforuniversalwindowsplatf orm 2) Instalar http://sqlitebrowser.org/ 3) Criar novo Projeto aulauwpsqlite no Menu - File - New Project e clicar no botão [OK] 1
4) Selecionar a versão do Windows 10 SDK e clicar no botão [OK] 2
5) Selecionar no Menu Tools - Nuget Package Manager Package Manager Console 3
6) No Package Manager Console executar o seguinte comando Update-Package Microsoft.NETCore.UniversalWindowsPlatform 7) No Package Manager Console executar o seguinte comando Install-Package sqlite 4
8) No Package Manager Console executar o seguinte comando Install-Package SQLite.Net-PCL 9) Criar as Pastas Model, View e ViewModel clicando com o botão direito do mouse no Projeto aulauwpsqlite 5
10) Alterar a classe App.xaml.cs using SQLite.Net; using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace aulauwpsqlite sealed partial class App : Application public static string DB_PATH = Path.Combine(Path.Combine (ApplicationData.Current.LocalFolder.Path, "PessoaManager.sqlite")); public App() this.initializecomponent(); this.suspending += OnSuspending; if (!CheckFileExists("PessoaManager.sqlite").Result) using (var db = new SQLiteConnection (new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH)) db.createtable<pessoa>(); Debug.WriteLine(DB_PATH); private async Task<bool> CheckFileExists(string filename) try var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync (filename); return true; catch return false; protected override void OnLaunched(LaunchActivatedEventArgs e) #if DEBUG if (System.Diagnostics.Debugger.IsAttached) this.debugsettings.enableframeratecounter = true; #endif Frame rootframe = Window.Current.Content as Frame; if (rootframe == null) rootframe = new Frame(); rootframe.navigationfailed += OnNavigationFailed; 6
if (e.previousexecutionstate == ApplicationExecutionState.Terminated) Window.Current.Content = rootframe; if (e.prelaunchactivated == false) if (rootframe.content == null) rootframe.navigate(typeof(mainpage), e.arguments); Window.Current.Activate(); void OnNavigationFailed(object sender, NavigationFailedEventArgs e) throw new Exception("Failed to load Page " + e.sourcepagetype.fullname); private void OnSuspending(object sender, SuspendingEventArgs e) var deferral = e.suspendingoperation.getdeferral(); deferral.complete(); 11) No Solution Explorer, criar a classe Pessoa.cs clicando com o botão direito do mouse sobre a pasta Model - Add - Class 7
12) Escrever o nome do arquivo Pessoa.cs e clicar no botão [Add] 13) Escrever a classe Pessoa.cs using System; namespace aulauwpsqlite public class Pessoa [SQLite.Net.Attributes.PrimaryKey, SQLite.Net.Attributes.AutoIncrement] public int Id get; set; public string Nome get; set; public string Fone get; set; public string DataCriacao get; set; public Pessoa() //construtor public Pessoa(string nome, string fone) Nome = nome; Fone = fone; DataCriacao = DateTime.Now.ToString(); 8
14) No Solution Explorer, criar a classe DatabaseHelper.cs clicando com o botão direito do mouse sobre a pasta ViewModel - Add - Class 15) Escrever a classe DatabaseHelper.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace aulauwpsqlite class DatabaseHelper public void CreateDatabase(string DB_PATH) if (!CheckFileExists(DB_PATH).Result) using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection (new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH)) conn.createtable<pessoa>(); private async Task<bool> CheckFileExists(string filename) 9
try var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync (filename); return true; catch return false; public void Insert(Pessoa objpessoa) using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) conn.runintransaction(() => conn.insert(objpessoa); ); public Pessoa ReadPessoa(int PessoaId) using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) var existingpessoa = conn.query<pessoa>("select * from Pessoa where Id =" + PessoaId).FirstOrDefault(); return existingpessoa; public ObservableCollection<Pessoa> ReadAllPessoa() try using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) List<Pessoa> mycollection = conn.table<pessoa>().tolist<pessoa>(); ObservableCollection<Pessoa> PessoaList = new ObservableCollection<Pessoa>(myCollection); return PessoaList; catch return null; public void UpdateDetails(Pessoa ObjPessoa) using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) var existingpessoa = conn.query<pessoa> ("select * from Pessoa where Id =" + ObjPessoa.Id).FirstOrDefault(); if (existingpessoa!= null) conn.runintransaction(() => 10
); conn.update(objpessoa); public void DeleteAllPessoa() using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) conn.droptable<pessoa>(); conn.createtable<pessoa>(); conn.dispose(); conn.close(); public void DeletePessoa(int Id) using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) var existingpessoa = conn.query<pessoa> ("select * from Pessoa where Id =" + Id).FirstOrDefault(); if (existingpessoa!= null) conn.runintransaction(() => conn.delete(existingpessoa); ); 11
16) No Solution Explorer, criar a classe ReadAllPessoaList.cs clicando com o botão direito do mouse sobre a pasta ViewModel - Add Class 17) Escreva a classe ReadAllPessoaList.cs using System.Collections.ObjectModel; namespace aulauwpsqlite public class ReadAllPessoaList DatabaseHelper Db_Helper = new DatabaseHelper(); public ObservableCollection<Pessoa> GetAllPessoa() return Db_Helper.ReadAllPessoa(); 12
18) No Solution Explorer, criar a AddPage.xaml clicando com o botão direito do mouse sobre a pasta View - Add Blank Page e clicar no botão [Add] 19) Escrever o AddPage.xaml <Page x:class="aulauwpsqlite.addpessoa" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:aulauwpsqlite" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d"> <Grid x:name="layoutroot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Margin="12,17,0,28"> <TextBlock Text="Pessoa App - Adicionar" Margin="9,-7,0,0"/> </StackPanel> <Grid x:name="contentpanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <TextBox Name="NomeTextBox" Margin="10" Header="Nome"/> <TextBox InputScope="Digits" Name="FoneTextBox" Margin="10" MaxLength="10" Header="Fone" /> <Button x:name="adicionarpessoabutton" Content="Adicionar" Margin="10" HorizontalAlignment="Stretch" Click="AdicionarPessoaButton_Click"/> <Button x:name="cancelarbutton" Content="Cancelar" 13
Margin="10" HorizontalAlignment="Stretch" Click="CancelarButton_Click"/> </StackPanel> </Grid> </Grid> </Page> 20) Escrever o AddPage.xaml.cs using System; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace aulauwpsqlite public sealed partial class AddPessoa : Page public AddPessoa() this.initializecomponent(); private async void AdicionarPessoaButton_Click(object sender, RoutedEventArgs e) DatabaseHelper Db_Helper = new DatabaseHelper(); if (NomeTextBox.Text!= "" & FoneTextBox.Text!= "") Db_Helper.Insert(new Pessoa(NomeTextBox.Text, FoneTextBox.Text)); Frame.Navigate(typeof(MainPage)); else MessageDialog messagedialog = new MessageDialog ("Prencher os campos"); await messagedialog.showasync(); private void CancelarButton_Click(object sender, RoutedEventArgs e) Frame.Navigate(typeof(MainPage)); 14
21) No Solution Explorer, criar a DetailsPage.xaml clicando com o botão direito do mouse sobre a pasta View - Add Blank Page e clicar no botão [Add] 22) Escrever o DetailsPage.xaml <Page x:class="aulauwpsqlite.detailspage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:aulauwpsqlite" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d"> <Grid x:name="layoutroot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Margin="12,17,0,28"> <TextBlock Text="Pessoa App - Alterar / Excluir" Margin="9,-7,0,0"/> </StackPanel> <Grid x:name="contentpanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <TextBox Name="NomeTextBox" Margin="10" Header="Nome"/> <TextBox InputScope="Digits" Name="FoneTextBox" Margin="10" MaxLength="10" Header="Fone" /> <Button x:name="alterarpessoabutton" Content="Alterar" Margin="10" HorizontalAlignment="Stretch" Click="AlterarPessoaButton_Click"/> <Button x:name="excluirpessoabutton" Content="Excluir" 15
Margin="10" HorizontalAlignment="Stretch" Click="ExcluirPessoaButton_Click"/> <Button x:name="cancelarbutton" Content="Cancelar" Margin="10" HorizontalAlignment="Stretch" Click="CancelarButton_Click"/> </StackPanel> </Grid> </Grid> </Page> 23) Escrever a DetailsPage.xaml.cs using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace aulauwpsqlite public sealed partial class DetailsPage : Page DatabaseHelper Db_Helper = new DatabaseHelper(); Pessoa currentpessoa = new Pessoa(); public DetailsPage() this.initializecomponent(); protected override void OnNavigatedTo(NavigationEventArgs e) currentpessoa = e.parameter as Pessoa; NomeTextBox.Text = currentpessoa.nome; FoneTextBox.Text = currentpessoa.fone; private void AlterarPessoaButton_Click(object sender, RoutedEventArgs e) currentpessoa.nome = NomeTextBox.Text; currentpessoa.fone = FoneTextBox.Text; Db_Helper.UpdateDetails(currentPessoa); Frame.Navigate(typeof(MainPage)); private void ExcluirPessoaButton_Click(object sender, RoutedEventArgs e) Db_Helper.DeletePessoa(currentPessoa.Id); Frame.Navigate(typeof(MainPage)); private void CancelarButton_Click(object sender, RoutedEventArgs e) Frame.Navigate(typeof(MainPage)); 16
24) No Solution Explorer, criar a MainPage.xaml clicando com o botão direito do mouse sobre a pasta View - Add Blank Page e clicar no botão [Add] 25) Escrever o MainPage.xaml <Page x:class="aulauwpsqlite.mainpage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:aulauwpsqlite" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d"> <Grid x:name="layoutroot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Margin="12,17,0,28"> <TextBlock Text="Pessoas App" TextWrapping="Wrap" Margin="9,-7,0,0" FontSize="28"/> </StackPanel> <Grid x:name="contentpanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid Grid.Row="0"> <Grid.ColumnDefinitions> 17
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Button x:name="adicionarpessoabutton" Grid.Column="0" Content="Adicionar" Margin="5" HorizontalAlignment="Stretch" Click="AdicionarPessoaButton_Click"/> <Button x:name="excluirpessoasbutton" Grid.Column="1" IsEnabled="False" Content="Excluir Todos" Margin="5" HorizontalAlignment="Stretch" Click="ExcluirPessoasButton_Click"/> </Grid> <ListView BorderBrush="#FF141EE4" Grid.Row="1" x:name="listboxobj" SelectionChanged="listBoxobj_SelectionChanged"> <ListView.ItemTemplate> <DataTemplate> <Grid> <Border Margin="5" BorderBrush="White" BorderThickness="1"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBlock Margin="5,0,0,0" Grid.Row="0" x:name="nometextblock" TextWrapping="Wrap" Text="Binding Nome" FontSize="28" Foreground="White"/> <TextBlock Grid.Row="0" Text=">" FontSize="28" HorizontalAlignment="Right" VerticalAlignment="Center" Foreground="White"/> <TextBlock Margin="5,0,0,0" Grid.Row="1" x:name="fonetextblock" TextWrapping="Wrap" Foreground="White" FontSize="18" Text="Binding Fone" /> </Grid> </Border> </Grid> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </ListView.ItemContainerStyle> </ListView> </Grid> </Grid> </Page> 26) Escrever a MainPage.xaml.cs using System.Collections.ObjectModel; using System.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace aulauwpsqlite public sealed partial class MainPage : Page ObservableCollection<Pessoa> DB_PessoaList = new ObservableCollection<Pessoa>(); public MainPage() this.initializecomponent(); this.loaded += ReadPessoaList_Loaded; private void ReadPessoaList_Loaded(object sender, RoutedEventArgs e) ReadAllPessoaList dbpessoas = new ReadAllPessoaList(); DB_PessoaList = dbpessoas.getallpessoa();//get all DB Pessoas if (DB_PessoaList.Count > 0) ExcluirPessoasButton.IsEnabled = true; 18
listboxobj.itemssource = DB_PessoaList.OrderByDescending(i => i.id).tolist();//binding DB data to LISTBOX and Latest Pessoa ID can Display first. private void listboxobj_selectionchanged(object sender, SelectionChangedEventArgs e) if (listboxobj.selectedindex!= -1) Pessoa listitem = listboxobj.selecteditem as Pessoa;//Get slected listbox item Pessoa ID Frame.Navigate(typeof(DetailsPage), listitem); private void AdicionarPessoaButton_Click(object sender, RoutedEventArgs e) Frame.Navigate(typeof(AddPessoa)); private void ExcluirPessoasButton_Click(object sender, RoutedEventArgs e) DatabaseHelper delete = new DatabaseHelper(); delete.deleteallpessoa();//delete all DB Pessoas DB_PessoaList.Clear();//Clear collections ExcluirPessoasButton.IsEnabled = false; listboxobj.itemssource = DB_PessoaList; 27) No menu Build selecionar a opção Build Solution 19
28) No menu Build selecionar a opção Deploy Solution 20
29) No menu Debug selecionar a opção Start Debugging 30) No DB Browser for SQLite abra o arquivo PessoaManager.sqlite criado pelo App 21
31) Na Aba Navegar Dados verificar se os dados digitados no App foram gravados no SQLite 22