Add project files.

This commit is contained in:
Miguel 2024-06-15 11:24:07 +02:00
parent 9fe7defff6
commit f61d8b7883
7 changed files with 250 additions and 0 deletions

9
App.xaml Normal file
View File

@ -0,0 +1,9 @@
<Application x:Class="EscribePassword.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:EscribePassword"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

14
App.xaml.cs Normal file
View File

@ -0,0 +1,14 @@
using System.Configuration;
using System.Data;
using System.Windows;
namespace EscribePassword
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

10
AssemblyInfo.cs Normal file
View File

@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

17
EscribePassword.csproj Normal file
View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.6.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>

25
EscribePassword.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.34928.147
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EscribePassword", "EscribePassword.csproj", "{10D3496B-A382-49CD-833F-54C23578CA5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{10D3496B-A382-49CD-833F-54C23578CA5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{10D3496B-A382-49CD-833F-54C23578CA5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{10D3496B-A382-49CD-833F-54C23578CA5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{10D3496B-A382-49CD-833F-54C23578CA5C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A613A9CA-493C-4F35-B086-15CE07262CE0}
EndGlobalSection
EndGlobal

39
MainWindow.xaml Normal file
View File

@ -0,0 +1,39 @@
<Window x:Class="EscribePassword.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:EscribePassword" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MView />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DataGrid Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Passwords}"
SelectedItem="{Binding SelectedPassword}" AutoGenerateColumns="False" CanUserAddRows="False"
CanUserDeleteRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Usuario" Binding="{Binding Usuario}" Width="*" />
<DataGridTextColumn Header="Contraseña" Binding="{Binding Password}" Width="*" />
<DataGridTemplateColumn Header="Acciones" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Eliminar"
Command="{Binding DataContext.EliminarCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<StackPanel Grid.Row="1" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Center">
<Button Content="Agregar" Command="{Binding AgregarCommand}" Margin="5" />
</StackPanel>
</Grid>
</Window>

136
MainWindow.xaml.cs Normal file
View File

@ -0,0 +1,136 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.Json;
using System.IO;
using System.Windows;
namespace EscribePassword
{
public partial class MView : ObservableObject
{
[ObservableProperty]
private ObservableCollection<Passwords> passwords;
[ObservableProperty]
private Passwords selectedPassword;
public RelayCommand AgregarCommand { get; }
public RelayCommand<Passwords> EliminarCommand { get; }
public MView()
{
// Suscribirse al evento de cierre de la aplicación
Application.Current.Exit += OnApplicationExit;
passwords = new ObservableCollection<Passwords>(EstadoPersistente.Instance.Passwords);
AgregarCommand = new RelayCommand(Agregar);
EliminarCommand = new RelayCommand<Passwords>(Eliminar);
}
private void OnApplicationExit(object sender, ExitEventArgs e)
{
EstadoPersistente.Instance.Passwords = new List<Passwords>(passwords);
EstadoPersistente.Instance.GuardarEstado();
}
private void Agregar()
{
Passwords newPassword = new Passwords { Usuario = "NuevoUsuario", Password = "NuevaContraseña" };
passwords.Add(newPassword);
SelectedPassword = newPassword;
}
private void Eliminar(Passwords password)
{
if (password != null)
{
passwords.Remove(password);
SelectedPassword = null;
}
}
}
public class EstadoPersistente
{
// Ruta donde se guardará el estado
private static readonly string _filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "estado.json");
// Instancia privada estática, parte del patrón Singleton
private static EstadoPersistente _instance;
private List<Passwords> passwords;
public List<Passwords> Passwords
{
get
{
if (passwords == null) passwords = new List<Passwords>();
return passwords;
}
set
{
passwords = value;
}
}
// Constructor público sin parámetros requerido para la deserialización
public EstadoPersistente()
{
passwords = new List<Passwords>();
}
// Propiedad pública estática para acceder a la instancia
public static EstadoPersistente Instance
{
get
{
if (_instance == null)
{
_instance = CargarEstado();
}
return _instance;
}
}
// Método para guardar el estado en un archivo JSON
public void GuardarEstado()
{
var options = new JsonSerializerOptions
{
WriteIndented = true // para una salida JSON formateada legiblemente
};
string json = JsonSerializer.Serialize(this, options);
File.WriteAllText(_filePath, json);
}
// Método estático para cargar el estado desde un archivo JSON
private static EstadoPersistente CargarEstado()
{
try
{
if (File.Exists(_filePath))
{
string json = File.ReadAllText(_filePath);
return JsonSerializer.Deserialize<EstadoPersistente>(json);
}
return new EstadoPersistente(); // Devuelve una nueva instancia si no existe el archivo
}
catch
{
return new EstadoPersistente(); // Devuelve una nueva instancia si hay un error durante la carga
}
}
}
public partial class Passwords : ObservableObject
{
[ObservableProperty]
private string usuario;
[ObservableProperty]
private string password;
}
}