Ejemplo n.º 1
0
        private void ManyDecoratorsSolution(List <KeyValuePair <string, string> > pairs)
        {
            var operation              = new SimpleOperation();
            var metricDecorator        = new MetricsDecorator(operation);
            var errorHandlingDecorator = new ErrorHandlingDecorator(metricDecorator);

            //Note that the ordering of your decorators matters. If you want to clock everything,
            //including the error handling, then your metric decorator should be last. But if you
            //want your error handling to cover any potential problems with the metrics, error handling
            //should be your last decoration and so on...

            var result = errorHandlingDecorator.DoOperation(pairs);

            Console.WriteLine($"Return from the multiple decorators is {result}");
        }
        public void DoesNotCatchExceptionsDuringExecitionTest()
        {
            var operation = new SimpleOperation();

            operation.ActionToExecute = delegate
            {
                throw new AggregateException();
            };

            Assert.Throws <AggregateException>(
                () =>
                Run.InParallel
                .This(operation)
                .Execute());
        }
Ejemplo n.º 3
0
        public void TestRunSimpleOperationTwiceAtOnTime()
        {
            var       i         = 0;
            const int timeoutMs = 500;
            var       operation = new SimpleOperation("zzz", () => { i++; Thread.Sleep(timeoutMs); });

            Task.Run(() =>
            {
                Assert.Equal(OperationState.Idle, operation.State);
                var firstRunResult = operation.Run();
                Assert.False(firstRunResult.HasValue);
            });

            Task.Run(() =>
            {
                Assert.Equal(OperationState.Running, operation.State);
                var secondRunResult = operation.Run();
                Assert.False(secondRunResult.HasValue);
            });
            Thread.Sleep(timeoutMs + 50);
            Assert.Equal(OperationState.Idle, operation.State);
            Assert.Equal(1, i);
        }
Ejemplo n.º 4
0
        public void Run()
        {
            var pairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("key1", "value1"),
                new KeyValuePair <string, string>("key2", "value2")
            };

            //The original operator handles all of the metrics, error handline, etc, along with its normal intended function
            var originalOperator = new OriginalOperation();
            var result1          = originalOperator.DoOperation(pairs);

            Console.WriteLine($"Return from concrete call: {result1}");
            Console.WriteLine();

            //The simple operator is passed to a decorator of our choosing, to add (or decorate) additional functionality
            //around the specific action we care about. This separates the concerns of the Operation from other shared concerns
            //that other Operations might similarly have, like: validation, logging, error handling, metrics, etc...
            var simpleOperation1 = new SimpleOperation();
            var metricDecorator  = new MetricsDecorator(simpleOperation1);
            var result2          = metricDecorator.DoOperation(pairs);

            Console.WriteLine($"Return from metric decorator: {result2}");
            Console.WriteLine();

            var simpleOperation2       = new SimpleOperation();
            var errorHandlingDecorator = new ErrorHandlingDecorator(simpleOperation2);
            var result3 = errorHandlingDecorator.DoOperation(pairs);

            Console.WriteLine($"Return from error handling decorator: {result3}");
            Console.WriteLine();

            //What if we wanted to both get the metrics and handle any potential errors?
            //Do we need another decorator for that? Maybe an ErrorHandlingAndMetricsDecorator?
            //Think of a way to solve this, and then look at the below method to see how I solved it.
            ManyDecoratorsSolution(pairs);
        }
Ejemplo n.º 5
0
    public static string Calculate(int operand1, int operand2, string operation)
    {
        int result;

        try
        {
            switch (operation)
            {
            case "+":
                result = SimpleOperation.Addition(operand1, operand2);
                break;

            case "*":
                result = SimpleOperation.Multiplication(operand1, operand2);
                break;

            case "/":
                result = SimpleOperation.Division(operand1, operand2);
                break;

            case "":
                throw new ArgumentException("Operation cannot be empty.", "operation");

            case null:
                throw new ArgumentNullException("operation", "Operation cannot be null.");

            default:
                throw new ArgumentOutOfRangeException("operation", $"Operation {operation} does not exist.");
            }
        }
        catch (DivideByZeroException)
        {
            return("Division by zero is not allowed.");
        }

        return($"{operand1} {operation} {operand2} = {result}");
    }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            SimpleOperation addOperation = (a, b) => a + b;

            SimpleOperation substractOperation = (a, b) => a - b;

            SimpleOperation multiplyOperation = (a, b) => a * b;

            SimpleOperationEx divideOperation = (int a, int b, out int result) =>
            {
                try
                {
                    result = a / b;
                    return(true);
                }
                catch (DivideByZeroException)
                {
                    result = -1;
                    return(false);
                }
            };

            Console.WriteLine("Введите первое число:");
            int number1 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Введите второе число:");
            int number2 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Введите знак арифметической операции:");
            string sign = Console.ReadLine();

            switch (sign)
            {
            case "+":
            {
                Console.WriteLine(addOperation(number1, number2));
            }
            break;

            case "-":
            {
                Console.WriteLine(substractOperation(number1, number2));
            }
            break;

            case "*":
            {
                Console.WriteLine(multiplyOperation(number1, number2));
            }
            break;

            case "/":
            {
                if (divideOperation(number1, number2, out int divideResult))
                {
                    Console.WriteLine(divideResult);
                }
                else
                {
                    Console.WriteLine("Нельзя делить на 0!!!");
                }
            }
            break;

            default:
                Console.WriteLine("Нет такого знака!");
                break;
            }


            Console.ReadKey();
        }
Ejemplo n.º 7
0
 public void MethodInit()
 {
     context = new SimpleOperation<Person>();
 }
Ejemplo n.º 8
0
 public void MethodFInish()
 {
     context.Dispose();
     context = null;
 }