- •Курсовая проект
- •Реферат
- •Постановка задачи
- •1. Анализ решаемой проблемы
- •2. Системное проектирование
- •Разработка спецификаций функций
- •3. Функциональное проектирование
- •3.1 Разработка обобщенного алгоритма функционирования приложения
- •Разработка структуры приложения и структуры данных
- •3.3 Разработка программного кода приложения
- •Результаты тестирования приложения. Используемые тесты
- •Запуск приложения:
- •Ввод данных в базу:
- •Описание приложения, инструкция по его использованию
- •Начало работы программы.
- •Ввод данных в базу
- •Список использованных источников
- •Приложение
Список использованных источников
Использование C#. Специальное издание. – М.: Издательский дом «Вильямс», 2002. – 528 с.
Майо Д. C#: Искусство программирования. Энциклопедия программиста. – СПб.: ООО «ДиаСофтЮП», 2002. – 656 с.
Павловская Т.А. C#. Программирование на языке высокого уровня. Учебник для вузов. – СПб.: Санкт-Петербург, 2007. – 432 с.
Приложение
using StoreDB;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace StoreDatabase
{
public struct EntryLists
{
public List<Entry> entries;
public EntryLists(List<Entry> entries)
{
this.entries = entries;
}
public void PrintEntry(int index = -1)
{
if (index < 0)
{
foreach (Entry e in entries)
{
e.PrintEntry();
}
}
else
{
entries[index].PrintEntry();
}
}
public Entry this[int index]
{
get { return entries[index]; }
set { entries[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
List<Entry> entries = new List<Entry>();
EntryLists entryLists = new EntryLists(entries);
Console.WriteLine("Главное меню");
while (true)
{
Console.WriteLine(
"1. Добавить автомобиль\n" +
"2. Удалить автомобиль\n" +
"3. Поиск\n" +
"4. Выход");
int state = Int32.Parse(Console.ReadLine());
switch (state)
{
case 1:
EntryHelper.CreateEntry(entryLists);
break;
case 2:
EntryHelper.DeleteEntry();
break;
case 3:
EntryHelper.FindEntry();
break;
case 4:
return;
}
}
}
}
public static class EntryHelper
{
private enum SearchType
{
ByCost,
ByAvtoname
}
public static void CreateEntry(EntryLists entryLists)
{
Console.WriteLine("Введите цену автомобиля: ");
int cost = ConvertHelper.StringToInt(Console.ReadLine());
Console.WriteLine("Введите название автомобиля: ");
string avtoname = Console.ReadLine();
Console.WriteLine("Введите автосалон: ");
string avtostore = Console.ReadLine();
Console.WriteLine("Введите отдел автосалона: ");
string otdel = Console.ReadLine();
Console.WriteLine("Расположение автосалона(город): ");
string city = Console.ReadLine();
entryLists.entries.Add(new Entry(cost, avtoname, avtostore, otdel, city));
SerializeObject(entryLists.entries);
}
public static void DeleteEntry()
{
List<Entry> entries = DeserializeObject();
while (true)
{
if (entries.Count > 0)
{
Console.WriteLine("Введите название автомобиля для удаления: ");
string value = Console.ReadLine();
int index = GetEntryIndex(entries, value, SearchType.ByAvtoname);
if (index >= 0)
entries.RemoveAt(index);
else
{
Console.WriteLine("Не удается найти запись с таким именем, попробуйте еще раз");
continue;
}
Console.WriteLine("Запись удалена");
SerializeObject(entries);
return;
}
Console.WriteLine("Список записей пуст");
return;
}
}
public static void FindEntry()
{
List<Entry> entries = DeserializeObject();
EntryLists entryLists = new EntryLists(entries);
while (true)
{
if (entries.Count > 0)
{
Console.WriteLine("Искать автомобиль по:\n" +
"1. Цене\n" +
"2. Названию\n" +
"3. Просмотреть все\n" +
"4. Назад");
int state = ConvertHelper.StringToInt(Console.ReadLine());
switch (state)
{
case 1:
Console.WriteLine("Введите цену автомобиля: ");
string cost = Console.ReadLine();
int indexP = GetEntryIndex(entryLists.entries, cost);
entryLists.PrintEntry(indexP);
break;
case 2:
Console.WriteLine("Введите название автомобиля: ");
string avtoname = Console.ReadLine();
int indexN = GetEntryIndex(entryLists.entries, avtoname, SearchType.ByAvtoname);
entryLists.PrintEntry(indexN);
break;
case 3:
entryLists.PrintEntry();
break;
case 4:
return;
}
}
else
{
Console.WriteLine("Список записей пуст");
return;
}
}
}
private static int GetEntryIndex(List<Entry> entries, string value, SearchType searchType = SearchType.ByCost)
{
if (searchType == SearchType.ByCost)
{
int cost = ConvertHelper.StringToInt(value);
int index = entries.FindIndex(x => x.product.cost == cost);
return index;
}
else
{
int index = entries.FindIndex(x => x.product.avtoname == value);
return index;
}
}
private static void SerializeObject(List<Entry> entries)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fs = new FileStream("entries.dat", FileMode.OpenOrCreate, FileAccess.Write))
{
if (entries.Count > 0)
{
formatter.Serialize(fs, entries);
Console.WriteLine("Записи успешно сериализованы");
}
else
{
fs.SetLength(0);
}
}
}
private static List<Entry> DeserializeObject()
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fs = new FileStream("entries.dat", FileMode.Open, FileAccess.Read))
{
return (List<Entry>)formatter.Deserialize(fs);
}
}
catch (Exception)
{
Console.WriteLine("Can't deserialize an empty stream");
return new List<Entry>();
}
}
}
}
namespace StoreDatabase
{
[Serializable]
public class Entry
{
public Product product;
public Avtostore avtostore;
public Separation separation;
public City city;
public Entry(int cost, string avtoname, string avtostore, string separation, string city)
{
product = new Product(avtoname, cost);
this.avtostore = new Avtostore(avtostore);
this.separation = new Separation(separation);
this.city = new City(city);
}
public void PrintEntry()
{
string productInfo = $"Product - {product}\n" +
$"Avtostore - {avtostore}\n" +
$"Separation - {separation}\n" +
$"Store location - {city} city.";
Console.WriteLine(productInfo);
}
}
}
namespace StoreDatabase
{
public class ConvertHelper
{
private delegate int StrToInt(string value);
public static int StringToInt(string value)
{
StrToInt strToInt = ConvertStrToInt;
return strToInt.Invoke(value);
}
private static int ConvertStrToInt(string value)
{
try
{
if (string.IsNullOrEmpty(value))
{
throw new StringNullOrEmpty($"can't convert {value} typeOf {value.GetType()} to int");
}
int result;
if (int.TryParse(value, out result))
{
return Int32.Parse(value);
}
return -1;
}
catch (StringNullOrEmpty e)
{
Console.WriteLine("Error: " + e.Message);
return -1;
}
}
}
}
namespace StoreDatabase
{
public class StringNullOrEmpty : Exception
{
public StringNullOrEmpty() : base()
{
}
public StringNullOrEmpty(string message) : base(message)
{
}
public StringNullOrEmpty(string message, Exception inner)
: base(message, inner)
{
}
}
}
namespace StoreDB
{
[Serializable]
public class City : ObjectStringify
{
public string city { get; }
public City(string city)
{
this.city = city;
}
}
}
namespace StoreDB
{
[Serializable]
public class Separation : ObjectStringify
{
public string separation { get; }
public Separation(string separation)
{
this.separation = separation;
}
}
}
namespace StoreDB
{
[Serializable]
public abstract class ObjectStringify
{
public override string ToString()
{
var propertiesArray = GetType().GetProperties();
if (propertiesArray[0].ReflectedType != typeof(Product))
{
return propertiesArray[0].GetValue(this, null).ToString();
}
string value = propertiesArray[0].GetValue(this, null)
+ $"\nCost - {propertiesArray[1].GetValue(this, null)}";
return value;
}
}
}
namespace StoreDB
{
[Serializable]
public class Product : ObjectStringify
{
public string avtoname { get; }
public int cost { get; }
public Product(string avtoname, int cost)
{
this.avtoname = avtoname;
this.cost = cost;
}
public static bool operator <(Product a, Product b)
{
return a.cost < b.cost;
}
public static bool operator >(Product a, Product b)
{
return a.cost > b.cost;
}
public static bool operator <=(Product a, Product b)
{
return a.cost <= b.cost;
}
public static bool operator >=(Product a, Product b)
{
return a.cost >= b.cost;
}
}
}
namespace StoreDB
{
[Serializable]
public class Avtostore : ObjectStringify
{
public string avtostore { get; }
public Avtostore(string avtostore)
{
this.avtostore = avtostore;
}
}
}