Compare commits

...

5 Commits

Author SHA1 Message Date
I1nur
7b71e9de81 all done 2024-12-24 06:22:29 +04:00
I1nur
15edafea60 almost done 2024-12-24 03:37:47 +04:00
I1nur
9e0c116449 stll has errors 2024-12-24 00:38:23 +04:00
I1nur
6d3fd79a5d big commit 2024-12-23 22:31:49 +04:00
I1nur
0e193dfc49 big commit 2024-12-23 16:53:19 +04:00
92 changed files with 10160 additions and 75 deletions

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities.Enums
{
[Flags]
public enum ExpenseCategoryType
{
None = 0,
Food = 1,
Utilities = 2,
Entertainment = 4,
Health = 8
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities.Enums
{
public enum FamilyMemberType
{
None = 0,
Father = 1,
Mother = 2,
Son = 3,
Daughter = 4
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities.Enums
{
[Flags]
public enum IncomeCategoryType
{
None = 0,
Salary = 1,
Bonus = 2,
Investment = 4
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class ExpenseBudget
{
public int Id { get; private set; }
[Browsable(false)]
public int FamilyMemberId { get; private set; }
[DisplayName("Участник")]
public string FullName { get; private set; } = string.Empty;
[DisplayName("Дата")]
public DateTime Date { get; private set; }
public string Expenses => FamilyMember_Expenses != null ?
string.Join(", ", FamilyMember_Expenses.Select(x => $"{x.ExpenseName} {x.Sum}")) : string.Empty;
[Browsable(false)]
public IEnumerable<FamilyMember_ExpenseBudget> FamilyMember_Expenses { get; private set; } = [];
public static ExpenseBudget СreateOperation(int id, int familyMemberId, IEnumerable<FamilyMember_ExpenseBudget> familyMember_Expenses)
{
return new ExpenseBudget
{
Id = id,
FamilyMemberId = familyMemberId,
FamilyMember_Expenses = familyMember_Expenses,
Date = DateTime.Now
};
}
public void SetExpenseBudget(IEnumerable<FamilyMember_ExpenseBudget> familyMember_Expenses)
{
if (familyMember_Expenses != null && familyMember_Expenses.Any())
{
FamilyMember_Expenses = familyMember_Expenses;
}
}
}
}

View File

@ -0,0 +1,29 @@
using FamilyBudget.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class ExpenseBudgetCategory
{
public int Id { get; private set; }
[DisplayName("Тип расхода")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Название")]
public ExpenseCategoryType ExpenseCategoryType { get; private set; }
[DisplayName("Категория")]
public static ExpenseBudgetCategory CreateEntity(int id, string name, ExpenseCategoryType expenseCategoryType)
{
return new ExpenseBudgetCategory
{
Id = id,
Name = name,
ExpenseCategoryType = expenseCategoryType
};
}
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class Family
{
public int Id { get; private set; }
[DisplayName("Фамилия")]
public string Name { get; private set; } = string.Empty;
public static Family CreateEntity(int id, string name)
{
return new Family
{
Id = id,
Name = name ?? string.Empty,
};
}
}
}

View File

@ -0,0 +1,37 @@
using DocumentFormat.OpenXml.Wordprocessing;
using FamilyBudget.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class FamilyMember
{
public int Id { get; set; }
[DisplayName("Имя")]
public string Name { get; private set; } = string.Empty;
[Browsable(false)]
public int FamilyId { get; private set; }
[DisplayName("Семья")]
public string FamilyName { get; private set; } = string.Empty;
public string FullName => $"{Name} {FamilyName}";
[DisplayName("Член семьи")]
public FamilyMemberType MemberType { get; private set; }
public static FamilyMember CreateEntity(int id, string name, int familyId, FamilyMemberType memberType)
{
return new FamilyMember
{
Id = id,
Name = name ?? string.Empty,
FamilyId = familyId,
MemberType = memberType
};
}
};
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class FamilyMember_ExpenseBudget
{
public int Id { get; private set; }
public int ExpenseBudgetId { get; private set; }
public int ExpenseBudgetCategoryID { get; private set; }
public int Sum { get; private set; }
public string ExpenseName { get; private set; } = string.Empty;
public static FamilyMember_ExpenseBudget CreateElement(int id, int expenseCategoryID, int expenseBudgetId, int sum)
{
return new FamilyMember_ExpenseBudget()
{
Id = id,
ExpenseBudgetCategoryID = expenseCategoryID,
ExpenseBudgetId = expenseBudgetId,
Sum = sum
};
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class FamilyMember_IncomeBudget
{
public int Id { get; private set; }
public int IncomeBudgetId { get; private set;}
public int IncomeBudgetCategoryId { get; private set; }
public int Sum { get; private set; }
public string IncomeName { get; private set; } = string.Empty;
public static FamilyMember_IncomeBudget CreateElement(int id, int incomeBudgetCategoryId, int incomeBudgetId, int sum)
{
return new FamilyMember_IncomeBudget()
{
Id = id,
IncomeBudgetId = incomeBudgetId,
IncomeBudgetCategoryId = incomeBudgetCategoryId,
Sum = sum
};
}
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class IncomeBudget
{
public int Id { get; private set; }
[Browsable(false)]
public int FamilyMemberId { get; private set; }
[DisplayName("Участник")]
public string FullName { get; private set; } = string.Empty;
[DisplayName("Дата")]
public DateTime Date { get; private set; }
[DisplayName("Доходы")]
public string Incomes => FamilyMember_Incomes != null ?
string.Join(", ", FamilyMember_Incomes.Select(x => $"{x.IncomeName} {x.Sum}")) : string.Empty;
[Browsable(false)]
public IEnumerable<FamilyMember_IncomeBudget> FamilyMember_Incomes { get; private set; } = [];
public static IncomeBudget CreateOperation(int id, int familyMemberId, IEnumerable<FamilyMember_IncomeBudget> FamilyMember_Incomes)
{
return new IncomeBudget
{
Id = id,
FamilyMemberId = familyMemberId,
FamilyMember_Incomes = FamilyMember_Incomes,
Date = DateTime.Now
};
}
public void SetIncomeBudget(IEnumerable<FamilyMember_IncomeBudget> familyMember_Incomes)
{
if (familyMember_Incomes != null && familyMember_Incomes.Any())
{
FamilyMember_Incomes = familyMember_Incomes;
}
}
}
}

View File

@ -0,0 +1,29 @@
using FamilyBudget.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Entities
{
public class IncomeBudgetCategory
{
public int Id { get; private set; }
[DisplayName("Тип дохода")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Название")]
public IncomeCategoryType IncomeCategoryType { get; private set; }
[DisplayName("Категория")]
public static IncomeBudgetCategory CreateEntity(int id, string name, IncomeCategoryType incomeCategoryType)
{
return new IncomeBudgetCategory
{
Id = id,
Name = name ?? string.Empty,
IncomeCategoryType = incomeCategoryType
};
}
}
}

View File

@ -8,4 +8,44 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="PDFsharp-MigraDoc-GDI" Version="6.1.1" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Container" Version="5.11.11" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -1,39 +0,0 @@
namespace FamilyBudget
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace FamilyBudget
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,179 @@
namespace FamilyBudget
{
partial class FormFamilyBudget
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormFamilyBudget));
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
FamiliesToolStripMenuItem = new ToolStripMenuItem();
участникиСемьиToolStripMenuItem = new ToolStripMenuItem();
категорияДоходовToolStripMenuItem = new ToolStripMenuItem();
категорияРасходовToolStripMenuItem = new ToolStripMenuItem();
операцииToolStripMenuItem = new ToolStripMenuItem();
расходToolStripMenuItem = new ToolStripMenuItem();
IncomeToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
движениеПоСправочникамToolStripMenuItem = new ToolStripMenuItem();
движениеОперацийToolStripMenuItem = new ToolStripMenuItem();
движениеТратToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(799, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { FamiliesToolStripMenuItem, участникиСемьиToolStripMenuItem, категорияДоходовToolStripMenuItem, категорияРасходовToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
//
// FamiliesToolStripMenuItem
//
FamiliesToolStripMenuItem.Name = "FamiliesToolStripMenuItem";
FamiliesToolStripMenuItem.Size = new Size(184, 22);
FamiliesToolStripMenuItem.Text = "Семьи";
FamiliesToolStripMenuItem.Click += FamiliesToolStripMenuItem_Click;
//
// участникиСемьиToolStripMenuItem
//
участникиСемьиToolStripMenuItem.Name = "участникиСемьиToolStripMenuItem";
участникиСемьиToolStripMenuItem.Size = new Size(184, 22);
участникиСемьиToolStripMenuItem.Text = "Участники семьи";
участникиСемьиToolStripMenuItem.Click += FamilyMembers;
//
// категорияДоходовToolStripMenuItem
//
категорияДоходовToolStripMenuItem.Name = атегорияДоходовToolStripMenuItem";
категорияДоходовToolStripMenuItem.Size = new Size(184, 22);
категорияДоходовToolStripMenuItem.Text = "Категория доходов";
категорияДоходовToolStripMenuItem.Click += CategoryIncomesToolStripMenuItem_Click;
//
// категорияРасходовToolStripMenuItem
//
категорияРасходовToolStripMenuItem.Name = атегорияРасходовToolStripMenuItem";
категорияРасходовToolStripMenuItem.Size = new Size(184, 22);
категорияРасходовToolStripMenuItem.Text = "Категория расходов";
категорияРасходовToolStripMenuItem.Click += CategoryExpensesToolStripMenuItem_Click;
//
// операцииToolStripMenuItem
//
операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { расходToolStripMenuItem, IncomeToolStripMenuItem });
операцииToolStripMenuItem.Name = "операцииToolStripMenuItem";
операцииToolStripMenuItem.Size = new Size(75, 20);
операцииToolStripMenuItem.Text = "Операции";
//
// расходToolStripMenuItem
//
расходToolStripMenuItem.Name = "расходToolStripMenuItem";
расходToolStripMenuItem.Size = new Size(112, 22);
расходToolStripMenuItem.Text = "Расход";
расходToolStripMenuItem.Click += ExpenseToolStripMenuItem_Click;
//
// IncomeToolStripMenuItem
//
IncomeToolStripMenuItem.Name = "IncomeToolStripMenuItem";
IncomeToolStripMenuItem.Size = new Size(112, 22);
IncomeToolStripMenuItem.Text = "Доход";
IncomeToolStripMenuItem.Click += IncomeToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { движениеПоСправочникамToolStripMenuItem, движениеОперацийToolStripMenuItem, движениеТратToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 20);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// движениеПоСправочникамToolStripMenuItem
//
движениеПоСправочникамToolStripMenuItem.Name = "движениеПоСправочникамToolStripMenuItem";
движениеПоСправочникамToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
движениеПоСправочникамToolStripMenuItem.Size = new Size(276, 22);
движениеПоСправочникамToolStripMenuItem.Text = "Движение по справочникам";
движениеПоСправочникамToolStripMenuItem.Click += directoryReportToolStripMenuItem_Click;
//
// движениеОперацийToolStripMenuItem
//
движениеОперацийToolStripMenuItem.Name = "движениеОперацийToolStripMenuItem";
движениеОперацийToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
движениеОперацийToolStripMenuItem.Size = new Size(276, 22);
движениеОперацийToolStripMenuItem.Text = "Движение операций";
движениеОперацийToolStripMenuItem.Click += budgetReportToolStripMenuItem_Click;
//
// движениеТратToolStripMenuItem
//
движениеТратToolStripMenuItem.Name = "движениеТратToolStripMenuItem";
движениеТратToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
движениеТратToolStripMenuItem.Size = new Size(276, 22);
движениеТратToolStripMenuItem.Text = "Движение трат";
движениеТратToolStripMenuItem.Click += expenseReportToolStripMenuItem_Click;
//
// FormFamilyBudget
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = (Image)resources.GetObject("$this.BackgroundImage");
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(799, 512);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormFamilyBudget";
StartPosition = FormStartPosition.CenterScreen;
Text = "FormFamilyBudget";
Load += FormFamilyBudget_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem операцииToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem;
private ToolStripMenuItem FamiliesToolStripMenuItem;
private ToolStripMenuItem участникиСемьиToolStripMenuItem;
private ToolStripMenuItem расходToolStripMenuItem;
private ToolStripMenuItem IncomeToolStripMenuItem;
private ToolStripMenuItem категорияДоходовToolStripMenuItem;
private ToolStripMenuItem категорияРасходовToolStripMenuItem;
private ToolStripMenuItem движениеПоСправочникамToolStripMenuItem;
private ToolStripMenuItem движениеОперацийToolStripMenuItem;
private ToolStripMenuItem движениеТратToolStripMenuItem;
}
}

View File

@ -0,0 +1,130 @@
using FamilyBudget.Forms;
using System.ComponentModel;
using Unity;
namespace FamilyBudget
{
public partial class FormFamilyBudget : Form
{
private readonly IUnityContainer _container;
public FormFamilyBudget(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void FormFamilyBudget_Load(object sender, EventArgs e)
{
}
private void FamiliesToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilies>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FamilyMembers(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilyMembers>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void IncomeToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilyMember_IncomeBudgets>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ExpenseToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilyMember_ExpenseBudgets>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CategoryIncomesToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormIncomeBudgetCategories>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CategoryExpensesToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormExpenseBudgetCategories>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void directoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void budgetReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormBudgetReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void expenseReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormExpenseReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,186 @@
namespace FamilyBudget.Forms
{
partial class FormBudgetReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dateTimePickerStart = new DateTimePicker();
dateTimePickerEnd = new DateTimePicker();
buttonCreate = new Button();
textBoxPath = new TextBox();
button2 = new Button();
comboBoxExpenses = new ComboBox();
comboBoxIncomes = new ComboBox();
label5 = new Label();
label4 = new Label();
label3 = new Label();
label2 = new Label();
label1 = new Label();
SuspendLayout();
//
// dateTimePickerStart
//
dateTimePickerStart.Location = new Point(113, 169);
dateTimePickerStart.Name = "dateTimePickerStart";
dateTimePickerStart.Size = new Size(200, 23);
dateTimePickerStart.TabIndex = 0;
//
// dateTimePickerEnd
//
dateTimePickerEnd.Location = new Point(113, 215);
dateTimePickerEnd.Name = "dateTimePickerEnd";
dateTimePickerEnd.Size = new Size(200, 23);
dateTimePickerEnd.TabIndex = 1;
//
// buttonCreate
//
buttonCreate.Location = new Point(147, 254);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(127, 22);
buttonCreate.TabIndex = 2;
buttonCreate.Text = "сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonMakeReport_Click;
//
// textBoxPath
//
textBoxPath.Location = new Point(113, 42);
textBoxPath.Name = "textBoxPath";
textBoxPath.Size = new Size(171, 23);
textBoxPath.TabIndex = 3;
//
// button2
//
button2.Location = new Point(286, 41);
button2.Name = "button2";
button2.Size = new Size(27, 24);
button2.TabIndex = 4;
button2.Text = "..";
button2.UseVisualStyleBackColor = true;
button2.Click += buttonSelectFilePath_Click;
//
// comboBoxExpenses
//
comboBoxExpenses.FormattingEnabled = true;
comboBoxExpenses.Location = new Point(113, 125);
comboBoxExpenses.Name = "comboBoxExpenses";
comboBoxExpenses.Size = new Size(200, 23);
comboBoxExpenses.TabIndex = 5;
//
// comboBoxIncomes
//
comboBoxIncomes.FormattingEnabled = true;
comboBoxIncomes.Location = new Point(112, 85);
comboBoxIncomes.Name = "comboBoxIncomes";
comboBoxIncomes.Size = new Size(201, 23);
comboBoxIncomes.TabIndex = 6;
//
// label5
//
label5.AutoSize = true;
label5.Location = new Point(20, 215);
label5.Name = "label5";
label5.Size = new Size(68, 15);
label5.TabIndex = 11;
label5.Text = "Дата конца";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(20, 169);
label4.Name = "label4";
label4.Size = new Size(74, 15);
label4.TabIndex = 10;
label4.Text = "Дата начала";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(20, 125);
label3.Name = "label3";
label3.Size = new Size(45, 15);
label3.TabIndex = 9;
label3.Text = "Расход";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(20, 85);
label2.Name = "label2";
label2.Size = new Size(41, 15);
label2.TabIndex = 8;
label2.Text = "Доход";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(20, 42);
label1.Name = "label1";
label1.Size = new Size(87, 15);
label1.TabIndex = 7;
label1.Text = "Путь до файла";
//
// FormBudgetReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(415, 314);
Controls.Add(label5);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(comboBoxIncomes);
Controls.Add(comboBoxExpenses);
Controls.Add(button2);
Controls.Add(textBoxPath);
Controls.Add(buttonCreate);
Controls.Add(dateTimePickerEnd);
Controls.Add(dateTimePickerStart);
Name = "FormBudgetReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчет по движению бюджета";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerStart;
private DateTimePicker dateTimePickerEnd;
private Button buttonCreate;
private TextBox textBoxPath;
private Button button2;
private ComboBox comboBoxExpenses;
private ComboBox comboBoxIncomes;
private Label label5;
private Label label4;
private Label label3;
private Label label2;
private Label label1;
}
}

View File

@ -0,0 +1,86 @@
using FamilyBudget.Reports;
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormBudgetReport : Form
{
private readonly IUnityContainer _container;
public FormBudgetReport(IUnityContainer container, IIncomeBudgetCategoryRepository incomes, IExpenseBudgetCategoryRepository expenses)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxIncomes.DataSource = incomes.ReadIncomeBudgetCategories();
comboBoxIncomes.ValueMember = "Id";
comboBoxIncomes.DisplayMember = "Name";
comboBoxExpenses.DataSource = expenses.ReadExpenseBudgetCategories();
comboBoxExpenses.ValueMember = "Id";
comboBoxExpenses.DisplayMember = "Name";
}
private void buttonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxPath.Text = sfd.FileName;
}
private void buttonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxPath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxIncomes.SelectedIndex < 0 || comboBoxExpenses.SelectedIndex < 0)
{
throw new Exception("Не выбран доход или расход");
}
if (dateTimePickerEnd.Value <= dateTimePickerStart.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxPath.Text, (int)comboBoxIncomes.SelectedValue!,
(int)comboBoxExpenses.SelectedValue!, dateTimePickerStart.Value, dateTimePickerEnd.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,116 @@
namespace FamilyBudget.Forms
{
partial class FormDirectoryReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
checkBoxFamilies = new CheckBox();
checkBoxMembers = new CheckBox();
checkBoxIncomes = new CheckBox();
checkBoxExpenses = new CheckBox();
buttonCreate = new Button();
SuspendLayout();
//
// checkBoxFamilies
//
checkBoxFamilies.AutoSize = true;
checkBoxFamilies.Location = new Point(32, 29);
checkBoxFamilies.Name = "checkBoxFamilies";
checkBoxFamilies.Size = new Size(62, 19);
checkBoxFamilies.TabIndex = 0;
checkBoxFamilies.Text = "Семьи";
checkBoxFamilies.UseVisualStyleBackColor = true;
//
// checkBoxMembers
//
checkBoxMembers.AutoSize = true;
checkBoxMembers.Location = new Point(32, 76);
checkBoxMembers.Name = "checkBoxMembers";
checkBoxMembers.Size = new Size(121, 19);
checkBoxMembers.TabIndex = 1;
checkBoxMembers.Text = "Участники семьи";
checkBoxMembers.UseVisualStyleBackColor = true;
//
// checkBoxIncomes
//
checkBoxIncomes.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
checkBoxIncomes.AutoSize = true;
checkBoxIncomes.Location = new Point(32, 123);
checkBoxIncomes.Name = "checkBoxIncomes";
checkBoxIncomes.Size = new Size(60, 19);
checkBoxIncomes.TabIndex = 2;
checkBoxIncomes.Text = "Доход";
checkBoxIncomes.UseVisualStyleBackColor = true;
//
// checkBoxExpenses
//
checkBoxExpenses.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
checkBoxExpenses.AutoSize = true;
checkBoxExpenses.Location = new Point(32, 175);
checkBoxExpenses.Name = "checkBoxExpenses";
checkBoxExpenses.Size = new Size(64, 19);
checkBoxExpenses.TabIndex = 3;
checkBoxExpenses.Text = "Расход";
checkBoxExpenses.UseVisualStyleBackColor = true;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCreate.Location = new Point(186, 99);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(110, 23);
buttonCreate.TabIndex = 4;
buttonCreate.Text = "сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonBuild_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(318, 230);
Controls.Add(buttonCreate);
Controls.Add(checkBoxExpenses);
Controls.Add(checkBoxIncomes);
Controls.Add(checkBoxMembers);
Controls.Add(checkBoxFamilies);
Name = "FormDirectoryReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Выгрузка справочников";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxFamilies;
private CheckBox checkBoxMembers;
private CheckBox checkBoxIncomes;
private CheckBox checkBoxExpenses;
private Button buttonCreate;
}
}

View File

@ -0,0 +1,60 @@
using FamilyBudget.Reports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxFamilies.Checked &&
!checkBoxMembers.Checked && !checkBoxIncomes.Checked && !checkBoxExpenses.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if
(_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxFamilies.Checked, checkBoxMembers.Checked,
checkBoxExpenses.Checked, checkBoxIncomes.Checked))
{
MessageBox.Show("Документ сформирован", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,126 @@
namespace FamilyBudget.Forms
{
partial class FormExpenseBudgetCategories
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panelEditing = new Panel();
buttonEdit = new Button();
buttonDelete = new Button();
buttonAdd = new Button();
dataGridViewExpanses = new DataGridView();
panelEditing.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewExpanses).BeginInit();
SuspendLayout();
//
// panelEditing
//
panelEditing.Controls.Add(buttonEdit);
panelEditing.Controls.Add(buttonDelete);
panelEditing.Controls.Add(buttonAdd);
panelEditing.Dock = DockStyle.Right;
panelEditing.Location = new Point(544, 0);
panelEditing.Name = "panelEditing";
panelEditing.Size = new Size(126, 404);
panelEditing.TabIndex = 0;
//
// buttonEdit
//
buttonEdit.BackgroundImage = Properties.Resources.free_icon_edit_tools_8847052;
buttonEdit.BackgroundImageLayout = ImageLayout.Stretch;
buttonEdit.Location = new Point(27, 116);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(75, 61);
buttonEdit.TabIndex = 9;
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += buttonEdit_Click;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.free_icon_dustbin_7709786;
buttonDelete.BackgroundImageLayout = ImageLayout.Stretch;
buttonDelete.Location = new Point(27, 208);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 61);
buttonDelete.TabIndex = 7;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.free_icon_plus_181672;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(27, 36);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 61);
buttonAdd.TabIndex = 6;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewExpanses
//
dataGridViewExpanses.AllowUserToAddRows = false;
dataGridViewExpanses.AllowUserToDeleteRows = false;
dataGridViewExpanses.AllowUserToResizeColumns = false;
dataGridViewExpanses.AllowUserToResizeRows = false;
dataGridViewExpanses.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewExpanses.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewExpanses.Dock = DockStyle.Fill;
dataGridViewExpanses.Location = new Point(0, 0);
dataGridViewExpanses.MultiSelect = false;
dataGridViewExpanses.Name = "dataGridViewExpanses";
dataGridViewExpanses.ReadOnly = true;
dataGridViewExpanses.RowHeadersVisible = false;
dataGridViewExpanses.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewExpanses.Size = new Size(544, 404);
dataGridViewExpanses.TabIndex = 1;
//
// FormExpenseBudgetCategories
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(670, 404);
Controls.Add(dataGridViewExpanses);
Controls.Add(panelEditing);
Name = "FormExpenseBudgetCategories";
StartPosition = FormStartPosition.CenterParent;
Text = "Список категории расходов";
Load += FormFamilyMembers_Load;
panelEditing.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewExpanses).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelEditing;
private DataGridView dataGridViewExpanses;
private Button buttonDelete;
private Button buttonAdd;
private Button buttonEdit;
}
}

View File

@ -0,0 +1,133 @@
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormExpenseBudgetCategories : Form
{
private readonly IUnityContainer _container;
private readonly IExpenseBudgetCategoryRepository _expenseBudgetCategoryRepository;
public FormExpenseBudgetCategories(IUnityContainer container, IExpenseBudgetCategoryRepository expenseBudgetCategoryRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_expenseBudgetCategoryRepository = expenseBudgetCategoryRepository ?? throw new ArgumentNullException();
}
private void FormFamilyMembers_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormExpenseBudgetCategory>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormFamilyMember>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_expenseBudgetCategoryRepository.DeleteExpenseBudgetCategory(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewExpanses.DataSource = _expenseBudgetCategoryRepository.ReadExpenseBudgetCategories();
dataGridViewExpanses.Columns["id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewExpanses.Rows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewExpanses.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormExpenseBudgetCategory>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,124 @@
namespace FamilyBudget.Forms
{
partial class FormExpenseBudgetCategory
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
labelCategory = new Label();
textBoxName = new TextBox();
buttonCancel = new Button();
buttonSave = new Button();
checkedListBoxExpenses = new CheckedListBox();
label2 = new Label();
SuspendLayout();
//
// labelCategory
//
labelCategory.Anchor = AnchorStyles.Top;
labelCategory.AutoSize = true;
labelCategory.Location = new Point(25, 30);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(60, 15);
labelCategory.TabIndex = 7;
labelCategory.Text = "название:";
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.None;
textBoxName.Location = new Point(154, 27);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(224, 23);
textBoxName.TabIndex = 6;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(303, 233);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(25, 233);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// checkedListBoxExpenses
//
checkedListBoxExpenses.FormattingEnabled = true;
checkedListBoxExpenses.Location = new Point(154, 73);
checkedListBoxExpenses.Name = "checkedListBoxExpenses";
checkedListBoxExpenses.Size = new Size(224, 130);
checkedListBoxExpenses.TabIndex = 10;
//
// label2
//
label2.Anchor = AnchorStyles.Top;
label2.AutoSize = true;
label2.Location = new Point(25, 73);
label2.Name = "label2";
label2.Size = new Size(120, 15);
label2.TabIndex = 11;
label2.Text = "Категория расходов:";
//
// FormExpenseBudgetCategory
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(404, 280);
Controls.Add(label2);
Controls.Add(checkedListBoxExpenses);
Controls.Add(labelCategory);
Controls.Add(textBoxName);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormExpenseBudgetCategory";
StartPosition = FormStartPosition.CenterParent;
Text = "Категория расходов";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelCategory;
private TextBox textBoxName;
private Button buttonCancel;
private Button buttonSave;
private CheckedListBox checkedListBoxExpenses;
private Label label2;
}
}

View File

@ -0,0 +1,95 @@
using FamilyBudget.Entities;
using FamilyBudget.Entities.Enums;
using FamilyBudget.Repositories;
using FamilyBudget.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormExpenseBudgetCategory : Form
{
private readonly IExpenseBudgetCategoryRepository _expenseBudgetCategoryRepository;
private int? _expenseId;
public int Id
{
set
{
try
{
var expense = _expenseBudgetCategoryRepository.ReadExpenseBudgetCategoryById(value);
if (expense == null)
{
throw new InvalidDataException(nameof(expense));
}
foreach (ExpenseCategoryType elem in Enum.GetValues(typeof(ExpenseCategoryType)))
{
if ((elem & expense.ExpenseCategoryType) != 0)
{
checkedListBoxExpenses.SetItemChecked(checkedListBoxExpenses.Items.IndexOf(
elem), true);
}
}
textBoxName.Text = expense.Name;
_expenseId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получени данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormExpenseBudgetCategory(IExpenseBudgetCategoryRepository expenseBudgetCategoryRepository)
{
InitializeComponent();
_expenseBudgetCategoryRepository = expenseBudgetCategoryRepository ?? throw new ArgumentNullException(nameof(
expenseBudgetCategoryRepository));
foreach (ExpenseCategoryType elem in Enum.GetValues(typeof(ExpenseCategoryType)))
{
checkedListBoxExpenses.Items.Add(elem);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) || checkedListBoxExpenses.CheckedItems.Count == 0)
throw new Exception("Имеются незаполненные поля");
if (_expenseId.HasValue)
_expenseBudgetCategoryRepository.UpdateExpenseBudgetCategoryById(CreateExpenseBudgetCategory(_expenseId.Value));
else
_expenseBudgetCategoryRepository.CreateExpenseBudgetCategory(CreateExpenseBudgetCategory(0));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private ExpenseBudgetCategory CreateExpenseBudgetCategory(int id)
{
ExpenseCategoryType expenseType = ExpenseCategoryType.None;
foreach (ExpenseCategoryType elem in checkedListBoxExpenses.CheckedItems)
{
expenseType |= elem;
}
return ExpenseBudgetCategory.CreateEntity(id, textBoxName.Text, expenseType);
}
}
}

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>

View File

@ -0,0 +1,107 @@
namespace FamilyBudget.Forms
{
partial class FormExpenseReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dateTimePickerExpense = new DateTimePicker();
buttonSelect = new Button();
labelFile = new Label();
buttonSave = new Button();
comboBoxExpenses = new ComboBox();
SuspendLayout();
//
// dateTimePickerExpense
//
dateTimePickerExpense.Location = new Point(27, 82);
dateTimePickerExpense.Name = "dateTimePickerExpense";
dateTimePickerExpense.Size = new Size(200, 23);
dateTimePickerExpense.TabIndex = 0;
//
// buttonSelect
//
buttonSelect.Location = new Point(27, 27);
buttonSelect.Name = "buttonSelect";
buttonSelect.Size = new Size(75, 23);
buttonSelect.TabIndex = 1;
buttonSelect.Text = "Выбрать ";
buttonSelect.UseVisualStyleBackColor = true;
buttonSelect.Click += buttonSelectFile_Click;
//
// labelFile
//
labelFile.AutoSize = true;
labelFile.Location = new Point(151, 31);
labelFile.Name = "labelFile";
labelFile.Size = new Size(36, 15);
labelFile.TabIndex = 2;
labelFile.Text = "Файл";
//
// buttonSave
//
buttonSave.Location = new Point(72, 183);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(105, 23);
buttonSave.TabIndex = 3;
buttonSave.Text = "Сформировать";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonCreate_Click;
//
// comboBoxExpenses
//
comboBoxExpenses.FormattingEnabled = true;
comboBoxExpenses.Location = new Point(27, 130);
comboBoxExpenses.Name = "comboBoxExpenses";
comboBoxExpenses.Size = new Size(200, 23);
comboBoxExpenses.TabIndex = 4;
//
// FormExpenseReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(258, 255);
Controls.Add(comboBoxExpenses);
Controls.Add(buttonSave);
Controls.Add(labelFile);
Controls.Add(buttonSelect);
Controls.Add(dateTimePickerExpense);
Name = "FormExpenseReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Траты";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerExpense;
private Button buttonSelect;
private Label labelFile;
private Button buttonSave;
private ComboBox comboBoxExpenses;
}
}

View File

@ -0,0 +1,77 @@
using FamilyBudget.Reports;
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormExpenseReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormExpenseReport(IUnityContainer container, IExpenseBudgetCategoryRepository expense)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxExpenses.DataSource = expense.ReadExpenseBudgetCategories();
comboBoxExpenses.DisplayMember = "Name";
comboBoxExpenses.ValueMember = "Id";
}
private void buttonSelectFile_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
labelFile.Text = Path.GetFileName(_fileName);
}
}
private void buttonCreate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxExpenses.SelectedIndex < 0)
{
throw new Exception("Не выбран расход");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, (int)comboBoxExpenses.SelectedValue!, dateTimePickerExpense.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,126 @@
namespace FamilyBudget.Forms
{
partial class FormFamilies
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridViewFamilies = new DataGridView();
buttonAdd = new Button();
buttonEdit = new Button();
buttonDelete = new Button();
panel1 = new Panel();
((System.ComponentModel.ISupportInitialize)dataGridViewFamilies).BeginInit();
panel1.SuspendLayout();
SuspendLayout();
//
// dataGridViewFamilies
//
dataGridViewFamilies.AllowUserToAddRows = false;
dataGridViewFamilies.AllowUserToDeleteRows = false;
dataGridViewFamilies.AllowUserToResizeColumns = false;
dataGridViewFamilies.AllowUserToResizeRows = false;
dataGridViewFamilies.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewFamilies.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewFamilies.Dock = DockStyle.Fill;
dataGridViewFamilies.Location = new Point(0, 0);
dataGridViewFamilies.MultiSelect = false;
dataGridViewFamilies.Name = "dataGridViewFamilies";
dataGridViewFamilies.ReadOnly = true;
dataGridViewFamilies.RowHeadersVisible = false;
dataGridViewFamilies.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewFamilies.Size = new Size(765, 432);
dataGridViewFamilies.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.free_icon_plus_181672;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(22, 24);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 61);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonEdit
//
buttonEdit.BackgroundImage = Properties.Resources.free_icon_edit_tools_8847052;
buttonEdit.BackgroundImageLayout = ImageLayout.Stretch;
buttonEdit.Location = new Point(22, 150);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(75, 61);
buttonEdit.TabIndex = 2;
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += ButtonUpd_Click;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.free_icon_dustbin_7709786;
buttonDelete.BackgroundImageLayout = ImageLayout.Stretch;
buttonDelete.Location = new Point(22, 263);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 61);
buttonDelete.TabIndex = 3;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// panel1
//
panel1.Controls.Add(buttonEdit);
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(651, 0);
panel1.Name = "panel1";
panel1.Size = new Size(114, 432);
panel1.TabIndex = 4;
//
// FormFamilies
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(765, 432);
Controls.Add(panel1);
Controls.Add(dataGridViewFamilies);
Name = "FormFamilies";
StartPosition = FormStartPosition.CenterParent;
Text = "Список семей";
Load += FormFamiliesLoad;
((System.ComponentModel.ISupportInitialize)dataGridViewFamilies).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewFamilies;
private Button buttonAdd;
private Button buttonEdit;
private Button buttonDelete;
private Panel panel1;
}
}

View File

@ -0,0 +1,113 @@
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormFamilies : Form
{
private readonly IUnityContainer _container;
private readonly IFamilyRepository _familyRepository;
public FormFamilies(IUnityContainer container, IFamilyRepository familyRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_familyRepository = familyRepository ?? throw new ArgumentNullException(nameof(familyRepository));
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamily>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormFamiliesLoad(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormFamily>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_familyRepository.DeleteFamily(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewFamilies.DataSource = _familyRepository.ReadFamilies();
dataGridViewFamilies.Columns["id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewFamilies.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewFamilies.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
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.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->

View File

@ -0,0 +1,100 @@
namespace FamilyBudget.Forms
{
partial class FormFamily
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
textBoxFamily = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
labelFamily = new Label();
SuspendLayout();
//
// textBoxFamily
//
textBoxFamily.Anchor = AnchorStyles.Top;
textBoxFamily.Location = new Point(131, 41);
textBoxFamily.Name = "textBoxFamily";
textBoxFamily.Size = new Size(153, 23);
textBoxFamily.TabIndex = 0;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(43, 112);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 1;
buttonSave.Text = "сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(220, 112);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 2;
buttonCancel.Text = "отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// labelFamily
//
labelFamily.Anchor = AnchorStyles.Top;
labelFamily.AutoSize = true;
labelFamily.Location = new Point(57, 44);
labelFamily.Name = "labelFamily";
labelFamily.Size = new Size(61, 15);
labelFamily.TabIndex = 3;
labelFamily.Text = "Фамилия:";
//
// FormFamily
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(343, 170);
Controls.Add(labelFamily);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxFamily);
Name = "FormFamily";
StartPosition = FormStartPosition.CenterParent;
Text = "Семья";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxFamily;
private Button buttonSave;
private Button buttonCancel;
private Label labelFamily;
}
}

View File

@ -0,0 +1,73 @@
using FamilyBudget.Entities;
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FamilyBudget.Forms
{
public partial class FormFamily : Form
{
private readonly IFamilyRepository _familyRepository;
private int? _familyId;
public int Id
{
set
{
try
{
var family = _familyRepository.ReadFamilyById(value);
if (family == null)
{
throw new InvalidDataException(nameof(family));
}
textBoxFamily.Text = family.Name;
_familyId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.
Error);
return;
}
}
}
public FormFamily(IFamilyRepository familyRepository)
{
InitializeComponent();
_familyRepository = familyRepository ?? throw new ArgumentNullException(nameof(familyRepository));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFamily.Text)) throw new Exception("Имеются незаполненные поля");
if (_familyId.HasValue)
{
_familyRepository.UpdateFamily(CreateFamily(_familyId.Value));
}
else
{
_familyRepository.CreateFamily(CreateFamily(0));
}
Close(); }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Family CreateFamily(int id) => Family.CreateEntity(id, textBoxFamily.Text);
}
}

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>

View File

@ -0,0 +1,148 @@
namespace FamilyBudget.Forms
{
partial class FormFamilyMember
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
labelName = new Label();
textBoxName = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
comboBoxFamily = new ComboBox();
labelFamily = new Label();
comboBoxFamilyMember = new ComboBox();
labelMember = new Label();
SuspendLayout();
//
// labelName
//
labelName.Anchor = AnchorStyles.Top;
labelName.AutoSize = true;
labelName.Location = new Point(77, 61);
labelName.Name = "labelName";
labelName.Size = new Size(34, 15);
labelName.TabIndex = 0;
labelName.Text = "Имя:";
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top;
textBoxName.Location = new Point(123, 53);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(215, 23);
textBoxName.TabIndex = 1;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(59, 269);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 2;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(246, 269);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// comboBoxFamily
//
comboBoxFamily.FormattingEnabled = true;
comboBoxFamily.Location = new Point(123, 106);
comboBoxFamily.Name = "comboBoxFamily";
comboBoxFamily.Size = new Size(215, 23);
comboBoxFamily.TabIndex = 4;
//
// labelFamily
//
labelFamily.Anchor = AnchorStyles.Top;
labelFamily.AutoSize = true;
labelFamily.Location = new Point(66, 109);
labelFamily.Name = "labelFamily";
labelFamily.Size = new Size(45, 15);
labelFamily.TabIndex = 5;
labelFamily.Text = "Семья:";
//
// comboBoxFamilyMember
//
comboBoxFamilyMember.FormattingEnabled = true;
comboBoxFamilyMember.Location = new Point(123, 160);
comboBoxFamilyMember.Name = "comboBoxFamilyMember";
comboBoxFamilyMember.Size = new Size(215, 23);
comboBoxFamilyMember.TabIndex = 6;
//
// labelMember
//
labelMember.Anchor = AnchorStyles.Top;
labelMember.AutoSize = true;
labelMember.Location = new Point(17, 163);
labelMember.Name = "labelMember";
labelMember.Size = new Size(98, 15);
labelMember.TabIndex = 7;
labelMember.Text = "Участник семьи:";
//
// FormFamilyMember
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(387, 337);
Controls.Add(labelMember);
Controls.Add(comboBoxFamilyMember);
Controls.Add(labelFamily);
Controls.Add(comboBoxFamily);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxName);
Controls.Add(labelName);
Name = "FormFamilyMember";
StartPosition = FormStartPosition.CenterParent;
Text = "Участник семьи";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private TextBox textBoxName;
private Button buttonSave;
private Button buttonCancel;
private ComboBox comboBoxFamily;
private Label labelFamily;
private ComboBox comboBoxFamilyMember;
private Label labelMember;
}
}

