Esempio n. 1
0
        public void GetOrSetTest()
        {
            var once = Once.Create <int>();

            Assert.Equal(10, once.GetOrSet(() => 10));
            Assert.Equal(10, once.GetOrSet(() => 20));
        }
Esempio n. 2
0
        public async Task PredicateDeterminesIfOnceRunsAgainAsync()
        {
            bool enabled = false;
            int  counter = 0;
            // ReSharper disable once AccessToModifiedClosure
            var once = new Once(() => enabled, async() =>
            {
                await Task.Delay(10);
                enabled = false;
                ++counter;
            });
            await Task.WhenAll(Enumerable.Range(1, 10).Select(n => once.RunAsync()).ToList());

            counter.Should().Be(0);
            enabled = true;
            await Task.WhenAll(Enumerable.Range(1, 10).Select(n => once.RunAsync()).ToList());

            counter.Should().Be(1);
            await Task.WhenAll(Enumerable.Range(1, 10).Select(n => once.RunAsync()).ToList());

            counter.Should().Be(1);
            enabled = true;
            await Task.WhenAll(Enumerable.Range(1, 10).Select(n => once.RunAsync()).ToList());

            counter.Should().Be(2);
        }
Esempio n. 3
0
        public static void save_main_data(string file_path)
        {
            Once save_data = new Once();

            save_data.potentials = Data.cut_sentence_result.potentials;
            save_data.sen_res    = Data.sen_res;
            File.WriteAllText(file_path, JsonConvert.SerializeObject(save_data));
        }
Esempio n. 4
0
        public void Once_indicates_not_poisoned_for_success()
        {
            var once = new Once(() => { });

            Assert.False(once.Poisoned);
            once.Execute();
            Assert.False(once.Poisoned);
        }
Esempio n. 5
0
        public void Once_indicates_poisoned_after_a_failure()
        {
            var once = new Once(() => { throw new Exception(); });

            Assert.False(once.Poisoned);
            Assert.Throws <PoisonException>(() => once.Execute());
            Assert.True(once.Poisoned);
        }
Esempio n. 6
0
        public static void load_main_data(string file_path)
        {
            string text = File.ReadAllText(file_path);
            Once   once = JsonConvert.DeserializeObject <Data.Once>(text);

            Data.cut_sentence_result.potentials = once.potentials;
            Data.sen_res = once.sen_res;
        }
Esempio n. 7
0
 public static T GetOrSet <T>(this Once <T> self, Func <T> valueFactory)
 {
     if (self.HasValue)
     {
         return(self);
     }
     self.TrySet(valueFactory());
     return(self);
 }
Esempio n. 8
0
 public static void Run <T>(this Once <T> self, Action <T>?action, Action?actionIfEmpty)
 {
     if (self.HasValue)
     {
         action?.Invoke(self);
         return;
     }
     actionIfEmpty?.Invoke();
 }
Esempio n. 9
0
        public void Once_throws_if_the_action_throws()
        {
            var expected = new Exception();
            var once     = new Once(() => { throw expected; });

            var thrown = Assert.Throws <PoisonException>(() => once.Execute());

            Assert.Same(thrown.InnerException, expected);
        }
Esempio n. 10
0
        public void Once_runs_an_action_the_first_time_through()
        {
            var executions = 0;
            var once       = new Once(() => executions += 1);

            once.Execute();

            Assert.Equal(1, executions);
        }
Esempio n. 11
0
        public void Once_does_not_execute_actions_twice()
        {
            var executions = 0;
            var once       = new Once(() => executions += 1);

            once.Execute();
            once.Execute();

            Assert.Equal(1, executions);
        }
Esempio n. 12
0
        public void NormalTest2()
        {
            var once = Once.Create(10);

            Assert.True(once.HasValue);
            Assert.Equal(10, once);
            Assert.Equal(10, once.Value);

            Assert.False(once.TrySet(20));
            Assert.Equal(10, once);
        }
Esempio n. 13
0
        public void TestOnceCallsOnlyOnce()
        {
            int value = 0;
            var once  = new Once <int>(() => Interlocked.Increment(ref value));

            Parallel.For(0, 1000, _ =>
            {
                once.EnsureDone();
            });
            Assert.AreEqual(1, value);
        }
Esempio n. 14
0
        public void RunTest()
        {
            var once = Once.Create <int>();

            once.Run(
                value => Assert.Equal(10, value),
                () => Assert.False(once.HasValue));

            once.TrySet(10);
            once.Run(
                value => Assert.Equal(10, value),
                () => Assert.False(once.HasValue));
        }
