예제 #1
0
        public void Repeat_async_with_log_handler_should_log()
        {
            // Arrange
            Func <Task <int> > customMethodReturnWithCustomExceptionAsync = () =>
                                                                            Task.Factory.StartNew <int>(() => throw new CustomException());
            int totalAttempts = 0;
            var callback      = new FlowUtils.RetryCallback((a, e) =>
            {
                totalAttempts = a;
            });

            // Act
            try
            {
                FlowUtils.RetryAsync(
                    customMethodReturnWithCustomExceptionAsync,
                    FlowUtils.CreateCallbackRetryStrategy(callback) + FlowUtils.CreateFixedDelayRetryStrategy(2)).Wait();
            }
            catch (AggregateException)
            {
            }

            // Assert
            Assert.Equal(2, totalAttempts);
        }
예제 #2
0
        public void Repeat_async_with_first_fail_handler_should_work_fine()
        {
            // Arrange
            int totalAttempts = 0;

            // Act
            var result = FlowUtils.RetryAsync(
                () =>
            {
                return(Task.Factory.StartNew(() =>
                {
                    totalAttempts++;
                    if (totalAttempts < 5)
                    {
                        throw new CustomException();
                    }
                    return 10;
                }));
            },
                FlowUtils.CreateFixedDelayRetryStrategy(8)
                ).Result;

            // Assert
            Assert.Equal(10, result);
            Assert.True(totalAttempts > 4);
        }