View File

@ -0,0 +1,84 @@
using FamilyBudget.Entities;
using FamilyBudget.Entities.Enums;
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FamilyBudget.Forms
{
public partial class FormFamilyMember : Form
{
private readonly IFamilyMemberRepository _familyMemberRepository;
private readonly IFamilyRepository _familyRepository;
private int? _familyMemberId;
public int Id
{
set
{
try
{
var familyMember = _familyMemberRepository.ReadFamilyMemberById(value);
if (familyMember == null)
{
throw new InvalidDataException(nameof(familyMember));
}
comboBoxFamily.SelectedValue = familyMember.FamilyId;
comboBoxFamilyMember.SelectedItem = familyMember.MemberType;
textBoxName.Text = familyMember.Name;
_familyMemberId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.
Error);
return;
}
}
}
public FormFamilyMember(IFamilyMemberRepository familyMemberRepository, IFamilyRepository familyRepository)
{
InitializeComponent();
_familyMemberRepository = familyMemberRepository ?? throw new ArgumentNullException(nameof(
familyMemberRepository));
_familyRepository = familyRepository ?? throw new ArgumentNullException(nameof(
familyRepository));
comboBoxFamilyMember.DataSource = Enum.GetValues(typeof(FamilyMemberType));
comboBoxFamily.DataSource = _familyRepository.ReadFamilies();
comboBoxFamily.DisplayMember = "Name";
comboBoxFamily.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxFamily.SelectedIndex < 0 || comboBoxFamilyMember.SelectedIndex < 0)
throw new Exception("Имеются незаполненные поля");
if (_familyMemberId.HasValue)
_familyMemberRepository.UpdateFamilyMember(CreateFamilyMember(_familyMemberId.Value));
else
_familyMemberRepository.CreateFamilyMember(CreateFamilyMember(0));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private FamilyMember CreateFamilyMember(int id) => FamilyMember.CreateEntity(id, textBoxName.Text, (int)comboBoxFamily.SelectedValue!, (FamilyMemberType)comboBoxFamilyMember.SelectedItem!);
}
}

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>

