Initial commit

This commit is contained in:
user
2026-07-12 16:06:18 +04:00
commit 1d16eeacb2
23 changed files with 2298 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
# Visual Studio
.vs/
*.suo
*.user
*.userosscache
*.sln.docstates
# Build results
[Bb]in/
[Oo]bj/
Debug/
Release/
x64/
x86/
# Visual Studio cache
.vscode/
.idea/
# ReSharper
_ReSharper*/
*.ReSharper*
# Logs
*.log
# Temporary files
*.tmp
*.temp
*.cache
# Generated files
*.pdb
*.dll
*.exe
# Test results
TestResults/
*.trx
# NuGet packages
packages/
*.nupkg
# MS Access temporary files
*.laccdb
*.ldb
# User-specific settings
*.user
*.suo
# Database backups
*.bak
*.backup
# OS files
.DS_Store
Thumbs.db
# Publish files
Publish/
*.publish.xml
# Keep database file
!Database.accdb
BIN
View File
Binary file not shown.
+31
View File
@@ -0,0 +1,31 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.33130.400
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Database", "Database\Database.csproj", "{BAF17228-60DE-4081-A24F-F6DD8A12C06A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Debug|x64.ActiveCfg = Debug|x64
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Debug|x64.Build.0 = Debug|x64
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Release|Any CPU.Build.0 = Release|Any CPU
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Release|x64.ActiveCfg = Release|x64
{BAF17228-60DE-4081-A24F-F6DD8A12C06A}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D5EB1D96-D46B-4FBF-B2F5-859350FD64B0}
EndGlobalSection
EndGlobal
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
+112
View File
@@ -0,0 +1,112 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BAF17228-60DE-4081-A24F-F6DD8A12C06A}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>Database</RootNamespace>
<AssemblyName>Database</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Fishes.cs" />
<Compile Include="FishFood.cs" />
<Compile Include="FishRations.cs" />
<Compile Include="FishTypes.cs" />
<Compile Include="Locations.cs" />
<Compile Include="MainForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="MainForm.Designer.cs">
<DependentUpon>MainForm.cs</DependentUpon>
</Compile>
<Compile Include="OleDBDataGridViewHandler.cs" />
<Compile Include="OleDBHandler.cs" />
<Compile Include="Plants.cs" />
<Compile Include="PlantTypes.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+29
View File
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;
namespace Database
{
class FishFood : OleDBDataGridViewHandler
{
public FishFood(DataGridView dataGridView) : base("fish_food", dataGridView) {}
public void Insert(String name)
{
(string, object) pair = ("data", name);
OleDBHandler.Insert(nameTable, pair);
RefreshView();
}
public void Update(String name)
{
int id = CurrentId();
if (id < 0)
return;
(string, object) pair = ("data", name);
OleDBHandler.Update(nameTable, id, pair);
RefreshView();
}
}
}
+35
View File
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Database
{
class FishRations : OleDBDataGridViewHandler
{
static OleDbCommand SelectCommand()
{
string command = "SELECT [FFF].[id], [FT].[data] AS [type], [FF].[data] AS [food]" +
"FROM [fish_types_fish_food] AS [FFF], [fish_types] AS [FT], [fish_food] AS [FF]" +
"WHERE [type_id] = [FT].[id] AND [food_id] = [FF].[id];";
var result = new OleDbCommand(command, OleDBHandler.Connection);
return result;
}
public FishRations(DataGridView dataGridView) : base(SelectCommand(), "fish_types_fish_food", dataGridView) { }
public void Insert(int typeId, int foodId)
{
string command = "SELECT COUNT(*) FROM [fish_types_fish_food]" +
$"WHERE [type_id] = {typeId} AND [food_id] = {foodId};";
var result = OleDBHandler.Execute(command, OleDBHandler.ExecuteType.Scalar);
if (Convert.ToInt32(result) > 0)
return;
(string, object) pair1 = ("type_id", typeId);
(string, object) pair2 = ("food_id", foodId);
OleDBHandler.Insert(nameTable, pair1, pair2);
RefreshView();
}
}
}
+29
View File
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;
namespace Database
{
class FishTypes : OleDBDataGridViewHandler
{
public FishTypes(DataGridView dataGridView) : base("fish_types", dataGridView) { }
public void Insert(String name)
{
(string, object) pair = ("data", name);
OleDBHandler.Insert(nameTable, pair);
RefreshView();
}
public void Update(String name)
{
int id = CurrentId();
if (id < 0)
return;
(string, object) pair = ("data", name);
OleDBHandler.Update(nameTable, id, pair);
RefreshView();
}
}
}
+51
View File
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;
namespace Database
{
class Fishes : OleDBDataGridViewHandler
{
static OleDbCommand SelectCommand() {
string command =
"SELECT [F].[id], [FT].[data] AS [type], [L].[data] AS [location], [F].[number]" +
"FROM[fishes] AS[F], [fish_types] AS[FT], [locations] AS[L]" +
"WHERE[type_id] = [FT].[id] AND[location_id] = [L].[id]";
var result = new OleDbCommand(command, OleDBHandler.Connection);
return result;
}
public Fishes(DataGridView dataGridView) : base(SelectCommand(), "fishes", dataGridView) {}
private bool Exists(int typeId, int locationId) {
string command = "SELECT COUNT(*) FROM [fishes]" +
$"WHERE [type_id] = {typeId} AND [location_id] = {locationId};";
var result = OleDBHandler.Execute(command, OleDBHandler.ExecuteType.Scalar);
if (Convert.ToInt32(result) > 0)
return true;
return false;
}
public void Insert(int number, int typeId, int locationId) {
if (Exists(typeId, locationId) == true)
return;
(string, object) pair1 = ("type_id", typeId);
(string, object) pair2 = ("location_id", locationId);
(string, object) pair3 = ("number", number);
OleDBHandler.Insert(nameTable, pair1, pair2, pair3);
RefreshView();
}
public void Update(int number, int typeId, int locationId) {
if (Exists(typeId, locationId) == true)
return;
int id = CurrentId();
if (id < 0)
return;
(string, object) pair1 = ("type_id", typeId);
(string, object) pair2 = ("location_id", locationId);
(string, object) pair3 = ("number", number);
OleDBHandler.Update(nameTable, id, pair1, pair2, pair3);
RefreshView();
}
}
}
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;
namespace Database
{
class Locations : OleDBDataGridViewHandler
{
public Locations(DataGridView dataGridView) : base("locations", dataGridView) { }
public void Insert(String name) {
(string, object) pair = ("data", name);
OleDBHandler.Insert(nameTable, pair);
RefreshView();
}
public void Update(String name) {
int id = CurrentId();
if (id < 0)
return;
(string, object) pair = ("data", name);
OleDBHandler.Update(nameTable, id, pair);
RefreshView();
}
}
}
+1066
View File
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Database
{
public partial class MainForm : Form
{
private Fishes fishes;
private Plants plants;
private FishFood fishFood;
private Locations locations;
private FishTypes fishTypes;
private PlantTypes plantTypes;
private FishRations fishRations;
public MainForm()
{
InitializeComponent();
ConfigureWidgets();
ConfigureText();
}
private void ConfigureWidgets() {
fishes = new Fishes(fishesDataGridView);
plants = new Plants(plantsDataGridView);
fishFood = new FishFood(fishFoodDataGridView);
locations = new Locations(locationsDataGridView);
fishTypes = new FishTypes(fishTypesDataGridView);
plantTypes = new PlantTypes(plantTypesDataGridView);
fishRations = new FishRations(fishRationsDataGridView);
var initializerList = new (ComboBox, DataGridView)[6] {
(fishTypeFishesComboBox, fishTypesDataGridView),
(locationFishComboBox, locationsDataGridView),
(fishTypeRationsComboBox, fishTypesDataGridView),
(fishFoodRationsComboBox, fishFoodDataGridView),
(plantTypePlantsComboBox, plantTypesDataGridView),
(locationPlantsComboBox, locationsDataGridView)
};
foreach (var pair in initializerList) {
pair.Item1.DataSource = pair.Item2.DataSource;
pair.Item1.DropDownStyle = ComboBoxStyle.DropDownList;
pair.Item1.DisplayMember = "data";
pair.Item1.ValueMember = "id";
}
}
private void ConfigureText() {
var initializerList = new DataGridView[7] {
fishesDataGridView,
plantsDataGridView,
fishFoodDataGridView,
locationsDataGridView,
fishTypesDataGridView,
plantTypesDataGridView,
fishRationsDataGridView
};
foreach (var dataGridView in initializerList)
dataGridView.Columns["id"].HeaderText = "Identifier";
fishesDataGridView.Columns["id"].Visible = false;
plantsDataGridView.Columns["id"].Visible = false;
fishesDataGridView.Columns["type"].HeaderText = "Type of fish";
fishesDataGridView.Columns["location"].HeaderText = "Place of residence";
fishesDataGridView.Columns["number"].HeaderText = "Population";
plantsDataGridView.Columns["type"].HeaderText = "Type of plant";
plantsDataGridView.Columns["location"].HeaderText = "Plant location";
plantsDataGridView.Columns["number"].HeaderText = "Number of plants";
fishFoodDataGridView.Columns["data"].HeaderText = "Fish nutrition";
locationsDataGridView.Columns["data"].HeaderText = "Place of residence";
fishTypesDataGridView.Columns["data"].HeaderText = "Type of fish";
plantTypesDataGridView.Columns["data"].HeaderText = "Type of plant";
fishRationsDataGridView.Columns["type"].HeaderText = "Type of fish";
fishRationsDataGridView.Columns["food"].HeaderText = "What does it eat";
}
private void addLocation_Click(object sender, EventArgs e) {
string data = locationTextBox.Text.Trim();
if (data.Length < 1)
return;
locations.Insert(data);
}
private void updateLocation_Click(object sender, EventArgs e) {
string data = locationTextBox.Text.Trim();
if (data.Length < 1)
return;
locations.Update(data);
}
private void deleteLocation_Click(object sender, EventArgs e) {
locations.Delete();
}
private void addFishType_Click(object sender, EventArgs e) {
string data = fishTypeTextBox.Text.Trim();
if (data.Length < 1)
return;
fishTypes.Insert(data);
}
private void updateFishType_Click(object sender, EventArgs e) {
string data = fishTypeTextBox.Text.Trim();
if (data.Length < 1)
return;
fishTypes.Update(data);
}
private void deleteFishType_Click(object sender, EventArgs e) {
fishTypes.Delete();
}
private void addFishFood_Click(object sender, EventArgs e) {
string data = fishFoodTextBox.Text.Trim();
if (data.Length < 1)
return;
fishFood.Insert(data);
}
private void updateFishFood_Click(object sender, EventArgs e) {
string data = fishFoodTextBox.Text.Trim();
if (data.Length < 1)
return;
fishFood.Update(data);
}
private void deleteFishFood_Click(object sender, EventArgs e) {
fishFood.Delete();
}
private void addPlantType_Click(object sender, EventArgs e) {
string data = plantTypeTextBox.Text.Trim();
if (data.Length < 1)
return;
plantTypes.Insert(data);
}
private void updatePlantType_Click(object sender, EventArgs e) {
string data = plantTypeTextBox.Text.Trim();
if (data.Length < 1)
return;
plantTypes.Update(data);
}
private void deletePlantType_Click(object sender, EventArgs e) {
plantTypes.Delete();
}
private void addFish_Click(object sender, EventArgs e) {
int number = Convert.ToInt32(numberFishNumericUpDown.Value);
int typeId = Convert.ToInt32(fishTypeFishesComboBox.SelectedValue);
int locationId = Convert.ToInt32(locationFishComboBox.SelectedValue);
fishes.Insert(number, typeId, locationId);
}
private void updateFish_Click(object sender, EventArgs e) {
int number = Convert.ToInt32(numberFishNumericUpDown.Value);
int typeId = Convert.ToInt32(fishTypeFishesComboBox.SelectedValue);
int locationId = Convert.ToInt32(locationFishComboBox.SelectedValue);
fishes.Update(number, typeId, locationId);
}
private void deleteFish_Click(object sender, EventArgs e) {
fishes.Delete();
}
private void addPlant_Click(object sender, EventArgs e) {
int number = Convert.ToInt32(numberPlantsNumericUpDown.Value);
int typeId = Convert.ToInt32(plantTypePlantsComboBox.SelectedValue);
int locationId = Convert.ToInt32(locationPlantsComboBox.SelectedValue);
plants.Insert(number, typeId, locationId);
}
private void updatePlant_Click(object sender, EventArgs e) {
int number = Convert.ToInt32(numberPlantsNumericUpDown.Value);
int typeId = Convert.ToInt32(plantTypePlantsComboBox.SelectedValue);
int locationId = Convert.ToInt32(locationPlantsComboBox.SelectedValue);
plants.Update(number, typeId, locationId);
}
private void deletePlant_Click(object sender, EventArgs e) {
plants.Delete();
}
private void addFishRation_Click(object sender, EventArgs e) {
int typeId = Convert.ToInt32(fishTypeFishesComboBox.SelectedValue);
int foodId = Convert.ToInt32(fishFoodRationsComboBox.SelectedValue);
fishRations.Insert(typeId, foodId);
}
private void deleteFishRation_Click(object sender, EventArgs e) {
fishRations.Delete();
}
}
}
+120
View File
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: 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:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+56
View File
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Database
{
abstract class OleDBDataGridViewHandler
{
protected string nameTable;
private int idIndex;
public OleDbDataAdapter select;
private DataGridView dataGridView;
protected OleDBDataGridViewHandler(OleDbCommand selectCommand, string nameTable, DataGridView dataGridView, int idIndex = 0)
{
this.nameTable = nameTable;
this.idIndex = idIndex;
select = new OleDbDataAdapter(selectCommand);
this.dataGridView = dataGridView;
this.dataGridView.DataSource = new DataTable();
RefreshView();
var lastColIndex = dataGridView.Columns.Count - 1;
var lastColumn = dataGridView.Columns[lastColIndex];
lastColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
protected OleDBDataGridViewHandler(string nameTable, DataGridView dataGridView, string fields = "*", int idIndex = 0)
: this(OleDBHandler.SelectCommand(nameTable, fields), nameTable, dataGridView, idIndex)
{ }
protected void RefreshView()
{
var dataTable = this.dataGridView.DataSource as DataTable;
dataTable.Clear();
select.Fill(dataTable);
}
protected int CurrentId()
{
if (dataGridView.SelectedCells.Count < 1)
return -1;
var selectedRowIndex = dataGridView.SelectedCells[0].RowIndex;
var value = dataGridView.Rows[selectedRowIndex].Cells[idIndex].Value;
return Convert.ToInt32(value);
}
public void Delete()
{
int id = CurrentId();
if (id < 0)
return;
OleDBHandler.Delete(nameTable, id);
RefreshView();
}
}
}
+127
View File
@@ -0,0 +1,127 @@
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
using System.Text;
namespace Database {
static public class OleDBHandler {
static private OleDbConnection connection;
static public OleDbConnection Connection {
get {
if (connection == null) {
InitializeConnection();
}
return connection;
}
}
static private void InitializeConnection() {
try {
using (var ofDlg = new OpenFileDialog()) {
ofDlg.InitialDirectory = "c:\\";
ofDlg.Filter = "Access database files (*.accdb;*.mdb)|*.accdb;*.mdb";
ofDlg.RestoreDirectory = true;
ofDlg.CheckFileExists = true;
if (ofDlg.ShowDialog() == DialogResult.OK) {
connection = new OleDbConnection(string.Format(
"Provider = Microsoft.ACE.Oledb.12.0; Data Source = {0}"
, ofDlg.FileName
));
}
else {
Environment.Exit(0);
}
}
connection.Open();
}
catch (Exception e) {
MessageBox.Show(
e.Message
, "Database connection error"
, MessageBoxButtons.OK
, MessageBoxIcon.Error
);
Environment.Exit(e.HResult);
}
}
public enum ExecuteType { NonQuery, Scalar };
public static object Execute(string command, ExecuteType type)
{
using (var statement = new OleDbCommand(command, Connection))
{
switch (type)
{
case ExecuteType.NonQuery:
return statement.ExecuteNonQuery();
case ExecuteType.Scalar:
return statement.ExecuteScalar();
default:
throw new ArgumentException("An unsupported method is specified");
}
}
}
public static OleDbCommand SelectCommand(string tableName, string fields)
{
var command = $"SELECT {fields} FROM [{tableName}];";
return new OleDbCommand(command, Connection);
}
public static bool Delete(string tableName, int id) {
string command = $"DELETE FROM [{tableName}] WHERE [id] = {id};";
var result = Execute(command, ExecuteType.NonQuery);
return Convert.ToBoolean(result);
}
private static string UpdatePart(params (string, object)[] listPairColumnNameValue) {
StringBuilder result = new StringBuilder(string.Empty);
var size = listPairColumnNameValue.Length;
if (size < 1)
return result.ToString();
foreach (var pair in listPairColumnNameValue)
if(pair.Item2 is string)
result.Append($"[{pair.Item1}]='{pair.Item2}',");
else
result.Append($"[{pair.Item1}]={pair.Item2},");
return result.ToString().TrimEnd(',');
}
public static bool Update(string tableName, int id, params (string, object)[] listPairColumnNameValue)
{
string partCommand = UpdatePart(listPairColumnNameValue);
if (partCommand.Length < 1)
return true;
string command = $"UPDATE [{tableName}] SET {partCommand} WHERE [id] = {id};";
var result = Execute(command, ExecuteType.NonQuery);
return Convert.ToBoolean(result);
}
private static string InsertPart(params (string, object)[] listPairColumnNameValue)
{
var size = listPairColumnNameValue.Length;
if (size < 1)
return string.Empty;
StringBuilder left = new StringBuilder("(");
StringBuilder right = new StringBuilder("VALUES (");
foreach (var pair in listPairColumnNameValue) {
left.Append('[');
left.Append(pair.Item1);
left.Append("],");
if (pair.Item2 is string)
right.Append('\'' + pair.Item2.ToString() + '\'' + ',');
else
right.Append(pair.Item2.ToString() + ',');
}
var leftResult = left.ToString().TrimEnd(',') + ')';
var rightResult = right.ToString().TrimEnd(',') + ')';
return leftResult + rightResult;
}
public static bool Insert(string tableName, params (string, object)[] listPairColumnNameValue)
{
string partCommand = InsertPart(listPairColumnNameValue);
if (partCommand.Length < 1)
return true;
string command = $"INSERT INTO [{tableName}] {partCommand};";
var result = Execute(command, ExecuteType.NonQuery);
return Convert.ToBoolean(result);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;
namespace Database
{
class PlantTypes : OleDBDataGridViewHandler
{
public PlantTypes(DataGridView dataGridView) : base("plant_types", dataGridView) { }
public void Insert(String name)
{
(string, object) pair = ("data", name);
OleDBHandler.Insert(nameTable, pair);
RefreshView();
}
public void Update(String name)
{
int id = CurrentId();
if (id < 0)
return;
(string, object) pair = ("data", name);
OleDBHandler.Update(nameTable, id, pair);
RefreshView();
}
}
}
+50
View File
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Text;
using System.Windows.Forms;
namespace Database
{
class Plants : OleDBDataGridViewHandler
{
static OleDbCommand SelectCommand() {
string command =
"SELECT [F].[id], [PT].[data] AS [type], [L].[data] AS [location], [F].[number]" +
"FROM[plants] AS[F], [plant_types] AS[PT], [locations] AS[L]" +
"WHERE[type_id] = [PT].[id] AND[location_id] = [L].[id]";
var result = new OleDbCommand(command, OleDBHandler.Connection);
return result;
}
public Plants(DataGridView dataGridView) : base(SelectCommand(), "plants", dataGridView) { }
private bool Exists(int typeId, int locationId) {
string command = "SELECT COUNT(*) FROM [plants]" +
$"WHERE [type_id] = {typeId} AND [location_id] = {locationId};";
var result = OleDBHandler.Execute(command, OleDBHandler.ExecuteType.Scalar);
if (Convert.ToInt32(result) > 0)
return true;
return false;
}
public void Insert(int number, int typeId, int locationId) {
if (Exists(typeId, locationId) == true)
return;
(string, object) pair1 = ("type_id", typeId);
(string, object) pair2 = ("location_id", locationId);
(string, object) pair3 = ("number", number);
OleDBHandler.Insert(nameTable, pair1, pair2, pair3);
RefreshView();
}
public void Update(int number, int typeId, int locationId) {
if (Exists(typeId, locationId) == true)
return;
int id = CurrentId();
if (id < 0)
return;
(string, object) pair1 = ("type_id", typeId);
(string, object) pair2 = ("location_id", locationId);
(string, object) pair3 = ("number", number);
OleDBHandler.Update(nameTable, id, pair1, pair2, pair3);
RefreshView();
}
}
}
+24
View File
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Database
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
//MessageBox.Show(RuntimeInformation.FrameworkDescription);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанных со сборкой.
[assembly: AssemblyTitle("Database")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Database")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, следует установить атрибут ComVisible в TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("baf17228-60de-4081-a24f-f6dd8a12c06a")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+70
View File
@@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программным средством.
// Версия среды выполнения: 4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
// код создан повторно.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Database.Properties
{
/// <summary>
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
/// </summary>
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
// класс с помощью таких средств, как ResGen или Visual Studio.
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
// с параметром /str или заново постройте свой VS-проект.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Database.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Переопределяет свойство CurrentUICulture текущего потока для всех
/// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
+117
View File
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: 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:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+29
View File
@@ -0,0 +1,29 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Database.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>