예제 #3
0
        private void CleanCacheHandler(object obj)
        {
            var appsFolder = $@"C:\Users\{Environment.UserName}\AppData\Local\Apps\2.0";
            var buildInfo  = new[]
            {
                new InfoData(
                    "Clean cache",
                    $@"You are going to clean local applications cache. Be sure that no deployed programs running now. Cache folder location: ""{
                        appsFolder}"". By the way cleaning can be done manually:{Environment.NewLine
                        }1. By cmd.exe command: ""rundll32 dfshim CleanOnlineAppCache""] {Environment.NewLine
                        }2. Or just remove [{appsFolder}] folder content.")
            };

            var buildModel = new BuildInfoViewModel(buildInfo);
            var buildView  = new BuildInfoView(buildModel)
            {
                Owner = Application.Current.MainWindow
            };

            if (buildView.ShowDialog().GetValueOrDefault())
            {
                string errorString, messageText;
                if (FlowUtils.CleanCache(out errorString))
                {
                    messageText = "Operation completed!";
                }
                else
                {
                    messageText = $"Unable complete cleaning cause of error:{Environment.NewLine}{errorString}";
                }

                MessageBox.Show(messageText, "Information", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
예제 #4
0
        public void Repeat_with_log_handler_should_log()
        {
            // Arrange
            Action customMethodReturnWithCustomException = () => throw new CustomException();
            int    totalAttempts = 0;
            var    callback      = new FlowUtils.RetryCallback((a, e) =>
            {
                totalAttempts = a;
            });

            // Act
            try
            {
                FlowUtils.Retry(
                    customMethodReturnWithCustomException,
                    FlowUtils.CreateCallbackRetryStrategy(callback) + FlowUtils.CreateFixedDelayRetryStrategy(2)
                    );
            }
            catch (CustomException)
            {
                // suppress our specific exception
            }

            // Assert
            Assert.Equal(2, totalAttempts);
        }
예제 #5
0
        public void Repeat_async_with_fixed_retry_strategy_should_delay_correctly()
        {
            // Arrange
            Func <Task <int> > customMethodReturnWithCustomExceptionAsync = () =>
                                                                            Task.Factory.StartNew <int>(() => { throw new CustomException(); });
            var stopwatch = new Stopwatch();

            // Act
            stopwatch.Start();
            var task = FlowUtils.RetryAsync(
                customMethodReturnWithCustomExceptionAsync,
                FlowUtils.CreateFixedDelayRetryStrategy(3, TimeSpan.FromMilliseconds(50)),
                CancellationToken.None,
                typeof(CustomException));

            try
            {
                task.Wait();
            }
            catch (AggregateException)
            {
            }
            stopwatch.Stop();

            // Assert
            Assert.True(stopwatch.ElapsedMilliseconds >= 100);
        }
예제 #6
0
        public void Repeat_with_fixed_retry_strategy_and_first_fast_should_work()
        {
            // Arrange
            Action customMethodReturnWithCustomException = () => throw new CustomException();
            var    stopwatch = new Stopwatch();

            // Act
            stopwatch.Start();
            try
            {
                FlowUtils.Retry(
                    customMethodReturnWithCustomException,
                    FlowUtils.CreateFixedDelayRetryStrategy(4, TimeSpan.FromMilliseconds(50), true),
                    typeof(CustomException)
                    );
            }
            catch (CustomException)
            {
                // suppress our specific exception
            }
            stopwatch.Stop();

            // Assert
            Assert.True(stopwatch.ElapsedMilliseconds >= 100);
        }
예제 #7
0
        /// <inheritdoc/>
        public override bool Execute(Container container, out string errorString)
        {
            string fullPath = container.FullPath;

            errorString = null;
            try
            {
                if (string.IsNullOrEmpty(fullPath))
                {
                    errorString = $"{nameof(DeployManifest.SourcePath)} value is not path.";
                    return(false);
                }

                FlowUtils.RemoveDeployExtention(fullPath);
                var currentDirectory = new DirectoryInfo(fullPath);
                var manifestFiles    =
                    currentDirectory.GetFiles($"*.{Constants.ApplicationExtension}")
                    .Union(currentDirectory.GetFiles($"*.{Constants.ManifestExtension}")).ToArray();

                foreach (var manifestFile in manifestFiles)
                {
                    File.Delete(manifestFile.FullName);
                }

                return(true);
            }
            catch (Exception exception)
            {
                errorString = exception.Message;
                return(false);
            }
        }
예제 #8
0
        public void Repeat_with_fixed_retry_strategy_should_work()
        {
            // Arrange
            Func <int> customMethodReturn = () => 123;

            // Act & assert
            FlowUtils.Retry(customMethodReturn, FlowUtils.CreateFixedDelayRetryStrategy());
            FlowUtils.Retry(customMethodReturn, FlowUtils.CreateFixedDelayRetryStrategy(int.MaxValue, TimeSpan.MaxValue));
        }
예제 #9
0
        public void Memoize_with_default_dict_should_call_handler_once()
        {
            // Arrange
            int value     = 0;
            var memoized1 = FlowUtils.Memoize(() => ++ value);

            // Act & Assert
            Assert.Equal(1, memoized1());
            Assert.Equal(1, memoized1());
        }
예제 #10
0
        public void Raise_should_not_throw_if_event_delegate_is_null()
        {
            // Arrange
            EventArgsTestEvent = null;
            EventArgs eventArgs = new EventArgs();

            // Act
            FlowUtils.RaiseAll(this, eventArgs, ref EventArgsTestEvent);

            // Assert
        }
예제 #11
0
        public void Repeat_with_fixed_retry_strategy_should_throw_exceptions()
        {
            // Arrange
            Action customMethodReturnWithCustomException = () => throw new CustomException();

            // Act & assert
            Assert.Throws <CustomException>(
                () => FlowUtils.Retry(customMethodReturnWithCustomException,
                                      FlowUtils.CreateFixedDelayRetryStrategy()));
            Assert.Throws <CustomException>(
                () => FlowUtils.Retry(customMethodReturnWithCustomException,
                                      FlowUtils.CreateFixedDelayRetryStrategy(), typeof(InvalidOperationException)));
            Assert.Throws <CustomException>(
                () => FlowUtils.Retry(customMethodReturnWithCustomException,
                                      FlowUtils.CreateFixedDelayRetryStrategy(), typeof(CustomException)));
        }
예제 #12
0
        /// <inheritdoc/>
        public override bool Execute(Container container, out string errorString)
        {
            errorString = null;

            var certificate = container.Certificate ?? CertificateUtils.GenerateSelfSignedCertificate();

            var timestamp = !string.IsNullOrEmpty(container.TimestampUrl) ? new Uri(container.TimestampUrl) : null;

            // Signing .manifest
            FlowUtils.SignFile(container.Application.SourcePath, timestamp, certificate);

            // Recompute hash for .manifest file reference in .application
            UpdateApplicationHash(container);

            // Signing .application
            FlowUtils.SignFile(container.Deploy.SourcePath, timestamp, certificate);
            return(true);
        }
예제 #13
0
        public void Cache_with_max_count_should_save_within_count()
        {
            // Arrange
            int value     = 0;
            var memoized1 = FlowUtils.Memoize(
                (a) => ++ value,
                FlowUtils.CreateMaxCountCacheStrategy <int, int>(maxCount: 3, removeCount: 2)
                );

            // Act & assert
            Assert.Equal(1, memoized1(1));
            Assert.Equal(2, memoized1(2));
            Assert.Equal(3, memoized1(3));
            Assert.Equal(1, memoized1(1)); // cached here
            Assert.Equal(4, memoized1(4)); // cache reset here
            Assert.Equal(5, memoized1(1)); // not cached now
            Assert.Equal(3, memoized1(3)); // but this one is cached
        }
예제 #14
0
        public void Cache_with_max_age_should_cache_within_period()
        {
            // Arrange
            int value     = 0;
            var memoized1 = FlowUtils.Memoize(
                () => ++ value,
                FlowUtils.CreateMaxAgeCacheStrategy <int>(TimeSpan.FromSeconds(1))
                );

            // Act & assert
            Assert.Equal(1, memoized1());
            Assert.Equal(1, memoized1());
#if PORTABLE || NETSTANDARD1_6
            Task.Delay(1300).Wait();
#else
            Thread.Sleep(1300);
#endif
            Assert.Equal(2, memoized1());
        }
예제 #15
0
        public void Raise_all_should_call_test_handlers()
        {
            // Arrange
            int       a         = 0;
            EventArgs eventArgs = new EventArgs();
            EventHandler <EventArgs> testDelegate = (sender, args) =>
            {
                a += 1;
            };

            EventArgsTestEvent  = null;
            EventArgsTestEvent += testDelegate;
            EventArgsTestEvent += testDelegate;
            EventArgsTestEvent += testDelegate;

            // Act
            FlowUtils.RaiseAll(this, eventArgs, ref EventArgsTestEvent);

            // Assert
            Assert.Equal(3, a);
        }
예제 #16
0
        private void SelectedActionChanges(UserActions action)
        {
            InitEntrypoints(action);
            if (action == UserActions.New || action == UserActions.Update)
            {
                var deploy = SelectedFolder.DeployManifest ??
                             FlowUtils.CreateDeployManifest(SelectedFolder.FullPath, SelectedEntrypoint);
                var application = SelectedFolder.ApplicationManifest ??
                                  FlowUtils.CreateApplicationManifest(SelectedFolder.FullPath, SelectedEntrypoint);

                Version         = FlowUtils.ReadApplicationVersion(deploy) ?? Constants.DefaultVersion;
                ApplicationName = FlowUtils.ReadApplicationName(application);

                DeployManifest      = new ManifestEditorViewModel <DeployManifest>(deploy);
                ApplicationManifest = new ManifestEditorViewModel <ApplicationManifest>(application);
            }
            else
            {
                DeployManifest      = null;
                ApplicationManifest = null;
            }
        }
예제 #17
0
        private void SelectedEntrypointChanged(string selectedEntrypoint)
        {
            ApplicationName = selectedEntrypoint;
            if (DeployManifest != null && !string.IsNullOrEmpty(SelectedEntrypoint))
            {
                var deployFileName =
                    $"{Path.GetFileNameWithoutExtension(SelectedEntrypoint)}.{Constants.ApplicationExtension}";

                // Set DeployUrl
                var deploymentUrl = FlowUtils.GetDeployUrl(SelectedFolder.FullPath, deployFileName);

                var propertyField =
                    DeployManifest.Properties.First(p => p.PropertyName == nameof(BuildDeployManifest.DeploymentUrl));

                propertyField.StringValue = deploymentUrl;

                // Set SourcePath
                var root = SelectedFolder.FullPath;
                propertyField =
                    DeployManifest.Properties.First(p => p.PropertyName == nameof(BuildDeployManifest.SourcePath));
                propertyField.StringValue = Path.Combine(root, deployFileName);
            }
        }
예제 #18
0
        public void Repeat_async_with_fixed_retry_strategy_and_first_fast_should_work()
        {
            // Arrange
            Func <Task <int> > customMethodReturnWithCustomExceptionAsync = () =>
                                                                            Task.Factory.StartNew <int>(() => throw new CustomException());
            var stopwatch = new Stopwatch();

            // Act
            stopwatch.Start();
            try
            {
                FlowUtils.Retry(
                    customMethodReturnWithCustomExceptionAsync,
                    FlowUtils.CreateFixedDelayRetryStrategy(2, TimeSpan.FromMilliseconds(50), true),
                    typeof(CustomException)).Wait();
            }
            catch (AggregateException)
            {
            }
            stopwatch.Stop();

            // Assert
            Assert.True(stopwatch.ElapsedMilliseconds <= 50);
        }
예제 #19
0
        public void Raise_all_should_return_exception_of_all_handlers()
        {
            // Arrange
            int       a         = 10;
            EventArgs eventArgs = new EventArgs();
            EventHandler <EventArgs> testDelegate = (sender, args) =>
            {
                a = 20;
            };
            EventHandler <EventArgs> testDelegate2 = (sender, args) =>
            {
                a = 30;
                throw new Exception("test");
            };

            EventArgsTestEvent += testDelegate;
            EventArgsTestEvent += testDelegate2;

            // Act
            Assert.Throws <AggregateException>(() => { FlowUtils.RaiseAll(this, eventArgs, ref EventArgsTestEvent); });

            // Assert
            Assert.Equal(30, a);
        }
예제 #20
0
        public void Cache_with_composite_key_should_cache()
        {
            // Arrange
            int totalCalls = 0;
            Func <int, string, int> func = (a, b) => ++ totalCalls;
            var memoizedFunc             = FlowUtils.Memoize(
                func, FlowUtils.CreateMaxCountCacheStrategy <int, string, int>(100));

            // Act
            var val1 = memoizedFunc(10, "string");
            var val2 = memoizedFunc(10, "string");
            var val3 = memoizedFunc(10, "string2");
            var val4 = memoizedFunc(11, "string");
            var val5 = memoizedFunc(10, "string");
            var val6 = memoizedFunc(11, "string");

            // Assert
            Assert.Equal(1, val1);
            Assert.Equal(1, val2);
            Assert.Equal(2, val3);
            Assert.Equal(3, val4);
            Assert.Equal(1, val5);
            Assert.Equal(3, val6);
        }
 public virtual void TriggerFlow()
 {
     FlowUtils.TriggerFlow(Outputs, nameof(FlowOutput));
 }
예제 #22
0
        public override void TriggerFlow()
        {
            var outputTriggerName = GetInputValue <bool>(nameof(Bool), Bool) ? nameof(FlowNode.FlowOutput) : nameof(FalseOutput);

            FlowUtils.TriggerFlow(Outputs, outputTriggerName);
        }
 public void TriggerFlow()
 {
     FlowUtils.TriggerFlow(Outputs, nameof(FlowNode.FlowOutput));
 }