View File

@ -0,0 +1,176 @@
namespace FamilyBudget.Forms
{
partial class FormFamilyMember_ExpenseBudget
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
comboBoxFamilyMember = new ComboBox();
buttonCancel = new Button();
buttonSave = new Button();
labelDate = new Label();
labelFamilyMember = new Label();
dateTimePicker1 = new DateTimePicker();
groupBox1 = new GroupBox();
dataGridView = new DataGridView();
ColumnExpanseName = new DataGridViewComboBoxColumn();
ColumnSum = new DataGridViewTextBoxColumn();
groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// comboBoxFamilyMember
//
comboBoxFamilyMember.Anchor = AnchorStyles.Top;
comboBoxFamilyMember.FormattingEnabled = true;
comboBoxFamilyMember.Location = new Point(175, 82);
comboBoxFamilyMember.Name = "comboBoxFamilyMember";
comboBoxFamilyMember.Size = new Size(164, 23);
comboBoxFamilyMember.TabIndex = 21;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(312, 450);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 20;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(28, 450);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 19;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// labelDate
//
labelDate.Anchor = AnchorStyles.Top;
labelDate.AutoSize = true;
labelDate.Location = new Point(71, 35);
labelDate.Name = "labelDate";
labelDate.Size = new Size(41, 15);
labelDate.TabIndex = 18;
labelDate.Text = "Дата: ";
//
// labelFamilyMember
//
labelFamilyMember.Anchor = AnchorStyles.Top;
labelFamilyMember.AutoSize = true;
labelFamilyMember.Location = new Point(61, 82);
labelFamilyMember.Name = "labelFamilyMember";
labelFamilyMember.Size = new Size(101, 15);
labelFamilyMember.TabIndex = 17;
labelFamilyMember.Text = "Участник семьи: ";
//
// dateTimePicker1
//
dateTimePicker1.Anchor = AnchorStyles.Top;
dateTimePicker1.Enabled = false;
dateTimePicker1.Location = new Point(175, 35);
dateTimePicker1.Name = "dateTimePicker1";
dateTimePicker1.Size = new Size(164, 23);
dateTimePicker1.TabIndex = 14;
//
// groupBox1
//
groupBox1.Controls.Add(dataGridView);
groupBox1.Location = new Point(28, 123);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(359, 308);
groupBox1.TabIndex = 22;
groupBox1.TabStop = false;
groupBox1.Text = "Траты";
//
// dataGridView
//
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnExpanseName, ColumnSum });
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(3, 19);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(353, 286);
dataGridView.TabIndex = 0;
//
// ColumnExpanseName
//
ColumnExpanseName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnExpanseName.HeaderText = "Название";
ColumnExpanseName.Name = "ColumnExpanseName";
//
// ColumnSum
//
ColumnSum.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnSum.HeaderText = "Сумма";
ColumnSum.Name = "ColumnSum";
//
// FormFamilyMember_ExpenseBudget
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(430, 500);
Controls.Add(groupBox1);
Controls.Add(comboBoxFamilyMember);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelDate);
Controls.Add(labelFamilyMember);
Controls.Add(dateTimePicker1);
Name = "FormFamilyMember_ExpenseBudget";
StartPosition = FormStartPosition.CenterParent;
Text = "Добавление расхода";
groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox comboBoxFamilyMember;
private Button buttonCancel;
private Button buttonSave;
private Label labelDate;
private Label labelFamilyMember;
private DateTimePicker dateTimePicker1;
private GroupBox groupBox1;
private DataGridView dataGridView;
private DataGridViewComboBoxColumn ColumnExpanseName;
private DataGridViewTextBoxColumn ColumnSum;
}
}

