Материал: Лабораторная_работа_5_НикитинаДС

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам

Лабораторная работа 5 Вариант 2

классы для работы с файлами. сериализация

Никитина Дарья ПИН-31Д

Article.Cs

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

class ArticleComparer : IComparer<Article>

{

public int Compare(Article x, Article y)

{

if (x == null || y == null)

throw new ArgumentException("One or both arguments is not type of Article");

if (x.Score <= y.Score)

return x.Score == y.Score ? 0 : -1;

return 1;

}

}

[Serializable]

class Article : IRateAndCopy, IComparable, IComparer<Article>

{

public Person Author

{

get;

set;

}

public String Name

{

get;

set;

}

public double Score

{

get;

set;

}

public Article(Person a, string b, double c)

{

Author = a;

Name = b;

Score = c;

}

public Article()

{

Author = new Person();

Name = "";

Score = 0;

}

public override string ToString()

{

return Author.ToShortString() + "\n" + "Название статьи: " + Name + "\n" + "Рейтинг " + Score.ToString() + "\n";

}

public object DeepCopy()

{

Article Result = new Article();

Result.Author = (Person)Author.DeepCopy();

Result.Name = (string)Name.Clone();

Result.Score = Score;

return (object)Result;

}

public static Article Scan()

{

Person tauthor = (Person)Person.Scan().DeepCopy();

Console.WriteLine("Введите название");

string tname = Console.ReadLine();

Console.WriteLine("Введите рейтинг статьи");

double tRating = Convert.ToDouble(Console.ReadLine());

return new Article(tauthor, tname, tRating);

}

public int CompareTo(object obj)

{

if (obj == null) return 1;

Article article = obj as Article;

if (article != null)

return Name.CompareTo(obj);

throw new ArgumentException("Argument is not type of Article");

}

public int Compare(Article x, Article y)

{

if (x == null || y == null)

throw new ArgumentException("One or both arguments is not type of Article");

return string.Compare(x.Author.LName, y.Author.LName);

}

}

}

ChangeCollectionEventType.Cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

enum ChangeCollectionEventType

{

Add, Replace, Property

}

}

Edition.Cs

using System;

using System.Collections;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

[Serializable]

class Edition: INotifyPropertyChanged

{

protected string name;

protected DateTime outDate;

protected int count;

public event PropertyChangedEventHandler PropertyChanged;

public Edition(string name, DateTime date, int count)

{

this.name = name;

outDate = date;

this.count = count;

}

public Edition()

{

name = "";

outDate = DateTime.Now;

count = 0;

}

public string Name

{

get

{

return name;

}

set

{

name = value;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));

}

}

public DateTime OutDate

{

get

{

return outDate;

}

set

{

outDate = value;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("OutDate"));

}

}

public int Count

{

get

{

return count;

}

set

{

if (value > 0)

{

count = value;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count"));

}

else

{

ArgumentOutOfRangeException MyExeption = new ArgumentOutOfRangeException("_count", "Значение должно быть положительным");

throw MyExeption;

}

}

}

public virtual object DeepCopy()

{

Edition Result = new Edition();

Result.name = (string)this.name.Clone();

Result.outDate = this.outDate;

Result.count = this.count;

return (object)Result;

}

public override bool Equals(object obj)

{

Edition a = (Edition)obj;

return (string)a.name.Clone() == (string)this.name.Clone() && a.outDate == this.outDate && a.count == this.count;

}

public static bool operator ==(Edition a, Edition b)

{

return a.Equals(b);

}

public static bool operator !=(Edition a, Edition b)

{

return !a.Equals(b);

}

public override int GetHashCode()

{

return name.GetHashCode();

}

public override string ToString()

{

return name + " " + outDate.ToShortDateString() + " " + count;

}

public static Edition Scan()

{

Console.WriteLine("Введите название");

string tname = Console.ReadLine();

Console.WriteLine("Введите дату выхода");

DateTime TDate = DateTime.Parse(Console.ReadLine());

Console.WriteLine("Введите тираж");

int tcount = Convert.ToInt32(Console.ReadLine());

return new Edition((string)tname.Clone(), TDate, tcount);

}

}

}

Frequency.cs

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

enum Frequency

{

Weekly = 1, Monthly = 2, Yearly = 3

};

}

GenerateElement.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

delegate KeyValuePair<TKey, TValue> GenerateElement<TKey, TValue>(int j);

}

IRateAndCopy.cs

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

interface IRateAndCopy

{

double Score

{

get;

}

object DeepCopy();

}

}

Listener.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

class Listener<TKey>

{

private List<ListEntry> collectionsList = new List<ListEntry>();

public void OnChanged (MagazinesChangedEventArgs<TKey> args)

{

ListEntry newEntry = new ListEntry(args.CollectionName, args.EventType, args.ChangedProperty, args.ElementKey.ToString());

collectionsList.Add(newEntry);

}

public override string ToString()

{

string result = "";

foreach(ListEntry entry in collectionsList)

{

result += entry.ToString() + "\n\n";

}

return result;

}

}

class ListEntry