Esempio n. 15
0
        public void SerializeTest()
        {
            var once = Once.Create(10);

            var json = JsonSerializer.Serialize(once);

            Assert.NotEqual("", json);

            var obj = JsonSerializer.Deserialize <Once <int> >(json);

            Assert.True(obj.HasValue);
            Assert.Equal(10, obj);
        }
Esempio n. 16
0
        /// <summary>
        /// Run subscribed event handlers.
        /// </summary>
        /// <param name="argument">Main's argument parameter</param>
        /// <param name="updateSource">Main's updateSource</param>
        public void CallUpdateEventHandlers(string argument, UpdateType updateSource)
        {
            UpdateEventArgs Args = new UpdateEventArgs(argument, updateSource);

            // If you have a DRY way that doesn't involving updating a list on every call: send me an email 🤷
            None?.Invoke(this, Args);             // Always invoked
            if (updateSource.HasFlag(UpdateType.Terminal))
            {
                Terminal?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Trigger))
            {
                Trigger?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Mod))
            {
                Mod?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Script))
            {
                Script?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Update1))
            {
                Update1?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Update10))
            {
                Update10?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Update100))
            {
                Update100?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.Once))
            {
                Once?.Invoke(this, Args);
            }
            if (updateSource.HasFlag(UpdateType.IGC))
            {
                IGC?.Invoke(this, Args);
            }

            foreach (
                KeyValuePair <EventHandler <UpdateEventArgs>, EventHandlerMeta> EH in
                Subscribers.Where(pair => (updateSource & pair.Value.TargetUpdateType) != 0 || pair.Value.TargetUpdateType == UpdateType.None))
            {
                EH.Key.Invoke(this, Args);
            }
        }
Esempio n. 17
0
        public virtual async Task OpenInVisualStudio()
        {
            foreach (var configuration in new[] { ConfigurationRelease, ConfigurationDebug })
            {
                var b = Once.Create <Program>();
                b.Configuration = configuration;
                await b.PrepareBuild();
            }

            Process.Start(new ProcessStartInfo
            {
                FileName        = Path.GetFullPath(SlnFile),
                UseShellExecute = true
            });
        }
Esempio n. 18
0
        public void Once_throws_if_the_first_invocation_threw()
        {
            var invoked  = false;
            var expected = new Exception();
            var once     = new Once(() => { invoked = true; throw expected; });

            Assert.Throws <PoisonException>(() => once.Execute());
            Assert.True(invoked);

            invoked = false;
            var thrown = Assert.Throws <PoisonException>(() => once.Execute());

            Assert.Same(thrown.InnerException, expected);
            Assert.False(invoked);
        }
Esempio n. 19
0
        public void RunsOnce()
        {
            var count  = 0;
            var action =
                new Once(() =>
            {
                count++;
            });

            action.Invoke();
            action.Invoke();
            Assert.Equal(
                1,
                count
                );
        }
Esempio n. 20
0
        public void RanCountShouldBeTheNumberOfTimesRan()
        {
            var enabled = false;
            var counter = 0;
            var once    = new Once(() => enabled, () =>
            {
                enabled = false;
                ++counter;
            });

            for (int i = 0; i < 10; i++)
            {
                enabled = true;
                counter.Should().Be(once.RanCount);
                once.Run();
            }
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            Ever.y().Day.At(15, 00).Utc().Do(() => Console.WriteLine("test"));

            JobManager.Current.JobExceptionOccurred += Current_JobExceptionOccurred;

            Action job = () =>
            {
                throw new Exception("test");
            };

            Once.After(4).Seconds.Do(job);

            Ever.y(2).Seconds.Do(() => Console.WriteLine("hoi"));

            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 22
0
        static void RunTest()
        {
            Console.WriteLine("*** Run method ***");

            var once = Once.Create(10);

            once.Run(
                value => Console.WriteLine($"value = {value}"),
                () => Console.WriteLine($"value is empty."));

            var empty = Once.Create <int>();

            empty.Run(
                value => Console.WriteLine($"value = {value}"),
                () => Console.WriteLine($"value is empty."));

            Console.WriteLine("");
        }
Esempio n. 23
0
        /// <summary>
        /// Case1. Initialization with empty.
        /// </summary>
        static void Case2()
        {
            Console.WriteLine("*** Case2 ***");

            var greeting = Once.Create <string>();

            greeting.Value = "Hello";
            Console.WriteLine($"{(string)greeting}");
            OverwiteTest(greeting, "Goodby");

            var no = Once.Create <int>();

            no.TrySet(10);
            Console.WriteLine($"{no.Value}");
            OverwiteTest(no, 5);

            Console.WriteLine("");
        }
Esempio n. 24
0
        public void ActionOnlyCalledOnceInMultitreadedContext()
        {
            int counter = 0;
            var once    = new Once(() =>
            {
                Thread.Sleep(10);
                ++counter;
            });
            List <Thread> threads = new List <Thread>();

            for (int i = 0; i < 10; i++)
            {
                once.Run();
            }
            threads.ForEach(thread => thread.Start());
            threads.ForEach(thread => thread.Join());
            counter.Should().Be(1);
        }
Esempio n. 25
0
        public void DidRunShouldBeFalseBeforeFirstRunAndTrueAfter()
        {
            var enabled = false;
            var counter = 0;
            var once    = new Once(() => enabled, () =>
            {
                enabled = false;
                ++counter;
            });

            once.DidItRun.Should().Be(false);
            for (int i = 0; i < 10; i++)
            {
                enabled = true;
                once.Run();
                once.DidItRun.Should().Be(true);
            }
        }
Esempio n. 26
0
        public async Task ActionOnlyCalledOnceInMultiTaskContext()
        {
            int counter = 0;
            var once    = new Once(async() =>
            {
                await Task.Delay(10);
                ++counter;
            });
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(once.RunAsync());
            }
            await Task.WhenAll(tasks);

            counter.Should().Be(1);
        }