View File

@ -0,0 +1,69 @@
using FamilyBudget.Entities;
using FamilyBudget.Repositories;
using FamilyBudget.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FamilyBudget.Forms
{
public partial class FormFamilyMember_ExpenseBudget : Form
{
private readonly IExpenseBudgetRepository _expenseBudgetRepository;
public FormFamilyMember_ExpenseBudget(IExpenseBudgetRepository
expenseBudgetRepository, IFamilyMemberRepository familyMemberRepository, IExpenseBudgetCategoryRepository expenses)
{
InitializeComponent();
_expenseBudgetRepository = expenseBudgetRepository ?? throw new ArgumentNullException(nameof(
expenseBudgetRepository));
comboBoxFamilyMember.DataSource = familyMemberRepository.ReadFamilyMembers();
comboBoxFamilyMember.DisplayMember = "FullName";
comboBoxFamilyMember.ValueMember = "Id";
ColumnExpanseName.DataSource = expenses.ReadExpenseBudgetCategories();
ColumnExpanseName.DisplayMember = "Name";
ColumnExpanseName.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (dataGridView.RowCount < 1 || comboBoxFamilyMember.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
_expenseBudgetRepository.CreateExpenseBudget(ExpenseBudget.СreateOperation(0, (int)comboBoxFamilyMember.SelectedValue!,
CreateListExpenseBudgetFromGrid()));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<FamilyMember_ExpenseBudget> CreateListExpenseBudgetFromGrid()
{
var list = new List<FamilyMember_ExpenseBudget>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["ColumnExpanseName"].Value == null || row.Cells["ColumnSum"].Value == null)
{
continue;
}
list.Add(FamilyMember_ExpenseBudget.CreateElement(0, Convert.ToInt32(row.Cells["ColumnExpanseName"].Value), Convert.ToInt32(row.Cells["ColumnExpanseName"].Value)
, Convert.ToInt32(row.Cells["ColumnSum"].Value)));
}
return list.GroupBy(x => x.ExpenseBudgetId, x => x.Sum, (id, counts) =>
FamilyMember_ExpenseBudget.CreateElement(0, id, 0, counts.Sum())).ToList();
}
}
}

View File

