public void StopwatchToString_NullFormatString_NameDefaultsToStopwatch()
 {
     Stopwatch testStopwatch = new Stopwatch();
     Assert.AreEqual(
         "Stopwatch completed in 0ms.",
         testStopwatch.ToString(null),
         "Where a null format string is provided for the stopwatch name, the name should default to 'Stopwatch'.");
 }
 public void StopwatchToString_FormatStringWithNoParameters_StopwatchReferreredToUsingFormatString()
 {
     String value = Random.RandomString();
     Stopwatch testStopwatch = new Stopwatch();
     Assert.AreEqual(
         String.Format("{0} completed in 0ms.", value),
         testStopwatch.ToString(value),
         "Where a format string without additional parameters is provided, this is used for the stopwatch name.");
 }
        public void TakeAction(string i_MachineName, string i_IP, string i_ServiceName,string i_DisplayName, eOperationType i_OperationType)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            LogManager.Instance.WriteInfo("Action " + Enum.GetName(typeof(eOperationType), i_OperationType) + "on all agents started ");
            m_AgentsManager.TakeAction(i_MachineName, i_IP, i_ServiceName, i_DisplayName, i_OperationType);
            sw.Stop();
            LogManager.Instance.WriteInfo("Action " + Enum.GetName(typeof(eOperationType), i_OperationType) + "on all agents ended, took: "+sw.ToString());

        }
 public void StopwatchToString_FormatStringWithParameters_StopwatchReferreredToUsingFormattedString()
 {
     String value1 = Random.RandomString();
     String value2 = Random.RandomString();
     String value3 = Random.RandomString();
     Stopwatch testStopwatch = new Stopwatch();
     Assert.AreEqual(
         String.Format("{0} test {2} {1} completed in 0ms.", value1, value2, value3),
         testStopwatch.ToString("{0} test {2} {1}", value1, value2, value3),
         "Where a format string with parameters is provided, this is formatted and used for the stopwatch name.");
 }
 public void StopwatchToString_WithTimeElapsed_ContainsTimeElapsed()
 {
     Stopwatch testStopwatch = new Stopwatch();
     testStopwatch.Start();
     Thread.Sleep(Random.Next(1, 5));
     testStopwatch.Stop();
     Assert.AreEqual(
         testStopwatch.ElapsedMilliseconds,
         int.Parse(
             Regex.Match(testStopwatch.ToString(null), "completed in ([0-9]+).?[0-9]*ms.", RegexOptions.None)
                 .Groups[1]
                 .ToString()),
         "The number of milliseconds elapsed should be stated in the ToString result.");
 }
 public void TestPerformance()
 {
     ContextStack<int> contextStack = new ContextStack<int>();
     Stopwatch s = new Stopwatch();
     s.Start();
     Parallel.For(0, Loops, i =>
                                {
                                    using (contextStack.Region(i))
                                    {
                                        Assert.AreEqual(i, contextStack.Current);
                                    }
                                });
     s.Stop();
     Trace.WriteLine(s.ToString("{0} loops", Loops));
 }
 public void Stopwatch_ToString_ReturnsCorrectFormat()
 {
     Stopwatch s = new Stopwatch();
     Random random = Tester.RandomGenerator;
     s.Start();
     Thread.Sleep(random.Next(0, 1000));
     s.Stop();
     string randomString = random.RandomString();
     Assert.AreEqual(
         String.Format(
             "Test stopwatch {0} completed in {1}ms.",
             randomString,
             (s.ElapsedTicks * 1000M) / Stopwatch.Frequency),
         s.ToString("Test stopwatch {0}", randomString));
 }
		public static int ReverseArray(Stock[] input)
		{
			int counter = 0;
			Stopwatch time = new Stopwatch();
			time.Start();
			/*for (int i = 0; i < (input.Length - 1) / 2; i++)
			{
				Stock temp = input[i];
				input[i] = input[(input.Length - 1) - i];
				input[(input.Length - 1) - i] = temp;
				counter++;
			} 
			Debug.WriteLine(time.ToString());*/

			Parallel.For(0, (input.Length - 1) / 2, i => {
				Stock temp = input[i];
				input[i] = input[(input.Length - 1) - i];
				input[(input.Length - 1) - i] = temp;
				counter++;
			});
			
			Debug.WriteLine(time.ToString());

			return counter;
		}
