Ejemplo n.º 1
0
        public void DoubleValidator_IsValid_WrongType()
        {
            DoubleValidator validator = new DoubleValidator(1, true, 10, true);
            bool            result    = validator.IsValid("x", "Property", null, out _);

            Assert.False(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Параметр вращения по граням вращения (начало и конец),
        /// точке расположения вращения, размеру диаметра и шагу вращения
        /// </summary>
        /// <param name="parameters">Parameters of spin</param>
        public Spin(SpinParameters parameters)
        {
            if (parameters.BeginSpinFace == null ||
                parameters.EndSpinFace == null ||
                parameters.SpinLocationPoint.LastErrorCode != ErrorCodes.OK ||
                parameters.DiameterSize == default(double) ||
                !DoubleValidator.Validate(parameters.DiameterSize) ||
                parameters.SpinStep == default(double) ||
                !DoubleValidator.Validate(parameters.SpinStep)
                )
            {
                LastErrorCode = ErrorCodes.ArgumentNull;
                return;
            }

            if (parameters.DiameterSize <= default(double) ||
                !DoubleValidator.Validate(parameters.DiameterSize) ||
                !DoubleValidator.Validate(parameters.SpinLocationPoint.X) ||
                !DoubleValidator.Validate(parameters.SpinLocationPoint.Y)
                )
            {
                LastErrorCode = ErrorCodes.DoubleValueValidationError;
                return;
            }

            if (!CreateSpin(parameters))
            {
                return;
            }
        }
Ejemplo n.º 3
0
        public void DoubleValidator_IsValid_EqualMinMax()
        {
            DoubleValidator validator = new DoubleValidator(1, true, 1, true);
            bool            result    = validator.IsValid(2, "Property", null, out _);

            Assert.False(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Конструктор глушителя
        /// </summary>
        /// <param name="figureParameters">Parameters of muffler</param>
        /// <param name="kompasApp">Kompas application specimen</param>
        /// <param name="basePlane">Base plane of muffler, by default is null</param>
        public Muffler(KompasApplication kompasApp, MufflerParameters figureParameters,
                       ksEntity basePlane = null)
        {
            if (kompasApp == null ||
                figureParameters.Document3DPart == null ||
                figureParameters.BasePlanePoint.LastErrorCode != ErrorCodes.OK ||
                !(figureParameters.BasePlaneAxis == Obj3dType.o3d_planeXOY ||
                  figureParameters.BasePlaneAxis == Obj3dType.o3d_planeXOZ ||
                  figureParameters.BasePlaneAxis == Obj3dType.o3d_planeYOZ) ||
                !DoubleValidator.Validate(figureParameters.BasePlanePoint.X) ||
                !DoubleValidator.Validate(figureParameters.BasePlanePoint.Y))
            {
                LastErrorCode = ErrorCodes.ArgumentNull;
                return;
            }
            if (!(figureParameters.Direction == Direction_Type.dtNormal ||
                  figureParameters.Direction == Direction_Type.dtReverse))
            {
                LastErrorCode = ErrorCodes.ArgumentInvalid;
                return;
            }

            _kompasApp        = kompasApp;
            _figureParameters = figureParameters;

            Extrusion = CreateMuffler(figureParameters, basePlane);
            if (Extrusion == null)
            {
                return;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Create rounded chamfer in regular polygon sketch by base sketch,
        /// regular polygon parameters and base plane coordinates in plane
        /// </summary>
        /// <param name="doc3D">Kompas document 3D</param>
        /// <param name="doc3DPart">Kompas document 3D part with detail</param>
        /// <param name="regPolySketch">Sketch of regular polygon</param>
        /// <param name="regPolyParam">An object with parameters of regular polygon</param>
        /// <param name="basePlanePoint">Base plane point of regular polygon</param>
        /// <param name="directionType">Direction type</param>
        /// <returns>Entity of rounded chamfer or null in case of error</returns>
        public RoundedChamfer(KompasApplication kompasApp, RoundedChamferParameters figureParameters)
        {
            if (kompasApp == null ||
                figureParameters.Document3DPart == null ||
                figureParameters.RegularPolygonSketch == null ||
                figureParameters.RegularPolygonParameters == null
                )
            {
                LastErrorCode = ErrorCodes.ArgumentNull;
                return;
            }

            // KompasApplication kompasApp, ksPart doc3DPart, ksEntity regPolySketch, RegularPolygonParameter regPolyParam, KompasPoint2D basePlanePoint, Direction_Type directionType

            _figureParameters = figureParameters;

            _kompasApp = kompasApp;

            if (!DoubleValidator.Validate(_figureParameters.BasePlanePoint.X) ||
                !DoubleValidator.Validate(_figureParameters.BasePlanePoint.Y)
                )
            {
                LastErrorCode = ErrorCodes.DoubleValueValidationError;
                return;
            }
        }
Ejemplo n.º 6
0
        public static void TestDoubleCalculator()
        {
            Console.Clear();
            ICalculator <double>      calc = new DoubleCalculator();
            INumberValidator <double> validator = new DoubleValidator();
            double value1, value2, result;

            while (true)
            {
                try
                {
                    Console.Write("Введите операцию (+ - * /): ");
                    ConsoleKeyInfo key = Console.ReadKey();
                    if (key.Key == ConsoleKey.Escape)
                    {
                        return;
                    }
                    char operation = key.KeyChar;
                    if (operations.IndexOf(operation) == -1)
                    {
                        Console.WriteLine("\r\nА вот и не правильно");
                        continue;
                    }
                    Console.Write("\r\nВведите 2 числа разделенных пробелом: ");
                    if (!validator.ValidateTwoNumbers(Console.ReadLine(), out value1, out value2))
                    {
                        Console.WriteLine("Неверный ввод. Придется повторить");
                        continue;
                    }
                    switch (operation)
                    {
                    case '+':
                        result = calc.Add(value1, value2);
                        break;

                    case '-':
                        result = calc.Subtract(value1, value2);
                        break;

                    case '*':
                        result = calc.Multiply(value1, value2);
                        break;

                    case '/':
                        result = calc.Divide(value1, value2);
                        break;

                    default:
                        continue;
                    }
                    Console.WriteLine($"{ value1}{ operation}{ value2}={ result}");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Exception {e.GetType().Name}: {e.Message}");
                }
            }
        }
Ejemplo n.º 7
0
        public void Init()
        {
            Thread.CurrentThread.CurrentCulture       =
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

            validator = new DoubleValidator();
            validator.Initialize(new CachedValidationRegistry(), typeof(TestTarget).GetProperty("TargetField"));
            target = new TestTarget();
        }
Ejemplo n.º 8
0
        private IEnumerable <string> ValidateUnitGrams(string grams, [CallerMemberName] string propertyName = "")
        {
            var validator         = new DoubleValidator(minimum: MinimumGrams);
            var validationResults = validator.Validate(grams);

            SetValidationResults(validationResults, propertyName);

            return(validationResults);
        }
Ejemplo n.º 9
0
        private IEnumerable <string> ValidateMacroGrams(string grams, [CallerMemberName] string propertyName = "")
        {
            var validator         = new DoubleValidator(minimum: FoodUnitConstants.MinimumAllowedMacroGrams);
            var validationResults = validator.Validate(grams);

            SetValidationResults(validationResults, propertyName);

            return(validationResults);
        }
Ejemplo n.º 10
0
		public void Init()
		{
			Thread.CurrentThread.CurrentCulture =
				Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

			validator = new DoubleValidator();
			validator.Initialize(new CachedValidationRegistry(), typeof(TestTarget).GetProperty("TargetField"));
			target = new TestTarget();
		}
Ejemplo n.º 11
0
        /// <summary>
        /// Verifies the input.
        /// </summary>
        /// <param name="sender">Input TextBox.</param>
        /// <param name="e">TextCompositionEventArgs</param>
        private static void OnPreviewInputText(object sender, TextCompositionEventArgs e)
        {
            var textBox = (TextBox)sender;
            // If text box contains selected text we should replace it with e.Text
            string fullText = textBox.SelectionLength > 0
           ? textBox.Text.Replace(textBox.SelectedText, e.Text)
           : textBox.Text.Insert(textBox.CaretIndex, e.Text);

            e.Handled = !DoubleValidator.IsValid(fullText);
        }
Ejemplo n.º 12
0
        public void DoubleValidator_IsValid_NullPropertyName()
        {
            DoubleValidator validator = new DoubleValidator(1, true, 10, true);

            string errorMessage;

            Assert.Throws <ArgumentException>(() => validator.IsValid(2, null, null, out errorMessage));

            Assert.Throws <ArgumentException>(() => validator.IsValid(2, String.Empty, null, out errorMessage));
        }
        public void ValidateDoubleToBeLessThanOrEqualToEqualValue()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            validator.BeLessThanOrEqualTo(42);

            // Then
            Assert.True(true);
        }
        public void ValidateDoubleToBeOneOfExpectedValues()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            validator.BeOneOf(new double[] { 10, 42 });

            // Then
            Assert.True(true);
        }
        public void ValidateDoubleToBeValue()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            validator.Be(42);

            // Then
            Assert.True(true);
        }
        public void ValidateDoubleToBeApproximatelyValue()
        {
            // Given
            var validator = new DoubleValidator(42.12345d);

            // When
            validator.BeApproximately(42.123d, 0.1d);

            // Then
            Assert.True(true);
        }
        public void ValidateDoubleToBeGreaterThanOrEqualToSmallerValue()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            validator.BeGreaterThanOrEqualTo(13);

            // Then
            Assert.True(true);
        }
        public void ValidateDoubleToBePositive()
        {
            // Given
            var validator = new DoubleValidator(0);

            // When
            validator.BePositive();

            // Then
            Assert.True(true);
        }
        public void ValidateDoubleToBeBetweenValues()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            validator.BeBetween(13, 130);

            // Then
            Assert.True(true);
        }
Ejemplo n.º 20
0
        public void DoubleValidator_Ctor_EqualMinMax()
        {
            double          min            = 100;
            bool            isMinInclusive = true;
            double          max            = 100;
            bool            isMaxInclusive = true;
            DoubleValidator validator      = new DoubleValidator(min, isMinInclusive, max, isMaxInclusive);

            Assert.Equal(min, validator.MinValue);
            Assert.Equal(max, validator.MaxValue);
            Assert.Equal(isMinInclusive, validator.IsMinValueInclusive);
            Assert.Equal(isMaxInclusive, validator.IsMaxValueInclusive);
        }
        public void ValidateDoubleToBeApproximatelyValueViolated()
        {
            // Given
            var validator = new DoubleValidator(42.12345d);

            // When
            var exception = Assert.Throws <XunitException>(() => validator.BeApproximately(42d, 0.01d, "that's the bottom line"));

            // Then
            Assert.NotNull(exception);
            var rn = Environment.NewLine;

            Assert.Equal(
                $"{rn}validator{rn}is \"42,12345\"{rn}but was expected to be approximately \"42\" (+/- 0,01){rn}because that's the bottom line",
                exception.UserMessage);
        }
        public void ValidateDoubleToBeLessThanOrEqualToValueViolated()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            var exception = Assert.Throws <XunitException>(() => validator.BeLessThanOrEqualTo(13, "that's the bottom line"));

            // Then
            Assert.NotNull(exception);
            var rn = Environment.NewLine;

            Assert.Equal(
                $"{rn}validator{rn}is \"42\"{rn}but was expected to be less than or equal to \"13\"{rn}because that's the bottom line",
                exception.UserMessage);
        }
        public void ValidateDoubleToBePositiveViolated()
        {
            // Given
            var validator = new DoubleValidator(-42);

            // When
            var exception = Assert.Throws <XunitException>(() => validator.BePositive(because: "that's the bottom line"));

            // Then
            Assert.NotNull(exception);
            var rn = Environment.NewLine;

            Assert.Equal(
                $"{rn}validator{rn}is \"-42\"{rn}but was expected to have a positive value{rn}because that's the bottom line",
                exception.UserMessage);
        }
        public void ValidateDoubleToBeBetweenValuesMinimumViolated()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            var exception = Assert.Throws <XunitException>(() => validator.BeBetween(65, 130, "that's the bottom line"));

            // Then
            Assert.NotNull(exception);
            var rn = Environment.NewLine;

            Assert.Equal(
                $"{rn}validator{rn}is \"42\"{rn}but was expected to be between \"65\" and \"130\"{rn}because that's the bottom line",
                exception.UserMessage);
        }
        public void ValidateDoubleToBeOneOfViolated()
        {
            // Given
            var validator = new DoubleValidator(42);

            // When
            var exception = Assert.Throws <XunitException>(() => validator.BeOneOf(new double[] { 13, 39 }, because: "that's the bottom line"));

            // Then
            Assert.NotNull(exception);
            var rn = Environment.NewLine;

            Assert.Equal(
                $"{rn}validator{rn}is \"42\"{rn}but was expected to be one of the following values: \"13\", \"39\"{rn}because that's the bottom line",
                exception.UserMessage);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Kompas 2D Point
        /// </summary>
        /// <param name="xc">X coordinate</param>
        /// <param name="yc">Y coordinate</param>
        public KompasPoint2D(double xc, double yc)
        {
            X             = default(double);
            Y             = default(double);
            LastErrorCode = ErrorCodes.OK;

            if (!DoubleValidator.Validate(xc) ||
                !DoubleValidator.Validate(yc)
                )
            {
                LastErrorCode = ErrorCodes.ArgumentInvalid;
                return;
            }

            X = xc;
            Y = yc;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Get cylinder base plane indexes by indexes of faces of cylinder inside detail faces collection
        /// </summary>
        /// ksFaceDefinition.IsCylinder() defines is face cylindric or not,
        /// it seems to be unlogical, but in any case: base planes are NOT cylindric,
        /// they are just plane circles
        /// <param name="_doc3DPart">Document 3D part, represents detail</param>
        /// <param name="startIndex">Start index of faces in faces collection</param>
        /// <param name="endIndex">End index of faces in faces collection</param>
        /// <param name="outFirstIndex">First base plane index</param>
        /// <param name="outSecondIndex">Second base plane index</param>
        public static void GetCylinderBasePlaneIndexes(ksPart _doc3DPart, int startIndex, int endIndex, out int outFirstIndex, out int outSecondIndex)
        {
            /* TODO: функция getCylinderBasePlane работает только, если базовая плоскость больше размером, чем получаемая */
            var faceCollection = (ksEntityCollection)_doc3DPart.EntityCollection((short)Obj3dType.o3d_face);

            if (faceCollection == null ||
                !DoubleValidator.Validate(startIndex) ||
                !DoubleValidator.Validate(endIndex)
                )
            {
                outFirstIndex = outSecondIndex = -1;
                return;
            }

            bool isFirstIndexSet = false;

            int firstIndex  = -1;
            int secondIndex = -1;

            for (int i = startIndex - 1; i < endIndex; i++)
            {
                uint ST_MIX_SM = 0x0;                   // area in santimeters
                var  entity    = (ksEntity)faceCollection.GetByIndex(i);
                var  def       = (ksFaceDefinition)entity.GetDefinition();

                var area = Math.Round(def.GetArea(ST_MIX_SM), 10);                      // round to 10 numbers

                // If face isn't cylindric and if it is not base face (see xml-comment to this function)
                if (!def.IsCylinder() && isFirstIndexSet == false)
                {
                    isFirstIndexSet = true;
                    firstIndex      = i;
                }
                else if (!def.IsCylinder() && isFirstIndexSet == true)
                {
                    secondIndex = i;
                }
            }

            outFirstIndex  = firstIndex;
            outSecondIndex = secondIndex;

            return;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Получить индексы базовой плоскости цилиндра по индексам граней цилиндра
        /// внутри коллекции граней деталей
        /// </summary>
        /// <param name="_doc3DPart">Document 3D part, представляет деталь</param>
        /// <param name="startIndex">Start index of faces in faces collection</param>
        /// <param name="endIndex">End index of faces in faces collection</param>
        /// <param name="outFirstIndex">First base plane index</param>
        /// <param name="outSecondIndex">Second base plane index</param>
        public static void GetCylinderBasePlaneIndexes(ksPart _doc3DPart,
                                                       int startIndex, int endIndex, out int outFirstIndex, out int outSecondIndex)
        {
            var faceCollection = (ksEntityCollection)_doc3DPart.EntityCollection(
                (short)Obj3dType.o3d_face);

            if (faceCollection == null ||
                !DoubleValidator.Validate(startIndex) ||
                !DoubleValidator.Validate(endIndex)
                )
            {
                outFirstIndex = outSecondIndex = -1;
                return;
            }

            bool isFirstIndexSet = false;

            int firstIndex  = -1;
            int secondIndex = -1;

            for (int i = startIndex - 1; i < endIndex; i++)
            {
                uint ST_MIX_SM = 0x0;
                var  entity    = (ksEntity)faceCollection.GetByIndex(i);
                var  def       = (ksFaceDefinition)entity.GetDefinition();

                var area = Math.Round(def.GetArea(ST_MIX_SM), 10);

                if (!def.IsCylinder() && isFirstIndexSet == false)
                {
                    isFirstIndexSet = true;
                    firstIndex      = i;
                }
                else if (!def.IsCylinder() && isFirstIndexSet == true)
                {
                    secondIndex = i;
                }
            }

            outFirstIndex  = firstIndex;
            outSecondIndex = secondIndex;

            return;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Get cylinder base plane indexes by indexes of faces of cylinder inside detail faces collection
        /// </summary>
        /// ksFaceDefinition.IsCylinder () определяет, является ли грань цилиндрической или нет,
        /// это кажется нелогичным, но в любом случае: базовые плоскости НЕ являются цилиндрическими,
        /// они просто плоские круги
        /// <param name="_doc3DPart">Document 3D part, represents detail</param>
        /// <param name="startIndex">Start index of faces in faces collection</param>
        /// <param name="endIndex">End index of faces in faces collection</param>
        /// <param name="outFirstIndex">First base plane index</param>
        /// <param name="outSecondIndex">Second base plane index</param>
        public static void GetCylinderBasePlaneIndexes(ksPart _doc3DPart, int startIndex, int endIndex, out int outFirstIndex, out int outSecondIndex)
        {
            /* функция getCylinderBasePlane работает только, если базовая плоскость больше размером, чем получаемая */
            var faceCollection = (ksEntityCollection)_doc3DPart.EntityCollection((short)Obj3dType.o3d_face);

            if (faceCollection == null ||
                !DoubleValidator.Validate(startIndex) ||
                !DoubleValidator.Validate(endIndex)
                )
            {
                outFirstIndex = outSecondIndex = -1;
                return;
            }

            bool isFirstIndexSet = false;

            int firstIndex  = -1;
            int secondIndex = -1;

            for (int i = startIndex - 1; i < endIndex; i++)
            {
                uint ST_MIX_SM = 0x0;   //площадь в сантиметрах
                var  entity    = (ksEntity)faceCollection.GetByIndex(i);
                var  def       = (ksFaceDefinition)entity.GetDefinition();

                var area = Math.Round(def.GetArea(ST_MIX_SM), 10);  //округлить до 10 чисел

                // Если грань не является цилиндрической, и если она не является базовой гранью
                if (!def.IsCylinder() && isFirstIndexSet == false)
                {
                    isFirstIndexSet = true;
                    firstIndex      = i;
                }
                else if (!def.IsCylinder() && isFirstIndexSet == true)
                {
                    secondIndex = i;
                }
            }

            outFirstIndex  = firstIndex;
            outSecondIndex = secondIndex;

            return;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Get regular polygon param
        /// </summary>
        /// <param name="_kompas">Kompas object</param>
        /// <param name="anglesCount">Angles count</param>
        /// <param name="inscribedCircleRadius">Inscribed circle radius</param>
        /// <param name="point2D">Two-dimensional point of figure base</param>
        public RegularPolygonParameter(KompasApplication kompasApp, int anglesCount, double inscribedCircleRadius, KompasPoint2D point2D)
        {
            if (kompasApp == null)
            {
                LastErrorCode = ErrorCodes.ArgumentNull;
                return;
            }

            // Angles amount must be from 3 to 12
            if (anglesCount <= 2 ||
                anglesCount >= 13 ||
                !DoubleValidator.Validate(anglesCount) ||
                inscribedCircleRadius <= 0.0 ||
                !DoubleValidator.Validate(inscribedCircleRadius) ||
                !DoubleValidator.Validate(point2D.X) ||
                !DoubleValidator.Validate(point2D.Y)
                )
            {
                LastErrorCode = ErrorCodes.ArgumentInvalid;
                return;
            }

            // Regular polygon is base of hat
            ksRegularPolygonParam polyParam;

            polyParam = kompasApp.KompasObject.GetParamStruct((short)StructType2DEnum.ko_RegularPolygonParam);

            if (polyParam == null)
            {
                LastErrorCode = ErrorCodes.EntityDefinitionNull;
                return;
            }

            polyParam.count    = anglesCount;                                   // Count of angles
            polyParam.ang      = 0;                                             // Radius-vector angle from center to first top
            polyParam.describe = true;                                          // The polygon is DEscribed
            polyParam.radius   = inscribedCircleRadius;                         // INscribed circle radius, / W3 /
            polyParam.style    = 1;                                             // Line style
            polyParam.xc       = point2D.X; polyParam.yc = point2D.Y;           // Plane coordinates

            FigureParam = polyParam;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Get regular polygon param
        /// </summary>
        /// <param name="_kompas">Kompas object</param>
        /// <param name="anglesCount">Angles count</param>
        /// <param name="inscribedCircleRadius">Inscribed circle radius</param>
        /// <param name="point2D">Two-dimensional point of figure base</param>
        public RegularPolygonParameter(KompasApplication kompasApp, int anglesCount,
                                       double inscribedCircleRadius, KompasPoint2D point2D)
        {
            if (kompasApp == null)
            {
                LastErrorCode = ErrorCodes.ArgumentNull;
                return;
            }

            if (anglesCount <= 2 ||
                anglesCount >= 13 ||
                !DoubleValidator.Validate(anglesCount) ||
                inscribedCircleRadius <= 0.0 ||
                !DoubleValidator.Validate(inscribedCircleRadius) ||
                !DoubleValidator.Validate(point2D.X) ||
                !DoubleValidator.Validate(point2D.Y)
                )
            {
                LastErrorCode = ErrorCodes.ArgumentInvalid;
                return;
            }

            ksRegularPolygonParam polyParam;

            polyParam = kompasApp.KompasObject.GetParamStruct(
                (short)StructType2DEnum.ko_RegularPolygonParam);

            if (polyParam == null)
            {
                LastErrorCode = ErrorCodes.EntityDefinitionNull;
                return;
            }

            polyParam.count    = anglesCount;
            polyParam.ang      = 0;
            polyParam.describe = true;
            polyParam.radius   = inscribedCircleRadius;
            polyParam.style    = 1;
            polyParam.xc       = point2D.X; polyParam.yc = point2D.Y;

            FigureParam = polyParam;
        }