@ -0,0 +1,126 @@
<?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>
<metadata name="ColumnExpanseName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSum.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,112 @@
namespace FamilyBudget.Forms
{
partial class FormFamilyMember_ExpenseBudgets
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panel1 = new Panel();
buttonDelete = new Button();
buttonAdd = new Button();
dataGridViewExpenses = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewExpenses).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(693, 0);
panel1.Name = "panel1";
panel1.Size = new Size(107, 450);
panel1.TabIndex = 0;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.free_icon_dustbin_7709786;
buttonDelete.BackgroundImageLayout = ImageLayout.Stretch;
buttonDelete.Location = new Point(20, 234);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 61);
buttonDelete.TabIndex = 4;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.free_icon_plus_181672;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(20, 46);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 61);
buttonAdd.TabIndex = 3;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewExpenses
//
dataGridViewExpenses.AllowUserToAddRows = false;
dataGridViewExpenses.AllowUserToDeleteRows = false;
dataGridViewExpenses.AllowUserToResizeColumns = false;
dataGridViewExpenses.AllowUserToResizeRows = false;
dataGridViewExpenses.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewExpenses.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewExpenses.Dock = DockStyle.Fill;
dataGridViewExpenses.Location = new Point(0, 0);
dataGridViewExpenses.MultiSelect = false;
dataGridViewExpenses.Name = "dataGridViewExpenses";
dataGridViewExpenses.ReadOnly = true;
dataGridViewExpenses.RowHeadersVisible = false;
dataGridViewExpenses.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewExpenses.Size = new Size(693, 450);
dataGridViewExpenses.TabIndex = 1;
//
// FormFamilyMember_ExpenseBudgets
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewExpenses);
Controls.Add(panel1);
Name = "FormFamilyMember_ExpenseBudgets";
StartPosition = FormStartPosition.CenterParent;
Text = "Список добавления расходов";
Load += FormMemberExpenseBudgetLoad;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewExpenses).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private DataGridView dataGridViewExpenses;
private Button buttonDelete;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,110 @@
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormFamilyMember_ExpenseBudgets : Form
{
private readonly IUnityContainer _container;
private readonly IExpenseBudgetRepository _expenseBudgetRepository;
public FormFamilyMember_ExpenseBudgets(IUnityContainer container, IExpenseBudgetRepository expenseBudgetRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_expenseBudgetRepository = expenseBudgetRepository ?? throw new ArgumentNullException();
}
private void FormFamilyMembers_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilyMember_ExpenseBudget>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_expenseBudgetRepository.DeleteExpenseBudget(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewExpenses.DataSource = _expenseBudgetRepository.ReadExpenseBudgets();
dataGridViewExpenses.Columns["id"].Visible = false;
dataGridViewExpenses.Columns["date"].DefaultCellStyle.Format = "dd MMMM yyyy";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewExpenses.Rows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewExpenses.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void FormMemberExpenseBudgetLoad(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,174 @@
namespace FamilyBudget.Forms
{
partial class FormFamilyMember_IncomeBudget
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dateTimePicker1 = new DateTimePicker();
labelFamilyMember = new Label();
labelDate = new Label();
buttonSave = new Button();
buttonCancel = new Button();
comboBoxFamilyMember = new ComboBox();
dataGridView = new DataGridView();
ColumnIncomeName = new DataGridViewComboBoxColumn();
ColumnSum = new DataGridViewTextBoxColumn();
groupBox1 = new GroupBox();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
groupBox1.SuspendLayout();
SuspendLayout();
//
// dateTimePicker1
//
dateTimePicker1.Anchor = AnchorStyles.Top;
dateTimePicker1.Enabled = false;
dateTimePicker1.Location = new Point(151, 35);
dateTimePicker1.Name = "dateTimePicker1";
dateTimePicker1.Size = new Size(164, 23);
dateTimePicker1.TabIndex = 2;
//
// labelFamilyMember
//
labelFamilyMember.Anchor = AnchorStyles.Top;
labelFamilyMember.AutoSize = true;
labelFamilyMember.Location = new Point(20, 90);
labelFamilyMember.Name = "labelFamilyMember";
labelFamilyMember.Size = new Size(101, 15);
labelFamilyMember.TabIndex = 6;
labelFamilyMember.Text = "Участник семьи: ";
//
// labelDate
//
labelDate.Anchor = AnchorStyles.Top;
labelDate.AutoSize = true;
labelDate.Location = new Point(30, 35);
labelDate.Name = "labelDate";
labelDate.Size = new Size(41, 15);
labelDate.TabIndex = 8;
labelDate.Text = "Дата: ";
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(43, 491);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 9;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(276, 491);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 10;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// comboBoxFamilyMember
//
comboBoxFamilyMember.Anchor = AnchorStyles.Top;
comboBoxFamilyMember.FormattingEnabled = true;
comboBoxFamilyMember.Location = new Point(151, 82);
comboBoxFamilyMember.Name = "comboBoxFamilyMember";
comboBoxFamilyMember.Size = new Size(164, 23);
comboBoxFamilyMember.TabIndex = 11;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnIncomeName, ColumnSum });
dataGridView.Location = new Point(6, 22);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(349, 311);
dataGridView.TabIndex = 12;
//
// ColumnIncomeName
//
ColumnIncomeName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnIncomeName.HeaderText = "Название";
ColumnIncomeName.Name = "ColumnIncomeName";
ColumnIncomeName.Resizable = DataGridViewTriState.True;
ColumnIncomeName.SortMode = DataGridViewColumnSortMode.Automatic;
//
// ColumnSum
//
ColumnSum.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnSum.HeaderText = "Сумма";
ColumnSum.Name = "ColumnSum";
//
// groupBox1
//
groupBox1.Controls.Add(dataGridView);
groupBox1.Location = new Point(30, 123);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(361, 339);
groupBox1.TabIndex = 13;
groupBox1.TabStop = false;
groupBox1.Text = "Доходы";
//
// FormFamilyMember_IncomeBudget
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(403, 526);
Controls.Add(groupBox1);
Controls.Add(comboBoxFamilyMember);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelDate);
Controls.Add(labelFamilyMember);
Controls.Add(dateTimePicker1);
Name = "FormFamilyMember_IncomeBudget";
StartPosition = FormStartPosition.CenterParent;
Text = "Доход";
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
groupBox1.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePicker1;
private Label labelFamilyMember;
private Label labelDate;
private Button buttonSave;
private Button buttonCancel;
private ComboBox comboBoxFamilyMember;
private DataGridView dataGridView;
private GroupBox groupBox1;
private DataGridViewComboBoxColumn ColumnIncomeName;
private DataGridViewTextBoxColumn ColumnSum;
}
}

View File

@ -0,0 +1,69 @@
using FamilyBudget.Entities;
using FamilyBudget.Repositories;
using FamilyBudget.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FamilyBudget.Forms
{
public partial class FormFamilyMember_IncomeBudget : Form
{
private readonly IIncomeBudgetRepository _incomeBudgetRepository;
public FormFamilyMember_IncomeBudget(IIncomeBudgetRepository
incomeBudgetRepository, IFamilyMemberRepository familyMemberRepository, IIncomeBudgetCategoryRepository incomes)
{
InitializeComponent();
_incomeBudgetRepository = incomeBudgetRepository ?? throw new ArgumentNullException(nameof(
incomeBudgetRepository));
comboBoxFamilyMember.DataSource = familyMemberRepository.ReadFamilyMembers();
comboBoxFamilyMember.DisplayMember = "FullName";
comboBoxFamilyMember.ValueMember = "Id";
ColumnIncomeName.DataSource = incomes.ReadIncomeBudgetCategories();
ColumnIncomeName.DisplayMember = "Name";
ColumnIncomeName.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (dataGridView.RowCount < 1 || comboBoxFamilyMember.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
_incomeBudgetRepository.CreateIncomeBudget(IncomeBudget.CreateOperation(0, (int)comboBoxFamilyMember.SelectedValue!,
CreateListIncomeBudgetFromGrid()));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<FamilyMember_IncomeBudget> CreateListIncomeBudgetFromGrid()
{
var list = new List<FamilyMember_IncomeBudget>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["ColumnIncomeName"].Value == null || row.Cells["ColumnSum"].Value == null)
{
continue;
}
list.Add(FamilyMember_IncomeBudget.CreateElement(0, Convert.ToInt32(row.Cells["ColumnIncomeName"].Value), Convert.ToInt32(row.Cells["ColumnIncomeName"].Value)
, Convert.ToInt32(row.Cells["ColumnSum"].Value)));
}
return list.GroupBy(x => x.IncomeBudgetId, x => x.Sum, (id, counts) =>
FamilyMember_IncomeBudget.CreateElement(0, id, 0, counts.Sum())).ToList();
}
}
}

View File

@ -0,0 +1,126 @@
<?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>
<metadata name="ColumnIncomeName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSum.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,113 @@
namespace FamilyBudget.Forms
{
partial class FormFamilyMember_IncomeBudgets
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panel1 = new Panel();
button2 = new Button();
buttonAdd = new Button();
dataGridViewIncomes = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewIncomes).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(button2);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(679, 0);
panel1.Name = "panel1";
panel1.Size = new Size(121, 450);
panel1.TabIndex = 0;
//
// button2
//
button2.BackgroundImage = Properties.Resources.free_icon_dustbin_7709786;
button2.BackgroundImageLayout = ImageLayout.Stretch;
button2.Location = new Point(30, 230);
button2.Name = "button2";
button2.Size = new Size(75, 61);
button2.TabIndex = 2;
button2.UseVisualStyleBackColor = true;
button2.Click += ButtonDelete_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.free_icon_plus_181672;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(30, 29);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 61);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewIncomes
//
dataGridViewIncomes.AllowUserToAddRows = false;
dataGridViewIncomes.AllowUserToDeleteRows = false;
dataGridViewIncomes.AllowUserToResizeColumns = false;
dataGridViewIncomes.AllowUserToResizeRows = false;
dataGridViewIncomes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewIncomes.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewIncomes.Dock = DockStyle.Fill;
dataGridViewIncomes.Location = new Point(0, 0);
dataGridViewIncomes.MultiSelect = false;
dataGridViewIncomes.Name = "dataGridViewIncomes";
dataGridViewIncomes.ReadOnly = true;
dataGridViewIncomes.RowHeadersVisible = false;
dataGridViewIncomes.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewIncomes.Size = new Size(679, 450);
dataGridViewIncomes.TabIndex = 1;
//
// FormFamilyMember_IncomeBudgets
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewIncomes);
Controls.Add(panel1);
Name = "FormFamilyMember_IncomeBudgets";
StartPosition = FormStartPosition.CenterParent;
Text = "Список добавления доходов";
Load += FormFamilyMembersIncome_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewIncomes).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button button2;
private Button button1;
private Button buttonAdd;
private DataGridView dataGridViewIncomes;
}
}

View File