Example #9
0
        public void TestWeakConcurrentDictionaryReferences()
        {
            const int elements = 100000;
            Random random = new Random();
            WeakConcurrentDictionary<int, TestClass> weakConcurrentDictionary =
                new WeakConcurrentDictionary<int, TestClass>(allowResurrection: false);
            ConcurrentDictionary<int, TestClass> referenceDictionary = new ConcurrentDictionary<int, TestClass>();
            int nullCount = 0;
            int unreferencedNullCount = 0;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Parallel.For(
                0,
                elements,
                l =>
                {
                    // Include nulls ~25% of the time.
                    TestClass t;
                    if (random.Next(4) < 3)
                        t = new TestClass(random.Next(int.MinValue, int.MaxValue));
                    else
                    {
                        t = null;
                        Interlocked.Increment(ref nullCount);
                    }

                    weakConcurrentDictionary.Add(l, t);

                    // Only keep references ~33% of the time.
                    if (random.Next(3) == 0)
                        referenceDictionary.AddOrUpdate(l, t, (k, v) => t);
                    else if (t == null)
                        Interlocked.Increment(ref unreferencedNullCount);
                });
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.ToString("Populating dictionaries with {0} elements", elements));

            //GC.WaitForFullGCComplete(5000);
            stopwatch.Restart();
            long bytes = GC.GetTotalMemory(true);
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.ToString("Garbage collection"));
            Trace.WriteLine($"Memory: {bytes / 1024}K");

            // Check that we have l
            Assert.IsTrue(referenceDictionary.Count <= elements);

            int refCount = referenceDictionary.Count;

            stopwatch.Restart();
            int weakCount = weakConcurrentDictionary.Count;
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.ToString("Counting '{0}' elements", weakCount));

            stopwatch.Restart();
            weakCount = weakConcurrentDictionary.Count;
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.ToString("Counting '{0}' elements again", weakCount));

            int floor = refCount + unreferencedNullCount;

            Trace.WriteLine(
                string.Format(
                    "Referenced Dictionary Count: {1}{0}Weak Dictionary Count: {2}{0}Null values: {3} (unreferenced: {4}){0}Garbage Collected: {5}{0}Pending Collection: {6}{0}",
                    Environment.NewLine,
                    refCount,
                    weakCount,
                    nullCount,
                    unreferencedNullCount,
                    elements - weakCount,
                    weakCount - floor
                    ));

            // Check we only have references to referenced elements.
            Assert.AreEqual(refCount + unreferencedNullCount, weakCount);

            // Check everything that's still referenced is available.
            stopwatch.Restart();
            Parallel.ForEach(
                referenceDictionary,
                kvp =>
                {
                    TestClass value;
                    Assert.IsTrue(weakConcurrentDictionary.TryGetValue(kvp.Key, out value));
                    Assert.AreEqual(kvp.Value, value);
                });
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.ToString("Checking '{0}' elements", weakCount));
        }
        public Application(IApp page)
        {
            __that = this;

            this.yield = message =>
            {
                Native.window.alert("hello! " + new { message });
            };


            //((IHTMLElement)Native.document.body.parentNode).style.borderTop = "1em yellow yellow";

            //IStyleSheet.Default["html"].style.borderTop = "1em yellow yellow";


            IStyleSheet.Default["body"].style.borderLeft = "0em yellow solid";

            // activate all animations?
            IStyleSheet.Default["body"].style.transition = "border-left 300ms linear";
            IStyleSheet.Default["body"].style.borderLeft = "3em yellow solid";

            new IHTMLDiv
            {
                innerHTML = @"
<style>
html {
    transition: border-top 500ms linear;
    border-top: 4em solid cyan;
}

</style>"
            }.With(
           async div =>
           {
               //await Native.window.requestAnimationFrameAsync;

               // wont work for html?
               await Task.Delay(100);

               div.AttachToDocument();
           }
       );

            #region proof we can still find our element by id even if on a sub page
            new IHTMLTextArea { }.AttachTo(Native.document.body.parentNode).With(
                async area =>
                {
                    area.style.position = IStyle.PositionEnum.absolute;
                    area.style.right = "1em";
                    area.style.bottom = "1em";
                    area.style.zIndex = 1000;
                    area.readOnly = true;


                    Action colors = async delegate
                    {
                        for (int i = 0; i < 3; i++)
                        {

                            area.style.backgroundColor = "red";
                            await Task.Delay(200);
                            area.style.backgroundColor = "yellow";
                            await Task.Delay(200);
                        }
                        await Native.window.requestAnimationFrameAsync;
                        area.style.transition = "background-color 10000ms linear";

                        await Native.window.requestAnimationFrameAsync;

                        area.style.backgroundColor = "white";
                    };


                    colors();




                    var st = new Stopwatch();
                    st.Start();

                    while (true)
                    {
                        // proof we can still find our element by id even if on a sub page
                        area.value = page.message.innerText + "\n" + st.ToString();

                        await Task.Delay(500);
                    }
                }
            );
            #endregion





            //page.Location = Native.document.location.hash;

            // #/OtherPage.htm

            Console.WriteLine(new { Native.document.location.pathname });


            #region GoThirdPage
            Action GoThirdPage = delegate
            {
                //IStyleSheet.Default["body"].style.borderLeft = "0em yellow solid";

                //await Task.Delay(300);

                // Console.WriteLine("pushState");
                // Native.window.history.pushState(
                //    null,
                //    null,
                //     //"/thirdpage.htm"
                //    "/third-page"
                //);

                Console.WriteLine("replaceState");
                Native.window.history.pushState(
                    //"/third-page",
                    new { },
                    "/third-page",
                    async scope =>
                    {
                        // did the server prerender our page?
                        Console.WriteLine("at replaceState");

                        var xtitle = Native.document.title;

                        // { nodeName = #text } 
                        var hidden = (IHTMLElement)Native.document.body.querySelectorAll("hidden-body").FirstOrDefault();
                        Console.WriteLine("replaceState " + new { hidden });
                        var layout = default(IThirdPage);

                        if (hidden == null)
                        {
                            hidden = new IHTMLElement("hidden-body");
                            hidden.style.display = IStyle.DisplayEnum.none;

                            layout = new ThirdPage();
                            Native.document.title = layout.title.innerText;

                            var page_body = Native.document.body;

                            layout.body.appendChild(hidden);
                            page_body.parentNode.replaceChild(layout.body, page_body);

                            // we can also keep it memory
                            hidden.appendChild(page_body);
                        }
                        else
                        {
                            //{ nodeName = YDOB } 
                            var page_ydob = (IElement)hidden.querySelectorAll("ydob").FirstOrDefault();
                            if (page_ydob != null)
                            {
                                // chrome will skip body. have to repair on the client

                                var page_body = new IHTMLBody();

                                page_ydob.attributes.ToArray().WithEach(a => { page_ydob.removeAttribute(a.name); page_body.setAttribute(a.name, a.value); });
                                page_ydob.childNodes.ToArray().WithEach(a => { page_ydob.removeChild(a); page_body.appendChild(a); });

                                hidden.replaceChild(page_body, page_ydob);

                            }

                            layout = new ThirdPage.FromDocument();
                        }

                        // ready!

                        // one wait works half time only
                        //await Native.window.requestAnimationFrameAsync;
                        //await Native.window.requestAnimationFrameAsync;

                        //await Task.Delay(11);

                        var xthat = __that;
                        __that = null;
                        var x = new ThirdPageApplication(
                            layout,
                            xthat,
                            "pushState"
                        );

                        await scope;
                        __that = xthat;
                        Console.WriteLine("restore state!"); ;
                        Native.document.title = xtitle;

                        //Native.document.body.parentNode.replaceChild(hidden.querySelectorAll("body")[0], Native.document.body);
                        Native.document.body.parentNode.replaceChild(hidden.querySelectorAll("body").First(), Native.document.body);
                    }
                );
            };
            #endregion



            page.GoThirdPageViaCode.WhenClicked(
                  async button =>
                {
                    GoThirdPage();
                }
            );

            page.GoThirdPageViaLocation.WhenClicked(
                  async button =>
                  {
                      Native.document.location.href = "/third-page";
                  }
              );

            //if (Native.document.location.hash.StartsWith("#/"))
            //{
            //    Native.window.history.replaceState(
            //        new { foo = 1 },
            //        "",
            //        Native.document.location.hash.Substring(1)
            //    );

            //    //Native.window.history.replaceState(
            //    //    new { foo = 1 },
            //    //    scope =>
            //    //    {
            //    //        Native.document.body.style.backgroundColor = "yellow";
            //    //    }
            //    //);
            //}


            #region /third-page
            new[] { "ThirdPage.htm", "third-page" }.WithEach(
                async uri =>
                {
                    await Native.window.requestAnimationFrameAsync;

                    var selector = "a[href='" + uri + "']";


                    IStyleSheet.Default[selector].style.color = "red";


                    Native.document.body.querySelectorAll(IHTMLAnchor.HTMLElementEnum.a).WithEach(
                        xx =>
                        {
                            var x = (IHTMLAnchor)xx;


                            if (Native.document.location.href + uri != x.href)
                                return;

                            //Console.WriteLine(new { a = x.href, uri, Native.document.location.href });
                            // { a = http://192.168.43.252:13445/ThirdPage.htm, uri = ThirdPage.htm, href = http://192.168.43.252:13445/ } 

                            x.onclick +=
                                e =>
                                {
                                    e.preventDefault();
                                    GoThirdPage();
                                };
                        }
                    );

                    if (__that != null)
                        if (Native.document.location.pathname == "/" + uri)
                        {
                            //Native.window.history.replaceState(
                            //     null,
                            //     null,
                            //    //"/thirdpage.htm"
                            //    "/ThirdPage.htm"
                            //    //"/third-page"
                            // );


                            var layout = new ThirdPage.FromDocument();

                            new ThirdPageApplication(layout, __that, ".ctor");
                        }
                }
            );
            #endregion





            #region GoSearchPage
            Action GoSearchPage = delegate
            {
                //IStyleSheet.Default["body"].style.borderLeft = "0em yellow solid";

                //await Task.Delay(300);

                // Console.WriteLine("pushState");
                // Native.window.history.pushState(
                //    null,
                //    null,
                //     //"/thirdpage.htm"
                //    "/third-page"
                //);

                Console.WriteLine("replaceState");
                Native.window.history.pushState(
                    //"/third-page",
                    new { },
                    "/s",
                    async scope =>
                    {
                        // did the server prerender our page?
                        Console.WriteLine("at replaceState");

                        var xtitle = Native.document.title;

                        // { nodeName = #text } 
                        var hidden = (IHTMLElement)Native.document.body.querySelectorAll("hidden-body").FirstOrDefault();
                        Console.WriteLine("replaceState " + new { hidden });
                        var layout = default(ISearchPage);

                        if (hidden == null)
                        {
                            hidden = new IHTMLElement("hidden-body");
                            hidden.style.display = IStyle.DisplayEnum.none;

                            layout = new SearchPage();
                            Native.document.title = layout.title.innerText;

                            var page_body = Native.document.body;

                            layout.body.appendChild(hidden);
                            page_body.parentNode.replaceChild(layout.body, page_body);

                            // we can also keep it memory
                            hidden.appendChild(page_body);
                        }
                        else
                        {
                            //{ nodeName = YDOB } 
                            var page_ydob = (IElement)hidden.querySelectorAll("ydob").FirstOrDefault();
                            if (page_ydob != null)
                            {
                                // chrome will skip body. have to repair on the client

                                var page_body = new IHTMLBody();

                                page_ydob.attributes.ToArray().WithEach(a => { page_ydob.removeAttribute(a.name); page_body.setAttribute(a.name, a.value); });
                                page_ydob.childNodes.ToArray().WithEach(a => { page_ydob.removeChild(a); page_body.appendChild(a); });

                                hidden.replaceChild(page_body, page_ydob);

                            }

                            layout = new SearchPage.FromDocument();
                        }

                        // ready!

                        // one wait works half time only
                        //await Native.window.requestAnimationFrameAsync;
                        //await Native.window.requestAnimationFrameAsync;

                        //await Task.Delay(11);

                        var xthat = __that;
                        __that = null;
                        var x = new SearchPageApplication(
                            layout,
                            xthat
                        );

                        await scope;
                        __that = xthat;
                        Console.WriteLine("restore state!"); ;
                        Native.document.title = xtitle;
                        //Native.document.body.parentNode.replaceChild(hidden.querySelectorAll("body")[0], Native.document.body);
                        Native.document.body.parentNode.replaceChild(hidden.querySelectorAll("body").First(), Native.document.body);
                    }
                );
            };
            #endregion


            #region /s
            new[] { "SearchPage.htm", "s" }.WithEach(
              async uri =>
              {
                  await Native.window.requestAnimationFrameAsync;

                  var selector = "a[href='" + uri + "']";


                  IStyleSheet.Default[selector].style.color = "orange";

                  Native.document.body.querySelectorAll(IHTMLAnchor.HTMLElementEnum.a).WithEach(
                        xx =>
                        {
                            var x = (IHTMLAnchor)xx;


                            if (Native.document.location.href + uri != x.href)
                                return;

                            x.style.borderBottom = "1px dashed blue";

                            x.onclick +=
                                e =>
                                {
                                    e.preventDefault();
                                    GoSearchPage();
                                };
                        }
                  );

                  if (__that != null)
                      if (Native.document.location.pathname == "/" + uri)
                      {
                          var layout = new SearchPage.FromDocument();

                          new SearchPageApplication(layout, this);
                      }
              }
          );
            #endregion

        }