Esempio n. 27
0
        /// <summary>
        /// Case1. Initialization with a specified value.
        /// </summary>
        static void Case1()
        {
            Console.WriteLine("*** Case1 ***");

            var once = Once.Create("Hello");

            Console.WriteLine($"{once.Value}");

            // Explicit and implicit casts.
            Console.WriteLine($"{(string)once}");
            string greeting = once;

            Console.WriteLine($"{greeting}");

            // Overwrite protection.
            OverwiteTest(once, "Goodby");

            Console.WriteLine("");
        }
Esempio n. 28
0
        /// <summary>
        /// Tests that you cannot overwrite.
        /// </summary>
        static void OverwiteTest <T>(Once <T> once, T newValue)
        {
            if (!once.TrySet(newValue))
            {
                Console.WriteLine($"Cannot overwrite : {(T)once}");
            }

            try
            {
                once.Value = newValue;
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("InvalidOperationException occurred.");
            }
            finally
            {
                Console.WriteLine($"Cannot overwrite : {(T)once}");
            }
        }
Esempio n. 29
0
        public void OnceWorksWellWithBackgroundThreads()
        {
            bool threadEnabled = true;
            bool enabled       = false;
            int  counter       = 0;
            // ReSharper disable once AccessToModifiedClosure
            var once = new Once(() => enabled, () =>
            {
                enabled = false;
                ++counter;
            });
            // 10 worker threads
            var threads = Enumerable.Range(1, 10).Select(n => new Thread(() =>
            {
                // ReSharper disable once AccessToModifiedClosure
                while (threadEnabled)
                {
                    once.Run();
                }
            })).ToList();

            threads.ForEach(thread => thread.Start());

            var delay = 20;

            Thread.Sleep(delay);
            counter.Should().Be(0);
            enabled = true;
            Thread.Sleep(delay);
            counter.Should().Be(1);
            Thread.Sleep(delay);
            counter.Should().Be(1);
            enabled = true;
            Thread.Sleep(delay);
            counter.Should().Be(2);

            // done
            threadEnabled = false;
            threads.ForEach(thread => thread.Join());
        }
Esempio n. 30
0
        public void PredicateDeterminesIfOnceRunsAgain()
        {
            bool enabled = false;
            int  counter = 0;
            // ReSharper disable once AccessToModifiedClosure
            var once = new Once(() => enabled, () =>
            {
                enabled = false;
                ++counter;
            });

            Task.WhenAll(Enumerable.Range(1, 10).Select(n => Task.Run(() => once.Run())).ToList()).Wait();
            counter.Should().Be(0);
            enabled = true;
            Task.WhenAll(Enumerable.Range(1, 10).Select(n => Task.Run(() => once.Run())).ToList()).Wait();
            counter.Should().Be(1);
            Task.WhenAll(Enumerable.Range(1, 10).Select(n => Task.Run(() => once.Run())).ToList()).Wait();
            counter.Should().Be(1);
            enabled = true;
            Task.WhenAll(Enumerable.Range(1, 10).Select(n => Task.Run(() => once.Run())).ToList()).Wait();
            counter.Should().Be(2);
        }