@ -0,0 +1,96 @@
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormFamilyMember_IncomeBudgets : Form
{
private readonly IUnityContainer _container;
private readonly IIncomeBudgetRepository _incomeBudgetRepository;
public FormFamilyMember_IncomeBudgets(IUnityContainer container, IIncomeBudgetRepository incomeBudgetRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_incomeBudgetRepository = incomeBudgetRepository ?? throw new ArgumentNullException();
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilyMember_IncomeBudget>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_incomeBudgetRepository.DeleteIncomeBudget(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewIncomes.DataSource = _incomeBudgetRepository.ReadIncomeBudgets();
dataGridViewIncomes.Columns["id"].Visible = false;
dataGridViewIncomes.Columns["date"].DefaultCellStyle.Format = "dd MMMM yyyy";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewIncomes.Rows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewIncomes.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void FormFamilyMembersIncome_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,126 @@
namespace FamilyBudget.Forms
{
partial class FormFamilyMembers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridViewFamilyMembers = new DataGridView();
panel1 = new Panel();
buttonDelete = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewFamilyMembers).BeginInit();
panel1.SuspendLayout();
SuspendLayout();
//
// dataGridViewFamilyMembers
//
dataGridViewFamilyMembers.AllowUserToAddRows = false;
dataGridViewFamilyMembers.AllowUserToDeleteRows = false;
dataGridViewFamilyMembers.AllowUserToResizeColumns = false;
dataGridViewFamilyMembers.AllowUserToResizeRows = false;
dataGridViewFamilyMembers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewFamilyMembers.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewFamilyMembers.Dock = DockStyle.Fill;
dataGridViewFamilyMembers.Location = new Point(0, 0);
dataGridViewFamilyMembers.MultiSelect = false;
dataGridViewFamilyMembers.Name = "dataGridViewFamilyMembers";
dataGridViewFamilyMembers.ReadOnly = true;
dataGridViewFamilyMembers.RowHeadersVisible = false;
dataGridViewFamilyMembers.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewFamilyMembers.Size = new Size(800, 450);
dataGridViewFamilyMembers.TabIndex = 0;
//
// panel1
//
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonUpdate);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(704, 0);
panel1.Name = "panel1";
panel1.Size = new Size(96, 450);
panel1.TabIndex = 1;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.free_icon_dustbin_7709786;
buttonDelete.BackgroundImageLayout = ImageLayout.Stretch;
buttonDelete.Location = new Point(9, 259);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 61);
buttonDelete.TabIndex = 2;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonUpdate
//
buttonUpdate.BackgroundImage = Properties.Resources.free_icon_edit_tools_8847052;
buttonUpdate.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpdate.Location = new Point(9, 143);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(75, 61);
buttonUpdate.TabIndex = 1;
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.free_icon_plus_181672;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(9, 35);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 61);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormFamilyMembers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(panel1);
Controls.Add(dataGridViewFamilyMembers);
Name = "FormFamilyMembers";
StartPosition = FormStartPosition.CenterParent;
Text = "Список участников семьи";
Load += FormFamilyMembers_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewFamilyMembers).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewFamilyMembers;
private Panel panel1;
private Button buttonAdd;
private Button buttonDelete;
private Button buttonUpdate;
}
}

View File

@ -0,0 +1,113 @@
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormFamilyMembers : Form
{
private readonly IUnityContainer _container;
private readonly IFamilyMemberRepository _familyMemberRepository;
public FormFamilyMembers(IUnityContainer container, IFamilyMemberRepository familyMemberRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_familyMemberRepository = familyMemberRepository ?? throw new ArgumentNullException();
}
private void FormFamilyMembers_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFamilyMember>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormFamilyMember>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_familyMemberRepository.DeleteFamilyMember(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewFamilyMembers.DataSource = _familyMemberRepository.ReadFamilyMembers();
dataGridViewFamilyMembers.Columns["id"].Visible = false;
dataGridViewFamilyMembers.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewFamilyMembers.Rows.Count < 1) {
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewFamilyMembers.SelectedRows[id].Cells["Id"].Value);
return true;
}
}
}

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>

View File

@ -0,0 +1,126 @@
namespace FamilyBudget.Forms
{
partial class FormIncomeBudgetCategories
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panel1 = new Panel();
buttonEdit = new Button();
buttonDelete = new Button();
buttonAdd = new Button();
dataGridViewIncomes = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewIncomes).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonEdit);
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(664, 0);
panel1.Name = "panel1";
panel1.Size = new Size(136, 450);
panel1.TabIndex = 0;
//
// buttonEdit
//
buttonEdit.BackgroundImage = Properties.Resources.free_icon_edit_tools_8847052;
buttonEdit.BackgroundImageLayout = ImageLayout.Stretch;
buttonEdit.Location = new Point(34, 106);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(75, 61);
buttonEdit.TabIndex = 10;
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += buttonEdit_Click;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.free_icon_dustbin_7709786;
buttonDelete.BackgroundImageLayout = ImageLayout.Stretch;
buttonDelete.Location = new Point(34, 190);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(75, 61);
buttonDelete.TabIndex = 5;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.free_icon_plus_181672;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(34, 26);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(75, 61);
buttonAdd.TabIndex = 3;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewIncomes
//
dataGridViewIncomes.AllowUserToAddRows = false;
dataGridViewIncomes.AllowUserToDeleteRows = false;
dataGridViewIncomes.AllowUserToResizeColumns = false;
dataGridViewIncomes.AllowUserToResizeRows = false;
dataGridViewIncomes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewIncomes.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewIncomes.Dock = DockStyle.Fill;
dataGridViewIncomes.Location = new Point(0, 0);
dataGridViewIncomes.MultiSelect = false;
dataGridViewIncomes.Name = "dataGridViewIncomes";
dataGridViewIncomes.ReadOnly = true;
dataGridViewIncomes.RowHeadersVisible = false;
dataGridViewIncomes.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewIncomes.Size = new Size(664, 450);
dataGridViewIncomes.TabIndex = 1;
//
// FormIncomeBudgetCategories
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewIncomes);
Controls.Add(panel1);
Name = "FormIncomeBudgetCategories";
StartPosition = FormStartPosition.CenterParent;
Text = "Список категорий доходов";
Load += FormFamilyMembers_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewIncomes).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private DataGridView dataGridViewIncomes;
private Button buttonDelete;
private Button buttonAdd;
private Button buttonEdit;
}
}

View File

@ -0,0 +1,133 @@
using FamilyBudget.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormIncomeBudgetCategories : Form
{
private readonly IUnityContainer _container;
private readonly IIncomeBudgetCategoryRepository _incomeBudgetCategoryRepository;
public FormIncomeBudgetCategories(IUnityContainer container, IIncomeBudgetCategoryRepository incomeBudgetCategoryRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_incomeBudgetCategoryRepository = incomeBudgetCategoryRepository ?? throw new ArgumentNullException();
}
private void FormFamilyMembers_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormIncomeBudgetCategory>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormIncomeBudgetCategory>();
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_incomeBudgetCategoryRepository.DeleteIncomeBudgetCategory(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewIncomes.DataSource = _incomeBudgetCategoryRepository.ReadIncomeBudgetCategories();
dataGridViewIncomes.Columns["id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewIncomes.Rows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewIncomes.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormIncomeBudgetCategory>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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>

View File

@ -0,0 +1,124 @@
namespace FamilyBudget.Forms
{
partial class FormIncomeBudgetCategory
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonSave = new Button();
buttonCancel = new Button();
textBoxName = new TextBox();
labelCategory = new Label();
label1 = new Label();
checkedListBoxIncomes = new CheckedListBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(36, 253);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(320, 253);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top;
textBoxName.Location = new Point(171, 21);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(224, 23);
textBoxName.TabIndex = 2;
//
// labelCategory
//
labelCategory.Anchor = AnchorStyles.Top;
labelCategory.AutoSize = true;
labelCategory.Location = new Point(36, 24);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(60, 15);
labelCategory.TabIndex = 3;
labelCategory.Text = "название:";
//
// label1
//
label1.Anchor = AnchorStyles.Top;
label1.AutoSize = true;
label1.Location = new Point(36, 63);
label1.Name = "label1";
label1.Size = new Size(115, 15);
label1.TabIndex = 4;
label1.Text = "Категории доходов:";
//
// checkedListBoxIncomes
//
checkedListBoxIncomes.FormattingEnabled = true;
checkedListBoxIncomes.Location = new Point(171, 63);
checkedListBoxIncomes.Name = "checkedListBoxIncomes";
checkedListBoxIncomes.Size = new Size(224, 148);
checkedListBoxIncomes.TabIndex = 5;
//
// FormIncomeBudgetCategory
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(429, 299);
Controls.Add(checkedListBoxIncomes);
Controls.Add(label1);
Controls.Add(labelCategory);
Controls.Add(textBoxName);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormIncomeBudgetCategory";
StartPosition = FormStartPosition.CenterParent;
Text = "Категория дохода";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxName;
private Label labelCategory;
private Label label1;
private CheckedListBox checkedListBoxIncomes;
}
}

View File

@ -0,0 +1,95 @@
using FamilyBudget.Entities;
using FamilyBudget.Entities.Enums;
using FamilyBudget.Repositories;
using FamilyBudget.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace FamilyBudget.Forms
{
public partial class FormIncomeBudgetCategory : Form
{
private readonly IIncomeBudgetCategoryRepository _incomeBudgetCategoryRepository;
private int? _incomeId;
public int Id
{
set
{
try
{
var income = _incomeBudgetCategoryRepository.ReadIncomeBudgetCategoryById(value);
if (income == null)
{
throw new InvalidDataException(nameof(income));
}
foreach (IncomeCategoryType elem in Enum.GetValues(typeof(IncomeCategoryType)))
{
if ((elem & income.IncomeCategoryType) != 0)
{
checkedListBoxIncomes.SetItemChecked(checkedListBoxIncomes.Items.IndexOf(
elem), true);
}
}
textBoxName.Text = income.Name;
_incomeId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получени данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormIncomeBudgetCategory(IIncomeBudgetCategoryRepository incomeBudgetCategoryRepository)
{
InitializeComponent();
_incomeBudgetCategoryRepository = incomeBudgetCategoryRepository ?? throw new ArgumentNullException(nameof(
incomeBudgetCategoryRepository));
foreach (IncomeCategoryType elem in Enum.GetValues(typeof(IncomeCategoryType)))
{
checkedListBoxIncomes.Items.Add(elem);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) || checkedListBoxIncomes.CheckedItems.Count == 0)
throw new Exception("Имеются незаполненные поля");
if (_incomeId.HasValue)
_incomeBudgetCategoryRepository.UpdateExpenseBudgetCategoryById(CreateIncomeBudgetCategory(_incomeId.Value));
else
_incomeBudgetCategoryRepository.CreateIncomeBudgetCategory(CreateIncomeBudgetCategory(0));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private IncomeBudgetCategory CreateIncomeBudgetCategory(int id)
{
IncomeCategoryType incomeType = IncomeCategoryType.None;
foreach (IncomeCategoryType elem in checkedListBoxIncomes.CheckedItems)
{
incomeType |= elem;
}
return IncomeBudgetCategory.CreateEntity(id, textBoxName.Text, incomeType);
}
}
}

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>

View File

@ -1,3 +1,12 @@
using FamilyBudget.Repositories;
using FamilyBudget.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace FamilyBudget namespace FamilyBudget
{ {
internal static class Program internal static class Program
@ -11,7 +20,38 @@ namespace FamilyBudget
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new Form1()); Application.Run(CreateContainer().Resolve<FormFamilyBudget>());
}
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IFamilyRepository, FamilyRepository>(new TransientLifetimeManager());
container.RegisterType<IFamilyMemberRepository, FamilyMemberRepository>(new TransientLifetimeManager());
container.RegisterType<IExpenseBudgetRepository, ExpenseBudgetRepository>(new TransientLifetimeManager());
container.RegisterType<IIncomeBudgetRepository, IncomeBudgetRepository>(new TransientLifetimeManager());
container.RegisterType<IIncomeBudgetCategoryRepository, IncomeBudgetCategoryRepository>(new TransientLifetimeManager());
container.RegisterType<IExpenseBudgetCategoryRepository, ExpenseBudgetCategoryRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionString, ConnectionString>(new SingletonLifetimeManager());
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
} }
} }
} }

View File

