From 3ee973d91144af0b8b5e1321c947ba2a7f5aff80 Mon Sep 17 00:00:00 2001 From: goodboyalex Date: Wed, 7 Jul 2021 22:54:57 +0300 Subject: [PATCH 1/6] 20210707 --- anbs_cp/LikeDelphi.cs | 27 ++++++++++++++++++++++----- anbs_cp/TypeConverter.cs | 4 +--- anbs_cp/anbs_cp.csproj | 4 ++-- 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/anbs_cp/LikeDelphi.cs b/anbs_cp/LikeDelphi.cs index 9103027..42be5e9 100644 --- a/anbs_cp/LikeDelphi.cs +++ b/anbs_cp/LikeDelphi.cs @@ -1,10 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace anbs_cp { - public class LikeDelphi + public static class LikeDelphi { /* * Аналог функции "IncludeTrailingBackslash @@ -19,5 +17,24 @@ namespace anbs_cp } return result; } + public static List ParseString(string AString, char ADelim) + { + int from = -1; + int to = AString.Length; + List result = new List(); + do + { + from++; + to = AString.IndexOf(ADelim, from); + if (to <= 0) + { + to = AString.Length; + } + if (from != to) + result.Add(AString.Substring(from, to - from)); + from = to; + } while (to != AString.Length); + return result; + } } -} +} \ No newline at end of file diff --git a/anbs_cp/TypeConverter.cs b/anbs_cp/TypeConverter.cs index a765c2d..1909928 100644 --- a/anbs_cp/TypeConverter.cs +++ b/anbs_cp/TypeConverter.cs @@ -1,6 +1,4 @@ -using System; - -namespace anbs_componentspack +namespace anbs_componentspack { public static class TypeConverter { diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj index 86a736d..7e7517f 100644 --- a/anbs_cp/anbs_cp.csproj +++ b/anbs_cp/anbs_cp.csproj @@ -4,8 +4,8 @@ netcoreapp3.1 0.1.0 Alexander Babaev - delphi2c# - Library to import some useful functions from Delphi language to C# language. + ANB Software Components Pack + Library of some useful functions in C# language. From ed50c4a0ccce99ca20daf7ceb3fc8615c5fdacd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20?= =?UTF-8?q?=D0=91=D0=B0=D0=B1=D0=B0=D0=B5=D0=B2?= Date: Tue, 2 Nov 2021 13:42:33 +0300 Subject: [PATCH 2/6] 20211102 --- anbs_cp/FileSizeFormatter.cs | 78 ++++++++++++++++++++++++++++++++++++ anbs_cp/TypeConverter.cs | 8 ++-- 2 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 anbs_cp/FileSizeFormatter.cs diff --git a/anbs_cp/FileSizeFormatter.cs b/anbs_cp/FileSizeFormatter.cs new file mode 100644 index 0000000..a3ed3e2 --- /dev/null +++ b/anbs_cp/FileSizeFormatter.cs @@ -0,0 +1,78 @@ +using System; +namespace anbs_cp +{ + /// + /// Форматирует размер файла/папки в понятную строку + /// + public static class FileSizeFormatter + { + /// + /// Имена размеров (байт, килобайт, мегабайт, гигабайт и террабайт) + /// + public static string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; + /// + /// Знаков после запятой + /// + public static byte DecimalPlaces { get; set; } = 2; + /// + /// Максимально байт (далее идут Кбайты) + /// + public static long ByteMax { get; set; } = 1024; + /// + /// Максимально Кбайт (далее идут Мбайты) + /// + public static long KByteMax { get; set; } = 1048576; + /// + /// Максимально Мбайт (далее идут Гбайты) + /// + public static long MByteMax { get; set; } = 1073741824; + /// + /// Максимально Гбайт (далее идут Тбайты) + /// + public static long GByteMax { get; set; } = 1099511627776; + /// + /// Форматирование размера файла + /// + /// Размер файла в Байтах + /// Форматированный размер файла (например, 20 Мб) + public static string Format(long value) + { + //Bytes + if (value < ByteMax) + return $"{value} {SizeNames[0]}"; + //KiloBytes + if ((value >= ByteMax) && (value < KByteMax)) + return $"{FrmtSize(value, ByteMax)} {SizeNames[1]}"; + //MegaBytes + if ((value >= KByteMax) && (value < MByteMax)) + return $"{FrmtSize(value, KByteMax)} {SizeNames[2]}"; + //GigaBytes + if ((value >= MByteMax) && (value < GByteMax)) + return $"{FrmtSize(value, MByteMax)} {SizeNames[3]}"; + //TeraBytes + if (value >= GByteMax) + return $"{FrmtSize(value, GByteMax)} {SizeNames[4]}"; + //Не определён + return $"{value} {SizeNames[0]}"; + } + /// + /// Деление числа на число с DecimalPlaces знаками после запятой + /// + /// Делимое число + /// Число-делитель + /// Частное (с DecimalPlaces знаками после запятой) + private static string FrmtSize(long dividend, long divider) + { + long delim = 1; + + for (int i = 0; i <= DecimalPlaces; i++) + { + delim *= 10; + } + + decimal value = Math.Round((decimal)(dividend * delim / divider)) / delim; + + return $"{value}"; + } + } +} \ No newline at end of file diff --git a/anbs_cp/TypeConverter.cs b/anbs_cp/TypeConverter.cs index 1909928..f5485b8 100644 --- a/anbs_cp/TypeConverter.cs +++ b/anbs_cp/TypeConverter.cs @@ -4,19 +4,19 @@ { public static string IntToStr(int AInt) => AInt.ToString(); public static string IntToStr(long AInt) => AInt.ToString(); - public static int StrToInt(string AStr) + public static int StrToInt(string AStr, int ADefault = 0) { if (!int.TryParse(AStr, out int result)) { - result = 0; + result = ADefault; } return result; } - public static long StrToInt64(string AStr) + public static long StrToInt64(string AStr, long ADefault = 0) { if (!long.TryParse(AStr, out long result)) { - result = 0; + result = ADefault; } return result; } From 3a9dc475e908f61bd3abd7a5d9c10b7ee2291d6f Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 12 Nov 2021 06:58:50 +0300 Subject: [PATCH 3/6] 20211111 --- anbs_cp/FileSizeFormatter.cs | 76 ++++++---------- anbs_cp/IValueFormatter.cs | 71 +++++++++++++++ anbs_cp/LikeDelphi.cs | 44 ++++++---- anbs_cp/TStringList.cs | 164 ----------------------------------- anbs_cp/TypeConverter.cs | 94 +++++++++++++++++++- anbs_cp/anbs_cp.csproj | 26 +++++- 6 files changed, 239 insertions(+), 236 deletions(-) create mode 100644 anbs_cp/IValueFormatter.cs delete mode 100644 anbs_cp/TStringList.cs diff --git a/anbs_cp/FileSizeFormatter.cs b/anbs_cp/FileSizeFormatter.cs index a3ed3e2..a4cbd33 100644 --- a/anbs_cp/FileSizeFormatter.cs +++ b/anbs_cp/FileSizeFormatter.cs @@ -1,78 +1,56 @@ -using System; -namespace anbs_cp +namespace anbs_cp { /// /// Форматирует размер файла/папки в понятную строку /// - public static class FileSizeFormatter + public class FileSizeFormatter : IValueFormatter { + #region Cвойства класса /// /// Имена размеров (байт, килобайт, мегабайт, гигабайт и террабайт) /// - public static string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; + public string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; /// /// Знаков после запятой /// - public static byte DecimalPlaces { get; set; } = 2; + public byte DecimalPlaces { get; set; } = 2; /// /// Максимально байт (далее идут Кбайты) /// - public static long ByteMax { get; set; } = 1024; + public long ByteMax { get; set; } = 1024; /// /// Максимально Кбайт (далее идут Мбайты) /// - public static long KByteMax { get; set; } = 1048576; + public long KByteMax { get; set; } = 1048576; /// /// Максимально Мбайт (далее идут Гбайты) /// - public static long MByteMax { get; set; } = 1073741824; + public long MByteMax { get; set; } = 1073741824; /// /// Максимально Гбайт (далее идут Тбайты) /// - public static long GByteMax { get; set; } = 1099511627776; - /// - /// Форматирование размера файла - /// - /// Размер файла в Байтах - /// Форматированный размер файла (например, 20 Мб) - public static string Format(long value) - { - //Bytes - if (value < ByteMax) - return $"{value} {SizeNames[0]}"; - //KiloBytes - if ((value >= ByteMax) && (value < KByteMax)) - return $"{FrmtSize(value, ByteMax)} {SizeNames[1]}"; - //MegaBytes - if ((value >= KByteMax) && (value < MByteMax)) - return $"{FrmtSize(value, KByteMax)} {SizeNames[2]}"; - //GigaBytes - if ((value >= MByteMax) && (value < GByteMax)) - return $"{FrmtSize(value, MByteMax)} {SizeNames[3]}"; - //TeraBytes - if (value >= GByteMax) - return $"{FrmtSize(value, GByteMax)} {SizeNames[4]}"; - //Не определён - return $"{value} {SizeNames[0]}"; - } - /// - /// Деление числа на число с DecimalPlaces знаками после запятой - /// - /// Делимое число - /// Число-делитель - /// Частное (с DecimalPlaces знаками после запятой) - private static string FrmtSize(long dividend, long divider) - { - long delim = 1; + public long GByteMax { get; set; } = 1099511627776; + #endregion - for (int i = 0; i <= DecimalPlaces; i++) + #region Реализация интерфейса + /// + /// Реализация интерфейса + /// + public string[] ValueNames { get => SizeNames; set => SizeNames = value; } + /// + /// Реализация интерфейса + /// + public long[] MaxSizes + { + get => new long[] { ByteMax, KByteMax, MByteMax, GByteMax }; + set { - delim *= 10; + ByteMax = value[0]; + KByteMax = value[1]; + MByteMax = value[2]; + GByteMax = value[3]; } - - decimal value = Math.Round((decimal)(dividend * delim / divider)) / delim; - - return $"{value}"; } + #endregion } } \ No newline at end of file diff --git a/anbs_cp/IValueFormatter.cs b/anbs_cp/IValueFormatter.cs new file mode 100644 index 0000000..510d18e --- /dev/null +++ b/anbs_cp/IValueFormatter.cs @@ -0,0 +1,71 @@ +namespace anbs_cp +{ + /// + /// Форматирует размерности в понятную строку + /// + public interface IValueFormatter + { + + #region Определения интерфейса + /// + /// Имена размерностей + /// + public string[] ValueNames { get; set; } + /// + /// Знаков после запятой + /// + public byte DecimalPlaces { get; set; } + /// + /// Максимальные размеры (массив ulong[4]) + /// + public long[] MaxSizes { get; set; } + #endregion + + #region Методы интерфейса + /// + /// Форматирование размерности + /// + /// Размерность, требующая форматирования + /// Форматированная размерность (например, 20 Мб) + public string Format(long value) + { + //Bytes + if (value < MaxSizes[0]) + return $"{value} {ValueNames[0]}"; + //KiloBytes + if ((value >= MaxSizes[0]) && (value < MaxSizes[1])) + return $"{FrmtSize(value, MaxSizes[0])} {ValueNames[1]}"; + //MegaBytes + if ((value >= MaxSizes[1]) && (value < MaxSizes[2])) + return $"{FrmtSize(value, MaxSizes[1])} {ValueNames[2]}"; + //GigaBytes + if ((value >= MaxSizes[2]) && (value < MaxSizes[3])) + return $"{FrmtSize(value, MaxSizes[2])} {ValueNames[3]}"; + //TeraBytes + if (value >= MaxSizes[3]) + return $"{FrmtSize(value, MaxSizes[3])} {ValueNames[4]}"; + //Не определён + return $"{value} {ValueNames[0]}"; + } + /// + /// Деление числа на число с DecimalPlaces знаками после запятой + /// + /// Делимое число + /// Число-делитель + /// Частное (с DecimalPlaces знаками после запятой) + private string FrmtSize(long dividend, long divider) + { + long delim = 1; + + for (int i = 0; i <= DecimalPlaces; i++) + { + delim *= 10; + } + + decimal value = Math.Round((decimal)(dividend * delim / divider)) / delim; + + return $"{value}"; + } + #endregion + } +} \ No newline at end of file diff --git a/anbs_cp/LikeDelphi.cs b/anbs_cp/LikeDelphi.cs index 42be5e9..bf6831d 100644 --- a/anbs_cp/LikeDelphi.cs +++ b/anbs_cp/LikeDelphi.cs @@ -1,39 +1,47 @@ using System.Collections.Generic; - namespace anbs_cp { + /// + /// Класс, добавляющий реализацию некоторых методов Delphi, которые упрощают работу в C#. + /// public static class LikeDelphi { - /* - * Аналог функции "IncludeTrailingBackslash - */ - public static string IncludeTrailingBackslash(string Path) + /// + /// Аналог функции IncludeTrailingBackslash + /// + /// Путь, к которому нужно добавить slash + /// Путь со slash в конце + public static string IncludeTrailingBackslash(string path) { - string result = Path; - int Index = Path.Length - 1; - if (Path[Index] != '\\') + string result = path; + int Index = path.Length - 1; + if (path[Index] != '\\') { - result = $"{Path}\\"; + result = $"{path}\\"; } return result; } - public static List ParseString(string AString, char ADelim) + /// + /// Парсер строки в множество строк + /// + /// Строка, которую нужно разбить + /// Символ-делитель строки + /// Массив строк + public static List ParseString(string astring, char delim) { int from = -1; - int to = AString.Length; - List result = new List(); + int to; + List result = new(); do { from++; - to = AString.IndexOf(ADelim, from); + to = astring.IndexOf(delim, from); if (to <= 0) - { - to = AString.Length; - } + to = astring.Length; if (from != to) - result.Add(AString.Substring(from, to - from)); + result.Add(astring[from..(to-from)]); from = to; - } while (to != AString.Length); + } while (to != astring.Length); return result; } } diff --git a/anbs_cp/TStringList.cs b/anbs_cp/TStringList.cs deleted file mode 100644 index 596556d..0000000 --- a/anbs_cp/TStringList.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace anbs_componentspack -{ - public enum TStringListType - { - sltStringsOnly, //Только строки -- сортировка по строкам включена, имеющиеся объекты удалит - sltObjectsOnly, //Только объекты -- сортировка по объектам включена - sltBoth //И строки, и объекты -- сортировка отключена - } - public class TStringList - { - private List FLines; - private List FObjects; - private TStringListType type = TStringListType.sltBoth; - public TStringListType Type { get => type; set => type = value; } - public int Count => FLines.Count; - public override bool Equals(object obj) - { - return obj is TStringList list && - Count == list.Count; - } - public override int GetHashCode() - { - return HashCode.Combine(Count); - } - public void Add(string AString) - { - if (!(type == TStringListType.sltObjectsOnly)) - { - FLines.Add(AString); - if (!(type == TStringListType.sltStringsOnly)) - { - FObjects.Add(AString); - } - } - } - public void Add(object AObject) - { - if (!(type == TStringListType.sltStringsOnly)) - { - if (!(type == TStringListType.sltObjectsOnly)) - { - FLines.Add(AObject.ToString()); - - } - FObjects.Add(AObject); - } - } - public void Add(string AString, object AObject) - { - if (!(type == TStringListType.sltStringsOnly) && !(type == TStringListType.sltObjectsOnly)) - { - FLines.Add(AString); - FObjects.Add(AObject); - } - } - public (string, object) Get(int Index) => (FLines[Index], FObjects[Index]); - public string GetString(int Index) - { - string result = ""; - if (!(type == TStringListType.sltObjectsOnly)) - { - result = FLines[Index]; - } - return result; - } - public object GetObject(int Index) - { - object result = null; - if (!(type == TStringListType.sltStringsOnly)) - { - result = FObjects[Index]; - } - return result; - } - public void Delete(int Index) - { - if (!(type == TStringListType.sltObjectsOnly)) - { - FLines.RemoveAt(Index); - } - if (!(type == TStringListType.sltStringsOnly)) - { - FObjects.RemoveAt(Index); - } - } - public int IndexOf(string AString) => FLines.IndexOf(AString); - public int IndexOf(object AObject) => FObjects.IndexOf(AObject); - public void Sort() - { - switch (type) - { - case TStringListType.sltStringsOnly: - FLines.Sort(); - break; - case TStringListType.sltObjectsOnly: - FObjects.Sort(); - break; - case TStringListType.sltBoth: - break; - default: - break; - } - } - public void Clear() - { - FLines.Clear(); - FObjects.Clear(); - } - public void Assign(List ALines) - { - if (!(type == TStringListType.sltStringsOnly)) - { - throw new ArgumentException("Assign method works in TStringList only for the sltStringsOnly type. Your changes are not applied!"); - } - Clear(); - FLines.AddRange(ALines); - } - public string DelimetedText(char Delimeter) - { - string result = ""; - if (!(type == TStringListType.sltObjectsOnly)) - { - for (int i = 0; i < FLines.Count; i++) - { - result = $"{result}{Delimeter}{FLines[i]}"; - } - } - return result; - } - public string Text() - { - char Delim = '\n'; - return DelimetedText(Delim); - } - public void LoadFromFile(string FileName) - { - if (!File.Exists(FileName)) - { - throw new FileNotFoundException(); - } - StreamReader sr = new StreamReader(FileName); - string line = sr.ReadLine(); - while (line != null) - { - FLines.Add(line); - line = sr.ReadLine(); - } - sr.Close(); - } - public void SaveToFile(string FileName) - { - StreamWriter sw = new StreamWriter(FileName); - for (int i = 0; i < FLines.Count; i++) - { - sw.WriteLine(FLines[i]); - } - sw.Close(); - } - } -} diff --git a/anbs_cp/TypeConverter.cs b/anbs_cp/TypeConverter.cs index f5485b8..3ab4951 100644 --- a/anbs_cp/TypeConverter.cs +++ b/anbs_cp/TypeConverter.cs @@ -1,9 +1,50 @@ -namespace anbs_componentspack +namespace anbs_cp { + /// + /// Конвертер типов на манер Delphi + /// public static class TypeConverter { + #region Конвертация числа в строку + /// + /// Преобразование int в string + /// + /// Число + /// Строка public static string IntToStr(int AInt) => AInt.ToString(); + /// + /// Преобразование uint в string + /// + /// Число + /// Строка + public static string IntToStr(uint AInt) => AInt.ToString(); + /// + /// Преобразование long в string + /// + /// Число + /// Строка public static string IntToStr(long AInt) => AInt.ToString(); + /// + /// Преобразование ulong в string + /// + /// Число + /// Строка + public static string IntToStr(ulong AInt) => AInt.ToString(); + /// + /// Преобразование byte в string + /// + /// Число + /// Строка + public static string IntToStr(byte AInt) => AInt.ToString(); + #endregion + + #region Конвертация строки в число + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число public static int StrToInt(string AStr, int ADefault = 0) { if (!int.TryParse(AStr, out int result)) @@ -12,6 +53,26 @@ } return result; } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число + public static uint StrToUInt(string AStr, uint ADefault = 0) + { + if (!uint.TryParse(AStr, out uint result)) + { + result = ADefault; + } + return result; + } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число public static long StrToInt64(string AStr, long ADefault = 0) { if (!long.TryParse(AStr, out long result)) @@ -20,5 +81,34 @@ } return result; } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число + public static ulong StrToUInt64(string AStr, ulong ADefault = 0) + { + if (!ulong.TryParse(AStr, out ulong result)) + { + result = ADefault; + } + return result; + } + /// + /// Преобразование строки в число + /// + /// Строка + /// Значение по умолчанию (по умолчанию, 0) + /// Число + public static byte StrToByte(string AStr, byte ADefault = 0) + { + if (!byte.TryParse(AStr, out byte result)) + { + result = ADefault; + } + return result; + } + #endregion } -} +} \ No newline at end of file diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj index 7e7517f..f7f326e 100644 --- a/anbs_cp/anbs_cp.csproj +++ b/anbs_cp/anbs_cp.csproj @@ -1,12 +1,32 @@ - netcoreapp3.1 - 0.1.0 + net6.0-windows + 1.20211111.0 Alexander Babaev ANB Software Components Pack Library of some useful functions in C# language. - + Alexander Babaev + anbs_cp + anbs_cp + enable + enable + True + False + https://github.com/GoodBoyAlex/anbsoftware_componentspack + https://github.com/GoodBoyAlex/anbsoftware_componentspack + 1.2021.1111 + 1.2021.1111 + + + + 2 + True + + + + 2 + True From 2d69035bd72754d001c4810978bf0f0e42b3e23e Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 12 Nov 2021 07:12:08 +0300 Subject: [PATCH 4/6] 20211111-1 --- anbs_cp/CountFormatter.cs | 60 ++++++++++++++++++++++++++++++++++++ anbs_cp/FileSizeFormatter.cs | 4 +++ anbs_cp/anbs_cp.csproj | 2 +- 3 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 anbs_cp/CountFormatter.cs diff --git a/anbs_cp/CountFormatter.cs b/anbs_cp/CountFormatter.cs new file mode 100644 index 0000000..f6b608b --- /dev/null +++ b/anbs_cp/CountFormatter.cs @@ -0,0 +1,60 @@ +namespace anbs_cp +{ + /// + /// Форматирует число элементов в понятную строку + /// + public class CountFormatter : IValueFormatter + { + #region Cвойства класса + /// + /// Имена чисел ( , тысяч, миллионов, миллиардов и триллионов) + /// + public string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; + /// + /// Знаков после запятой + /// + public byte DecimalPlaces { get; set; } = 2; + /// + /// Максимально байт (далее идут Кбайты) + /// + public long ByteMax { get; set; } = 1024; + /// + /// Максимально Кбайт (далее идут Мбайты) + /// + public long KByteMax { get; set; } = 1048576; + /// + /// Максимально Мбайт (далее идут Гбайты) + /// + public long MByteMax { get; set; } = 1073741824; + /// + /// Максимально Гбайт (далее идут Тбайты) + /// + public long GByteMax { get; set; } = 1099511627776; + #endregion + + #region Реализация интерфейса + /// + /// Реализация интерфейса + /// + public string[] ValueNames { get => SizeNames; set => SizeNames = value; } + /// + /// Реализация интерфейса + /// + public long[] MaxSizes + { + get => new long[] { ByteMax, KByteMax, MByteMax, GByteMax }; + set + { + ByteMax = value[0]; + KByteMax = value[1]; + MByteMax = value[2]; + GByteMax = value[3]; + } + } + /// + /// Реализация интерфейса + /// + public string Format(long value) => (this as IValueFormatter).Format(value); + #endregion + } +} \ No newline at end of file diff --git a/anbs_cp/FileSizeFormatter.cs b/anbs_cp/FileSizeFormatter.cs index a4cbd33..e8e5537 100644 --- a/anbs_cp/FileSizeFormatter.cs +++ b/anbs_cp/FileSizeFormatter.cs @@ -51,6 +51,10 @@ GByteMax = value[3]; } } + /// + /// Реализация интерфейса + /// + public string Format(long value) => (this as IValueFormatter).Format(value); #endregion } } \ No newline at end of file diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj index f7f326e..bc9380c 100644 --- a/anbs_cp/anbs_cp.csproj +++ b/anbs_cp/anbs_cp.csproj @@ -1,7 +1,7 @@ - net6.0-windows + net6.0 1.20211111.0 Alexander Babaev ANB Software Components Pack From 438c1238767ffca7fb738ca693eef66efb9135c3 Mon Sep 17 00:00:00 2001 From: Alexander Babaev Date: Fri, 12 Nov 2021 14:55:04 +0300 Subject: [PATCH 5/6] 20211112 --- anbs_cp/CountFormatter.cs | 40 ++-------- anbs_cp/FileSizeFormatter.cs | 4 - anbs_cp/IValueFormatter.cs | 47 ++++++----- anbs_cp/anbs_cp.csproj | 4 + anbsoftware.componentspack.sln | 12 ++- demo/CountValueTest.Designer.cs | 134 ++++++++++++++++++++++++++++++++ demo/CountValueTest.cs | 42 ++++++++++ demo/CountValueTest.resx | 60 ++++++++++++++ demo/Program.cs | 15 ++++ demo/demo.csproj | 16 ++++ 10 files changed, 317 insertions(+), 57 deletions(-) create mode 100644 demo/CountValueTest.Designer.cs create mode 100644 demo/CountValueTest.cs create mode 100644 demo/CountValueTest.resx create mode 100644 demo/Program.cs create mode 100644 demo/demo.csproj diff --git a/anbs_cp/CountFormatter.cs b/anbs_cp/CountFormatter.cs index f6b608b..05bba3a 100644 --- a/anbs_cp/CountFormatter.cs +++ b/anbs_cp/CountFormatter.cs @@ -7,54 +7,28 @@ { #region Cвойства класса /// - /// Имена чисел ( , тысяч, миллионов, миллиардов и триллионов) + /// Имена чисел (тысяч, миллионов, миллиардов и т.п.) /// - public string[] SizeNames { get; set; } = { "Байт", "Кб", "Мб", "Гб", "Тб" }; + public string[] CountNames { get; set; } = { "", "тыс.", "млн.", "млрд." }; /// /// Знаков после запятой /// - public byte DecimalPlaces { get; set; } = 2; + public byte DecimalPlaces { get; set; } = 1; /// - /// Максимально байт (далее идут Кбайты) + /// Делители чисел /// - public long ByteMax { get; set; } = 1024; - /// - /// Максимально Кбайт (далее идут Мбайты) - /// - public long KByteMax { get; set; } = 1048576; - /// - /// Максимально Мбайт (далее идут Гбайты) - /// - public long MByteMax { get; set; } = 1073741824; - /// - /// Максимально Гбайт (далее идут Тбайты) - /// - public long GByteMax { get; set; } = 1099511627776; + public long[] Delimeters { get; set; } = { 1000, 1000000, 1000000000 }; #endregion #region Реализация интерфейса /// /// Реализация интерфейса /// - public string[] ValueNames { get => SizeNames; set => SizeNames = value; } + public string[] ValueNames { get => CountNames; set => CountNames = value; } /// /// Реализация интерфейса /// - public long[] MaxSizes - { - get => new long[] { ByteMax, KByteMax, MByteMax, GByteMax }; - set - { - ByteMax = value[0]; - KByteMax = value[1]; - MByteMax = value[2]; - GByteMax = value[3]; - } - } - /// - /// Реализация интерфейса - /// - public string Format(long value) => (this as IValueFormatter).Format(value); + public long[] MaxSizes { get => Delimeters; set => Delimeters = value; } #endregion } } \ No newline at end of file diff --git a/anbs_cp/FileSizeFormatter.cs b/anbs_cp/FileSizeFormatter.cs index e8e5537..a4cbd33 100644 --- a/anbs_cp/FileSizeFormatter.cs +++ b/anbs_cp/FileSizeFormatter.cs @@ -51,10 +51,6 @@ GByteMax = value[3]; } } - /// - /// Реализация интерфейса - /// - public string Format(long value) => (this as IValueFormatter).Format(value); #endregion } } \ No newline at end of file diff --git a/anbs_cp/IValueFormatter.cs b/anbs_cp/IValueFormatter.cs index 510d18e..36e0d3b 100644 --- a/anbs_cp/IValueFormatter.cs +++ b/anbs_cp/IValueFormatter.cs @@ -29,23 +29,29 @@ /// Форматированная размерность (например, 20 Мб) public string Format(long value) { - //Bytes - if (value < MaxSizes[0]) - return $"{value} {ValueNames[0]}"; - //KiloBytes - if ((value >= MaxSizes[0]) && (value < MaxSizes[1])) - return $"{FrmtSize(value, MaxSizes[0])} {ValueNames[1]}"; - //MegaBytes - if ((value >= MaxSizes[1]) && (value < MaxSizes[2])) - return $"{FrmtSize(value, MaxSizes[1])} {ValueNames[2]}"; - //GigaBytes - if ((value >= MaxSizes[2]) && (value < MaxSizes[3])) - return $"{FrmtSize(value, MaxSizes[2])} {ValueNames[3]}"; - //TeraBytes - if (value >= MaxSizes[3]) - return $"{FrmtSize(value, MaxSizes[3])} {ValueNames[4]}"; - //Не определён - return $"{value} {ValueNames[0]}"; + //Левая граница + long leftnum; + //Правая граница + long rightnum; + + for (int i = 0; i <= MaxSizes.Length; i++) + { + if (i == 0) + leftnum = 0; + else + leftnum = MaxSizes[i - 1]; + + if (i == MaxSizes.Length) + rightnum = long.MaxValue; + else + rightnum = MaxSizes[i]; + + if ((value >= leftnum) && (value < rightnum)) + return $"{FormatValue(value, leftnum)} {ValueNames[i]}"; + + } + + return value.ToString(); } /// /// Деление числа на число с DecimalPlaces знаками после запятой @@ -53,8 +59,13 @@ /// Делимое число /// Число-делитель /// Частное (с DecimalPlaces знаками после запятой) - private string FrmtSize(long dividend, long divider) + private string FormatValue(long dividend, long divider) { + if (divider == 0) + { + return $"{dividend}"; + } + long delim = 1; for (int i = 0; i <= DecimalPlaces; i++) diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj index bc9380c..8d583a6 100644 --- a/anbs_cp/anbs_cp.csproj +++ b/anbs_cp/anbs_cp.csproj @@ -29,4 +29,8 @@ True + + + + diff --git a/anbsoftware.componentspack.sln b/anbsoftware.componentspack.sln index 4570fac..adc732b 100644 --- a/anbsoftware.componentspack.sln +++ b/anbsoftware.componentspack.sln @@ -1,10 +1,15 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31424.327 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "anbs_cp", "anbs_cp\anbs_cp.csproj", "{442A56CC-1061-4EB5-8B67-3E3D997976D7}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "demo", "demo\demo.csproj", "{3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}" + ProjectSection(ProjectDependencies) = postProject + {442A56CC-1061-4EB5-8B67-3E3D997976D7} = {442A56CC-1061-4EB5-8B67-3E3D997976D7} + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +20,9 @@ Global {442A56CC-1061-4EB5-8B67-3E3D997976D7}.Debug|Any CPU.Build.0 = Debug|Any CPU {442A56CC-1061-4EB5-8B67-3E3D997976D7}.Release|Any CPU.ActiveCfg = Release|Any CPU {442A56CC-1061-4EB5-8B67-3E3D997976D7}.Release|Any CPU.Build.0 = Release|Any CPU + {3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}.Debug|Any CPU.Build.0 = Release|Any CPU + {3BB0778D-3C34-4DD8-A54E-CB476BEF2F7B}.Release|Any CPU.ActiveCfg = Debug.CNF|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/demo/CountValueTest.Designer.cs b/demo/CountValueTest.Designer.cs new file mode 100644 index 0000000..6656a3b --- /dev/null +++ b/demo/CountValueTest.Designer.cs @@ -0,0 +1,134 @@ +namespace demo +{ + partial class CountValueTest + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.InsertDataLabel = new System.Windows.Forms.Label(); + this.InsertDataBox = new System.Windows.Forms.TextBox(); + this.ResultLabel = new System.Windows.Forms.Label(); + this.CalculateButton = new System.Windows.Forms.Button(); + this.SelectFormatterLabel = new System.Windows.Forms.Label(); + this.SelectFormatterBox = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // InsertDataLabel + // + this.InsertDataLabel.AutoSize = true; + this.InsertDataLabel.Location = new System.Drawing.Point(12, 66); + this.InsertDataLabel.Name = "InsertDataLabel"; + this.InsertDataLabel.Size = new System.Drawing.Size(197, 17); + this.InsertDataLabel.TabIndex = 0; + this.InsertDataLabel.Text = "&Insert any int value:"; + // + // InsertDataBox + // + this.InsertDataBox.Location = new System.Drawing.Point(12, 86); + this.InsertDataBox.Name = "InsertDataBox"; + this.InsertDataBox.Size = new System.Drawing.Size(246, 24); + this.InsertDataBox.TabIndex = 1; + // + // ResultLabel + // + this.ResultLabel.Dock = System.Windows.Forms.DockStyle.Bottom; + this.ResultLabel.Location = new System.Drawing.Point(0, 143); + this.ResultLabel.Margin = new System.Windows.Forms.Padding(5); + this.ResultLabel.Name = "ResultLabel"; + this.ResultLabel.Padding = new System.Windows.Forms.Padding(5); + this.ResultLabel.Size = new System.Drawing.Size(270, 79); + this.ResultLabel.TabIndex = 2; + this.ResultLabel.Text = "&Insert any int value to insert box above and press \"Calculate\" button to see res" + + "ult..."; + this.ResultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // CalculateButton + // + this.CalculateButton.Location = new System.Drawing.Point(81, 116); + this.CalculateButton.Name = "CalculateButton"; + this.CalculateButton.Size = new System.Drawing.Size(103, 23); + this.CalculateButton.TabIndex = 3; + this.CalculateButton.Text = "Calc&ulate"; + this.CalculateButton.UseVisualStyleBackColor = true; + this.CalculateButton.Click += new System.EventHandler(this.CalculateButton_Click); + // + // SelectFormatterLabel + // + this.SelectFormatterLabel.AutoSize = true; + this.SelectFormatterLabel.Location = new System.Drawing.Point(12, 9); + this.SelectFormatterLabel.Name = "SelectFormatterLabel"; + this.SelectFormatterLabel.Size = new System.Drawing.Size(161, 17); + this.SelectFormatterLabel.TabIndex = 4; + this.SelectFormatterLabel.Text = "&Select formatter:"; + // + // SelectFormatterBox + // + this.SelectFormatterBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.SelectFormatterBox.FlatStyle = System.Windows.Forms.FlatStyle.System; + this.SelectFormatterBox.FormattingEnabled = true; + this.SelectFormatterBox.Items.AddRange(new object[] { + "CountFormatter", + "FileSizeFormatter"}); + this.SelectFormatterBox.Location = new System.Drawing.Point(12, 29); + this.SelectFormatterBox.Name = "SelectFormatterBox"; + this.SelectFormatterBox.Size = new System.Drawing.Size(246, 25); + this.SelectFormatterBox.TabIndex = 5; + // + // CountValueTest + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 17F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(270, 222); + this.Controls.Add(this.SelectFormatterBox); + this.Controls.Add(this.SelectFormatterLabel); + this.Controls.Add(this.CalculateButton); + this.Controls.Add(this.ResultLabel); + this.Controls.Add(this.InsertDataBox); + this.Controls.Add(this.InsertDataLabel); + this.Font = new System.Drawing.Font("Courier New", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); + this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "CountValueTest"; + this.ShowIcon = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Formatter Test Unit"; + this.Load += new System.EventHandler(this.CountValueTest_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label InsertDataLabel; + private TextBox InsertDataBox; + private Label ResultLabel; + private Button CalculateButton; + private Label SelectFormatterLabel; + private ComboBox SelectFormatterBox; + } +} \ No newline at end of file diff --git a/demo/CountValueTest.cs b/demo/CountValueTest.cs new file mode 100644 index 0000000..defe9b7 --- /dev/null +++ b/demo/CountValueTest.cs @@ -0,0 +1,42 @@ +using anbs_cp; +namespace demo +{ + public partial class CountValueTest : Form + { + public CountValueTest() + { + InitializeComponent(); + } + + private void CalculateButton_Click(object sender, EventArgs e) + { + + if (string.IsNullOrEmpty(InsertDataBox.Text)) + return; + + IValueFormatter formatter; + + long value = TypeConverter.StrToInt64(InsertDataBox.Text); + + switch (SelectFormatterBox.SelectedIndex) + { + case 0: + formatter = new CountFormatter(); + break; + case 1: + formatter = new FileSizeFormatter(); + break; + default: + formatter = new CountFormatter(); + break; + } + + ResultLabel.Text = formatter.Format(value); + } + + private void CountValueTest_Load(object sender, EventArgs e) + { + SelectFormatterBox.SelectedIndex = 0; + } + } +} \ No newline at end of file diff --git a/demo/CountValueTest.resx b/demo/CountValueTest.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/demo/CountValueTest.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/demo/Program.cs b/demo/Program.cs new file mode 100644 index 0000000..47c0157 --- /dev/null +++ b/demo/Program.cs @@ -0,0 +1,15 @@ +namespace demo +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); + Application.Run(new CountValueTest()); + } + } +} \ No newline at end of file diff --git a/demo/demo.csproj b/demo/demo.csproj new file mode 100644 index 0000000..10977d6 --- /dev/null +++ b/demo/demo.csproj @@ -0,0 +1,16 @@ + + + + WinExe + net6.0-windows + enable + true + enable + Release;Debug.CNF + + + + + + + \ No newline at end of file From f7949f8e6daa45c6f59fa59cbef7f1dfa7a16a8c Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 12 Nov 2021 19:39:03 +0300 Subject: [PATCH 6/6] Create README.md --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..55a1358 --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# anbsoftware_componentspack +some classes that extend the capabilities of the C # language + +# Welcome to ANB Software Components Pack! + +You are on the component set «ANB» page. Thanks for your interest in the project + +# License + +MIIT