diff --git a/src/RevitCheckingLevels/Models/CheckingLevelConfig.cs b/src/RevitCheckingLevels/Models/CheckingLevelConfig.cs index da7fa27fa..917b677e9 100644 --- a/src/RevitCheckingLevels/Models/CheckingLevelConfig.cs +++ b/src/RevitCheckingLevels/Models/CheckingLevelConfig.cs @@ -1,34 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - using Autodesk.Revit.DB; -using dosymep.Bim4Everyone.ProjectConfigs; using dosymep.Bim4Everyone; +using dosymep.Bim4Everyone.ProjectConfigs; using dosymep.Serializers; + using pyRevitLabs.Json; -namespace RevitCheckingLevels.Models { - internal class CheckingLevelConfig : ProjectConfig { - [JsonIgnore] public override string ProjectConfigPath { get; set; } +namespace RevitCheckingLevels.Models; +internal class CheckingLevelConfig : ProjectConfig { + [JsonIgnore] public override string ProjectConfigPath { get; set; } - [JsonIgnore] public override IConfigSerializer Serializer { get; set; } + [JsonIgnore] public override IConfigSerializer Serializer { get; set; } - public static CheckingLevelConfig GetCheckingLevelConfig() { - return new ProjectConfigBuilder() - .SetSerializer(new ConfigSerializer()) - .SetPluginName(nameof(RevitCheckingLevels)) - .SetRevitVersion(ModuleEnvironment.RevitVersion) - .SetProjectConfigName(nameof(CheckingLevelConfig) + ".json") - .Build(); - } + public static CheckingLevelConfig GetCheckingLevelConfig() { + return new ProjectConfigBuilder() + .SetSerializer(new ConfigSerializer()) + .SetPluginName(nameof(RevitCheckingLevels)) + .SetRevitVersion(ModuleEnvironment.RevitVersion) + .SetProjectConfigName(nameof(CheckingLevelConfig) + ".json") + .Build(); } +} - internal class CheckingLevelSettings : ProjectSettings { - public ElementId LinkTypeId { get; set; } - public override string ProjectName { get; set; } - } +internal class CheckingLevelSettings : ProjectSettings { + public ElementId LinkTypeId { get; set; } + public override string ProjectName { get; set; } } diff --git a/src/RevitCheckingLevels/Models/ErrorType.cs b/src/RevitCheckingLevels/Models/ErrorType.cs index 1f8d2a9a7..d2c52f0c8 100644 --- a/src/RevitCheckingLevels/Models/ErrorType.cs +++ b/src/RevitCheckingLevels/Models/ErrorType.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,192 +6,167 @@ using RevitCheckingLevels.Models.LevelParser; -namespace RevitCheckingLevels.Models { - internal class ErrorType : IEquatable, IComparable, IComparable { - public static readonly ErrorType NotStandard = - new ErrorType(0) { - Name = "Имена уровней не соответствуют стандарту", - Description = - "Имена уровней должны соответствовать данному формату: \"[Название этажа][\'_\'][Название блока][\'.\'][Номер уровня][\'_\'][Отметка уровня]\"." - }; - - public static readonly ErrorType NotElevation = - new ErrorType(1) { - Name = "Отметки уровня не соответствуют фактическим", - Description = - $"Имена уровней должны оканчиваться значением параметра \"{LabelUtils.GetLabelFor(BuiltInParameter.LEVEL_ELEV)}\" в метрах с разделителем дробной части в виде точки." - }; - - public static readonly ErrorType NotMillimeterElevation = - new ErrorType(2) { - Name = "Отметка уровня не округлена", - Description = - $"Значение параметра \"{LabelUtils.GetLabelFor(BuiltInParameter.LEVEL_ELEV)}\" (в миллиметрах) до 7 знака после запятой должно быть равно \"0\"." - }; - - public static readonly ErrorType NotRangeElevation = - new ErrorType(3) { - Name = "Уровни замоделированы не по стандарту", - Description = - $"Значение параметра \"{LabelUtils.GetLabelFor(BuiltInParameter.LEVEL_ELEV)}\" должно отступать на 1500мм от предыдущего." - }; - - public static readonly ErrorType NotFoundLevels = - new ErrorType(4) { - Name = "Уровни не найдены в координационном файле", - Description = "Все уровни проекта должны присутствовать в координационном файле." - }; - - public ErrorType(int id) { - Id = id; - } - - public int Id { get; } - public string Name { get; private set; } - public string Description { get; private set; } +namespace RevitCheckingLevels.Models; +internal class ErrorType : IEquatable, IComparable, IComparable { + public static readonly ErrorType NotStandard = + new(0) { + Name = "Имена уровней не соответствуют стандарту", + Description = + "Имена уровней должны соответствовать данному формату: \"[Название этажа][\'_\'][Название блока][\'.\'][Номер уровня][\'_\'][Отметка уровня]\"." + }; + + public static readonly ErrorType NotElevation = + new(1) { + Name = "Отметки уровня не соответствуют фактическим", + Description = + $"Имена уровней должны оканчиваться значением параметра \"{LabelUtils.GetLabelFor(BuiltInParameter.LEVEL_ELEV)}\" в метрах с разделителем дробной части в виде точки." + }; + + public static readonly ErrorType NotMillimeterElevation = + new(2) { + Name = "Отметка уровня не округлена", + Description = + $"Значение параметра \"{LabelUtils.GetLabelFor(BuiltInParameter.LEVEL_ELEV)}\" (в миллиметрах) до 7 знака после запятой должно быть равно \"0\"." + }; + + public static readonly ErrorType NotRangeElevation = + new(3) { + Name = "Уровни замоделированы не по стандарту", + Description = + $"Значение параметра \"{LabelUtils.GetLabelFor(BuiltInParameter.LEVEL_ELEV)}\" должно отступать на 1500мм от предыдущего." + }; + + public static readonly ErrorType NotFoundLevels = + new(4) { + Name = "Уровни не найдены в координационном файле", + Description = "Все уровни проекта должны присутствовать в координационном файле." + }; + + public ErrorType(int id) { + Id = id; + } - #region IEquatable + public int Id { get; } + public string Name { get; private set; } + public string Description { get; private set; } - public bool Equals(ErrorType other) { - if(ReferenceEquals(null, other)) { - return false; - } + #region IEquatable - if(ReferenceEquals(this, other)) { - return true; - } + public bool Equals(ErrorType other) { + return other is not null && (ReferenceEquals(this, other) || Id == other.Id); + } - return Id == other.Id; + public override bool Equals(object obj) { + if(obj is null) { + return false; } - public override bool Equals(object obj) { - if(ReferenceEquals(null, obj)) { - return false; - } + return ReferenceEquals(this, obj) || obj.GetType() == GetType() && Equals((ErrorType) obj); + } - if(ReferenceEquals(this, obj)) { - return true; - } + public override int GetHashCode() { + return Id; + } - if(obj.GetType() != GetType()) { - return false; - } + public static bool operator ==(ErrorType left, ErrorType right) { + return Equals(left, right); + } - return Equals((ErrorType) obj); - } + public static bool operator !=(ErrorType left, ErrorType right) { + return !Equals(left, right); + } - public override int GetHashCode() { - return Id; - } + #endregion - public static bool operator ==(ErrorType left, ErrorType right) { - return Equals(left, right); - } + #region IComparable - public static bool operator !=(ErrorType left, ErrorType right) { - return !Equals(left, right); - } + public int CompareTo(ErrorType other) { + return ReferenceEquals(this, other) ? 0 : other is null ? 1 : Id.CompareTo(other.Id); + } - #endregion + public int CompareTo(object obj) { + return CompareTo(obj as ErrorType); + } - #region IComparable + #endregion - public int CompareTo(ErrorType other) { - if(ReferenceEquals(this, other)) { - return 0; - } + public override string ToString() { + return Name; + } +} - if(ReferenceEquals(null, other)) { - return 1; - } +internal static class LevelInfoExtensions { + public static bool IsNotStandard(this LevelInfo levelInfo) { + return levelInfo.Errors.Count > 0; + } - return Id.CompareTo(other.Id); + public static bool IsNotElevation(this LevelInfo levelInfo) { + if(levelInfo.IsNotStandard()) { + return false; } - public int CompareTo(object obj) { - return CompareTo(obj as ErrorType); + if(levelInfo.Elevation == null) { + return false; } - #endregion + double meterElevation = levelInfo.Level.GetMeterElevation(); + return !LevelExtensions.IsAlmostEqual(levelInfo.Elevation.Value, meterElevation, 0.001); + } - public override string ToString() { - return Name; - } + public static bool IsNotMillimeterElevation(this LevelInfo levelInfo) { + double millimeterElevation = levelInfo.Level.GetMillimeterElevation(); + millimeterElevation = Math.Round(millimeterElevation, 7, MidpointRounding.AwayFromZero); + return !LevelExtensions.IsAlmostEqual(millimeterElevation % 1, 0.0000001, 0.0000001); } - internal static class LevelInfoExtensions { - public static bool IsNotStandard(this LevelInfo levelInfo) { - return levelInfo.Errors.Count > 0; + public static bool IsNotRangeElevation(this LevelInfo levelInfo, IEnumerable levelInfos) { + if(levelInfo.Errors.Count > 0) { + return false; } - public static bool IsNotElevation(this LevelInfo levelInfo) { - if(levelInfo.IsNotStandard()) { - return false; - } + var filtered = levelInfos + .Where(item => item.Level.Id != levelInfo.Level.Id) + .Where(item => item.Errors.Count == 0) + .ToArray(); - if(levelInfo.Elevation == null) { - return false; - } - - double meterElevation = levelInfo.Level.GetMeterElevation(); - return !LevelExtensions.IsAlmostEqual(levelInfo.Elevation.Value, meterElevation, 0.001); + if(levelInfo.HasSubLevel()) { + return filtered + .Where(item => item.HasSubLevel()) + .Where(item => item.IsEqualBlockName(levelInfo)) + .Any(item => + Math.Abs(levelInfo.Level.GetMillimeterElevation() + - item.Level.GetMillimeterElevation()) < 1500); } - public static bool IsNotMillimeterElevation(this LevelInfo levelInfo) { - double millimeterElevation = levelInfo.Level.GetMillimeterElevation(); - millimeterElevation = Math.Round(millimeterElevation, 7, MidpointRounding.AwayFromZero); - return !LevelExtensions.IsAlmostEqual(millimeterElevation % 1, 0.0000001, 0.0000001); - } + if(!levelInfo.HasSubLevel()) { + bool first = filtered + .Where(item => !item.HasSubLevel()) + .Any(item => item.IsEqualLevelName(levelInfo) && item.IsEqualBlockName(levelInfo)); - public static bool IsNotRangeElevation(this LevelInfo levelInfo, IEnumerable levelInfos) { - if(levelInfo.Errors.Count > 0) { - return false; - } - - var filtered = levelInfos - .Where(item => item.Level.Id != levelInfo.Level.Id) - .Where(item => item.Errors.Count == 0) - .ToArray(); - - if(levelInfo.HasSubLevel()) { - return filtered - .Where(item => item.HasSubLevel()) - .Where(item => item.IsEqualBlockName(levelInfo)) - .Any(item => - Math.Abs(levelInfo.Level.GetMillimeterElevation() - - item.Level.GetMillimeterElevation()) < 1500); - } - - if(!levelInfo.HasSubLevel()) { - bool first = filtered - .Where(item => !item.HasSubLevel()) - .Any(item => item.IsEqualLevelName(levelInfo) && item.IsEqualBlockName(levelInfo)); - - bool second = filtered - .Where(item => !item.HasSubLevel()) - .Any(item => item.IsEqualBlockName(levelInfo) && item.IsEqualElevation(levelInfo)); - - return first || second; - } + bool second = filtered + .Where(item => !item.HasSubLevel()) + .Any(item => item.IsEqualBlockName(levelInfo) && item.IsEqualElevation(levelInfo)); - return false; + return first || second; } - public static bool IsNotFoundLevels(this LevelInfo levelInfo, IEnumerable linkLevelInfos) { - return !linkLevelInfos.Any(item => item.Level.Name.Equals(levelInfo.Level.Name)); - } + return false; + } - public static string GetNotStandardTooltip(this LevelInfo levelInfo) { - return string.Join(Environment.NewLine, levelInfo.Errors); - } + public static bool IsNotFoundLevels(this LevelInfo levelInfo, IEnumerable linkLevelInfos) { + return !linkLevelInfos.Any(item => item.Level.Name.Equals(levelInfo.Level.Name)); + } - public static string GetNotElevationTooltip(this LevelInfo levelInfo) { - return $"Значение отметки: фактическое \"{levelInfo.Level.GetFormattedMeterElevation()}\", " + - $"в имени уровня \"{levelInfo.ElevationName}\"."; - } + public static string GetNotStandardTooltip(this LevelInfo levelInfo) { + return string.Join(Environment.NewLine, levelInfo.Errors); + } - public static string GetNotMillimeterElevationTooltip(this LevelInfo levelInfo) { - return $"Значение отметки: фактическое \"{levelInfo.Level.GetFormattedMillimeterElevation()}\"."; - } + public static string GetNotElevationTooltip(this LevelInfo levelInfo) { + return $"Значение отметки: фактическое \"{levelInfo.Level.GetFormattedMeterElevation()}\", " + + $"в имени уровня \"{levelInfo.ElevationName}\"."; + } + + public static string GetNotMillimeterElevationTooltip(this LevelInfo levelInfo) { + return $"Значение отметки: фактическое \"{levelInfo.Level.GetFormattedMillimeterElevation()}\"."; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/LevelExtensions.cs b/src/RevitCheckingLevels/Models/LevelExtensions.cs index 3685a0162..a9037ed0d 100644 --- a/src/RevitCheckingLevels/Models/LevelExtensions.cs +++ b/src/RevitCheckingLevels/Models/LevelExtensions.cs @@ -1,98 +1,95 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System; using Autodesk.Revit.DB; using RevitCheckingLevels.Models.LevelParser; -namespace RevitCheckingLevels.Models { - internal static class LevelExtensions { - public static readonly Units MetricUnits - = new Units(UnitSystem.Metric) { DecimalSymbol = DecimalSymbol.Dot }; +namespace RevitCheckingLevels.Models; +internal static class LevelExtensions { + public static readonly Units MetricUnits + = new(UnitSystem.Metric) { DecimalSymbol = DecimalSymbol.Dot }; - public static bool IsAlmostEqual(double left, double right, - double eps = double.Epsilon) { - return Math.Abs(left - right) <= eps; - } + public static bool IsAlmostEqual(double left, double right, + double eps = double.Epsilon) { + return Math.Abs(left - right) <= eps; + } #if REVIT_2020_OR_LESS - public static readonly FormatOptions MeterFormatOptions - = new FormatOptions(DisplayUnitType.DUT_METERS) { Accuracy = 0.001 }; - - public static readonly FormatOptions MillimeterFormatOptions - = new FormatOptions(DisplayUnitType.DUT_MILLIMETERS) { Accuracy = 0.0000001 }; - - public static string GetFormattedMeterElevation(this Level level) { - var formatValueOptions = new FormatValueOptions(); - formatValueOptions.SetFormatOptions(MeterFormatOptions); - formatValueOptions.AppendUnitSymbol = true; - return UnitFormatUtils.Format(MetricUnits, UnitType.UT_Length, - level.Elevation, false, false, formatValueOptions); - } - - public static string GetFormattedMeterElevation(this LevelInfo level) { - var formatValueOptions = new FormatValueOptions(); - formatValueOptions.SetFormatOptions(MeterFormatOptions); - formatValueOptions.AppendUnitSymbol = true; - return UnitFormatUtils.Format(MetricUnits, UnitType.UT_Length, - level.Elevation ?? 0, false, false, formatValueOptions); - } - - public static string GetFormattedMillimeterElevation(this Level level) { - var formatValueOptions = new FormatValueOptions(); - formatValueOptions.SetFormatOptions(MillimeterFormatOptions); - formatValueOptions.AppendUnitSymbol = true; - return UnitFormatUtils.Format(MetricUnits, UnitType.UT_Length, - level.Elevation, false, false, formatValueOptions); - } - - public static double GetMeterElevation(this Level level) => - UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS); - - public static double GetMillimeterElevation(this Level level) => - UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_MILLIMETERS); + public static readonly FormatOptions MeterFormatOptions + = new FormatOptions(DisplayUnitType.DUT_METERS) { Accuracy = 0.001 }; + + public static readonly FormatOptions MillimeterFormatOptions + = new FormatOptions(DisplayUnitType.DUT_MILLIMETERS) { Accuracy = 0.0000001 }; + + public static string GetFormattedMeterElevation(this Level level) { + var formatValueOptions = new FormatValueOptions(); + formatValueOptions.SetFormatOptions(MeterFormatOptions); + formatValueOptions.AppendUnitSymbol = true; + return UnitFormatUtils.Format(MetricUnits, UnitType.UT_Length, + level.Elevation, false, false, formatValueOptions); + } + + public static string GetFormattedMeterElevation(this LevelInfo level) { + var formatValueOptions = new FormatValueOptions(); + formatValueOptions.SetFormatOptions(MeterFormatOptions); + formatValueOptions.AppendUnitSymbol = true; + return UnitFormatUtils.Format(MetricUnits, UnitType.UT_Length, + level.Elevation ?? 0, false, false, formatValueOptions); + } + + public static string GetFormattedMillimeterElevation(this Level level) { + var formatValueOptions = new FormatValueOptions(); + formatValueOptions.SetFormatOptions(MillimeterFormatOptions); + formatValueOptions.AppendUnitSymbol = true; + return UnitFormatUtils.Format(MetricUnits, UnitType.UT_Length, + level.Elevation, false, false, formatValueOptions); + } + + public static double GetMeterElevation(this Level level) => + UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS); + + public static double GetMillimeterElevation(this Level level) => + UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_MILLIMETERS); #else - public static readonly FormatOptions MeterFormatOptions - = new FormatOptions(UnitTypeId.Meters) { Accuracy = 0.001 }; - - public static readonly FormatOptions MillimeterFormatOptions - = new FormatOptions(UnitTypeId.Millimeters) { Accuracy = 0.0000001 }; - - public static string GetFormattedMeterElevation(this Level level) { - var formatValueOptions = new FormatValueOptions(); - formatValueOptions.SetFormatOptions(MeterFormatOptions); - formatValueOptions.AppendUnitSymbol = true; - return UnitFormatUtils.Format(MetricUnits, SpecTypeId.Length, - level.Elevation, false, formatValueOptions); - } - - public static string GetFormattedMeterElevation(this LevelInfo level) { - var formatValueOptions = new FormatValueOptions(); - formatValueOptions.SetFormatOptions(MeterFormatOptions); - formatValueOptions.AppendUnitSymbol = true; - return UnitFormatUtils.Format(MetricUnits, SpecTypeId.Length, - level.Elevation ?? 0, false, formatValueOptions); - } - - public static string GetFormattedMillimeterElevation(this Level level) { - var formatValueOptions = new FormatValueOptions(); - formatValueOptions.SetFormatOptions(MillimeterFormatOptions); - formatValueOptions.AppendUnitSymbol = true; - return UnitFormatUtils.Format(MetricUnits, SpecTypeId.Length, - level.Elevation, false, formatValueOptions); - } - - public static double GetMeterElevation(this Level level) => - UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters); - - public static double GetMillimeterElevation(this Level level) => - UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Millimeters); + public static readonly FormatOptions MeterFormatOptions + = new(UnitTypeId.Meters) { Accuracy = 0.001 }; + + public static readonly FormatOptions MillimeterFormatOptions + = new(UnitTypeId.Millimeters) { Accuracy = 0.0000001 }; + + public static string GetFormattedMeterElevation(this Level level) { + var formatValueOptions = new FormatValueOptions(); + formatValueOptions.SetFormatOptions(MeterFormatOptions); + formatValueOptions.AppendUnitSymbol = true; + return UnitFormatUtils.Format(MetricUnits, SpecTypeId.Length, + level.Elevation, false, formatValueOptions); + } -#endif + public static string GetFormattedMeterElevation(this LevelInfo level) { + var formatValueOptions = new FormatValueOptions(); + formatValueOptions.SetFormatOptions(MeterFormatOptions); + formatValueOptions.AppendUnitSymbol = true; + return UnitFormatUtils.Format(MetricUnits, SpecTypeId.Length, + level.Elevation ?? 0, false, formatValueOptions); + } + + public static string GetFormattedMillimeterElevation(this Level level) { + var formatValueOptions = new FormatValueOptions(); + formatValueOptions.SetFormatOptions(MillimeterFormatOptions); + formatValueOptions.AppendUnitSymbol = true; + return UnitFormatUtils.Format(MetricUnits, SpecTypeId.Length, + level.Elevation, false, formatValueOptions); + } + + public static double GetMeterElevation(this Level level) { + return UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters); + } + + public static double GetMillimeterElevation(this Level level) { + return UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Millimeters); } + +#endif } diff --git a/src/RevitCheckingLevels/Models/LevelParser/BlockType.cs b/src/RevitCheckingLevels/Models/LevelParser/BlockType.cs index c036c7903..22a7a9cf5 100644 --- a/src/RevitCheckingLevels/Models/LevelParser/BlockType.cs +++ b/src/RevitCheckingLevels/Models/LevelParser/BlockType.cs @@ -1,75 +1,74 @@ -namespace RevitCheckingLevels.Models.LevelParser { +namespace RevitCheckingLevels.Models.LevelParser; +/// +/// Префиксы блоков здания. +/// +internal class BlockType : PrefixName { /// - /// Префиксы блоков здания. + /// Конструирует объект блока здания. /// - internal class BlockType : PrefixName { - /// - /// Конструирует объект блока здания. - /// - /// Наименование типа уровня. - protected BlockType(string name) - : base(name) { + /// Наименование типа уровня. + protected BlockType(string name) + : base(name) { - } + } - /// - /// Секция. - /// - public static readonly BlockType Section = new BlockType("С"); + /// + /// Секция. + /// + public static readonly BlockType Section = new("С"); - /// - /// Корпус. - /// - public static readonly BlockType Body = new BlockType("К"); + /// + /// Корпус. + /// + public static readonly BlockType Body = new("К"); - /// - /// Парковка. - /// - public static readonly BlockType Parking = new BlockType("ПРК"); + /// + /// Парковка. + /// + public static readonly BlockType Parking = new("ПРК"); - /// - /// Пристройка. - /// - public static readonly BlockType Outbuilding = new BlockType("ПРС"); + /// + /// Пристройка. + /// + public static readonly BlockType Outbuilding = new("ПРС"); - /// - /// Дошкольная образовательная организация. - /// - public static readonly BlockType Kindergarten = new BlockType("ДОО"); + /// + /// Дошкольная образовательная организация. + /// + public static readonly BlockType Kindergarten = new("ДОО"); - /// - /// Школа - /// - public static readonly BlockType School = new BlockType("Ш"); + /// + /// Школа + /// + public static readonly BlockType School = new("Ш"); - /// - /// Образовательный комплекс. - /// - public static readonly BlockType EducationalComplex = new BlockType("ОК"); + /// + /// Образовательный комплекс. + /// + public static readonly BlockType EducationalComplex = new("ОК"); - /// - /// Храм. - /// - public static readonly BlockType Temple = new BlockType("ХРМ"); + /// + /// Храм. + /// + public static readonly BlockType Temple = new("ХРМ"); - /// - /// Физкультурно-оздоровительный комплекс. - /// - public static readonly BlockType SportsComplex = new BlockType("ФОК"); + /// + /// Физкультурно-оздоровительный комплекс. + /// + public static readonly BlockType SportsComplex = new("ФОК"); - /// - /// Бизнес-центр. - /// - public static readonly BlockType BusinessCenter = new BlockType("БЦ"); + /// + /// Бизнес-центр. + /// + public static readonly BlockType BusinessCenter = new("БЦ"); - /// - /// Музей. - /// - public static readonly BlockType Museum = new BlockType("МУЗ"); + /// + /// Музей. + /// + public static readonly BlockType Museum = new("МУЗ"); - /// - /// Многофункциональный центр. - /// - public static readonly BlockType MultifunctionalCenter = new BlockType("МФЦ"); - } + /// + /// Многофункциональный центр. + /// + public static readonly BlockType MultifunctionalCenter = new("МФЦ"); } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/LevelParser/LevelBlock.cs b/src/RevitCheckingLevels/Models/LevelParser/LevelBlock.cs index 010ea8ddd..8aa41212b 100644 --- a/src/RevitCheckingLevels/Models/LevelParser/LevelBlock.cs +++ b/src/RevitCheckingLevels/Models/LevelParser/LevelBlock.cs @@ -1,63 +1,62 @@ -using System.Globalization; - -namespace RevitCheckingLevels.Models.LevelParser { - internal class LevelBlock : ILevelBlock { - /// - /// Номер блока. - /// - public int BlockNum { get; set; } - - /// - /// Номер уровня. - /// - public int? SubLevel { get; set; } - - /// - /// Тип блока. - /// - public BlockType BlockType { get; set; } - - public bool HasSubLevel() { - return SubLevel.HasValue; - } - - public string FormatLevelBlockName(CultureInfo cultureInfo) { - return SubLevel == null - ? BlockType.Name + BlockNum - : BlockType.Name + BlockNum + "." + SubLevel; - } +using System.Globalization; + +namespace RevitCheckingLevels.Models.LevelParser; +internal class LevelBlock : ILevelBlock { + /// + /// Номер блока. + /// + public int BlockNum { get; set; } + + /// + /// Номер уровня. + /// + public int? SubLevel { get; set; } + + /// + /// Тип блока. + /// + public BlockType BlockType { get; set; } + + public bool HasSubLevel() { + return SubLevel.HasValue; + } + + public string FormatLevelBlockName(CultureInfo cultureInfo) { + return SubLevel == null + ? BlockType.Name + BlockNum + : BlockType.Name + BlockNum + "." + SubLevel; } +} + +internal class LevelBlockRange : ILevelBlock { + /// + /// Начальный блок уровня. + /// + public LevelBlock StartBlock { get; set; } + + /// + /// Конечный блок уровня. + /// + public LevelBlock FinishBlock { get; set; } - internal class LevelBlockRange : ILevelBlock { - /// - /// Начальный блок уровня. - /// - public LevelBlock StartBlock { get; set; } - - /// - /// Конечный блок уровня. - /// - public LevelBlock FinishBlock { get; set; } - - public bool HasSubLevel() { - return false; - } - - public string FormatLevelBlockName(CultureInfo cultureInfo) { - return StartBlock.FormatLevelBlockName(cultureInfo) - + "-" - + FinishBlock.FormatLevelBlockName(cultureInfo); - } + public bool HasSubLevel() { + return false; } - internal interface ILevelBlock { - bool HasSubLevel(); - - /// - /// Форматирует наименование блока. - /// - /// - /// Возвращает форматирование имя блока. - string FormatLevelBlockName(CultureInfo cultureInfo); + public string FormatLevelBlockName(CultureInfo cultureInfo) { + return StartBlock.FormatLevelBlockName(cultureInfo) + + "-" + + FinishBlock.FormatLevelBlockName(cultureInfo); } +} + +internal interface ILevelBlock { + bool HasSubLevel(); + + /// + /// Форматирует наименование блока. + /// + /// + /// Возвращает форматирование имя блока. + string FormatLevelBlockName(CultureInfo cultureInfo); } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/LevelParser/LevelInfo.cs b/src/RevitCheckingLevels/Models/LevelParser/LevelInfo.cs index 1a05861ba..0b71f64af 100644 --- a/src/RevitCheckingLevels/Models/LevelParser/LevelInfo.cs +++ b/src/RevitCheckingLevels/Models/LevelParser/LevelInfo.cs @@ -1,87 +1,85 @@ -using System; using System.Collections.Generic; using Autodesk.Revit.DB; -namespace RevitCheckingLevels.Models.LevelParser { +namespace RevitCheckingLevels.Models.LevelParser; +/// +/// Информация об уровне. +/// +internal class LevelInfo { /// - /// Информация об уровне. + /// Разобранный уровень. /// - internal class LevelInfo { - /// - /// Разобранный уровень. - /// - public Level Level { get; set; } - - public string LevelName { get; set; } - public string BlockName { get; set; } - public string ElevationName { get; set; } - - public bool HasSubLevel() { - return BlockName.Contains("."); - } - - public bool IsEqualBlockName(LevelInfo levelInfo) { - return levelInfo.BlockName.Equals(BlockName); - } - - public bool IsEqualLevelName(LevelInfo levelInfo) { - return levelInfo.LevelName.Equals(LevelName); - } - - public bool IsEqualElevation(LevelInfo levelInfo) { - return levelInfo.ElevationName.Equals(ElevationName); - } - - /// - /// Номер этажа. - /// - public int? LevelNum { get; set; } - - /// - /// Тип этажа. - /// - public LevelType LevelType { get; set; } - - /// - /// Блоки уровня. - /// - public IReadOnlyCollection LevelBlocks { get; set; } = new List(); - - /// - /// Отметка уровня. - /// - public double? Elevation { get; set; } - - /// - /// Список ошибок при разборе имени. - /// - public IReadOnlyCollection Errors { get; set; } = new List(); - - public string FormatLevelName() { - return Errors.Count > 0 - ? Level.Name - : $"{GetLevelName()}_{GetBlockName()}_{GetElevation()}"; - } - - public string GetLevelName() { - return $"{LevelType?.Name}{LevelNum:D2} этаж"; - } - - public string GetBlockName() { - return string.Join(", ", LevelBlocks); - } - - public string GetElevation() { - return FormatElevation(Elevation); - } - - public string FormatElevation(double? elevation) { - return elevation?.ToString("F3", LevelParserImpl.CultureInfo); - } - - public override string ToString() { - return $"{GetLevelName()}_{GetBlockName()}_{GetElevation()}"; - } + public Level Level { get; set; } + + public string LevelName { get; set; } + public string BlockName { get; set; } + public string ElevationName { get; set; } + + public bool HasSubLevel() { + return BlockName.Contains("."); + } + + public bool IsEqualBlockName(LevelInfo levelInfo) { + return levelInfo.BlockName.Equals(BlockName); + } + + public bool IsEqualLevelName(LevelInfo levelInfo) { + return levelInfo.LevelName.Equals(LevelName); + } + + public bool IsEqualElevation(LevelInfo levelInfo) { + return levelInfo.ElevationName.Equals(ElevationName); + } + + /// + /// Номер этажа. + /// + public int? LevelNum { get; set; } + + /// + /// Тип этажа. + /// + public LevelType LevelType { get; set; } + + /// + /// Блоки уровня. + /// + public IReadOnlyCollection LevelBlocks { get; set; } = []; + + /// + /// Отметка уровня. + /// + public double? Elevation { get; set; } + + /// + /// Список ошибок при разборе имени. + /// + public IReadOnlyCollection Errors { get; set; } = []; + + public string FormatLevelName() { + return Errors.Count > 0 + ? Level.Name + : $"{GetLevelName()}_{GetBlockName()}_{GetElevation()}"; + } + + public string GetLevelName() { + return $"{LevelType?.Name}{LevelNum:D2} этаж"; + } + + public string GetBlockName() { + return string.Join(", ", LevelBlocks); + } + + public string GetElevation() { + return FormatElevation(Elevation); + } + + public string FormatElevation(double? elevation) { + return elevation?.ToString("F3", LevelParserImpl.CultureInfo); + } + + public override string ToString() { + return $"{GetLevelName()}_{GetBlockName()}_{GetElevation()}"; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/LevelParser/LevelParserImpl.cs b/src/RevitCheckingLevels/Models/LevelParser/LevelParserImpl.cs index 34285f3d6..f39b03918 100644 --- a/src/RevitCheckingLevels/Models/LevelParser/LevelParserImpl.cs +++ b/src/RevitCheckingLevels/Models/LevelParser/LevelParserImpl.cs @@ -1,168 +1,166 @@ -using System; -using System.Linq; +using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Text.RegularExpressions; using Autodesk.Revit.DB; -namespace RevitCheckingLevels.Models.LevelParser { - internal class LevelParserImpl { - private readonly Level _level; - public static readonly CultureInfo CultureInfo = GetCultureInfo(); +namespace RevitCheckingLevels.Models.LevelParser; +internal class LevelParserImpl { + public static readonly CultureInfo CultureInfo = GetCultureInfo(); - private readonly List _errors = new List(); - private readonly List _levelBlocks = new List(); + private readonly List _errors = []; + private readonly List _levelBlocks = []; - public LevelParserImpl(Level level) { - _level = level; - } + public LevelParserImpl(Level level) { + Level = level; + } - public Level Level => _level; - public string LevelName => _level.Name; + public Level Level { get; } + public string LevelName => Level.Name; - public LevelInfo ReadLevelInfo() { - string[] splittedName = LevelName.Split( - new[] { '_' }, StringSplitOptions.RemoveEmptyEntries); + public LevelInfo ReadLevelInfo() { + string[] splittedName = LevelName.Split( + new[] { '_' }, StringSplitOptions.RemoveEmptyEntries); - var levelInfo = new LevelInfo { Level = _level, Errors = _errors, LevelBlocks = _levelBlocks}; - ReadLevelName(levelInfo, splittedName.ElementAtOrDefault(0)); - ReadBlockName(levelInfo, splittedName.ElementAtOrDefault(1)); - ReadElevation(levelInfo, splittedName.ElementAtOrDefault(2)); - - return levelInfo; - } + var levelInfo = new LevelInfo { Level = Level, Errors = _errors, LevelBlocks = _levelBlocks }; + ReadLevelName(levelInfo, splittedName.ElementAtOrDefault(0)); + ReadBlockName(levelInfo, splittedName.ElementAtOrDefault(1)); + ReadElevation(levelInfo, splittedName.ElementAtOrDefault(2)); - private void ReadLevelName(LevelInfo levelInfo, string levelName) { - levelInfo.LevelName = levelName; - if(levelName == null) { - _errors.Add("Не удалось прочитать уровень."); - return; - } + return levelInfo; + } - var splittedLevelName = levelName.Split(new[] { ' ' }, - StringSplitOptions.RemoveEmptyEntries); + private void ReadLevelName(LevelInfo levelInfo, string levelName) { + levelInfo.LevelName = levelName; + if(levelName == null) { + _errors.Add("Не удалось прочитать уровень."); + return; + } - if(splittedLevelName.Length == 2) { - (string levelType, string levelNum) = ReadPrefix(splittedLevelName[0]); - if(!splittedLevelName[1].Equals("этаж")) { - _errors.Add("После уровня должна идти надпись \"этаж\"."); - } + string[] splittedLevelName = levelName.Split(new[] { ' ' }, + StringSplitOptions.RemoveEmptyEntries); - levelInfo.LevelNum = ReadInt32(levelNum, "Не удалось прочитать номер этажа."); - levelInfo.LevelType = ReadPrefix(levelType, "Не удалось прочитать тип уровня."); - } else { - _errors.Add("Не удалось прочитать уровень."); + if(splittedLevelName.Length == 2) { + (string levelType, string levelNum) = ReadPrefix(splittedLevelName[0]); + if(!splittedLevelName[1].Equals("этаж")) { + _errors.Add("После уровня должна идти надпись \"этаж\"."); } + + levelInfo.LevelNum = ReadInt32(levelNum, "Не удалось прочитать номер этажа."); + levelInfo.LevelType = ReadPrefix(levelType, "Не удалось прочитать тип уровня."); + } else { + _errors.Add("Не удалось прочитать уровень."); } + } - private void ReadBlockName(LevelInfo levelInfo, string blockName) { - levelInfo.BlockName = blockName; - if(blockName == null) { - _errors.Add("Не удалось прочитать тип блока."); - return; - } + private void ReadBlockName(LevelInfo levelInfo, string blockName) { + levelInfo.BlockName = blockName; + if(blockName == null) { + _errors.Add("Не удалось прочитать тип блока."); + return; + } - if(blockName.Contains('.')) { - _levelBlocks.Add(ReadBlock(blockName)); - } else { - var blockRange = blockName.Split(new[] {','}, - StringSplitOptions.RemoveEmptyEntries); - - foreach(string block in blockRange) { - if(block.Contains('-')) { - var levelBlockRange = ReadBlockRange(blockName); - if(!levelBlockRange.StartBlock.BlockType - .Equals(levelBlockRange.FinishBlock.BlockType)) { - _errors.Add("Наименование типов блоков не совпадают."); - } - - if(levelBlockRange.StartBlock.BlockNum > levelBlockRange.FinishBlock.BlockNum) { - _errors.Add("Значение начального номера блока больше значения конечного блока."); - } - - if(levelBlockRange.StartBlock.BlockNum == levelBlockRange.FinishBlock.BlockNum) { - _errors.Add("Значение начального номера блока и значения конечного блока равны."); - } - } else { - _levelBlocks.Add(ReadBlock(blockName)); + if(blockName.Contains('.')) { + _levelBlocks.Add(ReadBlock(blockName)); + } else { + string[] blockRange = blockName.Split(new[] { ',' }, + StringSplitOptions.RemoveEmptyEntries); + + foreach(string block in blockRange) { + if(block.Contains('-')) { + var levelBlockRange = ReadBlockRange(blockName); + if(!levelBlockRange.StartBlock.BlockType + .Equals(levelBlockRange.FinishBlock.BlockType)) { + _errors.Add("Наименование типов блоков не совпадают."); } + + if(levelBlockRange.StartBlock.BlockNum > levelBlockRange.FinishBlock.BlockNum) { + _errors.Add("Значение начального номера блока больше значения конечного блока."); + } + + if(levelBlockRange.StartBlock.BlockNum == levelBlockRange.FinishBlock.BlockNum) { + _errors.Add("Значение начального номера блока и значения конечного блока равны."); + } + } else { + _levelBlocks.Add(ReadBlock(blockName)); } } } + } - private void ReadElevation(LevelInfo levelInfo, string elevation) { - levelInfo.ElevationName = elevation; - if(elevation == null) { - _errors.Add("Не удалось прочитать отметку уровня."); - return; - } - - if(!Regex.IsMatch(elevation, @"-?\d+\.\d\d\d")) { - _errors.Add("Отметка уровня не верного формата."); - return; - } + private void ReadElevation(LevelInfo levelInfo, string elevation) { + levelInfo.ElevationName = elevation; + if(elevation == null) { + _errors.Add("Не удалось прочитать отметку уровня."); + return; + } - if(double.TryParse(elevation, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo, out double result)) { - levelInfo.Elevation = result; - return; - } + if(!Regex.IsMatch(elevation, @"-?\d+\.\d\d\d")) { + _errors.Add("Отметка уровня не верного формата."); + return; + } - _errors.Add("Не удалось прочитать отметку уровня."); + if(double.TryParse(elevation, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo, out double result)) { + levelInfo.Elevation = result; + return; } - private LevelBlock ReadBlock(string blockName) { - (string blockType, string blockNum) = ReadPrefix(blockName); + _errors.Add("Не удалось прочитать отметку уровня."); + } - int? subLevel = blockName.Contains('.') - ? ReadInt32(blockName.Split('.').LastOrDefault(), "Не удалось прочитать значение номера уровня.") - : (int?) null; + private LevelBlock ReadBlock(string blockName) { + (string blockType, string blockNum) = ReadPrefix(blockName); - return new LevelBlock() { - SubLevel = subLevel, - BlockNum = ReadInt32(blockNum, null), - BlockType = ReadPrefix(blockType, "Не удалось прочитать тип блока.") - }; - } + int? subLevel = blockName.Contains('.') + ? ReadInt32(blockName.Split('.').LastOrDefault(), "Не удалось прочитать значение номера уровня.") + : null; - private LevelBlockRange ReadBlockRange(string blockName) { - string[] blockRange = blockName.Split('-'); - return new LevelBlockRange() { - StartBlock = ReadBlock(blockRange[0]), - FinishBlock = ReadBlock(blockRange[1]) - }; - } + return new LevelBlock() { + SubLevel = subLevel, + BlockNum = ReadInt32(blockNum, null), + BlockType = ReadPrefix(blockType, "Не удалось прочитать тип блока.") + }; + } - private (string prefixName, string prefixNum) ReadPrefix(string prefixName) { - var match = Regex.Match(prefixName, "^(?'type'[A-Za-zА-Яа-я]+)?(?'num'\\d{1,2})?"); - return (match.Groups["type"].Value, match.Groups["num"].Value); - } + private LevelBlockRange ReadBlockRange(string blockName) { + string[] blockRange = blockName.Split('-'); + return new LevelBlockRange() { + StartBlock = ReadBlock(blockRange[0]), + FinishBlock = ReadBlock(blockRange[1]) + }; + } - private T ReadPrefix(string prefixName, string errorText) - where T : PrefixName { - var prefix = PrefixName.GetPrefixByName(prefixName); - if(prefix == null) { - _errors.Add(errorText); - } + private (string prefixName, string prefixNum) ReadPrefix(string prefixName) { + var match = Regex.Match(prefixName, "^(?'type'[A-Za-zА-Яа-я]+)?(?'num'\\d{1,2})?"); + return (match.Groups["type"].Value, match.Groups["num"].Value); + } - return prefix; + private T ReadPrefix(string prefixName, string errorText) + where T : PrefixName { + var prefix = PrefixName.GetPrefixByName(prefixName); + if(prefix == null) { + _errors.Add(errorText); } - private int ReadInt32(string value, string errorText) { - if(!int.TryParse(value, out int result)) { - if(errorText == null) { - return 1; - } - _errors.Add(errorText); - } + return prefix; + } - return result; + private int ReadInt32(string value, string errorText) { + if(!int.TryParse(value, out int result)) { + if(errorText == null) { + return 1; + } + _errors.Add(errorText); } - private static CultureInfo GetCultureInfo() { - var cultureInfo = (CultureInfo) CultureInfo.GetCultureInfo("ru-Ru").Clone(); - cultureInfo.NumberFormat.NumberDecimalSeparator = "."; - return cultureInfo; - } + return result; + } + + private static CultureInfo GetCultureInfo() { + var cultureInfo = (CultureInfo) CultureInfo.GetCultureInfo("ru-Ru").Clone(); + cultureInfo.NumberFormat.NumberDecimalSeparator = "."; + return cultureInfo; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/LevelParser/LevelType.cs b/src/RevitCheckingLevels/Models/LevelParser/LevelType.cs index 2a6c7eb44..94a6a032a 100644 --- a/src/RevitCheckingLevels/Models/LevelParser/LevelType.cs +++ b/src/RevitCheckingLevels/Models/LevelParser/LevelType.cs @@ -1,45 +1,44 @@ -namespace RevitCheckingLevels.Models.LevelParser { +namespace RevitCheckingLevels.Models.LevelParser; +/// +/// Префиксы типа уровня. +/// +internal class LevelType : PrefixName { /// - /// Префиксы типа уровня. + /// Конструирует объект типа уровня. /// - internal class LevelType : PrefixName { - /// - /// Конструирует объект типа уровня. - /// - /// Наименование типа уровня. - protected LevelType(string name) - : base(name) { + /// Наименование типа уровня. + protected LevelType(string name) + : base(name) { - } + } - /// - /// Кровля. Префикс "К". - /// - public static readonly LevelType TopLevel = new LevelType("К"); + /// + /// Кровля. Префикс "К". + /// + public static readonly LevelType TopLevel = new("К"); - /// - /// Надземный этаж. Без префикса. - /// - public static readonly LevelType BasicLevel = new LevelType(string.Empty); + /// + /// Надземный этаж. Без префикса. + /// + public static readonly LevelType BasicLevel = new(string.Empty); - /// - /// Подземный этаж. Префикс "П". - /// - public static readonly LevelType UndergroundLevel = new LevelType("П"); + /// + /// Подземный этаж. Префикс "П". + /// + public static readonly LevelType UndergroundLevel = new("П"); - /// - /// Диспетчерская. Префикс "Д". - /// - public static readonly LevelType ControlRoom = new LevelType("Д"); + /// + /// Диспетчерская. Префикс "Д". + /// + public static readonly LevelType ControlRoom = new("Д"); - /// - /// Технический этаж. Префикс "Т". - /// - public static readonly LevelType TechnicalLevel = new LevelType("Т"); + /// + /// Технический этаж. Префикс "Т". + /// + public static readonly LevelType TechnicalLevel = new("Т"); - /// - /// Техподполье. Префикс "ТХ". - /// - public static readonly LevelType TechUnderground = new LevelType("ТХ"); - } + /// + /// Техподполье. Префикс "ТХ". + /// + public static readonly LevelType TechUnderground = new("ТХ"); } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/LevelParser/PrefixName.cs b/src/RevitCheckingLevels/Models/LevelParser/PrefixName.cs index 6fdb18658..c9fd8843d 100644 --- a/src/RevitCheckingLevels/Models/LevelParser/PrefixName.cs +++ b/src/RevitCheckingLevels/Models/LevelParser/PrefixName.cs @@ -1,72 +1,65 @@ -using System; +using System; using System.Linq; -namespace RevitCheckingLevels.Models.LevelParser { - /// - /// Класс содержащий имя префикса. - /// - internal class PrefixName : IEquatable { +namespace RevitCheckingLevels.Models.LevelParser; +/// +/// Класс содержащий имя префикса. +/// +internal class PrefixName : IEquatable { - #region IEquatable + #region IEquatable - /// - public bool Equals(PrefixName other) { - if(ReferenceEquals(null, other)) - return false; - if(ReferenceEquals(this, other)) - return true; - return Name == other.Name; - } + /// + public bool Equals(PrefixName other) { + return other is not null && (ReferenceEquals(this, other) || Name == other.Name); + } - /// - public override bool Equals(object obj) { - if(ReferenceEquals(null, obj)) - return false; - if(ReferenceEquals(this, obj)) - return true; - if(obj.GetType() != this.GetType()) - return false; - return Equals((PrefixName) obj); + /// + public override bool Equals(object obj) { + if(obj is null) { + return false; } - /// - public override int GetHashCode() { - return Name.GetHashCode(); - } + return ReferenceEquals(this, obj) || obj.GetType() == GetType() && Equals((PrefixName) obj); + } - public static bool operator ==(PrefixName left, PrefixName right) { - return Equals(left, right); - } + /// + public override int GetHashCode() { + return Name.GetHashCode(); + } - public static bool operator !=(PrefixName left, PrefixName right) { - return !Equals(left, right); - } + public static bool operator ==(PrefixName left, PrefixName right) { + return Equals(left, right); + } - #endregion + public static bool operator !=(PrefixName left, PrefixName right) { + return !Equals(left, right); + } - /// - /// Конструирует объект префикса. - /// - /// Наименование префикса. - protected PrefixName(string name) { - Name = name; - } + #endregion - /// - /// Наименование префикса. - /// - public string Name { get; } + /// + /// Конструирует объект префикса. + /// + /// Наименование префикса. + protected PrefixName(string name) { + Name = name; + } - public static T GetPrefixByName(string prefixName) - where T : PrefixName { - return (T) typeof(T).GetFields() - .Select(item => item.GetValue(null)) - .OfType() - .FirstOrDefault(item => prefixName.Equals(item.Name)); - } + /// + /// Наименование префикса. + /// + public string Name { get; } - public override string ToString() { - return Name; - } + public static T GetPrefixByName(string prefixName) + where T : PrefixName { + return typeof(T).GetFields() + .Select(item => item.GetValue(null)) + .OfType() + .FirstOrDefault(item => prefixName.Equals(item.Name)); + } + + public override string ToString() { + return Name; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/Models/RevitRepository.cs b/src/RevitCheckingLevels/Models/RevitRepository.cs index 070829051..870693717 100644 --- a/src/RevitCheckingLevels/Models/RevitRepository.cs +++ b/src/RevitCheckingLevels/Models/RevitRepository.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Autodesk.Revit.ApplicationServices; @@ -9,103 +9,101 @@ using RevitCheckingLevels.Models.LevelParser; -namespace RevitCheckingLevels.Models { - internal class RevitRepository { - public RevitRepository(UIApplication uiApplication) { - UIApplication = uiApplication; - } +namespace RevitCheckingLevels.Models; +internal class RevitRepository { + public RevitRepository(UIApplication uiApplication) { + UIApplication = uiApplication; + } - public UIApplication UIApplication { get; } - public UIDocument ActiveUIDocument => UIApplication.ActiveUIDocument; + public UIApplication UIApplication { get; } + public UIDocument ActiveUIDocument => UIApplication.ActiveUIDocument; - public Application Application => UIApplication.Application; - public Document Document => ActiveUIDocument.Document; - - public bool IsKoordFile() { - return Document.Title.Contains("_KOORD"); - } + public Application Application => UIApplication.Application; + public Document Document => ActiveUIDocument.Document; - public bool IsKoordFile(RevitLinkType revitLinkType) { - return revitLinkType.Name.Contains("_KOORD"); - } + public bool IsKoordFile() { + return Document.Title.Contains("_KOORD"); + } - public IEnumerable GetLevels() { - return GetLevels(Document); - } + public bool IsKoordFile(RevitLinkType revitLinkType) { + return revitLinkType.Name.Contains("_KOORD"); + } - public bool HasLinkInstance(RevitLinkType linkType) { - return new FilteredElementCollector(Document) - .WhereElementIsNotElementType() - .OfClass(typeof(RevitLinkInstance)) - .OfType() - .Any(item => item.GetTypeId() == linkType.Id); - } + public IEnumerable GetLevels() { + return GetLevels(Document); + } - public IEnumerable GetLevels(RevitLinkType linkType) { - var linkInstance = new FilteredElementCollector(Document) - .WhereElementIsNotElementType() - .OfClass(typeof(RevitLinkInstance)) - .OfType() - .FirstOrDefault(item => item.GetTypeId() == linkType.Id); + public bool HasLinkInstance(RevitLinkType linkType) { + return new FilteredElementCollector(Document) + .WhereElementIsNotElementType() + .OfClass(typeof(RevitLinkInstance)) + .OfType() + .Any(item => item.GetTypeId() == linkType.Id); + } - return linkInstance == null - ? Enumerable.Empty() - : GetLevels(linkInstance.GetLinkDocument()); - } + public IEnumerable GetLevels(RevitLinkType linkType) { + var linkInstance = new FilteredElementCollector(Document) + .WhereElementIsNotElementType() + .OfClass(typeof(RevitLinkInstance)) + .OfType() + .FirstOrDefault(item => item.GetTypeId() == linkType.Id); - public IEnumerable GetRevitLinkTypes() { - return new FilteredElementCollector(Document) - .WhereElementIsElementType() - .OfClass(typeof(RevitLinkType)) - .OfType() - .OrderBy(item => item.Name); - } + return linkInstance == null + ? Enumerable.Empty() + : GetLevels(linkInstance.GetLinkDocument()); + } - public IEnumerable GetLevelCreationNames(IEnumerable levelInfos) { - var levels = GetLevels(Document).ToList(); - return levelInfos - .Select(item => CreateLevelCreationName(item, levels)); - } + public IEnumerable GetRevitLinkTypes() { + return new FilteredElementCollector(Document) + .WhereElementIsElementType() + .OfClass(typeof(RevitLinkType)) + .OfType() + .OrderBy(item => item.Name); + } - public void UpdateElevations(IEnumerable levels) { - using(Transaction transaction = Document.StartTransaction("Обновление отметок уровня")) { - foreach(LevelCreationName levelCreationName in levels.Where(item => !item.DuplicateName)) { - levelCreationName.LevelInfo.Level.Name = levelCreationName.LevelName; - } + public IEnumerable GetLevelCreationNames(IEnumerable levelInfos) { + var levels = GetLevels(Document).ToList(); + return levelInfos + .Select(item => CreateLevelCreationName(item, levels)); + } - transaction.Commit(); - } + public void UpdateElevations(IEnumerable levels) { + using var transaction = Document.StartTransaction("Обновление отметок уровня"); + foreach(var levelCreationName in levels.Where(item => !item.DuplicateName)) { + levelCreationName.LevelInfo.Level.Name = levelCreationName.LevelName; } - private string GetLevelName(LevelInfo levelInfo) { - double elevation = levelInfo.Level.GetMeterElevation(); - string elevationName = levelInfo.FormatElevation(elevation); + transaction.Commit(); + } - var elements = levelInfo.Level.Name.Split('_'); - elements[2] = elevationName; - return string.Join("_", elements); - } + private string GetLevelName(LevelInfo levelInfo) { + double elevation = levelInfo.Level.GetMeterElevation(); + string elevationName = levelInfo.FormatElevation(elevation); - private LevelCreationName CreateLevelCreationName(LevelInfo levelInfo, List levels) { - var levelName = GetLevelName(levelInfo); - var duplicateName = IsDuplicateLevelName(levelName, levels); - return new LevelCreationName() {LevelInfo = levelInfo, LevelName = levelName, DuplicateName = duplicateName}; - } + string[] elements = levelInfo.Level.Name.Split('_'); + elements[2] = elevationName; + return string.Join("_", elements); + } - private bool IsDuplicateLevelName(string levelName, List levels) { - return levels.Any(item => item.Name.Equals(levelName)); - } + private LevelCreationName CreateLevelCreationName(LevelInfo levelInfo, List levels) { + string levelName = GetLevelName(levelInfo); + bool duplicateName = IsDuplicateLevelName(levelName, levels); + return new LevelCreationName() { LevelInfo = levelInfo, LevelName = levelName, DuplicateName = duplicateName }; + } - private IEnumerable GetLevels(Document document) { - return new FilteredElementCollector(document) - .OfCategory(BuiltInCategory.OST_Levels) - .OfType(); - } + private bool IsDuplicateLevelName(string levelName, List levels) { + return levels.Any(item => item.Name.Equals(levelName)); } - internal class LevelCreationName { - public bool DuplicateName { get; set; } - public string LevelName { get; set; } - public LevelInfo LevelInfo { get; set; } + private IEnumerable GetLevels(Document document) { + return new FilteredElementCollector(document) + .OfCategory(BuiltInCategory.OST_Levels) + .OfType(); } +} + +internal class LevelCreationName { + public bool DuplicateName { get; set; } + public string LevelName { get; set; } + public LevelInfo LevelInfo { get; set; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/RevitCheckingLevels.csproj b/src/RevitCheckingLevels/RevitCheckingLevels.csproj index ceb69152e..5c2fe887e 100644 --- a/src/RevitCheckingLevels/RevitCheckingLevels.csproj +++ b/src/RevitCheckingLevels/RevitCheckingLevels.csproj @@ -1,5 +1,6 @@  true + 12 \ No newline at end of file diff --git a/src/RevitCheckingLevels/RevitCheckingLevelsCommand.cs b/src/RevitCheckingLevels/RevitCheckingLevelsCommand.cs index 87408a72e..f29c8aa03 100644 --- a/src/RevitCheckingLevels/RevitCheckingLevelsCommand.cs +++ b/src/RevitCheckingLevels/RevitCheckingLevelsCommand.cs @@ -1,84 +1,70 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System; using System.Windows; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; -using DevExpress.XtraScheduler.Outlook.Interop; - -using dosymep; using dosymep.Bim4Everyone; -using dosymep.SimpleServices; -using dosymep.WPF.ViewModels; using Ninject; -using pyRevitLabs.Json.Serialization; - using RevitCheckingLevels.Models; -using RevitCheckingLevels.Services; using RevitCheckingLevels.ViewModels; using RevitCheckingLevels.Views; using Application = Autodesk.Revit.ApplicationServices.Application; -namespace RevitCheckingLevels { - [Transaction(TransactionMode.Manual)] - public class RevitCheckingLevelsCommand : BasePluginCommand { - public RevitCheckingLevelsCommand() { - PluginName = "Проверка уровней"; - } - - protected override void Execute(UIApplication uiApplication) { - using(IKernel kernel = new StandardKernel()) { - kernel.Bind() - .ToConstant(uiApplication) - .InTransientScope(); - kernel.Bind() - .ToConstant(uiApplication.Application) - .InTransientScope(); - - kernel.Bind() - .ToSelf() - .InSingletonScope(); - - kernel.Bind() - .ToSelf() - .InSingletonScope(); - - kernel.Bind() - .ToMethod(c => CheckingLevelConfig.GetCheckingLevelConfig()); - - kernel.Bind().ToSelf() - .WithPropertyValue(nameof(Window.Title), PluginName) - .WithPropertyValue(nameof(Window.DataContext), - c => c.Kernel.Get()); - - if(!FromGui) { - var mainViewModel = kernel.Get(); - mainViewModel.ViewLoadCommand.Execute(null); - if(!mainViewModel.HasErrors) { - return; - } - } +namespace RevitCheckingLevels; +[Transaction(TransactionMode.Manual)] +public class RevitCheckingLevelsCommand : BasePluginCommand { + public RevitCheckingLevelsCommand() { + PluginName = "Проверка уровней"; + } - Window mainWindow = kernel.Get(); - bool? dialogResult = mainWindow.ShowDialog(); + protected override void Execute(UIApplication uiApplication) { + using IKernel kernel = new StandardKernel(); + kernel.Bind() + .ToConstant(uiApplication) + .InTransientScope(); + kernel.Bind() + .ToConstant(uiApplication.Application) + .InTransientScope(); + + kernel.Bind() + .ToSelf() + .InSingletonScope(); + + kernel.Bind() + .ToSelf() + .InSingletonScope(); + + kernel.Bind() + .ToMethod(c => CheckingLevelConfig.GetCheckingLevelConfig()); + + kernel.Bind().ToSelf() + .WithPropertyValue(nameof(Window.Title), PluginName) + .WithPropertyValue(nameof(Window.DataContext), + c => c.Kernel.Get()); + + if(!FromGui) { + var mainViewModel = kernel.Get(); + mainViewModel.ViewLoadCommand.Execute(null); + if(!mainViewModel.HasErrors) { + return; + } + } - if(!FromGui) { - var mainViewModel = kernel.Get(); - if(mainViewModel.HasErrors) { - throw new InvalidOperationException("Были обнаружены ошибки в уровнях."); - } - } + Window mainWindow = kernel.Get(); + bool? dialogResult = mainWindow.ShowDialog(); - Notification(dialogResult); + if(!FromGui) { + var mainViewModel = kernel.Get(); + if(mainViewModel.HasErrors) { + throw new InvalidOperationException("Были обнаружены ошибки в уровнях."); } } + + Notification(dialogResult); } -} \ No newline at end of file +} diff --git a/src/RevitCheckingLevels/Services/NavigationService.cs b/src/RevitCheckingLevels/Services/NavigationService.cs index d4372de85..5a3511e67 100644 --- a/src/RevitCheckingLevels/Services/NavigationService.cs +++ b/src/RevitCheckingLevels/Services/NavigationService.cs @@ -1,32 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System; using dosymep.WPF.ViewModels; -namespace RevitCheckingLevels.Services { - internal interface INavigationService { - BaseViewModel CurrentView { get; } - void NavigateTo() where T : BaseViewModel; - } +namespace RevitCheckingLevels.Services; +internal interface INavigationService { + BaseViewModel CurrentView { get; } + void NavigateTo() where T : BaseViewModel; +} - internal class NavigationService : BaseViewModel, INavigationService { - private BaseViewModel _currentView; - private readonly Func _viewModelFactory; +internal class NavigationService : BaseViewModel, INavigationService { + private BaseViewModel _currentView; + private readonly Func _viewModelFactory; - public NavigationService(Func viewModelFactory) { - _viewModelFactory = viewModelFactory; - } + public NavigationService(Func viewModelFactory) { + _viewModelFactory = viewModelFactory; + } - public BaseViewModel CurrentView { - get => _currentView; - private set => this.RaiseAndSetIfChanged(ref _currentView, value); - } + public BaseViewModel CurrentView { + get => _currentView; + private set => RaiseAndSetIfChanged(ref _currentView, value); + } - public void NavigateTo() where T : BaseViewModel { - CurrentView = _viewModelFactory(typeof(T)); - } + public void NavigateTo() where T : BaseViewModel { + CurrentView = _viewModelFactory(typeof(T)); } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/ViewModels/LevelViewModel.cs b/src/RevitCheckingLevels/ViewModels/LevelViewModel.cs index dfcde333d..c195924fb 100644 --- a/src/RevitCheckingLevels/ViewModels/LevelViewModel.cs +++ b/src/RevitCheckingLevels/ViewModels/LevelViewModel.cs @@ -1,44 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Input; - -using Autodesk.Revit.DB; - -using dosymep.WPF.Commands; using dosymep.WPF.ViewModels; using RevitCheckingLevels.Models; using RevitCheckingLevels.Models.LevelParser; -namespace RevitCheckingLevels.ViewModels { - internal class LevelViewModel : BaseViewModel { - private readonly LevelInfo _levelInfo; - private ErrorType _errorType; - private string _toolTipInfo; +namespace RevitCheckingLevels.ViewModels; +internal class LevelViewModel : BaseViewModel { + private ErrorType _errorType; + private string _toolTipInfo; - public LevelViewModel(LevelInfo levelInfoInfo) { - _levelInfo = levelInfoInfo; - } + public LevelViewModel(LevelInfo levelInfoInfo) { + LevelInfo = levelInfoInfo; + } - public string Name => _levelInfo.Level.Name; - public string MeterElevation => _levelInfo.Level.GetFormattedMeterElevation(); - public string MillimeterElevation => _levelInfo.Level.GetFormattedMillimeterElevation(); + public string Name => LevelInfo.Level.Name; + public string MeterElevation => LevelInfo.Level.GetFormattedMeterElevation(); + public string MillimeterElevation => LevelInfo.Level.GetFormattedMillimeterElevation(); - public LevelInfo LevelInfo => _levelInfo; + public LevelInfo LevelInfo { get; } - public ErrorType ErrorType { - get => _errorType; - set => this.RaiseAndSetIfChanged(ref _errorType, value); - } + public ErrorType ErrorType { + get => _errorType; + set => RaiseAndSetIfChanged(ref _errorType, value); + } - public string ToolTipInfo { - get => _toolTipInfo; - set => this.RaiseAndSetIfChanged(ref _toolTipInfo, value); - } + public string ToolTipInfo { + get => _toolTipInfo; + set => RaiseAndSetIfChanged(ref _toolTipInfo, value); } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/ViewModels/LinkTypeViewModel.cs b/src/RevitCheckingLevels/ViewModels/LinkTypeViewModel.cs index f1a9f7f72..58ed855fa 100644 --- a/src/RevitCheckingLevels/ViewModels/LinkTypeViewModel.cs +++ b/src/RevitCheckingLevels/ViewModels/LinkTypeViewModel.cs @@ -1,64 +1,57 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System; using System.Windows.Input; using Autodesk.Revit.DB; -using Autodesk.Revit.UI; using dosymep.WPF.Commands; using dosymep.WPF.ViewModels; -namespace RevitCheckingLevels.ViewModels { - internal class LinkTypeViewModel : BaseViewModel { - private readonly RevitLinkType _linkType; - private readonly Workset _workset; - private string _linkLoadToolTip; +namespace RevitCheckingLevels.ViewModels; +internal class LinkTypeViewModel : BaseViewModel { + private readonly Workset _workset; + private string _linkLoadToolTip; - public LinkTypeViewModel(RevitLinkType linkType) { - _linkType = linkType; - _workset = _linkType.Document.GetWorksetTable().GetWorkset(_linkType.WorksetId); + public LinkTypeViewModel(RevitLinkType linkType) { + Element = linkType; + _workset = Element.Document.GetWorksetTable().GetWorkset(Element.WorksetId); - LinkLoadCommand = new RelayCommand(LinkLoad, CanLinkLoad); - } + LinkLoadCommand = new RelayCommand(LinkLoad, CanLinkLoad); + } - public RevitLinkType Element => _linkType; + public RevitLinkType Element { get; } - public ElementId Id => _linkType.Id; - public string Name => _linkType.Name; - public bool IsLinkLoaded => _linkType.GetLinkedFileStatus() == LinkedFileStatus.Loaded; + public ElementId Id => Element.Id; + public string Name => Element.Name; + public bool IsLinkLoaded => Element.GetLinkedFileStatus() == LinkedFileStatus.Loaded; - public ICommand LinkLoadCommand { get; } + public ICommand LinkLoadCommand { get; } - public string LinkLoadToolTip { - get => _linkLoadToolTip; - set => this.RaiseAndSetIfChanged(ref _linkLoadToolTip, value); - } + public string LinkLoadToolTip { + get => _linkLoadToolTip; + set => RaiseAndSetIfChanged(ref _linkLoadToolTip, value); + } - private void LinkLoad(object p) { - _linkType.Load(); - OnPropertyChanged(nameof(IsLinkLoaded)); - } + private void LinkLoad(object p) { + Element.Load(); + OnPropertyChanged(nameof(IsLinkLoaded)); + } - private bool CanLinkLoad(object p) { - if(IsLinkLoaded) { - LinkLoadToolTip = "Данная связь уже загружена."; - return false; - } + private bool CanLinkLoad(object p) { + if(IsLinkLoaded) { + LinkLoadToolTip = "Данная связь уже загружена."; + return false; + } - if(!_workset.IsOpen) { - LinkLoadToolTip = $"Откройте рабочий набор \"{_workset.Name}\"." - + Environment.NewLine - + "Загрузка связанного файла из закрытого рабочего набора не поддерживается!"; + if(!_workset.IsOpen) { + LinkLoadToolTip = $"Откройте рабочий набор \"{_workset.Name}\"." + + Environment.NewLine + + "Загрузка связанного файла из закрытого рабочего набора не поддерживается!"; - return false; - } + return false; + } - LinkLoadToolTip = "Загрузить координационный файл"; - return true; + LinkLoadToolTip = "Загрузить координационный файл"; + return true; - } } } diff --git a/src/RevitCheckingLevels/ViewModels/MainViewModel.cs b/src/RevitCheckingLevels/ViewModels/MainViewModel.cs index 0945f4f0e..49c5a9383 100644 --- a/src/RevitCheckingLevels/ViewModels/MainViewModel.cs +++ b/src/RevitCheckingLevels/ViewModels/MainViewModel.cs @@ -1,8 +1,7 @@ -using System; +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using System.Windows; using System.Windows.Input; using Autodesk.Revit.DB; @@ -14,208 +13,210 @@ using RevitCheckingLevels.Models; using RevitCheckingLevels.Models.LevelParser; -namespace RevitCheckingLevels.ViewModels { - internal class MainViewModel : BaseViewModel { - private readonly RevitRepository _revitRepository; - private readonly CheckingLevelConfig _checkingLevelConfig; +namespace RevitCheckingLevels.ViewModels; +internal class MainViewModel : BaseViewModel { + private readonly RevitRepository _revitRepository; + private readonly CheckingLevelConfig _checkingLevelConfig; - private string _errorText; - private LevelViewModel _level; - private LinkTypeViewModel _linkType; + private string _errorText; + private LevelViewModel _level; + private LinkTypeViewModel _linkType; - public MainViewModel(RevitRepository revitRepository, CheckingLevelConfig checkingLevelConfig) { - _revitRepository = revitRepository; - _checkingLevelConfig = checkingLevelConfig; + public MainViewModel(RevitRepository revitRepository, CheckingLevelConfig checkingLevelConfig) { + _revitRepository = revitRepository; + _checkingLevelConfig = checkingLevelConfig; - ViewCommand = new RelayCommand(SaveSettings); - ViewLoadCommand = new RelayCommand(LoadView); - LoadLevelErrorsCommand = new RelayCommand(LoadLevelErrors); - UpdateElevationCommand = new RelayCommand(UpdateElevation); - } + ViewCommand = new RelayCommand(SaveSettings); + ViewLoadCommand = new RelayCommand(LoadView); + LoadLevelErrorsCommand = new RelayCommand(LoadLevelErrors); + UpdateElevationCommand = new RelayCommand(UpdateElevation); + } - public ICommand ViewCommand { get; } - public ICommand ViewLoadCommand { get; } - public ICommand LoadLevelErrorsCommand { get; } - public ICommand UpdateElevationCommand { get; } + public ICommand ViewCommand { get; } + public ICommand ViewLoadCommand { get; } + public ICommand LoadLevelErrorsCommand { get; } + public ICommand UpdateElevationCommand { get; } - public bool IsKoordFile => _revitRepository.IsKoordFile(); - public bool HasErrors => !IsKoordFile && (LinkType == null || !LinkType.IsLinkLoaded) || Levels.Count > 0; + public bool IsKoordFile => _revitRepository.IsKoordFile(); + public bool HasErrors => (!IsKoordFile && (LinkType == null || !LinkType.IsLinkLoaded)) || Levels.Count > 0; - public string ErrorText { - get => _errorText; - set => this.RaiseAndSetIfChanged(ref _errorText, value); - } + public string ErrorText { + get => _errorText; + set => RaiseAndSetIfChanged(ref _errorText, value); + } - public ObservableCollection Levels { get; } = new ObservableCollection(); + public ObservableCollection Levels { get; } = []; - public LevelViewModel Level { - get => _level; - set => this.RaiseAndSetIfChanged(ref _level, value); - } + public LevelViewModel Level { + get => _level; + set => RaiseAndSetIfChanged(ref _level, value); + } - public ObservableCollection LinkTypes { get; } = - new ObservableCollection(); + public ObservableCollection LinkTypes { get; } = + []; - public LinkTypeViewModel LinkType { - get => _linkType; - set => this.RaiseAndSetIfChanged(ref _linkType, value); - } + public LinkTypeViewModel LinkType { + get => _linkType; + set => RaiseAndSetIfChanged(ref _linkType, value); + } + + private void SaveSettings(object obj) { + var settings = _checkingLevelConfig.GetSettings(_revitRepository.Document) + ?? _checkingLevelConfig.AddSettings(_revitRepository.Document); + + settings.LinkTypeId = LinkType?.Id ?? ElementId.InvalidElementId; + _checkingLevelConfig.SaveProjectConfig(); + } + + private void LoadView(object p) { + LoadLinkFiles(null); + LoadLevelErrors((object) null); + } - private void SaveSettings(object obj) { - var settings = _checkingLevelConfig.GetSettings(_revitRepository.Document) - ?? _checkingLevelConfig.AddSettings(_revitRepository.Document); + private void LoadLinkFiles(object parameter) { + LinkTypes.Clear(); + + if(!IsKoordFile) { + foreach(var linkType in _revitRepository.GetRevitLinkTypes()) { + LinkTypes.Add(new LinkTypeViewModel(linkType)); + } - settings.LinkTypeId = LinkType?.Id ?? ElementId.InvalidElementId; - _checkingLevelConfig.SaveProjectConfig(); + // var settings = _checkingLevelConfig.GetSettings(_revitRepository.Document); + LinkType = LinkTypes.FirstOrDefault(item => _revitRepository.IsKoordFile(item.Element)); } + } + + private void LoadLevelErrors(object parameter) { + Levels.Clear(); + var levelInfos = _revitRepository.GetLevels() + .Select(item => new LevelParserImpl(item).ReadLevelInfo()) + .OrderBy(item => item.Level.Elevation) + .ToArray(); - private void LoadView(object p) { - LoadLinkFiles(null); - LoadLevelErrors((object) null); + foreach(var item in LoadLevelErrors(levelInfos)) { + Levels.Add(item); } - private void LoadLinkFiles(object parameter) { - LinkTypes.Clear(); + LoadLinkLevels(levelInfos); + Level = Levels.FirstOrDefault(); + } - if(!IsKoordFile) { - foreach(RevitLinkType linkType in _revitRepository.GetRevitLinkTypes()) { - LinkTypes.Add(new LinkTypeViewModel(linkType)); - } + private void LoadLinkLevels(LevelInfo[] levelInfos) { + ErrorText = null; + if(IsKoordFile) { + return; + } - // var settings = _checkingLevelConfig.GetSettings(_revitRepository.Document); - LinkType = LinkTypes.FirstOrDefault(item => _revitRepository.IsKoordFile(item.Element)); - } + if(LinkType == null) { + ErrorText = $"Проверки на соответствие координационному файлу не выполнены (файл не выбран)."; + return; } - private void LoadLevelErrors(object parameter) { - Levels.Clear(); - var levelInfos = _revitRepository.GetLevels() - .Select(item => new LevelParserImpl(item).ReadLevelInfo()) - .OrderBy(item => item.Level.Elevation) - .ToArray(); + if(!LinkType.IsLinkLoaded) { + ErrorText = $"Проверки на соответствие координационному файлу не выполнены (файл не загружен)."; + return; + } - foreach(LevelViewModel item in LoadLevelErrors(levelInfos)) { - Levels.Add(item); - } - LoadLinkLevels(levelInfos); - Level = Levels.FirstOrDefault(); + if(!_revitRepository.HasLinkInstance(LinkType.Element)) { + ErrorText = $"Проверки на соответствие координационному файлу не выполнены (экземпляры не созданы)."; + return; } - private void LoadLinkLevels(LevelInfo[] levelInfos) { - ErrorText = null; - if(IsKoordFile) { - return; - } - - if(LinkType == null) { - ErrorText = $"Проверки на соответствие координационному файлу не выполнены (файл не выбран)."; - return; - } + var linkLevelInfos = _revitRepository.GetLevels(LinkType.Element) + .Select(item => new LevelParserImpl(item).ReadLevelInfo()) + .OrderBy(item => item.Level.Elevation) + .ToArray(); - if(!LinkType.IsLinkLoaded) { - ErrorText = $"Проверки на соответствие координационному файлу не выполнены (файл не загружен)."; - return; - } + if(linkLevelInfos.Length == 0) { + ErrorText = $"Проверки на соответствие координационному файлу не выполнены (нет уровней)."; + return; + } + if(LoadLevelErrors(linkLevelInfos).Any()) { + ErrorText = $"Проверки на соответствие координационному файлу не выполнены (ошибки в коорд. файле)."; + return; + } - if(!_revitRepository.HasLinkInstance(LinkType.Element)) { - ErrorText = $"Проверки на соответствие координационному файлу не выполнены (экземпляры не созданы)."; - return; + foreach(var levelInfo in levelInfos) { + if(levelInfo.IsNotFoundLevels(linkLevelInfos)) { + Levels.Add(new LevelViewModel(levelInfo) { ErrorType = ErrorType.NotFoundLevels }); } + } + } - var linkLevelInfos = _revitRepository.GetLevels(LinkType.Element) - .Select(item => new LevelParserImpl(item).ReadLevelInfo()) - .OrderBy(item => item.Level.Elevation) - .ToArray(); - - if(linkLevelInfos.Length == 0) { - ErrorText = $"Проверки на соответствие координационному файлу не выполнены (нет уровней)."; - return; + private static IEnumerable LoadLevelErrors(LevelInfo[] levelInfos) { + foreach(var levelInfo in levelInfos) { + if(levelInfo.IsNotStandard()) { + yield return new LevelViewModel(levelInfo) { + ErrorType = ErrorType.NotStandard, + ToolTipInfo = levelInfo.GetNotStandardTooltip() + }; } - if(LoadLevelErrors(linkLevelInfos).Any()) { - ErrorText = $"Проверки на соответствие координационному файлу не выполнены (ошибки в коорд. файле)."; - return; + if(levelInfo.IsNotElevation()) { + yield return new LevelViewModel(levelInfo) { + ErrorType = ErrorType.NotElevation, + ToolTipInfo = levelInfo.GetNotElevationTooltip() + }; } - foreach(LevelInfo levelInfo in levelInfos) { - if(levelInfo.IsNotFoundLevels(linkLevelInfos)) { - Levels.Add(new LevelViewModel(levelInfo) {ErrorType = ErrorType.NotFoundLevels}); - } + if(levelInfo.IsNotMillimeterElevation()) { + yield return new LevelViewModel(levelInfo) { + ErrorType = ErrorType.NotMillimeterElevation, + ToolTipInfo = levelInfo.GetNotMillimeterElevationTooltip() + }; } - } - private static IEnumerable LoadLevelErrors(LevelInfo[] levelInfos) { - foreach(LevelInfo levelInfo in levelInfos) { - if(levelInfo.IsNotStandard()) { - yield return new LevelViewModel(levelInfo) { - ErrorType = ErrorType.NotStandard, ToolTipInfo = levelInfo.GetNotStandardTooltip() - }; - } - - if(levelInfo.IsNotElevation()) { - yield return new LevelViewModel(levelInfo) { - ErrorType = ErrorType.NotElevation, ToolTipInfo = levelInfo.GetNotElevationTooltip() - }; - } - - if(levelInfo.IsNotMillimeterElevation()) { - yield return new LevelViewModel(levelInfo) { - ErrorType = ErrorType.NotMillimeterElevation, - ToolTipInfo = levelInfo.GetNotMillimeterElevationTooltip() - }; - } - - if(levelInfo.IsNotRangeElevation(levelInfos)) { - yield return new LevelViewModel(levelInfo) {ErrorType = ErrorType.NotRangeElevation}; - } + if(levelInfo.IsNotRangeElevation(levelInfos)) { + yield return new LevelViewModel(levelInfo) { ErrorType = ErrorType.NotRangeElevation }; } } + } - private void UpdateElevation(object p) { - var levelCreationNames = _revitRepository.GetLevelCreationNames(Levels - .Where(item => item.ErrorType == ErrorType.NotElevation) - .Select(item => item.LevelInfo)) - .ToArray(); - - var duplicateNames = levelCreationNames - .Where(item => item.DuplicateName) - .Select(item => $"{item.LevelInfo.Level.Name} -> {item.LevelName}") - .OrderBy(item => item) - .ToArray(); - - if(duplicateNames.Length > 0) { - TaskDialog taskDialog = CreateTaskDialog(duplicateNames); - if(taskDialog.Show() == TaskDialogResult.CommandLink1) { - _revitRepository.UpdateElevations(levelCreationNames); - } else { - throw new OperationCanceledException(); - } - } else { + private void UpdateElevation(object p) { + var levelCreationNames = _revitRepository.GetLevelCreationNames(Levels + .Where(item => item.ErrorType == ErrorType.NotElevation) + .Select(item => item.LevelInfo)) + .ToArray(); + + string[] duplicateNames = levelCreationNames + .Where(item => item.DuplicateName) + .Select(item => $"{item.LevelInfo.Level.Name} -> {item.LevelName}") + .OrderBy(item => item) + .ToArray(); + + if(duplicateNames.Length > 0) { + var taskDialog = CreateTaskDialog(duplicateNames); + if(taskDialog.Show() == TaskDialogResult.CommandLink1) { _revitRepository.UpdateElevations(levelCreationNames); + } else { + throw new OperationCanceledException(); } - - LoadView(null); + } else { + _revitRepository.UpdateElevations(levelCreationNames); } - private static TaskDialog CreateTaskDialog(string[] duplicateNames) { - var taskDialog = new TaskDialog("Обновление отметки"); - taskDialog.TitleAutoPrefix = false; - taskDialog.AllowCancellation = true; - taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; - taskDialog.MainContent = "Имена уровней должны быть уникальными"; - taskDialog.MainInstruction = "Обновление отметки в имени невозможно."; - taskDialog.ExpandedContent = Environment.NewLine + " - " - + string.Join(Environment.NewLine + " - ", duplicateNames); - - taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, - "Игнорировать ошибки", - "Пропускает уровни с дублирующимися именами."); - taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, - "Отменить", - "Отменяет переименование всех уровней."); - return taskDialog; - } + LoadView(null); + } + + private static TaskDialog CreateTaskDialog(string[] duplicateNames) { + var taskDialog = new TaskDialog("Обновление отметки") { + TitleAutoPrefix = false, + AllowCancellation = true, + MainIcon = TaskDialogIcon.TaskDialogIconWarning, + MainContent = "Имена уровней должны быть уникальными", + MainInstruction = "Обновление отметки в имени невозможно.", + ExpandedContent = Environment.NewLine + " - " + + string.Join(Environment.NewLine + " - ", duplicateNames) + }; + + taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, + "Игнорировать ошибки", + "Пропускает уровни с дублирующимися именами."); + taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, + "Отменить", + "Отменяет переименование всех уровней."); + return taskDialog; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/ViewTemplateSelectors/ErrorTypeGroupRowTemplateSelector.cs b/src/RevitCheckingLevels/ViewTemplateSelectors/ErrorTypeGroupRowTemplateSelector.cs index 1031ce30e..ccbd609e0 100644 --- a/src/RevitCheckingLevels/ViewTemplateSelectors/ErrorTypeGroupRowTemplateSelector.cs +++ b/src/RevitCheckingLevels/ViewTemplateSelectors/ErrorTypeGroupRowTemplateSelector.cs @@ -1,23 +1,21 @@ -using System.Windows; +using System.Windows; using System.Windows.Controls; using DevExpress.Xpf.Grid; using dosymep.WPF; -using dosymep.WPF.Converters; using RevitCheckingLevels.Models; -namespace RevitCheckingLevels.ViewTemplateSelectors { - internal class ErrorTypeGroupRowTemplateSelector : DataTemplateSelector { - public DataTemplate DefaultTemplate { get; set; } - public DataTemplate UpdateElevationTemplate { get; set; } +namespace RevitCheckingLevels.ViewTemplateSelectors; +internal class ErrorTypeGroupRowTemplateSelector : DataTemplateSelector { + public DataTemplate DefaultTemplate { get; set; } + public DataTemplate UpdateElevationTemplate { get; set; } - public override DataTemplate SelectTemplate(object item, DependencyObject container) { - var errorType = (item as GroupRowData).GetGroupRowValue(); - return errorType == ErrorType.NotElevation - ? UpdateElevationTemplate - : DefaultTemplate; - } + public override DataTemplate SelectTemplate(object item, DependencyObject container) { + var errorType = (item as GroupRowData).GetGroupRowValue(); + return errorType == ErrorType.NotElevation + ? UpdateElevationTemplate + : DefaultTemplate; } } \ No newline at end of file diff --git a/src/RevitCheckingLevels/ViewTemplates/DefaultGroupRowTemplate.xaml b/src/RevitCheckingLevels/ViewTemplates/DefaultGroupRowTemplate.xaml index 1edaf97f3..4960502a7 100644 --- a/src/RevitCheckingLevels/ViewTemplates/DefaultGroupRowTemplate.xaml +++ b/src/RevitCheckingLevels/ViewTemplates/DefaultGroupRowTemplate.xaml @@ -4,24 +4,32 @@ xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"> - - + + - - - + + + diff --git a/src/RevitCheckingLevels/ViewTemplates/GridRowStyle.xaml b/src/RevitCheckingLevels/ViewTemplates/GridRowStyle.xaml index 35b462ad7..808ca19eb 100644 --- a/src/RevitCheckingLevels/ViewTemplates/GridRowStyle.xaml +++ b/src/RevitCheckingLevels/ViewTemplates/GridRowStyle.xaml @@ -2,8 +2,12 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"> - - \ No newline at end of file diff --git a/src/RevitCheckingLevels/ViewTemplates/UpdateElevationGroupRowTemplate.xaml b/src/RevitCheckingLevels/ViewTemplates/UpdateElevationGroupRowTemplate.xaml index 4eb2430af..a1f76a149 100644 --- a/src/RevitCheckingLevels/ViewTemplates/UpdateElevationGroupRowTemplate.xaml +++ b/src/RevitCheckingLevels/ViewTemplates/UpdateElevationGroupRowTemplate.xaml @@ -1,33 +1,43 @@ - + - - + + - - - + + + diff --git a/src/RevitCheckingLevels/Views/MainWindow.xaml b/src/RevitCheckingLevels/Views/MainWindow.xaml index 8286e55e8..2769543f7 100644 --- a/src/RevitCheckingLevels/Views/MainWindow.xaml +++ b/src/RevitCheckingLevels/Views/MainWindow.xaml @@ -4,25 +4,21 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" - xmlns:base="clr-namespace:dosymep.WPF.Views" xmlns:local="clr-namespace:RevitCheckingLevels.Views" xmlns:vms="clr-namespace:RevitCheckingLevels.ViewModels" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" - xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core" xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:commands="clr-namespace:dosymep.WPF.Commands" xmlns:converters="clr-namespace:dosymep.WPF.Converters" xmlns:selectors="clr-namespace:RevitCheckingLevels.ViewTemplateSelectors" - mc:Ignorable="d" WindowStartupLocation="CenterOwner" - Title="MainWindow" - Height="450" Width="800" - + Height="450" + Width="800" x:Name="_this" d:DataContext="{d:DesignInstance vms:MainViewModel, IsDesignTimeCreatable=False}"> @@ -33,16 +29,25 @@ DefaultTemplate="{StaticResource DefaultGroupRowTemplate}" UpdateElevationTemplate="{StaticResource UpdateElevationGroupRowTemplate}" /> - - + + - - + + - - - + + + @@ -64,17 +69,23 @@ Command="{Binding Source={StaticResource DisableCollapseGroupRowCommand}}" /> - - - + + + - - - + + + @@ -138,14 +148,27 @@ GroupRowTemplateSelector="{StaticResource ErrorTypeGroupRowTemplateSelector}" /> - - - - - + + + + + - + diff --git a/src/RevitCheckingLevels/Views/MainWindow.xaml.cs b/src/RevitCheckingLevels/Views/MainWindow.xaml.cs index 1a8233d56..856a7d65a 100644 --- a/src/RevitCheckingLevels/Views/MainWindow.xaml.cs +++ b/src/RevitCheckingLevels/Views/MainWindow.xaml.cs @@ -1,20 +1,19 @@ -using System.Windows; +using System.Windows; -namespace RevitCheckingLevels.Views { - public partial class MainWindow { - public MainWindow() { - InitializeComponent(); - } +namespace RevitCheckingLevels.Views; +public partial class MainWindow { + public MainWindow() { + InitializeComponent(); + } - public override string PluginName => nameof(RevitCheckingLevels); - public override string ProjectConfigName => nameof(MainWindow); + public override string PluginName => nameof(RevitCheckingLevels); + public override string ProjectConfigName => nameof(MainWindow); - private void ButtonOk_Click(object sender, RoutedEventArgs e) { - DialogResult = true; - } + private void ButtonOk_Click(object sender, RoutedEventArgs e) { + DialogResult = true; + } - private void ButtonCancel_Click(object sender, RoutedEventArgs e) { - DialogResult = false; - } + private void ButtonCancel_Click(object sender, RoutedEventArgs e) { + DialogResult = false; } } \ No newline at end of file