@ -0,0 +1,113 @@
//------------------------------------------------------------------------------
// <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 FamilyBudget.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FamilyBudget.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap family {
get {
object obj = ResourceManager.GetObject("family", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap free_icon_dustbin_7709786 {
get {
object obj = ResourceManager.GetObject("free-icon-dustbin-7709786", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap free_icon_edit_tools_8847052 {
get {
object obj = ResourceManager.GetObject("free-icon-edit-tools-8847052", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap free_icon_plus_181672 {
get {
object obj = ResourceManager.GetObject("free-icon-plus-181672", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap free_icon_plus_1816721 {
get {
object obj = ResourceManager.GetObject("free-icon-plus-1816721", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,136 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="free-icon-plus-181672" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\free-icon-plus-181672.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="free-icon-edit-tools-8847052" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\free-icon-edit-tools-8847052.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="family" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\family.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="free-icon-plus-1816721" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\free-icon-plus-1816721.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="free-icon-dustbin-7709786" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\free-icon-dustbin-7709786.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

@ -0,0 +1,57 @@
using FamilyBudget.Entities;
using FamilyBudget.Repositories;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Reports
{
internal class ChartReport
{
private readonly IExpenseBudgetRepository _expenseBudget;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IExpenseBudgetRepository expenseBudgetRepository,
ILogger<ChartReport> logger)
{
_expenseBudget = expenseBudgetRepository ??
throw new
ArgumentNullException(nameof(expenseBudgetRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, int expenseId, DateTime dateTime)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Расходы")
.AddPieChart($"Траты за {dateTime:dd MMMM yyyy}", GetData(expenseId, dateTime))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<(string Caption, double Value)> GetData(int expenseId, DateTime dateTime)
{
var data = _expenseBudget
.ReadExpenseBudgets(dateFrom: dateTime.Date, dateTo: dateTime.Date.AddDays(1), BudgetExpenseId: expenseId)
.GroupBy(x => x.FamilyMemberId, (key, group) => new {
FullName = group.FirstOrDefault()?.FullName ?? "Unknown",
Count = group.Sum(x => x.FamilyMember_Expenses.FirstOrDefault(x => x.ExpenseBudgetCategoryID == expenseId)?.Sum ?? 0)
})
.Select(x => (x.FullName.ToString(), (double)x.Count))
.ToList();
return data;
}
}
}

View File

@ -0,0 +1,103 @@
using FamilyBudget.Repositories;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Reports
{
internal class DocReport
{
private readonly IFamilyRepository _familyRepository;
private readonly IFamilyMemberRepository _memberRepository;
private readonly IExpenseBudgetCategoryRepository _expenseBudgetCategoryRepository;
private readonly IIncomeBudgetCategoryRepository _incomeBudgetCategoryRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IFamilyRepository familyRepository, IFamilyMemberRepository memberRepository, IExpenseBudgetCategoryRepository
expenseBudgetCategoryRepository, IIncomeBudgetCategoryRepository incomeBudgetCategoryRepository, ILogger<DocReport> logger)
{
_familyRepository = familyRepository ??
throw new
ArgumentNullException(nameof(familyRepository));
_memberRepository = memberRepository ??
throw new ArgumentNullException(nameof(memberRepository));
_expenseBudgetCategoryRepository = expenseBudgetCategoryRepository ??
throw new ArgumentNullException(nameof(expenseBudgetCategoryRepository));
_incomeBudgetCategoryRepository = incomeBudgetCategoryRepository ??
throw new ArgumentNullException(nameof(incomeBudgetCategoryRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeFamilies, bool includeMembers, bool includeIncomes, bool includeExpenses)
{
try
{
var builder = new WordBuilder(filePath)
.AddHeader("Документ со справочниками");
if (includeFamilies)
{
builder.AddParagraph("Семьи")
.AddTable([2400],
GetFamilies());
}
if (includeMembers)
{
builder.AddParagraph("Участники семьи")
.AddTable([2400, 2400], GetMembers());
}
if (includeIncomes)
{
builder.AddParagraph("Доходы")
.AddTable([2400, 2400], GetIncomes());
}
if (includeExpenses)
{
builder.AddParagraph("Расходы")
.AddTable([2400, 2400], GetExpenses());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetFamilies() =>
[
["Фамилия"],
.. _familyRepository
.ReadFamilies()
.Select(x => new string[] { x.Name }),
];
private List<string[]> GetMembers() =>
[
["Имя", "Роль"],
.. _memberRepository
.ReadFamilyMembers()
.Select(x => new string[] { x.Name, x.MemberType.ToString()}),
];
private List<string[]> GetIncomes() =>
[
["Название", "Тип дохода"],
.. _incomeBudgetCategoryRepository
.ReadIncomeBudgetCategories()
.Select(x => new string[] {x.Name, x.IncomeCategoryType.ToString() }),
];
private List<string[]> GetExpenses()
{
return [
["Название", "Тип дохода"],
.. _expenseBudgetCategoryRepository
.ReadExpenseBudgetCategories()
.Select(x => new string[] { x.Name, x.ExpenseCategoryType.ToString() }),
];
}
}
}

View File

@ -0,0 +1,336 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Reports
{
internal class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header,
StyleIndex.BoldTextWithBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "",
StyleIndex.BoldTextWithBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference =
new
StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text,
StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j],
StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j],
StyleIndex.SimpleTextWithoutBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j],
StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath,
SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets =
spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id =
spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells,
worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart =
workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts =
BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new
EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
Bold = new Bold() { Val = true },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new
EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new
EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin },
DiagonalBorder = new DiagonalBorder() { Style = BorderStyleValues.Thin }
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithBorder = 2,
BoldTextWithoutBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text,
StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex!
== rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null &&
c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null &&
cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value,
cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() +
columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}
}

View File

@ -0,0 +1,87 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace FamilyBudget.Reports
{
internal class PdfBuilder
{
private readonly string _filePath;
private readonly Document _document;
public PdfBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
DefineStyles();
}
public PdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
data = data
.Where(x => x.Value > 0.01)
.Select(x => (
Caption: x.Caption,
Value: x.Value
)).ToList();
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.LeftArea.Width = Unit.FromCentimeter(1);
chart.RightArea.Width = Unit.FromCentimeter(1);
chart.TopArea.AddLegend();
chart.TopArea.AddParagraph(title);
_document.LastSection.Add(chart);
return this;
}
public void Build()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
var style = _document.Styles.AddStyle("NormalBold", "Normal");
style.Font.Size = 14;
style.Font.Bold = true;
}
}
}

View File

@ -0,0 +1,85 @@
using FamilyBudget.Entities;
using FamilyBudget.Repositories;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Reports
{
internal class TableReport
{
private readonly IExpenseBudgetRepository _expenseBudgetRepository;
private readonly IIncomeBudgetRepository _incomeBudgetRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Человек", "Дата", "Заработано", "Потрачено"];
public TableReport(IExpenseBudgetRepository expenseBudgetRepository, IIncomeBudgetRepository incomeBudgetRepository,
ILogger<TableReport> logger)
{
_expenseBudgetRepository = expenseBudgetRepository ??
throw new
ArgumentNullException(nameof(expenseBudgetRepository));
_incomeBudgetRepository = incomeBudgetRepository ??
throw new
ArgumentNullException(nameof(incomeBudgetRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int incomeId, int expenseId, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по бюджету семьи", 0, 4)
.AddParagraph($"за период с {startDate:dd.MM.yyyy} по {endDate:dd.MM.yyyy}", 0)
.AddTable([15, 10, 15, 15], GetData(incomeId, expenseId, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int incomeId, int expenseId, DateTime startDate, DateTime
endDate)
{
_logger.LogDebug("{json}", JsonConvert.SerializeObject(_expenseBudgetRepository.ReadExpenseBudgets()));
var expenseData = _expenseBudgetRepository
.ReadExpenseBudgets(dateFrom: startDate, dateTo: endDate, BudgetExpenseId: expenseId)
.Select(x => new
{
x.FullName,
x.Date,
CountIn = (int?)null,
CountOut = x.FamilyMember_Expenses.FirstOrDefault(y => y.ExpenseBudgetCategoryID == expenseId)?.Sum
});
var incomeData = _incomeBudgetRepository
.ReadIncomeBudgets(dateFrom: startDate, dateTo: endDate, BudgetIncomeId: incomeId)
.Select(x => new
{
x.FullName,
x.Date,
CountIn = x.FamilyMember_Incomes.FirstOrDefault(y => y.IncomeBudgetCategoryId == incomeId)?.Sum,
CountOut = (int?)null,
});
var data = expenseData
.Union(incomeData)
.OrderBy(x => x.Date);
return new List<string[]>(){ item }
.Union(
data.Select(x => new string[] {x.FullName, x.Date.ToString("dd.MM.yyyy"), x.CountIn?.ToString("N0") ?? string.Empty,
x.CountOut?.ToString("N0") ?? string.Empty }))
.Union(
[["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString("N0"), data.Sum(x => x.CountOut ?? 0).ToString("N0")]])
.ToList();
}
}
}

View File

@ -0,0 +1,134 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Reports
{
internal class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
var runProperty = run.AppendChild(new RunProperties());
runProperty.AddChild(new Bold());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}
)
));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth()
{
Width =
widths[j].ToString()
}),
new Paragraph(new Run(new RunProperties(new Bold()), new
Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new
Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath,
WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IConnectionString
{
public string ConnectionString { get; }
}
}

View File

@ -0,0 +1,18 @@
using FamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IExpenseBudgetCategoryRepository
{
IEnumerable<ExpenseBudgetCategory> ReadExpenseBudgetCategories();
ExpenseBudgetCategory ReadExpenseBudgetCategoryById(int id);
void UpdateExpenseBudgetCategoryById(ExpenseBudgetCategory expenseBudgetCategory);
void CreateExpenseBudgetCategory(ExpenseBudgetCategory expenseBudgetCategory);
void DeleteExpenseBudgetCategory(int id);
}
}

View File

@ -0,0 +1,17 @@
using FamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IExpenseBudgetRepository
{
IEnumerable<ExpenseBudget> ReadExpenseBudgets(DateTime? dateFrom = null, DateTime? dateTo = null,
int? familyMemberId = null, int? BudgetExpenseId = null);
void CreateExpenseBudget(ExpenseBudget expenseBudget);
void DeleteExpenseBudget(int id);
}
}

View File

@ -0,0 +1,18 @@
using FamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IFamilyMemberRepository
{
IEnumerable<FamilyMember> ReadFamilyMembers();
FamilyMember ReadFamilyMemberById(int id);
void CreateFamilyMember(FamilyMember familyMember);
void UpdateFamilyMember(FamilyMember familyMember);
void DeleteFamilyMember(int id);
}
}

View File

@ -0,0 +1,18 @@
using FamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IFamilyRepository
{
IEnumerable<Family> ReadFamilies();
Family ReadFamilyById(int id);
void CreateFamily(Family family);
void UpdateFamily(Family family);
void DeleteFamily(int id);
}
}

View File

@ -0,0 +1,18 @@
using FamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IIncomeBudgetCategoryRepository
{
IEnumerable<IncomeBudgetCategory> ReadIncomeBudgetCategories();
IncomeBudgetCategory ReadIncomeBudgetCategoryById(int id);
void UpdateExpenseBudgetCategoryById(IncomeBudgetCategory income);
void CreateIncomeBudgetCategory(IncomeBudgetCategory income);
void DeleteIncomeBudgetCategory(int id);
}
}

View File

@ -0,0 +1,17 @@
using FamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories
{
public interface IIncomeBudgetRepository
{
IEnumerable<IncomeBudget> ReadIncomeBudgets(DateTime? dateFrom = null, DateTime? dateTo = null,
int? familyMemberId = null, int? BudgetIncomeId = null);
void CreateIncomeBudget(IncomeBudget incomeBudget);
void DeleteIncomeBudget(int id);
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories.Implementations
{
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost;Database=familyBudget;User Id=postgres;Password=postgres;";
}
}

View File

@ -0,0 +1,129 @@
using Dapper;
using FamilyBudget.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories.Implementations
{
internal class ExpenseBudgetCategoryRepository : IExpenseBudgetCategoryRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ExpenseBudgetCategoryRepository> _logger;
public ExpenseBudgetCategoryRepository(IConnectionString connectionString, ILogger<ExpenseBudgetCategoryRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateExpenseBudgetCategory(ExpenseBudgetCategory expenseBudgetCategory)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(expenseBudgetCategory));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO ExpenseBudgetCategory (ExpenseCategoryType, Name)
VALUES (@ExpenseCategoryType, @Name)";
connection.Execute(queryInsert, expenseBudgetCategory);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteExpenseBudgetCategory(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM ExpenseBudgetCategory
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<ExpenseBudgetCategory> ReadExpenseBudgetCategories()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM ExpenseBudgetCategory";
var expenses = connection.Query<ExpenseBudgetCategory>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(expenses));
return expenses;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public ExpenseBudgetCategory ReadExpenseBudgetCategoryById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM ExpenseBudgetCategory
WHERE Id=@id";
var expense = connection.QueryFirst<ExpenseBudgetCategory>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(expense));
return expense;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateExpenseBudgetCategoryById(ExpenseBudgetCategory expenseBudgetCategory)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(expenseBudgetCategory));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE ExpenseBudgetCategory
SET
Id=@Id,
Name=@Name,
ExpenseCategoryType=@ExpenseCategoryType
WHERE Id=@Id";
connection.Execute(queryUpdate, new
{
expenseBudgetCategory.Id,
expenseBudgetCategory.Name,
expenseBudgetCategory.ExpenseCategoryType
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,163 @@
using Dapper;
using FamilyBudget.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories.Implementations
{
internal class ExpenseBudgetRepository : IExpenseBudgetRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ExpenseBudgetRepository> _logger;
public ExpenseBudgetRepository(IConnectionString connectionString, ILogger<ExpenseBudgetRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateExpenseBudget(ExpenseBudget expenseBudget)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(expenseBudget));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO ExpenseBudget (FamilyMemberId, Date)
VALUES (@FamilyMemberId, @Date);
SELECT MAX(Id) FROM ExpenseBudget";
var expenseBudgetId = connection.QueryFirst<int>(queryInsert, expenseBudget, transaction);
var querySubInsert = @"
INSERT INTO FamilyMember_ExpenseBudget (ExpenseBudgetId, FamilyMemberId, Sum, ExpensebudgetCategoryId)
VALUES (@ExpenseBudgetId, @FamilyMemberId, @Sum, @ExpensebudgetCategoryId)";
foreach (var elem in expenseBudget.FamilyMember_Expenses)
{
connection.Execute(querySubInsert, new
{
ExpenseBudgetId = expenseBudgetId,
expenseBudget.FamilyMemberId,
elem.Sum,
ExpensebudgetCategoryId = elem.ExpenseBudgetCategoryID
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteExpenseBudget(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM FamilyMember_ExpenseBudget
WHERE ExpenseBudgetID = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM ExpenseBudget
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<ExpenseBudget> ReadExpenseBudgets(DateTime? dateFrom = null, DateTime? dateTo = null,
int? familyMemberId = null, int? BudgetExpenseId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("eb.Date >= @dateFrom");
}
if (dateTo.HasValue)
{
builder.AddCondition("eb.Date<= @dateTo");
}
if (familyMemberId.HasValue)
{
builder.AddCondition("eb.familyMemberId = @familyMemberId");
}
if (BudgetExpenseId.HasValue)
{
builder.AddCondition("fmeb.ExpenseBudgetCategoryId = @BudgetExpenseId");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = $@"SELECT
eb.Id,
eb.FamilyMemberId,
CONCAT(fm.Name, ' ', f.Name) AS FullName,
eb.Date,
fmeb.ExpenseBudgetId,
fmeb.ExpenseBudgetCategoryId,
fmeb.Sum,
e.Name AS ExpenseName
FROM expenseBudget eb
LEFT JOIN familymember_expensebudget fmeb ON fmeb.expensebudgetid = eb.id
INNER JOIN Familymember fm ON fm.Id = eb.FamilyMemberId
LEFT JOIN Family f ON f.Id = fm.FamilyId
LEFT JOIN expensebudgetcategory e ON e.Id = fmeb.ExpenseBudgetCategoryId
{builder.Build()}";
var expenseDict = new Dictionary<int, List<FamilyMember_ExpenseBudget>>();
var expenseBudget = connection.Query<ExpenseBudget, FamilyMember_ExpenseBudget, ExpenseBudget>(querySelect,
(expense, fmExpense) =>
{
if (!expenseDict.TryGetValue(expense.Id, out var fme))
{
fme = [];
expenseDict.Add(expense.Id, fme);
}
fme.Add(fmExpense);
return expense;
}, splitOn: "ExpenseBudgetCategoryId", param: new { dateFrom, dateTo, familyMemberId, BudgetExpenseId });
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(expenseBudget));
return expenseDict.Select(x =>
{
var pi = expenseBudget.First(y => y.Id == x.Key);
pi.SetExpenseBudget(x.Value);
return pi;
}).ToArray();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -0,0 +1,138 @@
using Dapper;
using FamilyBudget.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FamilyBudget.Repositories.Implementations
{
internal class FamilyMemberRepository : IFamilyMemberRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<FamilyMemberRepository> _logger;
public FamilyMemberRepository(IConnectionString connectionString, ILogger<FamilyMemberRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateFamilyMember(FamilyMember familyMember)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(familyMember));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO FamilyMember (FamilyId, Name, MemberType)
VALUES (@FamilyId, @Name, @MemberType)";
connection.Execute(queryInsert, new
{
familyMember.FamilyId,
familyMember.Name,
familyMember.MemberType
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteFamilyMember(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM FamilyMember
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public FamilyMember ReadFamilyMemberById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM FamilyMember
WHERE Id=@id";
var familyMember = connection.QueryFirst<FamilyMember>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(familyMember));
return familyMember;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<FamilyMember> ReadFamilyMembers()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT fm.*, f.name as FamilyName
FROM FamilyMember fm left join family f on f.id = fm.familyid";
var familyMembers = connection.Query<FamilyMember>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(familyMembers));
return familyMembers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateFamilyMember(FamilyMember familyMember)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(familyMember));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE FamilyMember
SET
familyId=@FamilyId,
Name=@Name,
MemberType=@MemberType
WHERE Id=@Id";
connection.Execute(queryUpdate, new
{
familyMember.Id,
familyMember.FamilyId,
familyMember.Name,
familyMember.MemberType
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,128 @@
using Dapper;
using FamilyBudget.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories.Implementations
{
internal class FamilyRepository : IFamilyRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<FamilyRepository> _logger;
public FamilyRepository(ConnectionString connectionString, ILogger<FamilyRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateFamily(Family family)
{
_logger.LogInformation("Объект создан");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(family));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Family (Name)
Values (@Name)";
connection.Execute(queryInsert, family);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошбика при добавлении объекта");
throw;
}
}
public void DeleteFamily(int id)
{
_logger.LogInformation($"Удаление объекта");
_logger.LogDebug($"Объект: {id} удален");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM family
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Family> ReadFamilies()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Family";
var failmies = connection.Query<Family>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(failmies));
return failmies;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Family ReadFamilyById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM family
WHERE Id=@Id";
var obj = connection.QueryFirst<Family>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(obj));
return obj;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateFamily(Family family)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(family));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE family
SET
Name=@Name
WHERE Id=@Id";
connection.Execute(queryUpdate, family);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,130 @@
using Dapper;
using FamilyBudget.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories.Implementations
{
internal class IncomeBudgetCategoryRepository : IIncomeBudgetCategoryRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<IIncomeBudgetCategoryRepository> _logger;
public IncomeBudgetCategoryRepository(IConnectionString connectionString, ILogger<IIncomeBudgetCategoryRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateIncomeBudgetCategory(IncomeBudgetCategory incomeBudgetCategory)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(incomeBudgetCategory));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO IncomeBudgetCategory (IncomeCategoryType, Name)
VALUES (@IncomeCategoryType, @Name)";
connection.Execute(queryInsert, incomeBudgetCategory);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteIncomeBudgetCategory(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM IncomeBudgetCategory
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<IncomeBudgetCategory> ReadIncomeBudgetCategories()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM IncomeBudgetCategory";
var incomes = connection.Query<IncomeBudgetCategory>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(incomes));
return incomes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public IncomeBudgetCategory ReadIncomeBudgetCategoryById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM IncomeBudgetCategory
WHERE Id=@id";
var income = connection.QueryFirst<IncomeBudgetCategory>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(income));
return income;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateExpenseBudgetCategoryById(IncomeBudgetCategory income)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(income));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE IncomeBudgetCategory
SET
Id=@Id,
Name=@Name,
IncomeCategoryType=@IncomeCategoryType
WHERE Id=@Id";
connection.Execute(queryUpdate, new
{
income.Id,
income.Name,
income.IncomeCategoryType
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,162 @@
using Dapper;
using DocumentFormat.OpenXml.Office2013.Word;
using FamilyBudget.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FamilyBudget.Repositories.Implementations
{
internal class IncomeBudgetRepository : IIncomeBudgetRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<IncomeBudgetRepository> _logger;
public IncomeBudgetRepository(IConnectionString connectionString, ILogger<IncomeBudgetRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateIncomeBudget(IncomeBudget incomeBudget)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(incomeBudget));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO IncomeBudget (FamilyMemberId, Date)
VALUES (@FamilyMemberId, @Date);
SELECT MAX(Id) FROM IncomeBudget";
var incomeBudgetId =
connection.QueryFirst<int>(queryInsert, incomeBudget, transaction);
var querySubInsert = @"
INSERT INTO FamilyMember_IncomeBudget (IncomeBudgetId, FamilyMemberId, Sum, IncomebudgetCategoryId)
VALUES (@IncomeBudgetId, @FamilyMemberId, @Sum, @IncomebudgetCategoryId)";
foreach (var elem in incomeBudget.FamilyMember_Incomes)
{
_logger.LogError("test2: {json}", JsonConvert.SerializeObject(elem));
connection.Execute(querySubInsert, new
{
IncomeBudgetId = incomeBudgetId,
incomeBudget.FamilyMemberId,
elem.Sum,
IncomebudgetCategoryId = elem.IncomeBudgetCategoryId
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteIncomeBudget(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM FamilyMember_IncomeBudget
WHERE IncomeBudgetId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM IncomeBudget
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<IncomeBudget> ReadIncomeBudgets(DateTime? dateFrom = null, DateTime? dateTo = null,
int? familyMemberId = null, int? BudgetIncomeId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("ib.Date >= @dateFrom");
}
if (dateTo.HasValue)
{
builder.AddCondition("ib.Date <= @dateTo");
}
if (familyMemberId.HasValue)
{
builder.AddCondition("ib.familyMemberId = @familyMemberId");
}
if (BudgetIncomeId.HasValue)
{
builder.AddCondition("fmib.IncomeBudgetCategoryId = @BudgetIncomeId");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = $@"SELECT
ib.Id,
ib.FamilyMemberId,
CONCAT(fm.Name, ' ', f.Name) AS FullName,
ib.Date,
fmib.IncomeBudgetId,
fmib.IncomeBudgetCategoryId,
fmib.Sum,
i.Name AS IncomeName
FROM incomeBudget ib
LEFT JOIN familymember_incomebudget fmib ON fmib.incomebudgetid = ib.id
INNER JOIN Familymember fm ON fm.Id = ib.FamilyMemberId
LEFT JOIN Family f ON f.Id = fm.FamilyId
LEFT JOIN incomebudgetcategory i ON i.Id = fmib.IncomeBudgetCategoryId
{builder.Build()}";
var incomeDict = new Dictionary<int, List<FamilyMember_IncomeBudget>>();
var incomesBudget = connection.Query<IncomeBudget, FamilyMember_IncomeBudget, IncomeBudget>(querySelect,
(income, fmIncome) =>
{
if (!incomeDict.TryGetValue(income.Id, out var fmi))
{
fmi = [];
incomeDict.Add(income.Id, fmi);
}
fmi.Add(fmIncome);
return income;
}, splitOn: "IncomeBudgetCategoryId", param: new { dateFrom, dateTo, familyMemberId, BudgetIncomeId });
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(incomesBudget));
return incomeDict.Select(x =>
{
var pi = incomesBudget.First(y => y.Id == x.Key);
pi.SetIncomeBudget(x.Value);
return pi;
}).ToArray();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectFamilyBudget.Repositories.Implementations;
public class QueryBuilder
{
private readonly StringBuilder _builder;
public QueryBuilder()
{
_builder = new();
}
public QueryBuilder AddCondition(string condition)
{
if (_builder.Length > 0)
{
_builder.Append(" AND ");
}
_builder.Append(condition);
return this;
}
public string Build()
{
if (_builder.Length == 0)
{
return string.Empty;
}
return $"WHERE {_builder}";
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/familyBudget_log.txt",
"rollingInterval": "Day"
}
}
]
}
}