Compare commits

...

2 Commits

Author SHA1 Message Date
24d6832ec0 исправления + Migrations 2024-05-08 01:41:20 +04:00
db6fa68cae Созданы классы 2024-05-08 01:30:04 +04:00
17 changed files with 512 additions and 9 deletions

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabWork.Interfaces;
namespace LabWork
{
public class ContactBindingModel : IContactModel
{
public int Id { get; set; }
public string ContactName { get; set; } = string.Empty;
public double Number { get; set; }
}
}

View File

@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabWork.Interfaces;
namespace LabWork
{
public class ContactLogic : IContactLogic
{
private readonly IContactStorage _ContactStorage;
public ContactLogic(IContactStorage ContactStorage)
{
_ContactStorage = ContactStorage;
}
public List<ContactViewModel>? ReadList(ContactSearchModel? model)
{
var list = model == null ? _ContactStorage.GetFullList() : _ContactStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public ContactViewModel? ReadElement(ContactSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _ContactStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public bool Create(ContactBindingModel model)
{
CheckModel(model);
if (_ContactStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Update(ContactBindingModel model)
{
CheckModel(model);
if (_ContactStorage.Update(model) == null)
{
return false;
}
return true;
}
public bool Delete(ContactBindingModel model)
{
CheckModel(model, false);
if (_ContactStorage.Delete(model) == null)
{
return false;
}
return true;
}
private void CheckModel(ContactBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ContactName))
{
throw new ArgumentNullException("Нет названия компонента",
nameof(model.ContactName));
}
if (model.Number <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Number));
}
var element = _ContactStorage.GetElement(new ContactSearchModel
{
ContactName = model.ContactName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabWork
{
public class ContactSearchModel
{
public int? Id { get; set; }
public string? ContactName { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabWork.Interfaces;
namespace LabWork
{
public class ContactViewModel
{
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ContactName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Number { get; set; }
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabWork.Interfaces;
using System.ComponentModel.DataAnnotations;
namespace LabWork.Database
{
public class Contact : IContactModel
{
public int Id { get; private set; }
[Required]
public string ContactName { get; private set; } = string.Empty;
[Required]
public double Number { get; set; }
public static Contact? Create(ContactBindingModel model)
{
if (model == null)
{
return null;
}
return new Contact()
{
Id = model.Id,
ContactName = model.ContactName,
Number = model.Number
};
}
public static Contact Create(ContactViewModel model)
{
return new Contact
{
Id = model.Id,
ContactName = model.ContactName,
Number = model.Number
};
}
public void Update(ContactBindingModel model)
{
if (model == null)
{
return;
}
ContactName = model.ContactName;
Number = model.Number;
}
public ContactViewModel GetViewModel => new()
{
Id = Id,
ContactName = ContactName,
Number = Number
};
}
}

View File

@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabWork.Database
{
public class ContactsDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder OptionsBuilder)
{
if (OptionsBuilder.IsConfigured == false)
{
OptionsBuilder.UseNpgsql(@"Host=localhost;Database=Contacts;Username=postgres;Password=postgres");
}
base.OnConfiguring(OptionsBuilder);
}
public virtual DbSet<Contact> Contacts { set; get; }
}
}

View File

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabWork.Interfaces;
using System.ComponentModel;
namespace LabWork.Database
{
public class ContactStorage : IContactStorage
{
public List<ContactViewModel> GetFullList()
{
using var context = new ContactsDatabase();
return context.Contacts.Select(x => x.GetViewModel).ToList();
}
public List<ContactViewModel> GetFilteredList(ContactSearchModel model)
{
if (string.IsNullOrEmpty(model.ContactName))
{
return new();
}
using var context = new ContactsDatabase();
return context.Contacts.Where(x => x.ContactName.Contains(model.ContactName)).Select(x => x.GetViewModel).ToList();
}
public ContactViewModel? GetElement(ContactSearchModel model)
{
if (string.IsNullOrEmpty(model.ContactName) && !model.Id.HasValue)
{
return null;
}
using var context = new ContactsDatabase();
return context.Contacts.FirstOrDefault(x =>
!string.IsNullOrEmpty(model.ContactName) && x.ContactName == model.ContactName ||
model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public ContactViewModel? Insert(ContactBindingModel model)
{
var newContact = Contact.Create(model);
if (newContact == null)
{
return null;
}
using var context = new ContactsDatabase();
context.Contacts.Add(newContact);
context.SaveChanges();
return newContact.GetViewModel;
}
public ContactViewModel? Update(ContactBindingModel model)
{
using var context = new ContactsDatabase();
var Contact = context.Contacts.FirstOrDefault(x => x.Id == model.Id);
if (Contact == null)
{
return null;
}
Contact.Update(model);
context.SaveChanges();
return Contact.GetViewModel;
}
public ContactViewModel? Delete(ContactBindingModel model)
{
using var context = new ContactsDatabase();
var element = context.Contacts.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Contacts.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -5,7 +5,7 @@
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer Contacts = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
@ -13,9 +13,9 @@
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (Contacts != null))
{ {
components.Dispose(); Contacts.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
@ -26,7 +26,7 @@
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeContact()
{ {
dataGridView = new DataGridView(); dataGridView = new DataGridView();
buttonAdd = new Button(); buttonAdd = new Button();

View File

@ -4,7 +4,7 @@ namespace LabWork
{ {
public FormContacts() public FormContacts()
{ {
InitializeComponent(); InitializeContact();
} }
} }
} }

View File

@ -56,7 +56,7 @@
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ContactModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabWork.Interfaces
{
public interface IContactLogic
{
List<ContactViewModel>? ReadList(ContactSearchModel? model);
ContactViewModel? ReadElement(ContactSearchModel model);
bool Create(ContactBindingModel model);
bool Update(ContactBindingModel model);
bool Delete(ContactBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabWork.Interfaces
{
public interface IContactModel
{
int Id { get; }
string ContactName { get; }
double Number { get; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabWork.Interfaces
{
public interface IContactStorage
{
List<ContactViewModel> GetFullList();
List<ContactViewModel> GetFilteredList(ContactSearchModel model);
ContactViewModel? GetElement(ContactSearchModel model);
ContactViewModel? Insert(ContactBindingModel model);
ContactViewModel? Update(ContactBindingModel model);
ContactViewModel? Delete(ContactBindingModel model);
}
}

View File

@ -0,0 +1,49 @@
// <auto-generated />
using LabWork.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace LabWork.Migrations
{
[DbContext(typeof(ContactsDatabase))]
[Migration("20240507213755_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("LabWork.Database.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ContactName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Number")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Contacts");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace LabWork.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Contacts",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ContactName = table.Column<string>(type: "text", nullable: false),
Number = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Contacts", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Contacts");
}
}
}

View File

@ -0,0 +1,46 @@
// <auto-generated />
using LabWork.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace LabWork.Migrations
{
[DbContext(typeof(ContactsDatabase))]
partial class ContactsDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("LabWork.Database.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ContactName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Number")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Contacts");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,17 +1,32 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using LabWork.Interfaces;
using LabWork.Database;
namespace LabWork namespace LabWork
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormContacts()); var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormContacts>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddTransient<IContactStorage, ContactStorage>();
services.AddTransient<IContactLogic, ContactLogic>();
//services.AddTransient<FormContact>();
services.AddTransient<FormContacts>();
} }
} }
} }