{

public string CollectionName { get; set; }

public ChangeCollectionEventType EventType { get; set; }

public string ChangedProperty { get; set; }

public string ElementKey { get; set; }

public ListEntry(string collectionName, ChangeCollectionEventType eventType, string changedProperty, string elementKey)

{

CollectionName = collectionName;

EventType = eventType;

ChangedProperty = changedProperty;

ElementKey = elementKey;

}

public override string ToString()

{

return string.Format(

"Collection name: {0}\nEvent type: {1}\nChanged property: {2}\nElement key: {3}",

CollectionName,

EventType,

ChangedProperty,

ElementKey

);

}

}

}

Magazine.Cs

using System;

using System.Collections;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

using System.Text;

using System.Threading.Tasks;

namespace DashaLabs

{

[Serializable]

class Magazine : Edition, IRateAndCopy, IEnumerable

{

private Frequency period;

private List<Person> editors;

private List<Article> articles;

public event PropertyChangedEventHandler PropertyChanged;

public double Score

{

get;

set;

}

public Magazine(string a, Frequency b, DateTime c, int d)

{

name = (string)a.Clone();

period = b;

outDate = c;

count = d;

editors = new List<Person>();

articles = new List<Article>();

}

public Magazine()

{

name = "";

period = Frequency.Monthly;

outDate = DateTime.Today;

count = 0;

editors = new List<Person>();

articles = new List<Article>();

}

public new String Name

{

get

{

return name;

}

set

{

name = value;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));

}

}

public Frequency Period

{

get

{

return period;

}

set

{

period = value;

}

}

public DateTime Outdate

{

get

{

return outDate;

}

set

{

outDate = value;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Outdate"));

}

}

public int Count

{

get

{

return count;

}

set

{

count = value;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count"));

}

}

public List<Article> Articles

{

get {

List<Article> result = new List<Article>();

articles.ForEach((art) => result.Add((Article)art.DeepCopy()));

return result;

}

set

{

List<Article> result = new List<Article>();

value.ForEach((art) => result.Add((Article)art.DeepCopy()));

articles = result;

}

}

public List<Person> Editors

{

get {

List<Person> result = new List<Person>();

editors.ForEach((persone) => result.Add((Person)persone.DeepCopy()));

return result;

}

set {

List<Person> result = new List<Person>();

value.ForEach((persone) => result.Add((Person)persone.DeepCopy()));

editors = result;

}

}

public bool this[Frequency a]

{

get

{

return period.Equals(a);

}

}

public void AddArticles(params Article[] a)

{

foreach (Article x in a)

articles.Add((Article)x.DeepCopy());

}

public void AddEditors(params Person[] a)

{

foreach (Person x in a)

editors.Add((Person)x.DeepCopy());

}

public override string ToString()

{

string result;

result = "Название: " + name + "\n" + "Периодичность: " + period.ToString() + "\n" + "Дата издания: " + outDate.ToShortDateString() + "\n" + "Тираж: " + count + "\n";

result += "Информация о статьях: \n";

foreach (Article a in articles)

result = result + a.ToString() + "\n";

foreach (Person a in editors)

result = result + a.ToString() + "\n";

return result;

}

public double AverageScore

{

get

{

double sum = 0;

foreach (Article a in articles)

sum += a.Score;

return sum / articles.Count;

}

}

public virtual string ToShortString()

{

return name + " " + period.ToString() + " " + outDate.ToShortDateString() + " " + count + "\n" + "Средний рейтинг: " + this.AverageScore;

}

public bool AddFromConsole()

{

Console.WriteLine("Введите данные о статье в следующем формате");

Console.WriteLine("ArticleName@FirstName@LastName@BirthDate@Score");

string result = Console.ReadLine();

try

{

string[] param = result.Split('@');

Person p = new Person(param[1], param[2], DateTime.Parse(param[3]));

Article article = new Article(p, param[0], Convert.ToDouble(param[4]));

articles.Add(article);

return true;

} catch (Exception e)

{

Console.WriteLine(e.Message);

}

return false;

}

public override object DeepCopy()

{

BinaryFormatter formatter = new BinaryFormatter();

Magazine result = new Magazine();

using(MemoryStream ms = new MemoryStream())

{

formatter.Serialize(ms, this);

ms.Seek(0, SeekOrigin.Begin);

result = (Magazine)formatter.Deserialize(ms);

}

return result;

}

public bool Save(string filename)

{

try

{

BinaryFormatter formatter = new BinaryFormatter();

using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate))

{

formatter.Serialize(fs, this);

}

} catch (Exception e)

{

Console.WriteLine(e);

return false;

}

return true;

}

public bool Load(string filename)

{

try

{

BinaryFormatter formatter = new BinaryFormatter();

using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate))

{

Magazine result = (Magazine)formatter.Deserialize(fs);

Articles = result.Articles;

Count = result.Count;

Editions = result.Editions;

Editors = result.Editors;

Name = result.Name;

OutDate = result.OutDate;

Outdate = result.Outdate;

Источник: https://studfile.net/preview/16465819/