Adiciona suporte a MVVM e integração com banco Access
- Atualizado `.gitignore` para ignorar `FodyWeavers.xsd` e `.history`. - Adicionado suporte a MVVM com `MainWindowViewModel` e comandos. - Criados conversores `BoolToVisibilityConverter` e `StringToVisibilityConverter`. - Implementado `AccessService` para acesso ao banco de dados Access. - Adicionado layout e lógica de interface no `MainWindow.xaml` e `.cs`. - Incluída dependência `System.Data.OleDb` no projeto. - Criados `ClienteSmart` e `IClienteRepository` para modelagem de dados.
This commit is contained in:
parent
f592470406
commit
22d308a397
4
.gitignore
vendored
4
.gitignore
vendored
@ -360,4 +360,6 @@ MigrationBackup/
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
FodyWeavers.xsd
|
||||
|
||||
.history
|
||||
5
App.xaml
5
App.xaml
@ -4,6 +4,9 @@
|
||||
xmlns:local="clr-namespace:BD_empresa"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
<ResourceDictionary>
|
||||
<local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
|
||||
<local:StringToVisibilityConverter x:Key="StringToVisibilityConverter" />
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
|
||||
@ -8,4 +8,11 @@
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Data.OleDb" Version="9.0.7" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="System.Data.OleDb" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
33
Converters.cs
Normal file
33
Converters.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace BD_empresa
|
||||
{
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool b && b)
|
||||
return Visibility.Visible;
|
||||
return Visibility.Collapsed;
|
||||
}
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return (value is Visibility v && v == Visibility.Visible);
|
||||
}
|
||||
}
|
||||
|
||||
public class StringToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value as string) ? Visibility.Collapsed : Visibility.Visible;
|
||||
}
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
85
Data/AccessService.cs
Normal file
85
Data/AccessService.cs
Normal file
@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.OleDb;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BD_empresa.Data
|
||||
{
|
||||
public class AccessService(string connectionString) : IClienteRepository
|
||||
{
|
||||
private readonly string _connectionString = connectionString;
|
||||
|
||||
public async Task<List<ClienteSmart>> SearchClientesAsync(string query)
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var clientes = new List<ClienteSmart>();
|
||||
using (var connection = new OleDbConnection(_connectionString))
|
||||
{
|
||||
connection.Open();
|
||||
string sql = @"SELECT Gestao, Cliente, Unidade, CNPJ_CPF, Codigo_Instalacao, Razao_Social FROM Dados_cadastrais WHERE CNPJ_CPF LIKE ? OR Codigo_Instalacao LIKE ? OR Razao_Social LIKE ? OR Cliente LIKE ?";
|
||||
using var cmd = new OleDbCommand(sql, connection);
|
||||
string likeQuery = $"%{query}%";
|
||||
cmd.Parameters.AddWithValue("?", likeQuery);
|
||||
cmd.Parameters.AddWithValue("?", likeQuery);
|
||||
cmd.Parameters.AddWithValue("?", likeQuery);
|
||||
cmd.Parameters.AddWithValue("?", likeQuery);
|
||||
using var reader = cmd.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
clientes.Add(new ClienteSmart
|
||||
{
|
||||
Gestao = reader["Gestao"].ToString(),
|
||||
Cliente = reader["Cliente"].ToString(),
|
||||
Unidade = reader["Unidade"].ToString(),
|
||||
CNPJ_CPF = reader["CNPJ_CPF"].ToString(),
|
||||
Codigo_Instalacao = reader["Codigo_Instalacao"].ToString(),
|
||||
Razao_Social = reader["Razao_Social"].ToString()
|
||||
});
|
||||
}
|
||||
}
|
||||
// Unifica clientes por CNPJ, retorna no máximo 3
|
||||
return clientes
|
||||
.GroupBy(c => c.CNPJ_CPF)
|
||||
.Select(g => g.First())
|
||||
.Take(3)
|
||||
.ToList();
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<List<ClienteSmart>> GetAllClientesAsync()
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var clientes = new List<ClienteSmart>();
|
||||
using (var connection = new OleDbConnection(_connectionString))
|
||||
{
|
||||
connection.Open();
|
||||
string sql = "SELECT Gestao, Cliente, Unidade, CNPJ_CPF, Codigo_Instalacao, Razao_Social FROM Dados_cadastrais";
|
||||
using var cmd = new OleDbCommand(sql, connection);
|
||||
using var reader = cmd.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
clientes.Add(new ClienteSmart
|
||||
{
|
||||
Gestao = reader["Gestao"].ToString(),
|
||||
Cliente = reader["Cliente"].ToString(),
|
||||
Unidade = reader["Unidade"].ToString(),
|
||||
CNPJ_CPF = reader["CNPJ_CPF"].ToString(),
|
||||
Codigo_Instalacao = reader["Codigo_Instalacao"].ToString(),
|
||||
Razao_Social = reader["Razao_Social"].ToString()
|
||||
});
|
||||
}
|
||||
}
|
||||
// Unifica clientes por CNPJ
|
||||
return clientes
|
||||
.GroupBy(c => c.CNPJ_CPF)
|
||||
.Select(g => g.First())
|
||||
.Take(3)
|
||||
.ToList();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
20
Data/ClienteSmart.cs
Normal file
20
Data/ClienteSmart.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace BD_empresa.Data
|
||||
{
|
||||
public class ClienteSmart : INotifyPropertyChanged
|
||||
{
|
||||
public string? Gestao { get; set; }
|
||||
public string? Cliente { get; set; }
|
||||
public string? Unidade { get; set; }
|
||||
public string? CNPJ_CPF { get; set; }
|
||||
public string? Codigo_Instalacao { get; set; }
|
||||
public string? Razao_Social { get; set; }
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
protected void OnPropertyChanged(string propertyName)
|
||||
{
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Data/IClienteRepository.cs
Normal file
11
Data/IClienteRepository.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BD_empresa.Data
|
||||
{
|
||||
public interface IClienteRepository
|
||||
{
|
||||
Task<List<ClienteSmart>> SearchClientesAsync(string query);
|
||||
Task<List<ClienteSmart>> GetAllClientesAsync();
|
||||
}
|
||||
}
|
||||
@ -8,5 +8,40 @@
|
||||
Title="MainWindow" Height="450" Width="800">
|
||||
<Grid>
|
||||
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<StackPanel Orientation="Horizontal" Margin="10" Grid.Row="0">
|
||||
<TextBox Width="400"
|
||||
Margin="0,0,10,0"
|
||||
VerticalAlignment="Center"
|
||||
Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<Button Content="Refresh"
|
||||
Command="{Binding RefreshCommand}"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding ErrorMessage}"
|
||||
Foreground="Red"
|
||||
Margin="10,5,10,0"
|
||||
Grid.Row="1"
|
||||
Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}" />
|
||||
<Grid Grid.Row="2">
|
||||
<ListView ItemsSource="{Binding Clientes}" Margin="10">
|
||||
<ListView.View>
|
||||
<GridView>
|
||||
<GridViewColumn Header="CNPJ" DisplayMemberBinding="{Binding CNPJ_CPF}" Width="120" />
|
||||
<GridViewColumn Header="Unidade" DisplayMemberBinding="{Binding Codigo_Instalacao}" Width="120" />
|
||||
<GridViewColumn Header="Razão Social" DisplayMemberBinding="{Binding Razao_Social}" Width="200" />
|
||||
<GridViewColumn Header="Nome" DisplayMemberBinding="{Binding Cliente}" Width="200" />
|
||||
</GridView>
|
||||
</ListView.View>
|
||||
</ListView>
|
||||
<Grid Visibility="{Binding IsLoading, Converter={StaticResource BoolToVisibilityConverter}}"
|
||||
Background="#80FFFFFF">
|
||||
<ProgressBar IsIndeterminate="True" Height="30" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
@ -19,6 +19,10 @@ namespace BD_empresa
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
// Caminho do banco de dados Access
|
||||
string accessDbPath = "X:\\Middle\\Informativo Setorial\\Modelo Word\\BD1_dados cadastrais e faturas.accdb";
|
||||
var accessService = new Data.AccessService($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={accessDbPath};Jet OLEDB:Database Password=gds21");
|
||||
DataContext = new ViewModels.MainWindowViewModel(accessService);
|
||||
}
|
||||
}
|
||||
}
|
||||
122
ViewModels/MainWindowViewModel.cs
Normal file
122
ViewModels/MainWindowViewModel.cs
Normal file
@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using BD_empresa.Data;
|
||||
|
||||
namespace BD_empresa.ViewModels
|
||||
{
|
||||
public class MainWindowViewModel : INotifyPropertyChanged
|
||||
{
|
||||
private readonly IClienteRepository _clienteRepository;
|
||||
private string? _searchText;
|
||||
private bool _isLoading;
|
||||
private string? _errorMessage;
|
||||
|
||||
public ObservableCollection<ClienteSmart> Clientes { get; } = [];
|
||||
|
||||
public string? SearchText
|
||||
{
|
||||
get => _searchText;
|
||||
set
|
||||
{
|
||||
if (_searchText != value)
|
||||
{
|
||||
_searchText = value;
|
||||
OnPropertyChanged();
|
||||
_ = SearchAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLoading
|
||||
{
|
||||
get => _isLoading;
|
||||
set { _isLoading = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public string? ErrorMessage
|
||||
{
|
||||
get => _errorMessage;
|
||||
set { _errorMessage = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public ICommand RefreshCommand { get; }
|
||||
|
||||
public MainWindowViewModel(IClienteRepository clienteRepository)
|
||||
{
|
||||
_clienteRepository = clienteRepository;
|
||||
RefreshCommand = new RelayCommand(async _ => await RefreshAsync());
|
||||
_ = RefreshAsync();
|
||||
}
|
||||
|
||||
public async Task SearchAsync()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(SearchText))
|
||||
{
|
||||
await RefreshAsync();
|
||||
return;
|
||||
}
|
||||
IsLoading = true;
|
||||
ErrorMessage = null;
|
||||
try
|
||||
{
|
||||
var results = await _clienteRepository.SearchClientesAsync(SearchText);
|
||||
Clientes.Clear();
|
||||
foreach (var cliente in results)
|
||||
Clientes.Add(cliente);
|
||||
if (Clientes.Count == 0)
|
||||
ErrorMessage = "Nenhum resultado encontrado.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorMessage = $"Erro: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RefreshAsync()
|
||||
{
|
||||
IsLoading = true;
|
||||
ErrorMessage = null;
|
||||
try
|
||||
{
|
||||
var results = await _clienteRepository.GetAllClientesAsync();
|
||||
Clientes.Clear();
|
||||
foreach (var cliente in results)
|
||||
Clientes.Add(cliente);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorMessage = $"Erro: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
|
||||
{
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
}
|
||||
|
||||
// RelayCommand para ICommand
|
||||
public class RelayCommand(Func<object?, Task> execute, Predicate<object?>? canExecute = null) : ICommand
|
||||
{
|
||||
private readonly Func<object?, Task> _execute = execute;
|
||||
private readonly Predicate<object?>? _canExecute = canExecute;
|
||||
|
||||
public bool CanExecute(object? parameter) => _canExecute?.Invoke(parameter) ?? true;
|
||||
public async void Execute(object? parameter) => await _execute(parameter);
|
||||
public event EventHandler? CanExecuteChanged;
|
||||
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user