AppCore.Helpers
1.0.6
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package AppCore.Helpers --version 1.0.6
NuGet\Install-Package AppCore.Helpers -Version 1.0.6
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AppCore.Helpers" Version="1.0.6" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AppCore.Helpers" Version="1.0.6" />
<PackageReference Include="AppCore.Helpers" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AppCore.Helpers --version 1.0.6
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: AppCore.Helpers, 1.0.6"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AppCore.Helpers@1.0.6
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AppCore.Helpers&version=1.0.6
#tool nuget:?package=AppCore.Helpers&version=1.0.6
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
AppCore.Helpers — примеры использования
Этот файл можно прикрепить к NuGet-пакету как README.md.
В нём собраны готовые примеры сервисов и карточек для Windows Forms проекта демонстрационного экзамена.
Подключение пакета
using AppCore.Helpers;
Пример настройки строки подключения через SQL Server-аутентификацию:
DatabaseService.Configure(
"Server=ИМЯ_СЕРВЕРА;Database=toy_shop;User ID=ЛОГИН;Password=ПАРОЛЬ;TrustServerCertificate=True;");
AuthService.cs
using AppCore.Helpers;
using Demo_Ex_8.Models;
using System.Data;
namespace Demo_Ex_8.Services
{
public static class AuthService
{
public static bool Login(string login, string password)
{
try
{
if (!ValidationHelper.ValidateRequiredFields(new()
{
{ "Логин", login },
{ "Пароль", password }
}))
{
return false;
}
string query = """
SELECT
u.id,
u.full_name,
u.login,
r.role_name
FROM users u
JOIN roles r ON r.id = u.role_id
WHERE u.login = @login
AND u.password = @password
""";
DataTable table = DatabaseService.ExecuteSelect(
query,
new Dictionary<string, object>
{
{ "@login", login },
{ "@password", password }
});
if (table.Rows.Count == 0)
{
MessageBoxHelper.Warning("Неверный логин или пароль");
return false;
}
DataRow row = table.Rows[0];
UserSession.SetUser(
Convert.ToInt32(row["id"]),
row["login"].ToString(),
row["full_name"].ToString(),
row["role_name"].ToString());
return true;
}
catch (Exception ex)
{
MessageBoxHelper.ShowException(ex);
return false;
}
}
public static void LoginAsGuest()
{
UserSession.SetGuest();
}
public static void Logout()
{
UserSession.Clear();
}
}
}
ProductsService.cs
using AppCore.Helpers;
using System.Data;
using System.Text;
namespace Demo_Ex_8.Services
{
public static class ProductsService
{
public static DataTable GetSuppliers()
{
return DatabaseService.ExecuteSelect(
"SELECT id, supplier_name FROM suppliers ORDER BY supplier_name");
}
public static DataTable GetManufacturers()
{
return DatabaseService.ExecuteSelect(
"SELECT id, manufacturer_name FROM manufacturers ORDER BY manufacturer_name");
}
public static DataTable GetUnits()
{
return DatabaseService.ExecuteSelect(
"SELECT id, unit_name FROM units ORDER BY unit_name");
}
public static DataTable GetCategories()
{
return DatabaseService.ExecuteSelect(
"SELECT id, category_name FROM categories ORDER BY category_name");
}
public static DataTable GetProductById(int productId)
{
return DatabaseService.ExecuteSelect(
"SELECT * FROM products WHERE id = @id",
new Dictionary<string, object>
{
{ "@id", productId }
});
}
public static DataTable GetProducts(
string search = "",
int supplierId = 0,
string sortType = "")
{
StringBuilder query = new("""
SELECT
p.id,
p.article,
p.title,
u.unit_name,
p.price,
s.supplier_name,
m.manufacturer_name,
c.category_name,
p.discount,
p.quantity,
p.description,
p.picture_path
FROM products p
JOIN units u ON p.unit_id = u.id
JOIN suppliers s ON p.supplier_id = s.id
JOIN manufacturers m ON p.manufacturer_id = m.id
JOIN categories c ON p.category_id = c.id
WHERE 1 = 1
""");
Dictionary<string, object> parameters = new();
QueryBuilderHelper.AddTextSearch(
query,
parameters,
search,
"p.title",
"p.article",
"p.description",
"s.supplier_name",
"m.manufacturer_name",
"c.category_name");
QueryBuilderHelper.AddExactFilter(
query,
parameters,
"p.supplier_id",
"@supplierId",
supplierId,
0);
QueryBuilderHelper.AddOrderBy(
query,
sortType,
new Dictionary<string, string>
{
{ "Цена по возрастанию", "p.price ASC" },
{ "Цена по убыванию", "p.price DESC" },
{ "Количество по возрастанию", "p.quantity ASC" },
{ "Количество по убыванию", "p.quantity DESC" },
{ "Скидка по возрастанию", "p.discount ASC" },
{ "Скидка по убыванию", "p.discount DESC" },
{ "Название А-Я", "p.title ASC" },
{ "Название Я-А", "p.title DESC" }
},
"p.id ASC");
return DatabaseService.ExecuteSelect(query.ToString(), parameters);
}
public static bool CreateProduct(
string article,
string title,
int unitId,
decimal price,
int supplierId,
int manufacturerId,
int categoryId,
int discount,
int quantity,
string description,
string picturePath)
{
string query = """
INSERT INTO products
(
article,
title,
unit_id,
price,
supplier_id,
manufacturer_id,
category_id,
discount,
quantity,
description,
picture_path
)
VALUES
(
@article,
@title,
@unitId,
@price,
@supplierId,
@manufacturerId,
@categoryId,
@discount,
@quantity,
@description,
@picturePath
)
""";
return DatabaseService.ExecuteNonQuery(
query,
new Dictionary<string, object>
{
{ "@article", article },
{ "@title", title },
{ "@unitId", unitId },
{ "@price", price },
{ "@supplierId", supplierId },
{ "@manufacturerId", manufacturerId },
{ "@categoryId", categoryId },
{ "@discount", discount },
{ "@quantity", quantity },
{ "@description", description },
{ "@picturePath", picturePath }
});
}
public static bool UpdateProduct(
int id,
string article,
string title,
int unitId,
decimal price,
int supplierId,
int manufacturerId,
int categoryId,
int discount,
int quantity,
string description,
string picturePath)
{
string query = """
UPDATE products
SET
article = @article,
title = @title,
unit_id = @unitId,
price = @price,
supplier_id = @supplierId,
manufacturer_id = @manufacturerId,
category_id = @categoryId,
discount = @discount,
quantity = @quantity,
description = @description,
picture_path = @picturePath
WHERE id = @id
""";
return DatabaseService.ExecuteNonQuery(
query,
new Dictionary<string, object>
{
{ "@id", id },
{ "@article", article },
{ "@title", title },
{ "@unitId", unitId },
{ "@price", price },
{ "@supplierId", supplierId },
{ "@manufacturerId", manufacturerId },
{ "@categoryId", categoryId },
{ "@discount", discount },
{ "@quantity", quantity },
{ "@description", description },
{ "@picturePath", picturePath }
});
}
public static bool DeleteProduct(int id)
{
return DatabaseService.ExecuteNonQuery(
"DELETE FROM products WHERE id = @id",
new Dictionary<string, object>
{
{ "@id", id }
});
}
public static bool ProductExistsInOrders(int productId)
{
object? result = DatabaseService.ExecuteScalar(
"""
SELECT COUNT(*)
FROM order_items
WHERE product_id = @productId
""",
new Dictionary<string, object>
{
{ "@productId", productId }
});
return Convert.ToInt32(result) > 0;
}
}
}
OrdersService.cs
using AppCore.Helpers;
using System.Data;
namespace Demo_Ex_8.Services
{
public static class OrdersService
{
public static DataTable GetOrders()
{
string query = """
SELECT
o.id,
o.order_date,
o.delivery_date,
o.pickup_point_id,
o.user_id,
o.receipt_code,
o.status_id,
s.status_name,
u.full_name,
CONCAT(
pp.postal_code,
', г. ',
c.city_name,
', ',
pp.street,
', ',
pp.house
) AS pickup_point
FROM orders o
JOIN statuses s ON s.id = o.status_id
JOIN users u ON u.id = o.user_id
JOIN pickup_points pp ON pp.id = o.pickup_point_id
JOIN cities c ON c.id = pp.city_id
ORDER BY o.id DESC
""";
return DatabaseService.ExecuteSelect(query);
}
public static DataTable GetOrderById(int orderId)
{
string query = """
SELECT
id,
order_date,
delivery_date,
pickup_point_id,
user_id,
receipt_code,
status_id
FROM orders
WHERE id = @id
""";
return DatabaseService.ExecuteSelect(
query,
new Dictionary<string, object>
{
{ "@id", orderId }
});
}
public static DataTable GetStatuses()
{
return DatabaseService.ExecuteSelect(
"SELECT id, status_name FROM statuses ORDER BY status_name");
}
public static DataTable GetUsers()
{
return DatabaseService.ExecuteSelect(
"SELECT id, full_name FROM users ORDER BY full_name");
}
public static DataTable GetPickupPoints()
{
string query = """
SELECT
pp.id,
CONCAT(
pp.postal_code,
', г. ',
c.city_name,
', ',
pp.street,
', ',
pp.house
) AS pickup_point
FROM pickup_points pp
JOIN cities c ON c.id = pp.city_id
ORDER BY pp.id
""";
return DatabaseService.ExecuteSelect(query);
}
public static bool CreateOrder(
DateTime orderDate,
DateTime deliveryDate,
int pickupPointId,
int userId,
string receiptCode,
int statusId)
{
string query = """
INSERT INTO orders
(
order_date,
delivery_date,
pickup_point_id,
user_id,
receipt_code,
status_id
)
VALUES
(
@orderDate,
@deliveryDate,
@pickupPointId,
@userId,
@receiptCode,
@statusId
)
""";
return DatabaseService.ExecuteNonQuery(
query,
new Dictionary<string, object>
{
{ "@orderDate", orderDate },
{ "@deliveryDate", deliveryDate },
{ "@pickupPointId", pickupPointId },
{ "@userId", userId },
{ "@receiptCode", receiptCode },
{ "@statusId", statusId }
});
}
public static bool UpdateOrder(
int id,
DateTime orderDate,
DateTime deliveryDate,
int pickupPointId,
int userId,
string receiptCode,
int statusId)
{
string query = """
UPDATE orders
SET
order_date = @orderDate,
delivery_date = @deliveryDate,
pickup_point_id = @pickupPointId,
user_id = @userId,
receipt_code = @receiptCode,
status_id = @statusId
WHERE id = @id
""";
return DatabaseService.ExecuteNonQuery(
query,
new Dictionary<string, object>
{
{ "@id", id },
{ "@orderDate", orderDate },
{ "@deliveryDate", deliveryDate },
{ "@pickupPointId", pickupPointId },
{ "@userId", userId },
{ "@receiptCode", receiptCode },
{ "@statusId", statusId }
});
}
public static bool DeleteOrder(int id)
{
string query = """
DELETE FROM order_items WHERE order_id = @id;
DELETE FROM orders WHERE id = @id;
""";
return DatabaseService.ExecuteNonQuery(
query,
new Dictionary<string, object>
{
{ "@id", id }
});
}
}
}
ProductCard.cs
using AppCore.Helpers;
using System.Data;
namespace Demo_Ex_8.Cards
{
public partial class ProductCard : UserControl
{
public int ProductId { get; private set; }
private readonly int _discountLimit;
private readonly Color _defaultColor;
private readonly Color _discountColor;
private readonly Color _outOfStockColor;
public event EventHandler<int>? CardClicked;
public ProductCard(
DataRow row,
int discountLimit,
Color defaultColor,
Color discountColor,
Color outOfStockColor)
{
InitializeComponent();
_discountLimit = discountLimit;
_defaultColor = defaultColor;
_discountColor = discountColor;
_outOfStockColor = outOfStockColor;
FillCard(row);
AttachClickEvent(this);
}
private void ProductCard_Click(object? sender, EventArgs e)
{
CardClicked?.Invoke(this, ProductId);
}
public void FillCard(DataRow row)
{
try
{
ProductId = Convert.ToInt32(row["id"]);
decimal price = Convert.ToDecimal(row["price"]);
int discount = Convert.ToInt32(row["discount"]);
int quantity = Convert.ToInt32(row["quantity"]);
CategoryLabel.Text = row["category_name"].ToString();
TitleLabel.Text = row["title"].ToString();
DescriptionLabel.Text = row["description"].ToString();
ManufacturerLabel.Text = row["manufacturer_name"].ToString();
SupplierLabel.Text = row["supplier_name"].ToString();
UnitLabel.Text = row["unit_name"].ToString();
QuantityLabel.Text = quantity.ToString();
DiscountLabel.Text = ProductViewHelper.FormatDiscount(discount);
ProductPicture.Image = ImageHelper.LoadImageOrDefault(
row["picture_path"].ToString(),
@"C:\Users\eleskov\Desktop\Подготовка к ДЭ\Demo_Ex_8\Demo_Ex_8\Resourse\picture.png");
ProductPicture.SizeMode = PictureBoxSizeMode.Zoom;
ProductViewHelper.ApplyProductBackground(
this,
quantity,
discount,
_discountLimit,
_defaultColor,
_discountColor,
_outOfStockColor);
ProductViewHelper.ApplyPriceLabels(
PriceLabel,
FinalPriceLabel,
price,
discount,
Color.Red,
Color.Black);
}
catch (Exception ex)
{
MessageBoxHelper.ShowException(ex);
}
}
private void AttachClickEvent(Control control)
{
control.Click -= ProductCard_Click;
control.Click += ProductCard_Click;
control.Cursor = Cursors.Hand;
foreach (Control child in control.Controls)
{
AttachClickEvent(child);
}
}
}
}
Как прикрепить README к NuGet-пакету
Положи файл README.md рядом с .csproj.
В .csproj добавь:
<PropertyGroup>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\" />
</ItemGroup>
После этого собери пакет:
dotnet pack -c Release
И загрузи новую версию на NuGet:
dotnet nuget push "bin\Release\AppCore.Helpers.1.0.3.nupkg" --api-key ТВОЙ_API_KEY --source https://api.nuget.org/v3/index.json
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0-windows7.0 is compatible. net9.0-windows was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0-windows7.0
- Microsoft.Data.SqlClient (>= 7.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.