コード例 #1
0
        static void InitializeContnt(IDefaultPage page)
        {
            Action<dynamic> stream =
                x =>
                {
                    object time = x.time;
                    object i = x.i;

                    Native.document.title = new { time, i }.ToString();
                    Console.WriteLine(new { time, i }.ToString());
                    page.Content.innerText = new { time, i }.ToString();
                };

            dynamic window = Native.window;

            window.stream = stream;

            var stop = new IHTMLButton("Stop").AttachToDocument();

            var iframe = new IHTMLIFrame { src = "/stream" }.AttachToDocument();
            iframe.Hide();

            page.Start.disabled = true;

            stop.onclick +=
                delegate
                {
                    stop.Orphanize();
                    page.Start.disabled = false;
                    iframe.Orphanize();
                };

            Native.document.body.style.cursor = IStyle.CursorEnum.@default;
        }
コード例 #2
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {

            //         { SourceMethod = Void Page_InitializeInternalFontFace() }
            //         { SourceMethod = ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement Initialize_0_html(WebServicePDFGenerator.HTML.Pages.App, ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement) }
            //     script: error JSC1000: Method: Initialize_0_html, Type: WebServicePDFGenerator.HTML.Pages.App; emmiting failed : System.IndexOutOfRangeException: Index was outside the bounds of the array.
            //at jsc.ILInstruction.get_TargetParameter() in X:\jsc.internal.git\compiler\jsc\CodeModel\ILInstruction.cs:line 1389

            new IHTMLButton { "pdf" }.AttachToDocument().WhenClicked(
                async button =>
                {
                    var base64 = await base.Invoke();

                    // { Length = 1228 }

                    new IHTMLPre {
                        new { base64.Length }
                    }.AttachToDocument();

                    var i = new IHTMLIFrame
                    {

                        src = "data:application/pdf;base64," + base64
                        //bytes =
                    }.AttachToDocument();

                    i.style.width = "100%";
                    i.style.height = "100%";

                }
             );

        }
コード例 #3
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            new IHTMLButton { innerText = "Fake discovery event" }.AttachToDocument().WhenClicked(
                btn =>
                {
                    btn.Orphanize();

                    // ask for credentials for new ui

                    // Refused to load the script 'http://192.168.1.100:26385/a' 
                    // because it violates the following Content Security Policy 
                    // directive: "script-src 'unsafe-eval' 'self' ".

                    //                    ---------------------------
                    //Extension error
                    //---------------------------
                    //Could not load extension from 'A:\'. Invalid value for 'content_security_policy': Both 'script-src' and 'object-src' 
                    // directives must be specified (either explicitly, or implicitly 
                    // via 'default-src'), and both must whitelist only secure resources. You may include any of the following sources: "'self'", "'unsafe-eval'", "http://127.0.0.1", "http://localhost", or any "https://" or "chrome-extension://" origin. For more information, see http://developer.chrome.com/extensions/contentSecurityPolicy.html
                    //---------------------------
                    //OK   
                    //---------------------------


                    //var s = new IHTMLScript { src = "http://192.168.1.100:26385/a" };

                    //// http://stackoverflow.com/questions/538745/how-to-tell-if-a-script-tag-failed-to-load
                    //s.onload +=
                    //    delegate
                    //    {
                    //    };

                    //s.AttachToDocument();

                    var i = new IHTMLIFrame { src = "http://192.168.1.100:20498" }.AttachToDocument();
                    i.onload += delegate
                    {
                        Native.Document.title = new { i.src }.ToString();
                    };
                    i.style.width = "100%";
                    i.style.height = "100%";
                }
            );
            @"Hello world".ToDocumentTitle();

        }
コード例 #4
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {

            new IHTMLButton { "click me" }.AttachToDocument().With(
                async button =>
                {


                    var first = await Task.WhenAny(
                        Native.window.async.onmessage,
                        button.async.onclick
                    );



                    button.disabled = true;

                    button.innerText = "at event";
                }
            );



            new IHTMLButton { "click to create new iframe" }.AttachToDocument().WhenClicked(
                async button =>
                {
                    var i = new IHTMLIFrame { src = "/" }.AttachToDocument();

                    await i.async.onload;


                    button.innerText = "click to send iframe a message";

                    //await button;
                    await button.async.onclick;

                    i.contentWindow.postMessage("hi");

                    //await Task.Delay(TimeSpan.

                    button.Orphanize();
                }
            );


        }
コード例 #5
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {


            new { }.With(
                async delegate
                {

                    var frame = new IHTMLIFrame();

                    frame.AttachToDocument();

                    frame.src = "about:blank";

                    await frame.async.onload;

                    frame.contentWindow.document.DesignMode = true;

                    // Additional information: The 'link' start tag on line 3 position 6 does not match the end tag of 'body'. Line 12, position 38.
                    this.content = frame.contentWindow.document.body;

                    while (await page.Yield.async.onclick)
                    {

                        Console.WriteLine(
                            new { this.content }
                            );

                        await this.yield();
                    }
                }
            );



        }
コード例 #6
0
		internal static IHTMLIFrame CreateEditor()
		{
			var edit = new IHTMLIFrame { src = "about:blank" };

			edit.style.width = "100%";
			edit.style.height = "100%";
			edit.style.border = "0";
			edit.style.margin = "0";
			edit.style.padding = "0";
			edit.frameBorder = "0";
			edit.border = "0";

			edit.WhenDocumentReady(
				document =>
				{

					document.WithContent(
						new XElement("style", "span { color: red; }"),
						new XElement("div",
							new XAttribute("style", "margin: 2em;"),
							new XElement("h1", "powered  by jsc"),
							new XElement("span", "hello world")
						)
					);

					document.DesignMode = true;
				}
			);
			return edit;
		}
コード例 #7
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            var w = Native.Window.Width;
            var h = Native.Window.Height;

            new IHTMLPre { }.AttachToDocument().With(
                i =>
                {
                    Action u = delegate
                    {
                        i.innerText = new { w, Native.Window.Width, h, Native.Window.Height }.ToString();
                    };

                    u();

                    Native.Window.onresize +=
                        delegate
                        {
                            u();
                        };
                }
            );

            var location = "" + Native.Document.location;
            var parent = "";

            new IHTMLPre
            {
                innerText = new
                {
                    location,
                    Native.Document.location.protocol,
                    Native.Document.location.host,
                    Native.Document.location.pathname,
                    Native.Document.location.search,
                    Native.Document.location.hash,
                }.ToString()
            }.AttachToDocument();

            Native.Window.parent.With(
                xparent =>
                {
                    // http://stackoverflow.com/questions/5934538/is-there-a-limitation-on-an-iframe-containing-another-iframe-with-the-same-url
                    parent = "" + xparent.document.location;

                    new IHTMLPre { innerText = new { parent }.ToString() }.AttachToDocument();
                }
            );

            if (w < 400)
            {
                Native.Document.body.style.backgroundColor = JSColor.Yellow;

                new IHTMLButton("reopen as a bigger document").AttachToDocument().onclick +=
                    delegate
                    {
                        var src = location;

                        if (location == parent)
                        {
                            var withouthash = src.TakeUntilIfAny("#");
                            var onlyhash = src.SkipUntilOrEmpty("#");

                            withouthash += "?";

                            if (onlyhash != "")
                            {
                                withouthash += "#" + onlyhash;
                            }

                            src = withouthash;
                        }

                        var iframe = new IHTMLIFrame { src = src, frameBorder = "0" };


                        iframe.style.minWidth = "800px";
                        iframe.style.minHeight = "600px";

                        iframe.style.position = IStyle.PositionEnum.absolute;
                        iframe.style.left = "0px";
                        iframe.style.top = "0px";
                        iframe.style.width = "100%";
                        iframe.style.height = "100%";

                        Native.Document.body.Clear();
                        Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;

                        iframe.onload +=
                            delegate
                            {
                                Console.WriteLine(
                                    new { location, iframe.src }
                                );

                                iframe.style.minWidth = "";
                                iframe.style.minHeight = "";

                            };


                        Console.WriteLine(
                             "will reload as: " + new { src }
                         );

                        iframe.AttachToDocument();
                    };

                return;
            }

            Native.Document.body.style.backgroundColor = JSColor.White;


            new IHTMLButton("this is dynamic content").AttachToDocument();

            new IHTMLButton("reload").AttachToDocument().onclick +=
                delegate
                {
                    Native.Document.location = Native.Document.location;
                };


            new IHTMLButton("add frame").AttachToDocument().onclick +=
                delegate
                {
                    var src = location;

                    if (location == parent)
                    {
                        var withouthash = src.TakeUntilIfAny("#");
                        var onlyhash = src.SkipUntilOrEmpty("#");

                        withouthash += "?";

                        if (onlyhash != "")
                        {
                            withouthash += "#" + onlyhash;
                        }

                        src = withouthash;
                    }




                    var iframe = new IHTMLIFrame { src = "about:blank" };


                    iframe.style.position = IStyle.PositionEnum.absolute;
                    iframe.style.left = "10%";
                    iframe.style.top = "10%";
                    iframe.style.width = "80%";
                    iframe.style.height = "80%";

                    iframe.AttachToDocument();


                    Console.WriteLine(
                         "will frame as: " + new { src }
                     );

                    Native.Window.requestAnimationFrame +=
                        delegate
                        {
                            iframe.src = src;

                            Console.WriteLine(
                                 "did it work? " + new { iframe.src }
                             );

                        };


                };


            new IHTMLButton("add frame via source").AttachToDocument().onclick +=
               delegate
               {
                   var iframe = new IHTMLIFrame { };


                   iframe.style.position = IStyle.PositionEnum.absolute;
                   iframe.style.left = "10%";
                   iframe.style.top = "10%";
                   iframe.style.width = "80%";
                   iframe.style.height = "80%";

                   iframe.AttachToDocument();


                   var x = iframe.contentWindow.open("about:blank", "_self");

                   x.document.write("<script src='/view-source'></script>");
                   x.document.close();



               };

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }
コード例 #8
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            var location = "" + Native.document.location;

#if false
            #region workaround for ThreeJS/chrome webgl upscale bug
            // workaround for not knowing how to tell three js to upscale correctly..
            // X:\jsc.svn\examples\javascript\Test\TestNestedIFrameForMoreWidth\TestNestedIFrameForMoreWidth\Application.cs
            // instead of reloading full app
            // could we run part of it instead?
            // like let jsc know that this sub application should be reloadable?
            // this will be like threading
            // the outer code wil just stop doing anything
            // and the inner app will take over.


            if (Native.window.Width < Native.screen.width)
            {
            #region make sure the url looks different to make iframe actually load
                Native.window.parent.With(
                    parent =>
                    {
                        // http://stackoverflow.com/questions/5934538/is-there-a-limitation-on-an-iframe-containing-another-iframe-with-the-same-url

                        var parentlocation = "";

                        try
                        {
                            parentlocation = parent.document.location.href;
                            Console.WriteLine(new { parentlocation });
                        }
                        catch
                        {
                            // we are sandboxed!
                        }

                        if (parentlocation.TakeUntilIfAny("#") == location.TakeUntilIfAny("#"))
                        {
                            var withouthash = location.TakeUntilIfAny("#");
                            var onlyhash = location.SkipUntilOrEmpty("#");

                            withouthash += "?";

                            if (onlyhash != "")
                            {
                                withouthash += "#" + onlyhash;
                            }

                            location = withouthash;
                        }
                    }
                );
            #endregion



                // this check only looks for default screen width
                // what about height and secondary screens?
                Console.WriteLine("will prepare... " + location);

                var iframe = new IHTMLIFrame
                {
                    frameBorder = "0",
                    allowFullScreen = true
                };

                iframe.style.minWidth = Native.screen.width + "px";
                iframe.style.minHeight = Native.screen.height + "px";

                iframe.style.position = IStyle.PositionEnum.absolute;
                iframe.style.left = "0px";
                iframe.style.top = "0px";
                iframe.style.width = "100%";
                iframe.style.height = "100%";

                Native.document.body.Clear();
                Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;

                Native.window.onmessage +=
                   e =>
                   {
                       Console.WriteLine("Native.Window.onmessage " + new { e.data });

                       // pure trickery :P
                       if ((string)e.data == "WebGLDynamicTerrainTemplate.loaded")
                       {
                           iframe.style.minWidth = "";
                           iframe.style.minHeight = "";
                       }
                   };

                iframe.onload +=
                    delegate
                    {
                        if (iframe.src != location)
                            return;

                        Native.window.requestAnimationFrame +=
                          delegate
                          {
                              Console.WriteLine("reload done! " + new { location, iframe.src });
                              iframe.contentWindow.postMessage("ready yet?");
                          };
                    };

                Native.window.requestAnimationFrame +=
                    delegate
                    {
                        Console.WriteLine("will reload... " + location);
                        iframe.AttachToDocument();
                        iframe.src = location;
                    };

                return;
            }




            #endregion

#endif


            #region await Three.js then do InitializeContent
            new[]
            {
                new global::WebGLDynamicTerrainTemplate.Design.ThreeTerrain().Content,

                new global::WebGLDynamicTerrainTemplate.Design.ShaderTerrain().Content,
                new global::WebGLDynamicTerrainTemplate.Design.ShaderExtrasTerrain().Content,
                new global::WebGLDynamicTerrainTemplate.Design.PostprocessingTerrain().Content,
            }.ForEach(
                (SourceScriptElement, i, MoveNext) =>
                {
                    SourceScriptElement.AttachToDocument().onload +=
                        delegate
                        {
                            MoveNext();
                        };
                }
            )(
                delegate
                {
                    InitializeContent(page);
                }
            );
            #endregion


            style.Content.AttachToHead();

        }
コード例 #9
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefaultPage page)
        {
            if (Native.Document.location.hash == "")
            {
                page.Content.innerText = "this page shall have child frames!";

                var a = new IHTMLIFrame
                {
                    src = "#/child1"
                }.AttachToDocument();

                var b = new IHTMLIFrame
                {
                    src = "#/child2"
                }.AttachToDocument();

                new IHTMLBreak().AttachToDocument();
            }
            else
            {
                page.Content.innerText = Native.Document.location.hash;

                window.parent.With(
                    parent =>
                    {

                        new IHTMLButton { innerText = "send parent a message" }.With(
                            btn =>
                            {
                                btn.onclick +=
                                    delegate
                                    {

                                        parent.postMessage("hi from " + Native.Document.location.hash);
                                    };
                            }
                        ).AttachToDocument();
                    }
                );
            }

            window.onmessage +=
                e =>
                {
                    new IHTMLButton { innerText = e.data + " (click to reply)" }.With(
                        btn =>
                        {
                            btn.style.color = JSColor.Blue;



                            btn.onclick +=
                                delegate
                                {
                                    btn.Orphanize();

                                    var source = (XWindow)(object)e.source;

                                    var WhoAmI = Native.Document.location.hash;

                                    if (WhoAmI == "")
                                        WhoAmI = "parent";

                                    source.postMessage("this is a reply from " + WhoAmI);
                                };
                        }
                    ).AttachToDocument();

                    //Native.Window.alert("window.onmessage: " + e.data);
                };

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }
コード例 #10
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // http://davidwalsh.name/add-rules-stylesheets
            // http://stackoverflow.com/questions/5359943/javascript-set-print-stylesheet

            var pstyle = new IHTMLStyle
            {
                type = "text/css",
                media = "print"
            };

            //pstyle.AttachTo(
            //    Native.document.head
            //);

            // .StyleSheet is available only if attached to DOM?
            pstyle["h1"].border = "13px solid green";
            //pstyle["h1"].backgroundColor = "yellow";




            //pstyle["h1"].color = "green";

            //IStyleSheet.Default["@media print { h1 }"].style.color = "yellow";

            // http://www.w3schools.com/css/css_mediatypes.asp

            #region test
            var mp = IStyleSheet.Default["@media print"];

            // { type = 4 } 
            Console.WriteLine(
                new
                {
                    mp.type,
                    CSSRuleTypes.MEDIA_RULE
                }
            );

            if (mp.type == CSSRuleTypes.MEDIA_RULE)
            {
                var mpr = (CSSMediaRule)(object)mp;

                foreach (var media in mpr.media)
                {
                    // { media = print } 
                    Console.WriteLine(new { media });
                }
            }
            #endregion

            //     __awIABmCv4jKFf2Sg5roQag(__bQIABjls6jSgl0UFIggGlQ()[1], 'h1').style.color = 'purple';

            //page.Header.cl

            //page.Header.EnsureID();

            // http://www.w3schools.com/css/css_attribute_selectors.asp

            //page.Header.setAttribute("style-id", "45");

            IStyleSheet.Default[CSSMediaTypes.print][page.Header].style.color =
                "blue";

            IStyleSheet.Default[CSSMediaTypes.print][page.Header].style.boxShadow =
             "inset 0 0 0 10000px yellow";


            //Console.WriteLine(
            //    new
            //    {
            //        page.Header.style.parentRule,
            //        page.Header.style.cssText,
            //        //IStyleSheet.Default[CSSMediaTypes.print]["h1"].style.cssText
            //    }
            //    );

            //            @media print
            //  {
            //    h1 {
            //        border: 3px solid blue;
            //    }

            //}

            //new IHTMLDiv { }.AttachToHead().innerHTML =
            //    @"<style type='text/css' media='print'>h1{ border: 13px solid yellow;}</style>";



            //f.FormBorderStyle = FormBorderStyle.None;
            new Form1{FormBorderStyle = FormBorderStyle.None}.AttachFormTo(page.output);

            //f.GetHTMLTarget().AttachTo(page.output);

            //f.Show();


            //f.WindowState = FormWindowState.Maximized;

            IStyleSheet.Default
                [CSSMediaTypes.print]
                [page.output].style.border = "0px solid black";
                    //IStyle.OverflowEnum.hidden;


            page.Print.onclick +=
                delegate
                {
                    Native.window.print();
                };

            IStyleSheet.Default
                [CSSMediaTypes.print]
                [page.Print].style.display = IStyle.DisplayEnum.none;


            var s = new SpecialLayout();

            var i = new IHTMLIFrame();

            // hide it from plain sight
            i.style.display = IStyle.DisplayEnum.none;

            //new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.checkbox }.AttachToDocument().With(
            //    x =>
            //    {
            //        x.onclick += delegate
            //        {
            //            i.ToggleVisible();
            //        };

            //    }
            //);


            // it will never load with out this call!
            i.AttachToDocument();

            // Uncaught TypeError: Cannot read property 'document' of undefined 

            page.PrintFromIframe.disabled = true;

            i.onload += delegate
            {
                var idoc = i.contentWindow.document;

                // http://stackoverflow.com/questions/16649943/css-to-set-a4-paper-size
                idoc.body.style.minWidth = "21cm";

                var x = new IHTMLStyle().AttachTo(idoc.body);

                s.AttachTo(idoc.body);



                x.StyleSheet[CSSMediaTypes.print][s.Header].style.color =
                    "yellow";

                x.StyleSheet[CSSMediaTypes.print][s.Header].style.boxShadow =
                 "inset 0 0 0 10000px red";

                s.Header.innerText = "test";
                x.StyleSheet[CSSMediaTypes.print][s.SpecialText].before.style.content = "'print hello world'";
                x.StyleSheet[CSSMediaTypes.print][s.SpecialText].before.style.color = "red";
                x.StyleSheet[CSSMediaTypes.print][s.SpecialText].before.style.borderBottom = "1px solid red";

                // http://www.w3schools.com/cssref/pr_gen_content.asp
                //x.StyleSheet
                //     //[CSSMediaTypes.print]
                //     ["#" + s.SpecialText.id + ":before"]
                //     .style.setProperty("content", "'hello world'", "");


                new Form1 { Text = "for print" }.AttachFormTo(s.output);

                page.PrintFromIframe.disabled = false;
                page.PrintFromIframe.onclick +=
                    delegate
                    {
                       
                        i.contentWindow.print();
                    };
            };


            i.src = "about:blank";
        }
コード例 #11
0
            // dynamic does not work in static yet?
            //static 
            void InitializeContent()
        {
            //        script: error JSC1000: Method: InitializeContent, Type: CSSTransform3DFPSExperimentByKeith.Application; emmiting failed : System.InvalidOperationException: unsupported flow detected, try to simplify.
            // Assembly V:\CSSTransform3DFPSExperimentByKeith.Application.exe
            // DeclaringType CSSTransform3DFPSExperimentByKeith.Application, CSSTransform3DFPSExperimentByKeith.Application, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null
            //         OwnerMethod InitializeContent
            //         Offset 00a0
            //         .Try ommiting the return, break or continue instruction.
            //          at jsc.Script.CompilerBase.BreakToDebugger(String e) in x:\jsc.internal.svn\compiler\jsc\Languages\CompilerBase.cs:line 266
            //   at jsc.ILBlock.PrestatementBlock.AddPrestatement(Prestatement p) in x:\jsc.internal.svn\compiler\jsc\CodeModel\ILBlock.cs:line 1654
            //   at jsc.ILBlock.PrestatementBlock.Populate(ILInstruction First, ILInstruction Last) in x:\jsc.internal.svn\compiler\jsc\CodeModel\ILBlock.cs:line 1606
            //   at jsc.ILBlock.PrestatementBlock.Populate() in x:\jsc.internal.svn\compiler\jsc\CodeModel\ILBlock.cs:line 1433
            //   at jsc.ILBlock.get_Prestatements() in x:\jsc.internal.svn\compiler\jsc\CodeModel\ILBlock.cs:line 1759
            //   at jsc.Languages.JavaScript.MethodBodyOptimizer.TryOptimize(IdentWriter w, ILBlock xb) in x:\jsc.internal.svn\compiler\jsc\Languages\JavaScript\MethodBodyOptimizer.cs:line 89
            //   at jsc.IL2Script.EmitBody(IdentWriter w, MethodBase SourceMethod, Boolean define_self) in x:\jsc.internal.svn\compiler\jsc\Languages\JavaScript\IL2Script.cs:line 576

            //Unhandled Exception: System.InvalidOperationException: Method: InitializeContent, Type: CSSTransform3DFPSExperimentByKeith.Application; emmiting failed : System.InvalidOperationException: unsupported flow detected, try to simplify.


            //dynamic window = Native.Window;

            //dynamic __osxPlane = window.__osxPlane;
            //IHTMLDiv __osxPlane_node = __osxPlane.node;

            var discover = new IHTMLIFrame
            {
                //border = "0",
                src = "http://discover.xavalon.net",
                allowFullScreen = true,
                frameBorder = "0"
            };


            //discover.style.transform = "scale(0.5)";
            //discover.style.transformOrigin = "0% 0%";

            //var scale = 1.25;
            var scale = 1;
            var zoom = 8;

            discover.style.transform = "scale(" + (1 / scale) + ")";
            discover.style.transformOrigin = "0% 0%";

            discover.style.SetSize(
                (int)(__wall_c.clientWidth * zoom * scale),
                 (int)(__wall_c.clientHeight * zoom * scale)
            );

            //dynamic ds = discover.style;

            //ds.zoom = (100.0 / zoom) + "%";

            discover.AttachTo(__wall_c);


            var c = new Controls.UserControl1();
            c.GetHTMLTarget().className = "nolock";


            #region button1
            c.button1.Click +=
                delegate
            {
                var cf = new Form1();

                cf.Show();

                cf.FormClosing +=
                    (ss, ee) =>
                        {
                            if (cf.WindowState == FormWindowState.Normal)
                            {
                                if (ee.CloseReason == CloseReason.UserClosing)
                                {
                                    ee.Cancel = true;
                                    cf.WindowState = FormWindowState.Minimized;
                                }
                            }
                        };

                cf.GetHTMLTarget().className = "nolock";

            };
            #endregion


            #region button2
            c.button2.Click +=
                delegate
            {
                var cf = new Form();

                var cw = new WebBrowser { Dock = DockStyle.Fill };

                cf.Controls.Add(cw);

                cw.Navigate(
            "http://discover.xavalon.net"

                        //"/"

                        );

                cf.FormClosing +=
                    (ss, ee) =>
                        {
                            if (cf.WindowState == FormWindowState.Normal)
                            {
                                if (ee.CloseReason == CloseReason.UserClosing)
                                {
                                    ee.Cancel = true;
                                    cf.WindowState = FormWindowState.Minimized;
                                }
                            }
                        };
                cf.Show();

                //Console.WriteLine("button2.Click");
                cf.GetHTMLTarget().className = "nolock";

                //cf.GetHTMLTarget().style.border = "2px solid red";

            };
            #endregion

            c.BackColor = Color.Transparent;

            var x = c.GetHTMLTargetContainer();

            x.style.transform = "scale(0.5)";
            x.style.transformOrigin = "0% 0%";

            x.style.SetSize(
                __osxPlane_node.clientWidth * 2,
                __osxPlane_node.clientHeight * 2
            );

            c.AttachControlTo(__osxPlane_node);




            #region onkeydown
            Native.Document.body.onkeydown += e =>
            {
                //Console.WriteLine(new { e.KeyCode });

                if (e.KeyCode == 87)
                    window.keyState.forward = true;
                if (e.KeyCode == 83)
                    window.keyState.backward = true;
                if (e.KeyCode == (int)Keys.A)
                    window.keyState.strafeleft = true;
                if (e.KeyCode == (int)Keys.D)
                    window.keyState.straferight = true;
            };

            Native.Document.body.onkeyup += e =>
            {
                if (e.KeyCode == 87)
                    window.keyState.forward = false;

                if (e.KeyCode == 83)
                    window.keyState.backward = false;

                if (e.KeyCode == (int)Keys.A)
                    window.keyState.strafeleft = false;
                if (e.KeyCode == (int)Keys.D)
                    window.keyState.straferight = false;

            };
            #endregion


            #region isnolock
            Func<INode, bool> isnolock =
                p =>
                {
                    var nolock = false;

                    while (p != Native.Document.body)
                    {
                        if (((IHTMLElement)p).className == "nolock")
                            nolock = true;

                        p = p.parentNode;
                    }

                    return nolock;
                };
            #endregion



            #region onmousemove
            Native.Document.body.tabIndex = 101;
            Native.Document.body.onmousedown +=
                e =>
                {
                    var nolock = isnolock(e.Element);
                    if (nolock)
                        return;

                    e.PreventDefault();
                    Native.Document.body.focus();
                    Native.Document.body.requestPointerLock();
                };

            Native.Document.body.onmousemove +=
                e =>
                {
                    if (Native.Document.pointerLockElement == Native.Document.body)
                    {
                        window.viewport.camera.rotation.x -= e.movementY / 2;
                        window.viewport.camera.rotation.z += e.movementX / 2;
                    }
                    else
                    {
                        var nolock = isnolock(e.Element);

                        if (nolock)
                            Native.Document.body.style.cursor = IStyle.CursorEnum.auto;
                        else
                            Native.Document.body.style.cursor = IStyle.CursorEnum.move;
                    }
                };


            Native.Document.body.onmouseup +=
                 e =>
                 {
                     if (Native.Document.pointerLockElement == Native.Document.body)
                     {
                         Native.Document.exitPointerLock();
                     }
                 };
            #endregion





            #region onframe
            Native.window.onframe += delegate
            {
                // is external target working bot ways?
                //window.speed = window.speed;

                //Console.WriteLine(new { window.keyState.forward });

                #region speed
                if (window.keyState.backward)
                {
                    if (window.speed > -window.maxSpeed)
                        window.speed -= window.accel;
                }
                else if (window.keyState.forward)
                {
                    if (window.speed < window.maxSpeed)
                        window.speed += window.accel;
                }
                else if (window.speed > 0)
                {
                    window.speed = Math.Max(window.speed - window.accel, 0);
                }
                else if (window.speed < 0)
                {
                    window.speed = Math.Max(window.speed + window.accel, 0);
                }
                else
                {
                    window.speed = 0;
                }
                #endregion


                #region strafespeed
                if (window.keyState.straferight)
                {
                    if (window.strafespeed > -window.maxSpeed)
                        window.strafespeed -= window.accel;
                }
                else if (window.keyState.strafeleft)
                {
                    if (window.strafespeed < window.maxSpeed)
                        window.strafespeed += window.accel;
                }
                else if (window.strafespeed > 0)
                {
                    window.strafespeed = Math.Max(window.strafespeed - window.accel, 0);
                }
                else if (window.strafespeed < 0)
                {
                    window.strafespeed = Math.Max(window.strafespeed + window.accel, 0);
                }
                else
                {
                    window.strafespeed = 0;
                }
                #endregion


                // sideway
                {

                    var xo = Math.Sin(window.viewport.camera.rotation.z * 0.0174532925);
                    var yo = Math.Cos(window.viewport.camera.rotation.z * 0.0174532925);

                    window.viewport.camera.position.x -= xo * window.speed;
                    window.viewport.camera.position.y -= yo * window.speed;
                }

                {
                    var xo = Math.Sin(window.viewport.camera.rotation.z * 0.0174532925 - 3.14 / 2);
                    var yo = Math.Cos(window.viewport.camera.rotation.z * 0.0174532925 - 3.14 / 2);

                    window.viewport.camera.position.x -= xo * window.strafespeed;
                    window.viewport.camera.position.y -= yo * window.strafespeed;
                }

                window.viewport.camera.update();


            };
            #endregion



        }
コード例 #12
0
        public static Action BindKeyboardToDiagnosticsConsole()
        {
            var diagnostics = new IHTMLIFrame { src = "/jsc", frameBorder = "0" };

            diagnostics.style.backgroundColor = "rgba(255, 255, 255, 0)";
            diagnostics.style.position = IStyle.PositionEnum.absolute;
            diagnostics.style.left = "0px";
            diagnostics.style.top = "-100%";
            diagnostics.style.width = "100%";
            diagnostics.style.height = "100%";

            // stay on top!
            diagnostics.style.zIndex = 10000;

            Console.WriteLine("You can now press tilde key to see the /jsc page.");

            diagnostics.AttachToDocument();

            // http://www.w3schools.com/css3/css3_transitions.asp
            diagnostics.style.With(
                       (dynamic s) => s.webkitTransition = "all 0.2s ease-in-out"
                 );
            diagnostics.style.With(
              (dynamic s) => s.transition = "all 0.3s ease-in-out"
            );


            Action Hide =
                delegate
                {
                    diagnostics.style.top = "-100%";
                    diagnostics.style.backgroundColor = "rgba(255, 255, 255, 0)";
                };

            Action Show =
                delegate
                {
                    diagnostics.style.top = "0%";
                    diagnostics.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
                };

            Action Toggle =
                delegate
                {
                    if (diagnostics.style.top == "0%")
                    {
                        Hide();

                    }
                    else
                    {
                        Show();

                    }
                };
            Action<int> AtKeyCode =
                KeyCode =>
                {
                    new { KeyCode }.ToString().ToDocumentTitle();

                    if (KeyCode == 27)
                    {
                        Hide();

                    }

                    // US
                    if (KeyCode == 222)
                    {
                        Toggle();
                    }
                    // EE
                    if (KeyCode == 192)
                    {
                        Toggle();
                    }
                };

            diagnostics.onload +=
                delegate
                {
                    diagnostics.contentWindow.document.onkeyup +=
                  e =>
                  {
                      AtKeyCode(e.KeyCode);
                  };

                    diagnostics.contentWindow.document.oncontextmenu +=
                        e =>
                        {
                            e.preventDefault();
                            Hide();

                        };
                };


            Native.document.onkeyup +=
                e =>
                {
                    AtKeyCode(e.KeyCode);
                };

            //Native.window.onorientationchange +=
            //    delegate
            //    {
            //        if (Native.window.orientation == 90)
            //            Show();
            //        else if (Native.window.orientation == -90)
            //            Show();
            //        else
            //            Hide();

            //    };
            return Toggle;
        }
コード例 #13
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // what is roslyn doing that is breaking async for us?


            //           02000002 LBAPrequelPromotion.Application
            //           script: error JSC1000: unsupported flow detected, try to simplify.
            //Assembly V:\LBAPrequelPromotion.Application.exe
            //DeclaringType LBAPrequelPromotion.Application, LBAPrequelPromotion.Application, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null
            //            OwnerMethod.ctor
            //            Offset 0065
            //            .Try ommiting the return, break or continue instruction.
            // not ready for roslyn!


            #region AtFormCreated
            FormStyler.AtFormCreated =
                 s =>
                 {
                     s.Context.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

                     var x = new ChromeTCPServerWithFrameNone.HTML.Pages.AppWindowDrag().AttachTo(s.Context.GetHTMLTarget());
                 };
            #endregion



            #region ChromeTCPServer
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                chrome.Notification.DefaultTitle = "LBA Redux";
                chrome.Notification.DefaultIconUrl = new HTML.Images.FromAssets.Preview().src;

                ChromeTCPServer.TheServerWithStyledForm.Invoke(
                    AppSource.Text,
                    AtFormCreated: FormStyler.AtFormCreated
                );

                return;
            }
            #endregion


            // https://docs.google.com/a/jsc-solutions.net/spreadsheet/ccc?key=0AjBm0oHdZ3DwdFhMb2UxVnBYUnNnUE16LUNiUzJJSVE#gid=0
            //<iframe src="https://docs.google.com/a/jsc-solutions.net/spreadsheet/embeddedform?formkey=dFhMb2UxVnBYUnNnUE16LUNiUzJJSVE6MQ" width="760" height="692" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>

            var onpause = new SAMPLES036 { volume = 0.3, autobuffer = true };
            var onunpause = new SAMPLES219 { autobuffer = true };

            onunpause.load();

            page.p96.InvokeOnComplete(
              delegate
              {

                  page.p512.InvokeOnComplete(
                      delegate
                      {




                          var diagnostics = new IHTMLIFrame { src = "https://docs.google.com/a/jsc-solutions.net/spreadsheet/embeddedform?formkey=dFhMb2UxVnBYUnNnUE16LUNiUzJJSVE6MQ", frameBorder = "0" };

                          diagnostics.style.backgroundColor = "rgba(255, 255, 255, 0)";
                          diagnostics.style.position = IStyle.PositionEnum.absolute;
                          diagnostics.style.left = "0px";
                          diagnostics.style.top = "-100%";
                          diagnostics.style.width = "100%";
                          diagnostics.style.height = "100%";
                          diagnostics.style.zIndex = 9000;
                          diagnostics.AttachToDocument();

                          // http://www.w3schools.com/css3/css3_transitions.asp
                          diagnostics.style.transition = "all 0.2s ease-in-out";
                          diagnostics.style.transition = "all 0.3s ease-in-out";


                          Action Hide =
                             delegate
                             {
                                 diagnostics.style.top = "-100%";
                                 diagnostics.style.backgroundColor = "rgba(255, 255, 255, 0)";

                                 onpause.play();
                                 onpause = new SAMPLES036 { volume = 0.3, autobuffer = true };
                             };

                          Action Show =
                              delegate
                              {
                                  diagnostics.style.top = "0%";
                                  diagnostics.style.backgroundColor = "rgba(255, 255, 255, 0.9)";

                                  onpause.play();
                                  onpause = new SAMPLES036 { volume = 0.3, autobuffer = true };
                              };

                          Action Toggle =
                              delegate
                              {
                                  if (diagnostics.style.top == "0%")
                                  {
                                      Hide();

                                  }
                                  else
                                  {
                                      Show();

                                  }
                              };
                          Action<int> AtKeyCode =
                              KeyCode =>
                              {
                                  //new { KeyCode }.ToString().ToDocumentTitle();

                                  if (KeyCode == 27)
                                  {
                                      Hide();

                                  }

                                  // EE
                                  if (KeyCode == 222)
                                  {
                                      Toggle();
                                  }

                                  // US
                                  if (KeyCode == 192)
                                  {
                                      Toggle();
                                  }
                              };


                          Native.Document.onkeyup +=
                              e =>
                              {
                                  AtKeyCode(e.KeyCode);
                              };

                          //Native.window.onorientationchange +=
                          //    delegate
                          //    {
                          //        Toggle();

                          //    };
                          page.fund.href = diagnostics.src;
                          page.fund.onclick +=
                              e =>
                              {
                                  e.preventDefault();
                                  e.stopPropagation();

                                  Toggle();
                              };

                          #region fundraiser
                          Action fundraiser = null;

                          fundraiser = delegate
                          {
                              var snd = new SAMPLES037 { volume = 0.01 + 0.1.Random() };

                              new Timer(
                                     delegate
                                     {
                                         page.fundspan.style.Opacity = 0.3;


                                         new Timer(
                                              delegate
                                              {
                                                  page.fundspan.style.Opacity = 1;
                                                  snd.play();

                                                  new Timer(
                                                      delegate
                                                      {
                                                          page.fundspan.style.Opacity = 0.7;


                                                          new Timer(
                                                              delegate
                                                              {
                                                                  page.fundspan.style.Opacity = 1;

                                                                  new Timer(
                                                                     delegate
                                                                     {
                                                                         page.fundspan.style.Opacity = 0.7;


                                                                         new Timer(
                                                                             delegate
                                                                             {
                                                                                 page.fundspan.style.Opacity = 1;

                                                                                 new Timer(
                                                                                    delegate
                                                                                    {
                                                                                        page.fundspan.style.Opacity = 0.7;


                                                                                        new Timer(
                                                                                            delegate
                                                                                            {
                                                                                                page.fundspan.style.Opacity = 1;

                                                                                                new Timer(
                                                                                                    delegate
                                                                                                    {
                                                                                                        fundraiser();
                                                                                                    }
                                                                                                 ).StartTimeout(3000);
                                                                                            }
                                                                                        ).StartTimeout(300);
                                                                                    }
                                                                                ).StartTimeout(300);
                                                                             }
                                                                         ).StartTimeout(300);
                                                                     }
                                                                 ).StartTimeout(300);
                                                              }
                                                          ).StartTimeout(300);
                                                      }
                                                  ).StartTimeout(300);
                                              }
                                          ).StartTimeout(10000 + 60000.Random());
                                     }
                                 ).StartTimeout(300);
                          };


                          fundraiser();
                          #endregion



                          Native.Document.title = "LBA Redux";
                          #region newicon
                          Action newicon = delegate
                          {

                              Native.Document.getElementsByTagName("link").AsEnumerable().ToList().WithEach(
                                  e =>
                                  {
                                      var link = (IHTMLLink)e;

                                      if (link.rel == "icon")
                                      {
                                          if (link.type == "image/png")
                                          {

                                              link.href = new fullbox().src;
                                          }
                                          else
                                          {
                                              link.Orphanize();
                                          }
                                      }
                                  }
                              );

                          };

                          newicon();
                          #endregion


                          #region music
                          var musicnext = new _01_Track_1 { volume = 0.1, autobuffer = true };
                          var music = default(_01_Track_1);

                          Action loop = null;

                          loop = delegate
                          {
                              music = musicnext.AttachToDocument();
                              musicnext = new _01_Track_1 { volume = 0.1, autobuffer = true };

                              music.onended +=
                                  delegate
                                  {
                                      Console.WriteLine(" music.onended ");
                                      music.Orphanize();

                                      loop();
                                  };

                              music.play();

                          };

                          loop();
                          #endregion

                          Native.window.onscroll +=
                              e =>
                              {
                                  if (e.Element != Native.Document)
                                      return;

                                  e.preventDefault();
                                  e.stopPropagation();

                                  Native.window.scrollTo(0, 0);
                              };


                          //new gong().AttachToDocument().play();
                          new ThreeDStuff.js.Tycoon4(
                              t =>
                              {
                                  page.Preview.onclick +=
                                      delegate
                                      {
                                          t.toolbar_btn_pause.RaiseClicked();
                                      };

                                  t.toolbar_btn_pause.Clicked +=
                                      delegate
                                      {


                                          if (t.toolbar_btn_pause.IsActivated)
                                          {

                                              onpause.play();
                                              onpause = new SAMPLES036 { volume = 0.3, autobuffer = true };

                                              t.PauseFogTween.Value = 0.7;
                                              music.volume = 0.01;
                                              page.Preview.Show();
                                          }
                                          else
                                          {
                                              //PauseFogTween.Value = 0;
                                              t.PauseFogTween.Value = 0;

                                              //gong.play();

                                              onunpause.play();
                                              onunpause = new SAMPLES219 { autobuffer = true };

                                              page.Preview.FadeOut();
                                              music.volume = 0.1;
                                          }
                                      };

                                  t.toolbar_btn_pause.RaiseClicked();

                                  new Timer(
                                         delegate
                                         {
                                             t.toolbar_btn_pause.RaiseClicked();
                                         }
                                     ).StartTimeout(4000);
                              }
                          );

                      }
                  );
              }
          );
        }
コード例 #14
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // http://stackoverflow.com/questions/6275953/how-to-display-div-over-a-java-applet-in-chrome



            new ConsoleForm().With(
                f =>
                {
                    f.InitializeConsoleFormWriter();

                    f.Show();

                    //var archive = applet.ToHTMLElement().AsXElement().Attribute("archive");
                    //archive.Value = ("" + Native.Document.location).TakeUntilLastOrEmpty("/") + "/" + archive.Value;

                    Console.WriteLine("calling applet.InitializeConsoleFormWriter");
                    applet.InitializeConsoleFormWriter(
                          Console.Write,
                          Console.WriteLine
                      );

                    Console.WriteLine("you are looking at FormsVirtualConsoleExperiment!!");

                    applet.AttachAppletToDocument();

                    var shadow = new IHTMLIFrame { src = "about:blank", frameBorder = "0", scrolling = "no" };

                    shadow.AttachToDocument();

                    shadow.style.SetLocation(120, 48);
                    shadow.style.zIndex = 0;

                    Action Update =
                        delegate
                        {
                            shadow.style.SetLocation(f.Left, f.Top, f.Width, f.Height);
                        };

                    f.LocationChanged +=
                        delegate
                        {
                            Update();
                        };

                    f.SizeChanged +=
                        delegate
                        {
                            Update();
                        };

                    Update();

                    Native.Window.onresize +=
                        delegate
                        {
                            applet.ToHTMLElement().style.SetSize(
                                 Native.Window.Width,
                                Native.Window.Height
                            );
                        };
                }
            );

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }
コード例 #15
0
		internal static IHTMLIFrame CreateEditor()
		{
			var edit = new IHTMLIFrame { src = "about:blank" };

			edit.style.width = "100%";
			edit.style.height = "100%";
			edit.style.border = "0";
			edit.style.margin = "0";
			edit.style.padding = "0";
			edit.frameborder = "0";
			edit.border = "0";

			edit.WhenDocumentReady(
				document =>
				{

					document.WithContent(StockPageDefault.Element);

					document.DesignMode = true;
				}
			);
			return edit;
		}
コード例 #16
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // what about namespaces?
            // what about 3D objects?
            // what about nugets?
            // what about canvas?
            // what about threejs ? will it end up like XAML?


            // shall we automatically define custom elements?
            Native.document.registerElement("example-com",
                e =>
            {
                //new XAttribute().Changed

                // http://msdn.microsoft.com/en-us/library/bb387098(v=vs.110).aspx
                // http://msdn.microsoft.com/en-us/library/system.xml.linq.xobject.changed(v=vs.110).aspx
                e.AsXElement().Changed +=
                    (sender, args) =>
                    {
                        // MutationObserver

                        // server side events too?
                    };

                var s = e.createShadowRoot();

                //var i = new IHTMLIFrame { src = "http://example.com" };
                var i = new IHTMLIFrame
                {
                    // prevent cyclic reload
                    src = "about:blank"

                    //src = "http://example.com"
                };

                s.appendChild(
                    i
                );




                e.attributes.WithEach(
                    a =>
                    {
                        //i.src = a.value;

                        new IHTMLPre { "attribute " + new { a.name, a.value } }.AttachToDocument();

                        if (a.name == "foo")
                        {
                            // are we observing that too?
                            i.src = a.value;
                        }
                    }
                );

                // does it mean we are nowready to get events for XLinq?
                // is it suppsoed to work?
                new MutationObserver(

                    new MutationCallback(
                    (mutations, o) =>
                {
                    foreach (var item in mutations)
                    {
                        var value = e.getAttributeNode(item.attributeName).value;

                        //i.src = ;

                        new IHTMLPre { "MutationObserver " + new { item.attributeName, value, item.type, item.target } }.AttachToDocument();


                        if (item.attributeName == "foo")
                        {
                            // are we observing that too?
                            i.src = value;
                        }
                    }
                }

                        )
                ).observe(e, new { attributes = true });

            },


                // http://www.w3.org/TR/2014/WD-dom-20140710/
                // https://code.google.com/p/mutation-summary/wiki/DOMMutationObservers
                // http://stackoverflow.com/questions/5416822/dom-mutation-events-replacement
                attributeChangedCallback:
                    (attributeName, e) =>
                    {
                        // css conditionals


                        new IHTMLPre { new { attributeName
                            }
                        }.AttachToDocument();
                    }
            );

            var z = new IHTMLElement("example-com")
            {
                //$foo = "bar"
                //new XAttribute("foo", "bar")
            }.AttachToDocument();

            z.setAttribute("foo", "http://example.com");


        }
コード例 #17
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            new ApplicationContent().With(
                Content =>
                {
                    Dispose = () => Content.Dispose();

                    var hh = new IHTMLDiv();

                    //hh.AttachToDocument();
                    hh.style.SetLocation(64, 32);
                    hh.style.color = JSColor.White;
                    hh.style.fontSize = "30px";


                    var vv = new IHTMLIFrame
                    {
                        border = "0",

                        // http://stackoverflow.com/questions/5845484/force-html5-youtube-video
                        //src = "http://www.youtube.com/embed/hKksAVmekAE?html5=1"

                        src = "http://www.youtube.com/embed/hKksAVmekAE"
                    };

                    vv.style.position = IStyle.PositionEnum.absolute;
                    vv.style.left = "0px";
                    vv.style.width = "20em";
                    vv.style.bottom = "0px";
                    vv.style.height = "10em";
                    vv.style.border = "0";

                    //vv.AttachToDocument();


                    new ScriptCoreLib.JavaScript.Runtime.Timer(
                        t =>
                        {
                            var c = t.Counter % 10;

                            Action<int, int> rewire =
                                (_c, _po) =>
                                {
                                    if (c == _c)
                                    {
                                        Content.po = _po;
                                        hh.innerText = "Spider Control Center Program Override Code: " + _po;
                                    }
                                };

                            rewire(1, 43);
                            rewire(2, 53);
                            rewire(3, 13);
                            rewire(4, 14);
                            rewire(5, 15);
                            rewire(6, 16);
                            rewire(7, 17);
                            rewire(8, 18);
                            rewire(9, 23);
                        },
                        0,
                        2000
                    );

                    Content.AtTick +=
                        delegate
                        {
                            // ?
                        };

                    Native.document.onclick +=
                        e =>
                        {
                        };

                    Native.document.onmousemove +=
                        e =>
                        {
                            var x = e.CursorX / Native.window.Width;
                            var y = e.CursorY / Native.window.Height;
                            var cx = 1f - x;
                            var cy = 1f - y;

                            if (x < 0.2)
                            {
                                Content.red_obstacle_L_y = (cy) * 30f;
                            }
                            else if (cx < 0.2)
                            {
                                Content.red_obstacle_R_y = (cy) * 30f;
                            }
                            else
                            {
                                Content.white_arrow_x = (x - 0.5f) * 30f;
                                Content.white_arrow_y = (cy) * 30f;
                            }
                        };
                }
            );


        }
コード例 #18
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            //            1b90:01:01 0046:0009 My.Solutions.Pages.Templates.Application create interface WebGLDopamineMolecule.AssetsLibrary::WebGLDopamineMolecule.HTML.Pages.IDefault
            //{ Location =
            // assembly: X:\jsc.svn\examples\javascript\My.Solutions.Pages.Templates\My.Solutions.Pages.Templates\bin\Debug\WebGLDopamineMolecule.exe
            // type: WebGLDopamineMolecule.Application, WebGLDopamineMolecule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
            // offset: 0x0587
            //  method:Void .ctor(WebGLDopamineMolecule.HTML.Pages.IDefault) }
            //1b90:01:01 RewriteToAssembly error: System.MissingMethodException: Method not found: 'Void ScriptCoreLib.JavaScript.DOM.IWindow.add_onframe(System.Action)'.

            glMatrix ref1;
            THREE.Color ref0;


            var h = Native.document.location.hash;


            // are we running as a clone?
            // if so our location hash should be stored as html.

            Native.document.getElementsByTagName("link").Select(k => (IHTMLLink)k).Where(k => k.rel == "location").ToList().ForEach(
                location =>
                {
                    //  href = file:///X:/temp/Spiral.htm#WebGLSpiral 

                    location.href.SkipUntilLastOrEmpty("#").With(
                        href =>
                        {
                            if (h == "")
                            {
                                h = "#" + href;
                            }

                        }
                    );
                }
            );



            DiagnosticsConsole.ApplicationContent.BindKeyboardToDiagnosticsConsole();


            Console.WriteLine("Templates loaded... " + new { Native.document.location, h });

            //{
            //    var html = new global::wolfenstein4kTemplate.HTML.Pages.DefaultPage();
            //    html.Container.AttachToDocument();
            //    new global::wolfenstein4kTemplate.Application(html);
            //}

            Action LoadEmAll = delegate { };

            var cc = new IHTMLCenter().AttachToDocument();
            cc.style.lineHeight = "0px";



            var cutoff = 480;

            #region iframe
            Action<int, int, double, IHTMLImage, string> iframe = (iwidth, iheight, maxextra, preview, alias) =>
            {
                // media selector?
                if (alias == "")
                {

                }

                var c = new IHTMLDiv().AttachTo(cc);

                //c.style.backgroundColor = JSColor.Black;
                c.style.display = IStyle.DisplayEnum.inline_block;
                c.style.position = IStyle.PositionEnum.relative;
                c.style.SetSize(iwidth, iheight);

                IHTMLElement content = preview;

                preview.style.SetLocation(0, 0);
                preview.AttachTo(c);
                preview.style.cursor = IStyle.CursorEnum.pointer;
                preview.title = "Click to activate, doubleclick to enlarge";

                var HasFocus = false;
                var HasMouse = false;


                Action content_SetExtraSize = delegate
                {

                };
                #region SetExtraSize
                var SetExtraSize = NumericEmitter.OfDouble(
                  (extrasizef, yy) =>
                  {

                      var extrasize = System.Convert.ToInt32(iwidth * extrasizef * 0.5);


                      content_SetExtraSize = delegate
                      {
                          content.style.zIndex = extrasize;




                          if (HasFocus)
                              content.style.boxShadow = "0px 0px " + (extrasize) + "px 0px rgba(255, 255, 0, 1)";
                          else
                              content.style.boxShadow = "0px 0px " + (extrasize) + "px 0px rgba(0, 0, 255, 1)";

                          //box-shadow: 0px 0px 70px 0px rgba(0, 0, 0, 1);

                          content.style.SetLocation(
                                System.Convert.ToInt32(iwidth * extrasizef * -0.5),
                              System.Convert.ToInt32(iheight * extrasizef * -0.5),
                              System.Convert.ToInt32(iwidth * (1 + extrasizef)),
                              System.Convert.ToInt32(iheight * (1 + extrasizef))
                          );
                      };

                      content_SetExtraSize();
                  }
              );
                #endregion


                #region HasMouse
                c.onmouseover +=
                 delegate
                 {
                     HasMouse = true;

                     if (HasFocus)
                         return;

                     SetExtraSize(maxextra, 0);
                 };




                c.onmouseout +=
                    delegate
                    {
                        HasMouse = false;

                        if (HasFocus)
                            return;

                        SetExtraSize(0, 0);
                    };
                #endregion


                #region Activate
                Action Activate =
                    delegate
                    {
                        // can we also do groups?

                        //preview.Orphanize();

                        var a = new IHTMLIFrame
                        {
                            width = iwidth,
                            height = iheight,
                            frameBorder = "0",
                            scrolling = "no",
                            allowFullScreen = true
                        }.AttachTo(c);

                        preview.style.Opacity = 0.7;


                        a.style.SetLocation(0, 0);



                        #region HasFocus
                        a.onload +=
                            delegate
                            {
                                //Native.Window.alert(
                                //    new {

                                //        a.contentWindow.performance.timing.connectStart,
                                //        a.contentWindow.performance.timing.loadEventStart,
                                //    }
                                //);

                                a.contentWindow.onblur +=
                                    delegate
                                    {
                                        HasFocus = false;
                                        if (HasMouse)
                                            SetExtraSize(maxextra * 1, 0);
                                        else
                                            SetExtraSize(0, 0);
                                    };

                                a.contentWindow.onfocus +=
                                    delegate
                                    {
                                        HasFocus = true;
                                        SetExtraSize(maxextra * 1.1, 0);
                                    };

                                if (HasMouse)
                                    a.contentWindow.focus();

                                new Timer(
                                    delegate
                                    {
                                        preview.FadeOut();

                                        new Timer(
                                          delegate
                                          {

                                              content = a;
                                              content_SetExtraSize();
                                          }
                                      ).StartTimeout(300);
                                    }
                                ).StartTimeout(1000);


                            };
                        #endregion



                        a.contentWindow.document.location.replace(alias);

                        //a.tabIndex = 1;





                    };

                LoadEmAll +=
                    delegate
                    {
                        if (Activate == null)
                            return;

                        Activate();
                        Activate = null;
                    };

                c.onclick +=
                    delegate
                    {
                        if (Activate == null)
                            return;

                        Activate();
                        Activate = null;

                        // unsubscribe event;
                    };
                #endregion






                SetExtraSize(0, 0);

            };
            #endregion



            #region y
            Action<string, Action, IHTMLImage> y =
                (alias, yield, preview) =>
                {
                    if (h == "")
                        if (Native.window.Width > cutoff)
                            iframe(96, 96, 3, preview, alias);
                        else
                            iframe(32, 32, 3, preview, alias);
                    else if (h == alias)
                        if (yield != null)
                            yield();
                };
            #endregion

            // jsc cannot handle multiple delegates on the same statement yet.


            y("#WebGLDopamineMolecule", () => new WebGLDopamineMolecule.Application(), new WebGLDopamineMolecule.HTML.Images.FromAssets.Preview());
            y("#WebGLEthanolMolecule", () => new WebGLEthanolMolecule.Application(), new WebGLEthanolMolecule.HTML.Images.FromAssets.Preview());
            y("#WebGLYomotsuTPS", () => new WebGLYomotsuTPS.Application(), new WebGLYomotsuTPS.HTML.Images.FromAssets.Preview());
            y("#WebGLYomotsuMD2Model", () => new WebGLYomotsuMD2Model.Application(), new WebGLYomotsuMD2Model.HTML.Images.FromAssets.Preview());
            y("#WebGLSphereRayTrace", () => new WebGLSphereRayTrace.Application(), new WebGLSphereRayTrace.HTML.Images.FromAssets.Preview());
            //y("#WebGLFireballExplosion", () => new WebGLFireballExplosion.Application(), new WebGLFireballExplosion.HTML.Images.FromAssets.Preview());
            y("#WebGLChocolux", () => new WebGLChocolux.Application(), new WebGLChocolux.HTML.Images.FromAssets.Preview());
            //y("#WebGLPuls", () => new WebGLPuls.Application(), new WebGLPuls.HTML.Images.FromAssets.Preview());
            y("#WebGLCelShader", () => new WebGLCelShader.Application(), new WebGLCelShader.HTML.Images.FromAssets.Preview());
            y("#WebGLClouds", () => new WebGLClouds.Application(), new WebGLClouds.HTML.Images.FromAssets.Preview());
            y("#WebGLCone", () => new WebGLCone.Application(), new WebGLCone.HTML.Images.FromAssets.Preview());
            y("#WebGLShaderDisturb", () => new WebGLShaderDisturb.Application(), new WebGLShaderDisturb.HTML.Images.FromAssets.Preview());
            y("#WebGLDynamicTerrainTemplate", () => new WebGLDynamicTerrainTemplate.Application(), new WebGLDynamicTerrainTemplate.HTML.Images.FromAssets.Preview());
            y("#WebGLEscherDrosteEffect", () => new WebGLEscherDrosteEffect.Application(), new WebGLEscherDrosteEffect.HTML.Images.FromAssets.Preview());
            y("#WebGLInvade", () => new WebGLInvade.Application(), new WebGLInvade.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson01", () => new WebGLLesson01.Application(), new WebGLLesson01.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson02", () => new WebGLLesson02.Application(), new WebGLLesson02.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson03", () => new WebGLLesson03.Application(), new WebGLLesson03.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson04", () => new WebGLLesson04.Application(), new WebGLLesson04.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson05", () => new WebGLLesson05.Application(), new WebGLLesson05.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson06", () => new WebGLLesson06.Application(), new WebGLLesson06.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson07", () => new WebGLLesson07.Application(), new WebGLLesson07.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson08", () => new WebGLLesson08.Application(), new WebGLLesson08.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson09", () => new WebGLLesson09.Application(), new WebGLLesson09.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson10", () => new WebGLLesson10.Application(), new WebGLLesson10.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson11", () => new WebGLLesson11.Application(), new WebGLLesson11.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson12", () => new WebGLLesson12.Application(), new WebGLLesson12.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson13", () => new WebGLLesson13.Application(), new WebGLLesson13.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson14", () => new WebGLLesson14.Application(), new WebGLLesson14.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson15", () => new WebGLLesson15.Application(), new WebGLLesson15.HTML.Images.FromAssets.Preview());
            y("#WebGLLesson16", () => new WebGLLesson16.Application(), new WebGLLesson16.HTML.Images.FromAssets.Preview());
            y("#WebGLNyanCat", () => new WebGLNyanCat.Application(), new WebGLNyanCat.HTML.Images.FromAssets.Preview());
            y("#WebGLPlanetGenerator", () => new WebGLPlanetGenerator.Application(), new WebGLPlanetGenerator.HTML.Images.FromAssets.Preview());
            y("#WebGLSimpleCubic", () => new WebGLSimpleCubic.Application(), new WebGLSimpleCubic.HTML.Images.FromAssets.Preview());
            y("#SpiderModel", () => new SpiderModel.Application(), new SpiderModel.HTML.Images.FromAssets.Preview());
            y("#WebGLWindWheel", () => new WebGLWindWheel.Application(), new WebGLWindWheel.HTML.Images.FromAssets.Preview());
            y("#WebGLTunnel", () => new WebGLTunnel.Application(), new WebGLTunnel.HTML.Images.FromAssets.Preview());
            y("#WebGLSpiral", () => new WebGLSpiral.Application(), new WebGLSpiral.HTML.Images.FromAssets.Preview());

            y("#WebGLCannonPhysicsEngine", () => new WebGLCannonPhysicsEngine.Application(), new WebGLCannonPhysicsEngine.HTML.Images.FromAssets.Preview());
            y("#WebGLBossHarvesterByOutsideOfSociety", () => new WebGLBossHarvesterByOutsideOfSociety.Application(), new WebGLBossHarvesterByOutsideOfSociety.HTML.Images.FromAssets.Preview());
            y("#WoodsXmasByRobert", () => new WoodsXmasByRobert.Application(), new WoodsXmasByRobert.HTML.Images.FromAssets.Preview());
            //y("#WebGLBeachballsByDoob", () => new WebGLBeachballsByDoob.Application(), new WebGLBeachballsByDoob.HTML.Images.FromAssets.Preview());

            y("#WebGLCity", () => new WebGLCity.Application(), new WebGLCity.HTML.Images.FromAssets.Preview());

            // glMatrix
            y("#WebGLHand", () => new WebGLHand.Application(), new WebGLHand.HTML.Images.FromAssets.Preview());
            y("#WebGLSpadeWarrior", () => new WebGLSpadeWarrior.Application(), new WebGLSpadeWarrior.HTML.Images.FromAssets.Preview());

            if (h == "")
            {
                var maxextra = 3;
                var iwidth = 96;
                var iheight = 96;


                if (Native.window.Width > cutoff)
                {
                    iframe(iwidth, iheight, maxextra, new HTML.Images.FromAssets.Preview(), "");
                    //iframe(iwidth, iheight, maxextra, new HTML.Images.FromAssets.Preview(), "");

                    new IHTMLButton { innerText = "Fullscreen" }.With(
                        btn =>
                        {
                            btn.style.position = IStyle.PositionEnum.absolute;
                            btn.style.left = "1em";
                            btn.style.bottom = "1em";

                            btn.onclick +=
                                  delegate
                                  {
                                      Native.Document.body.requestFullscreen();
                                  };


                        }
                    ).AttachToDocument();

                    new IHTMLButton { innerText = "Load Em All" }.With(
                        btn =>
                        {
                            btn.style.position = IStyle.PositionEnum.absolute;
                            btn.style.right = "1em";
                            btn.style.bottom = "1em";

                            btn.onclick +=
                                delegate
                                {
                                    btn.Orphanize();

                                    LoadEmAll();
                                };
                        }
                    ).AttachToDocument();
                }
                else
                {
                    iwidth = 32;
                    iheight = 32;
                }

                #region ApplyMargins
                Action ApplyMargins = delegate
                {
                    if (Native.window.Width < cutoff)
                    {
                        cc.style.margin = "0px";
                    }
                    else
                    {
                        cc.style.margin = "3%";
                        cc.style.marginTop = "10%";
                    }
                };

                ApplyMargins();

                Native.window.onresize +=
                    delegate
                    {
                        ApplyMargins();
                    };
                #endregion

                #region requestFullscreen
                Native.Document.body.ondblclick +=
                    delegate
                    {
                        //if (IsDisposed)
                        //    return;

                        // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/

                        Native.Document.body.requestFullscreen();

                        //AtResize();
                    };
                #endregion

            }

        }
コード例 #19
0
        public Application(IApp page)
        {
            // https://www.ssllabs.com/ssltest/analyze.html
            // https://sslanalyzer.comodoca.com/
            // https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/683/17/firefox-error-code-sec_error_unknown_issuer
            // z:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Extensions\TcpListenerExtensions.cs

            new { }.With(
                async delegate
                {
                    #region  magic
                    var isroot = Native.window.parent == Native.window.self;

                    //new IHTMLPre { new { isroot } }.AttachToDocument();

                    if (!isroot)
                    {
                        #region HopToParent
                        HopToParent.VirtualOnCompleted = async (that, continuation) =>
                        {
                            // the state is in a member variable?

                            var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                            // should not be a zero state
                            // or do we have statemachine name clash?

                            //new IHTMLPre {
                            //    "iframe about to jump to parent " + new { r.shadowstate.state }
                            //}.AttachToDocument();

                            Native.window.parent.postMessage(r.shadowstate);

                            // we actually wont use the response yet..
                        };
                        #endregion


                        // start the handshake
                        // we gain intellisense, but the type is partal, likely not respawned, acivated, initialized 

                        //  new IHTMLPre {
                        //  "inside iframe awaiting state"
                        //}.AttachToDocument();




                        var c = new MessageChannel();

                        c.port1.onmessage +=
                            m =>
                            {
                                var that = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)m.data;

                                //new IHTMLPre {
                                //            "inside iframe got state " +
                                //            new { that.state }
                                //      }.AttachToDocument();

                                // about to invoke

                                #region xAsyncStateMachineType
                                var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                                      item =>
                                      {
                                          // safety check 1

                                          //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                                          var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                                          if (xisIAsyncStateMachine)
                                          {
                                              //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                              return item.FullName == that.TypeName;
                                          }

                                          return false;
                                      }
                                  );
                                #endregion


                                var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                                var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                                var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                                #region 1__state
                                xAsyncStateMachineType.GetFields(
                                            System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                                        ).WithEach(
                                         AsyncStateMachineSourceField =>
                                         {

                                             Console.WriteLine(new { AsyncStateMachineSourceField });

                                             if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                                             {
                                                 AsyncStateMachineSourceField.SetValue(
                                                     NewStateMachineI,
                                                     that.state
                                                  );
                                             }

                                             var xStringField = that.StringFields.AsEnumerable().FirstOrDefault(
                                                 f => DecoratedString(f.FieldName) == DecoratedString(AsyncStateMachineSourceField.Name)
                                             );

                                             if (xStringField != null)
                                             {
                                                 // once we are to go back to client. we need to reverse it?

                                                 AsyncStateMachineSourceField.SetValue(
                                                     NewStateMachineI,
                                                     xStringField.value
                                                  );
                                                 // next xml?
                                                 // before lets send our strings back with the new state!
                                                 // what about exceptions?
                                             }
                                         }
                                    );
                                #endregion

                                //new IHTMLPre {
                                //        "inside iframe invoke state"
                                //    }.AttachToDocument();

                                NewStateMachineI.MoveNext();

                                // we can now send one hop back?
                            };

                        c.port1.start();
                        c.port2.start();

                        Native.window.parent.postMessage(null,
                            "*",
                            c.port2
                        );





                        return;
                    }

                    var lookup = new Dictionary<IHTMLIFrame, MessageEvent> { };

                    #region HopToIFrame
                    HopToIFrame.VirtualOnCompleted = async (that, continuation) =>
                    {
                        var m = default(MessageEvent);
                        var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                        if (lookup.ContainsKey(that.frame))
                        {
                            //    new IHTMLPre {
                            //    "parent already nows the iframe..."
                            //}.AttachToDocument();

                            m = lookup[that.frame];

                        }
                        else
                        {
                            //    new IHTMLPre {
                            //    "parent is awaiting handshake of the newly loaded iframe..."
                            //}.AttachToDocument();


                            // X:\jsc.svn\examples\javascript\Test\TestSwitchToIFrame\TestSwitchToIFrame\Application.cs
                            //var m = await that.frame.contentWindow.async.onmessage;
                            m = await that.frame.async.onmessage;

                            lookup[that.frame] = m;



                            #region onmessage
                            that.frame.ownerDocument.defaultView.onmessage +=
                                e =>
                                {
                                    if (e.source != that.frame.contentWindow)
                                        return;

                                    var shadowstate = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)e.data;

                                    // are we jumping into a new statemachine?

                                    //      new IHTMLPre {
                                    //      "parent saw iframe instructions to jump back " + new { shadowstate.state }
                                    //}.AttachToDocument();

                                    // about to invoke

                                    #region xAsyncStateMachineType
                                    var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                                          item =>
                                          {
                                              // safety check 1

                                              //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                                              var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                                              if (xisIAsyncStateMachine)
                                              {
                                                  //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                                  return item.FullName == shadowstate.TypeName;
                                              }

                                              return false;
                                          }
                                      );
                                    #endregion


                                    var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                                    var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                                    var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                                    #region 1__state
                                    xAsyncStateMachineType.GetFields(
                                                System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                                            ).WithEach(
                                             AsyncStateMachineSourceField =>
                                             {

                                                 Console.WriteLine(new { AsyncStateMachineSourceField });

                                                 if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                                                 {
                                                     AsyncStateMachineSourceField.SetValue(
                                                         NewStateMachineI,
                                                         shadowstate.state
                                                      );
                                                 }

                                                 var xStringField = shadowstate.StringFields.AsEnumerable().FirstOrDefault(
                                                       f => DecoratedString(f.FieldName) == DecoratedString(AsyncStateMachineSourceField.Name)
                                                   );

                                                 if (xStringField != null)
                                                 {
                                                     // once we are to go back to client. we need to reverse it?

                                                     AsyncStateMachineSourceField.SetValue(
                                                         NewStateMachineI,
                                                         xStringField.value
                                                      );
                                                     // next xml?
                                                     // before lets send our strings back with the new state!
                                                     // what about exceptions?
                                                 }
                                             }
                                        );
                                    #endregion

                                    //      new IHTMLPre {
                                    //      "parent saw iframe instructions to jump back. invoking... "
                                    //}.AttachToDocument();

                                    NewStateMachineI.MoveNext();

                                };
                            #endregion

                        }




                        //new IHTMLPre {
                        //    "parent is sending state after handshake..."
                        //}.AttachToDocument();


                        m.postMessage(r.shadowstate);
                    };
                    #endregion


                    #endregion

                    var hostname = Native.document.location.host.TakeUntilIfAny(":");
                    var hostport = Native.document.location.host.SkipUntilOrEmpty(":");

                    await new IHTMLButton { "login " + new{
                        Native.document.location.protocol,
                        Native.document.location.host,

                        Native.document.baseURI
                    } }.AttachToDocument().async.onclick;

                    // port + 1 iframe?
                    Native.document.body.style.backgroundColor = "cyan";

                    var hostport1 = Convert.ToInt32(hostport) + 1;
                    var host1 = hostname + ":" + hostport1;
                    var baseURI1 = "https://" + host1;

                    new IHTMLPre { new { host1 } }.AttachToDocument();


                    iframe = new IHTMLIFrame { src = baseURI1, frameBorder = "0" }.AttachToDocument();

                    // if the iframe is on another port, ssl client certificate may be prompted
                    //await (HopTo)iframe;
                    await (HopToIFrame)iframe;

                    //new IHTMLPre { "did we make it into iframe yet?" }.AttachToDocument();
                    // yes

                    //12031       ERROR_INTERNET_CONNECTION_RESET
                    //              The connection with the server has been reset.

                    var id = await new ApplicationWebService { }.Identity();


                    //await new IHTMLButton { "lets jump back " }.AttachToDocument().async.onclick;

                    //new IHTMLPre { "lets jump back to parent... " + new { id } }.AttachToDocument();

                    //await (HopTo)Native.window.parent;
                    await default(HopToParent);

                    //new IHTMLPre { "did we make it into parent yet? " + new { id } }.AttachToDocument();
                    Native.document.body.style.backgroundColor = "yellow";

                    new IHTMLButton { "GetSpecialData " + new { id } }.AttachToDocument().onclick += async delegate
                   {
                       #region statemachine fixup?
                       await Task.CompletedTask;
                       #endregion

                       //new IHTMLPre { "ready to call GetSpecialData" }.AttachToDocument();

                       Native.document.body.style.backgroundColor = "white";
                       var foo = "foo1";
                       await (HopToIFrame)iframe;
                       Native.document.body.style.backgroundColor = "cyan";
                       var data = await new ApplicationWebService { Foo = foo }.GetSpecialData();
                       Native.document.body.style.backgroundColor = "white";
                       await default(HopToParent);

                       // forks for chrome
                       // ie gives 404
                       // firefox bails

                       new IHTMLPre { new { data } }.AttachToDocument();

                       Native.document.body.style.backgroundColor = "cyan";
                   };
                }

            );
        }
コード例 #20
0
        static Application()
        {
            new IHTMLPre {
                new { Native.document.currentScript.src }
            }.AttachToDocument();



            #region HopToIFrame
            HopToIFrame.VirtualOnCompleted = async (that, continuation) =>
            {
                new IHTMLPre {
                    "enter HopToIFrame.VirtualOnCompleted.."
                }.AttachToDocument();

                var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                // X:\jsc.svn\examples\javascript\Test\TestSwitchToIFrame\TestSwitchToIFrame\Application.cs
                //var m = await that.frame.contentWindow.async.onmessage;
                var m = await that.frame.async.onmessage;

                //new IHTMLPre {
                //	" VirtualOnCompleted postMessageAsync " + new { r.shadowstate.state }
                //}.AttachToDocument();


                // um. we need to tell that iframe, where to jump to..
                //var firstmessageback = that.frame.contentWindow.postMessageAsync(r.shadowstate);

                m.postMessage(r.shadowstate);

                that.frame.ownerDocument.defaultView.onmessage +=
                    e =>
                    {
                        if (e.source != that.frame.contentWindow)
                            return;

                        var shadowstate = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)e.data;

                        // are we jumping into a new statemachine?

                        new IHTMLPre {
                            "iframe is about to jump to parent " + new { shadowstate.state }
                        }.AttachToDocument();

                        // about to invoke

                        #region xAsyncStateMachineType
                        var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                        item =>
                        {
                            // safety check 1

                            //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                            var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                            if (xisIAsyncStateMachine)
                            {
                                //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                return item.FullName == shadowstate.TypeName;
                            }

                            return false;
                        }
                    );
                        #endregion


                        var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                        var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                        var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                        #region 1__state
                        xAsyncStateMachineType.GetFields(
                              System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                          ).WithEach(
                           AsyncStateMachineSourceField =>
                           {

                               Console.WriteLine(new { AsyncStateMachineSourceField });

                               if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                               {
                                   AsyncStateMachineSourceField.SetValue(
                                       NewStateMachineI,
                                       shadowstate.state
                                    );
                               }


                           }
                      );
                        #endregion

                        Console.WriteLine("invoke MoveNext");
                        NewStateMachineI.MoveNext();

                    };

            };
            #endregion

            #region HopToParent
            HopToParent.VirtualOnCompleted = async (that, continuation) =>
            {
                // the state is in a member variable?

                var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                // should not be a zero state
                // or do we have statemachine name clash?

                new IHTMLPre {
                    "enter HopToParent.VirtualOnCompleted.. " + new { r.shadowstate.state }
                }.AttachToDocument();

                //Native.window.parent.postMessage(r.shadowstate);

                // we actually wont use the response yet..
            };
            #endregion



            // fsharpy look
            vctor = (IApp page) =>
        {
            // {{ href = blob:https%3A//192.168.1.196%3A27831/bafa8242-82bd-44ef-8581-9f76f909cd86 }}

            new IHTMLPre {
                    new { Native.document.location.href }
            }.AttachToDocument();

            if (Native.window.parent != Native.window)
            {
                // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs
                // inside iframe



                new { }.With(
                async delegate
                {
                    // start the handshake
                    // we gain intellisense, but the type is partal, likely not respawned, acivated, initialized 
                    //var m = await Native.window.parent.postMessageAsync<TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine>();

                    //	new IHTMLPre {
                    //			"inside iframe awaiting onmessage"
                    //}.AttachToDocument();

                    var m = await Native.window.parent.postMessageAsync<TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine>();
                    var shadowstate = m.data;

                    //var m = await Native.window.parent.async.onmessage;
                    //var shadowstate = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)m.data;

                    new IHTMLPre {
                                new { shadowstate.state }
                    }.AttachToDocument();

                    // about to invoke

                    #region xAsyncStateMachineType
                    var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                    item =>
                    {
                        // safety check 1

                        //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                        var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                        if (xisIAsyncStateMachine)
                        {
                            //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                            return item.FullName == shadowstate.TypeName;
                        }

                        return false;
                    }
                );
                    #endregion


                    var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                    var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                    var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                    #region 1__state
                    xAsyncStateMachineType.GetFields(
                          System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                      ).WithEach(
                       AsyncStateMachineSourceField =>
                       {

                           Console.WriteLine(new { AsyncStateMachineSourceField });

                           if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                           {
                               AsyncStateMachineSourceField.SetValue(
                                   NewStateMachineI,
                                   shadowstate.state
                                );
                           }


                       }
                  );
                    #endregion

                    NewStateMachineI.MoveNext();

                    // we can now send one hop back?
                }
            );


                return;
            }

            var codetask = new WebClient().DownloadStringTaskAsync(
                     new Uri(Worker.ScriptApplicationSource, UriKind.Relative)
            );

            #region click to switch
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201510/20151026

            new IHTMLButton { "click to switch" }.AttachToDocument().onclick += async delegate
        {
            Native.body.style.backgroundColor = "yellow";

            // can we compile shaders in frames in parallel?

            var code = await codetask;

            var aFileParts = new[] { code };
            var oMyBlob = new Blob(aFileParts, new { type = "text/javascript" });
            //var url = oMyBlob.ToObjectURL();
            var url = URL.createObjectURL(oMyBlob);

            var frame = new IHTMLIFrame {
                        new XElement("script", new XAttribute("src", url), " ")
            }.AttachToDocument();

            // can we our code in that blank document?

            // not fired for blank?
            await frame.async.onload;

            ////var x = frame.ownerDocument.createElement(IHTMLElement.HTMLElementEnum.button);
            ////x.AttachTo(frame.ownerDocument.documentElement);

            Native.body.style.backgroundColor = "cyan";


            await (HopToIFrame)frame;

            var f = new IHTMLButton { "in the frame! click to notify parent" }.AttachToDocument();

            // 134ms TypeError: Cannot set property 'outerscope' of null
            //var outerscope = "outerscope";

            f.onclick += async delegate
            {
                var innerscope = "innerscope";

                // can we jump back?
                // can we ask how many frames are there?
                // can we jump in any other frame?

                // if we jump back to another statemachine, can we reference the outer statemachine?
                // can we call the server?

                new IHTMLPre {
                            "inside iframe about to jump to parent " + new   {
                                //outerscope,
                                innerscope }
                }.AttachToDocument();

                // never completes?
                await default(HopToParent);

                // cant see it?
                Console.WriteLine("are we back?");

                new IHTMLPre {
                            "iframe onclick, inside parent now"
                }.AttachToDocument();

                // can we jump back? would we know where to jump back to?

                //await default(HopToIFrame);


            };


        };
            #endregion


        };

        }
コード例 #21
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            new { }.With(
              async delegate
              {
                  #region  magic
                  var isroot = Native.window.parent == Native.window.self;

                  new IHTMLPre { new { isroot } }.AttachToDocument();

                  if (!isroot)
                  {
                      #region HopToParent
                      HopToParent.VirtualOnCompleted = async (that, continuation) =>
                      {
                          // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151102/hoptoui
                          // the state is in a member variable?

                          var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                          // should not be a zero state
                          // or do we have statemachine name clash?

                          new IHTMLPre {
                                "iframe about to jump to parent " + new { r.shadowstate.state }
                            }.AttachToDocument();

                          Native.window.parent.postMessage(r.shadowstate);

                          // we actually wont use the response yet..
                      };
                      #endregion


                      // start the handshake
                      // we gain intellisense, but the type is partal, likely not respawned, acivated, initialized 

                      new IHTMLPre {
                        "inside iframe awaiting state"
                      }.AttachToDocument();




                      var c = new MessageChannel();

                      c.port1.onmessage +=
                          m =>
                          {
                              var that = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)m.data;

                              new IHTMLPre {
                                            "inside iframe got state " +
                                            new { that.state }
                                      }.AttachToDocument();

                              // about to invoke

                              #region xAsyncStateMachineType
                              var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                                    item =>
                                    {
                                        // safety check 1

                                        //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                                        var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                                        if (xisIAsyncStateMachine)
                                        {
                                            //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                            return item.FullName == that.TypeName;
                                        }

                                        return false;
                                    }
                                );
                              #endregion


                              var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                              var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                              var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                              #region 1__state
                              xAsyncStateMachineType.GetFields(
                                          System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                                      ).WithEach(
                                       AsyncStateMachineSourceField =>
                                       {

                                           Console.WriteLine(new { AsyncStateMachineSourceField });

                                           if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                                           {
                                               AsyncStateMachineSourceField.SetValue(
                                                   NewStateMachineI,
                                                   that.state
                                                );
                                           }

                                           var xStringField = that.StringFields.AsEnumerable().FirstOrDefault(
                                               f => DecoratedString(f.FieldName) == DecoratedString(AsyncStateMachineSourceField.Name)
                                           );

                                           if (xStringField != null)
                                           {
                                               // once we are to go back to client. we need to reverse it?

                                               AsyncStateMachineSourceField.SetValue(
                                                   NewStateMachineI,
                                                   xStringField.value
                                                );
                                               // next xml?
                                               // before lets send our strings back with the new state!
                                               // what about exceptions?
                                           }
                                       }
                                  );
                              #endregion

                              new IHTMLPre {
                                        "inside iframe invoke state"
                                    }.AttachToDocument();

                              NewStateMachineI.MoveNext();

                              // we can now send one hop back?
                          };

                      c.port1.start();
                      c.port2.start();

                      Native.window.parent.postMessage(null,
                          "*",
                          c.port2
                      );





                      return;
                  }

                  var lookup = new Dictionary<IHTMLIFrame, MessageEvent> { };

                  #region HopToIFrame
                  HopToIFrame.VirtualOnCompleted = async (that, continuation) =>
                  {
                      var m = default(MessageEvent);
                      var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                      if (lookup.ContainsKey(that.frame))
                      {
                          new IHTMLPre {
                            "parent already nows the iframe..."
                        }.AttachToDocument();

                          m = lookup[that.frame];

                      }
                      else
                      {
                          new IHTMLPre {
                            "parent is awaiting handshake of the newly loaded iframe..."
                        }.AttachToDocument();


                          // X:\jsc.svn\examples\javascript\Test\TestSwitchToIFrame\TestSwitchToIFrame\Application.cs
                          //var m = await that.frame.contentWindow.async.onmessage;
                          m = await that.frame.async.onmessage;

                          lookup[that.frame] = m;



                          #region onmessage
                          that.frame.ownerDocument.defaultView.onmessage +=
                              e =>
                              {
                                  if (e.source != that.frame.contentWindow)
                                      return;

                                  var shadowstate = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)e.data;

                                  // are we jumping into a new statemachine?

                                  new IHTMLPre {
                                    "parent saw iframe instructions to jump back " + new { shadowstate.state }
                              }.AttachToDocument();

                                  // about to invoke

                                  #region xAsyncStateMachineType
                                  var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                                        item =>
                                        {
                                            // safety check 1

                                            //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                                            var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                                            if (xisIAsyncStateMachine)
                                            {
                                                //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                                return item.FullName == shadowstate.TypeName;
                                            }

                                            return false;
                                        }
                                    );
                                  #endregion


                                  var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                                  var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                                  var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                                  #region 1__state
                                  xAsyncStateMachineType.GetFields(
                                              System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                                          ).WithEach(
                                           AsyncStateMachineSourceField =>
                                           {

                                               Console.WriteLine(new { AsyncStateMachineSourceField });

                                               if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                                               {
                                                   AsyncStateMachineSourceField.SetValue(
                                                       NewStateMachineI,
                                                       shadowstate.state
                                                    );
                                               }

                                               var xStringField = shadowstate.StringFields.AsEnumerable().FirstOrDefault(
                                                     f => DecoratedString(f.FieldName) == DecoratedString(AsyncStateMachineSourceField.Name)
                                                 );

                                               if (xStringField != null)
                                               {
                                                   // once we are to go back to client. we need to reverse it?

                                                   AsyncStateMachineSourceField.SetValue(
                                                       NewStateMachineI,
                                                       xStringField.value
                                                    );
                                                   // next xml?
                                                   // before lets send our strings back with the new state!
                                                   // what about exceptions?
                                               }
                                           }
                                      );
                                  #endregion

                                  new IHTMLPre {
                                    "parent saw iframe instructions to jump back. invoking... "
                              }.AttachToDocument();

                                  NewStateMachineI.MoveNext();

                              };
                          #endregion

                      }




                      new IHTMLPre {
                            "parent is sending state after handshake..."
                        }.AttachToDocument();


                      m.postMessage(r.shadowstate);
                  };
                  #endregion


                  #endregion


                  var hostname = Native.document.location.host.TakeUntilIfAny(":");
                  var hostport = Native.document.location.host.SkipUntilOrEmpty(":");

                  //var hostport1 = Convert.ToInt32(hostport) + 1;
                  var hostport1 = Convert.ToInt32(hostport);
                  var host1 = hostname + ":" + hostport1;
                  var baseURI1 = "https://" + host1;


                  new IHTMLButton { "Identity " + new { baseURI1 } }.AttachToDocument().onclick += async e =>
                  {
                      #region statemachine fixup?
                      await Task.CompletedTask;
                      #endregion


                      new IHTMLPre { "will jump into the iframe to do io and then jump back here" }.AttachToDocument();

                      //var iframe = new IHTMLIFrame { src = baseURI1 }.AttachToDocument();
                      iframe = new IHTMLIFrame { src = baseURI1 }.AttachToDocument();

                      // if the iframe is on another port, ssl client certificate may be prompted
                      //await (HopTo)iframe;
                      await (HopToIFrame)iframe;

                      new IHTMLPre { "did we make it into iframe yet?" }.AttachToDocument();
                      // yes

                      await new IHTMLButton { "lets jump back " }.AttachToDocument().async.onclick;

                      new IHTMLPre { "lets jump back to parent..." }.AttachToDocument();

                      //await (HopTo)Native.window.parent;
                      await default(HopToParent);

                      new IHTMLPre { "did we make it into parent yet?" }.AttachToDocument();

                      // do we have iframe ref or are we a new statemachine?
                      await new IHTMLButton { "lets jump back to iframe " + new { iframe } }.AttachToDocument().async.onclick;

                      await (HopToIFrame)iframe;

                      Native.document.body.Clear();

                      new IHTMLPre { "did we make it into iframe this time?" }.AttachToDocument();
                      // yes

                      // TypeError: Cannot read property '__4__this' of null
                      //var color = await base.Color();

                      var color = await new ApplicationWebService { }.Color();

                      Native.body.style.backgroundColor = color;

                      await default(HopToParent);

                      new IHTMLPre { "did we make it into parent yet? " + new { color } }.AttachToDocument();

                      Native.body.style.backgroundColor = color;
                  };

              }
          );

        }
コード例 #22
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page)
        {
            if (Native.document.location.hash == "")
            {
                page.Content.innerText = "this page shall have child frames!";

                var a = new IHTMLIFrame
                {
                }.AttachToDocument();

                a.contentWindow.document.location.replace("#/child1");

                var b = new IHTMLIFrame
                {
                }.AttachToDocument();

                b.contentWindow.document.location.replace("#/child2");

                new IHTMLBreak().AttachToDocument();
            }
            else
            {
                page.Content.innerText = Native.document.location.hash;

                Native.window.parent.With(
                    parent =>
                    {

                        new IHTMLButton { innerText = "send parent a message" }.With(
                            btn =>
                            {
                                btn.onclick +=
                                    delegate
                                    {

                                        parent.postMessage("hi from " + Native.document.location.hash);
                                    };
                            }
                        ).AttachToDocument();
                    }
                );
            }

            Native.window.onmessage +=
                e =>
                {
                    new IHTMLButton { innerText = e.data + " (click to reply)" }.With(
                        btn =>
                        {
                            if (Native.document.location.hash == "")
                                btn.style.color = JSColor.Blue;
                            else
                                btn.style.color = JSColor.Red;



                            btn.onclick +=
                                delegate
                                {
                                    btn.Orphanize();


                                    var WhoAmI = Native.document.location.hash;

                                    if (WhoAmI == "")
                                        WhoAmI = "parent";

                                    e.source.postMessage("this is a reply from " + WhoAmI);
                                };
                        }
                    ).AttachToDocument();

                };

        }
コード例 #23
0
		public Application(IApp page)
		{
			// X:\jsc.svn\examples\javascript\chrome\extensions\ChromeTabsExperiment\ChromeTabsExperiment\Application.cs

			dynamic self = Native.self;
			dynamic self_chrome = self.chrome;
			object self_chrome_tabs = self_chrome.tabs;

			#region self_chrome_tabs
			if (self_chrome_tabs != null)
			{
				Console.WriteLine("extension is now running...");

				#region isYTMissing
				new { }.With(
					async delegate
					{
						var vid = "TXExg6Xj3aA";

						var thumbnail = $"https://img.youtube.com/vi/{vid}/0.jpg";

						var thumbnailImage = new IHTMLImage
						{
							src = thumbnail
						};

						// wont get those events for 404?

						//Native.window.onerror += err =>
						//{
						//	Console.WriteLine(
						//		"window onerror " +

						//		new
						//		{
						//			thumbnail,
						//			err,

						//			thumbnailImage.complete,
						//			thumbnailImage.width,
						//			thumbnailImage.naturalWidth,
						//			thumbnailImage.naturalHeight
						//		}
						//	);

						//};

						//thumbnailImage.onerror += err =>
						//{
						//	Console.WriteLine(
						//		"thumbnailImage onerror " +

						//		new
						//		{
						//			thumbnail,
						//			err,

						//			thumbnailImage.complete,
						//			thumbnailImage.width,
						//			thumbnailImage.naturalWidth,
						//			thumbnailImage.naturalHeight
						//		}
						//	);

						//};


						await thumbnailImage.async.oncomplete;


						Console.WriteLine(
							new { thumbnail, thumbnailImage.complete, thumbnailImage.width, thumbnailImage.naturalWidth, thumbnailImage.naturalHeight }
						);


						var thumbnailBytes = await thumbnailImage.async.bytes;

						Console.WriteLine(
							new { thumbnailBytes.Length }
						);


						// crc?
						var sw = Stopwatch.StartNew();

						var crc = CRCExample.ActionScript.Crc32Helper.GetCrc32(thumbnailBytes);

						// 247ms {{ crc = 9e47636d, ElapsedMilliseconds = 7 }}

						var isYTMissing = 0x9e47636d == crc;

						Console.WriteLine(
								new { crc = crc.ToString("x8"), sw.ElapsedMilliseconds, isYTMissing }
							  );

					}
				);
				#endregion

				var oncePerTab = new Dictionary<TabIdInteger, object>();

				chrome.tabs.Updated += async (i, x, tab) =>
				{

					// chrome://newtab/

					// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150423

					#region tab
					if (tab == null)
					{
						Console.WriteLine("bugcheck :198 iframe? called with the wrong state?");
						return;
					}

					Console.WriteLine("enter async chrome.tabs.Updated " + new { tab.url, tab.status });


					if (tab.url.StartsWith("chrome-devtools://"))
					{
						return;
					}

					if (tab.url.StartsWith("chrome://"))
						return;


					// while running tabs.insertCSS: The extensions gallery cannot be scripted.
					if (tab.url.StartsWith("https://chrome.google.com/webstore/"))
						return;


					if (tab.status != "complete")
					{
						Console.WriteLine("exit async chrome.tabs.Updated, not complete?");
						return;
					}

					#endregion

					if (oncePerTab.ContainsKey(tab.id))
						return;

					oncePerTab[tab.id] = new object();

					// where is the hop to iframe?
					// X:\jsc.svn\examples\javascript\Test\TestSwitchToIFrame\TestSwitchToIFrame\Application.cs


					// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150403

					//await (HopToChromeTab)tab.id;
					Console.WriteLine("chrome.tabs.Updated will delay, to increment state");

					// why do we need this fake await?
					// cannot resume state otherwise?
					await Task.Delay(1);

					// 
					// X:\jsc.svn\market\synergy\javascript\chrome\chrome\chrome.idl
					var tabIdString = Convert.ToString((object)tab.id);

					// 13032ms chrome.tabs.Updated will HopToChromeTab {{ tabIdString = 608 }}
					Console.WriteLine("chrome.tabs.Updated will HopToChromeTab " + new { tabIdString });
					// state1:
					await (HopToChromeTab)tab;

					// TypeError: Cannot set property 'ztabIdString' of null
					ztabIdString = tabIdString;

					//await tab.id;

					// are we now on the tab?
					// can we jump back?

					// 531ms yt found {{ Length = 108 }}
					// X:\jsc.svn\examples\javascript\test\TestShadowForIFrame\TestShadowForIFrame\Application.cs
					//var yt1 = Native.document.querySelectorAll(" [class='youtube-player']");

					// <iframe width="420" height="315" src="https://www.youtube.com/embed/sJIh70IZua8" frameborder="0" allowfullscreen=""></iframe>

					// 503ms create iframe... {{ ztabIdString = null }}
					// what about jumping with files/uploads?
					Console.WriteLine("create iframe... " + new { ztabIdString });



					iframe = new IHTMLIFrame {
						//src = "about:blank"


						//new XElement("button", "did extension send us our code? " )

						new XElement("script", new XAttribute("src", url), " ")

					}.AttachTo(
					   Native.document.documentElement
					   );


					var yt1 = Native.document.querySelectorAll("iframe");

					Console.WriteLine("yt found " + new { yt1.Length });
					yt1.WithEach(
						  async e =>
						  {
							  //if (e == null)
							  // return;

							  var xiframe = (IHTMLIFrame)e;

							  //13ms yt found { { Length = 9 } }
							  //VM1190: 51533 515ms enter catch
							  //{
							  // mname = < 01ed > ldloca.s.try } ClauseCatchLocal:
							  // VM1190: 51533 515ms TypeError: Cannot read property 'src' of null


							  if (!xiframe.src.StartsWith("https://www.youtube.com/"))
							  {
								  return;
							  }

							  // can we interact, swap the videos?

							  var size = new { xiframe.clientWidth, xiframe.clientHeight };

							  var swap = new IHTMLDiv
							  {
								  //new IHTMLPre { xiframe.src },

								  //new IHTMLContent {  }
							  };

							  new IStyle(swap)
							  {
								  backgroundColor = "yellow",

								  width = size.clientWidth + "px",
								  height = size.clientHeight + "px",
								  overflow = IStyle.OverflowEnum.hidden

							  };

							  // https://code.google.com/p/dart/issues/detail?id=19561
							  // 27ms HierarchyRequestError: Failed to execute 'createShadowRoot' on 'Element': Author-created shadow roots are disabled for this element.
							  //swap.AttachTo(xiframe.shadow);

							  xiframe.ReplaceWith(swap);



							  var sh = new IHTMLDiv { }.AttachTo(swap.shadow);

							  var vid = xiframe.src.TakeUntilIfAny("?").SkipUntilOrEmpty("/embed/");




							  //						  Remote Address:[2a00: 1450:400f:802::100e]:443
							  //Request URL: https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg
							  //Request Method: GET
							  //Status Code: 404 OK


							  var thumbnail404 = $"https://img.youtube.com/vi/{vid}/0.jpg";
							  // lets look at the image. is the video removed?
							  // https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg

							  // http://stackoverflow.com/questions/22097747/getimagedata-error-the-canvas-has-been-tainted-by-cross-origin-data

							  //.AttachToHead();


							  new IStyle(sh)
							  {
								  width = size.clientWidth + "px",
								  height = size.clientHeight + "px",
								  overflow = IStyle.OverflowEnum.hidden,
								  position = IStyle.PositionEnum.relative,

								  backgroundImage = $"url('{thumbnail404}')",

							  };

							  //var info = new IHTMLPre { xiframe.src };
							  var info = new IHTMLPre { new { vid } };
							  // so we can later find it again...
							  lookup_info[thumbnail404] = info;

							  // assume its not missing until we know more
							  lookup_info_YTmissing[thumbnail404] = false;

							  info.AttachTo(sh);


							  new IStyle(info)
							  {
								  backgroundColor = "rgba(0,0,255, 0.5)",
								  color = "rgba(255,255,0, 0.9)",

								  left = "0px",
								  bottom = "0px",
								  right = "0px",
								  //height = size.clientHeight + "px",

								  position = IStyle.PositionEnum.absolute
							  };

							  // at this point we need to consult the extension as it can download the bytes

							  new { }.With(
								  async delegate
								  {
									  var xtabIdString = ztabIdString;
									  var xthumbnail404 = thumbnail404;

									  // 517ms about to jump to extension to inspect the damn image... {{ xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, xtabIdString = 608 }}
									  Console.WriteLine("about to jump to extension to inspect the damn image... " + new { xthumbnail404, xtabIdString });
									  // fixup?
									  await Task.Delay(1);

									  await default(HopToExtension);


									  Console.WriteLine("about to jump to extension to inspect the damn image... done " + new { xthumbnail404, xtabIdString });
									  // 43228ms about to jump to extension to inspect the damn image... done {{ xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, xtabIdString = 608 }}



									  // can we jump back once we know what it was?
									  var thumbnailImage = new IHTMLImage
									  {
										  src = xthumbnail404
									  };

									  await thumbnailImage.async.oncomplete;
									  var thumbnailBytes = await thumbnailImage.async.bytes;
									  var sw = Stopwatch.StartNew();
									  var crc = CRCExample.ActionScript.Crc32Helper.GetCrc32(thumbnailBytes);

									  // we only do strings at this point, not integers, we could do booleans tho...
									  var isYTMissing = Convert.ToString(0x9e47636d == crc);

									  var xtab = await chrome.tabs.get(tabId: Convert.ToInt32(xtabIdString));

									  //xthumbnail404 = https://img.youtube.com/vi/BZIeqnQ1rY0/0.jpg, isYTMissing = false, xtabIdString = 608, url = https://zproxy.wordpress.com/2015/04/05/thought-form-magicians/ }}
									  //  xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, isYTMissing = true, xtabIdString = 608, url = https://zproxy.wordpress.com/2015/04/05/thought-form-magicians/ }}

									  Console.WriteLine(">> " + new { xthumbnail404, isYTMissing, xtabIdString, xtab.url });

									  // can we jump back to the tab to color it red if missing?
									  // 43340ms >> {{ xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, isYTMissing = true, xtabIdString = 608 }}

									  //(HopToChromeTab)

									  // ok now we now what tab we are in but even if we jump back. we wont have a ref to the infobar?

									  await (HopToChromeTab)xtab;

									  Console.WriteLine(">> " + new { xthumbnail404, isYTMissing, xtabIdString } + " back in the tab?");

									  // would the old variables be reconnected for us?
									  // jumps should be able to resume an old startemachine.

									  lookup_info_YTmissing[xthumbnail404] = Convert.ToBoolean(isYTMissing);

									  var xinfo = lookup_info[xthumbnail404];

									  //xthumbnail404 = https://img.youtube.com/vi/BZIeqnQ1rY0/0.jpg, isYTMissing = false, xtabIdString = 744 }} back in the tab?

									  if (Convert.ToBoolean(isYTMissing))
									  {
										  // yikes. video pulled!
										  new IStyle(xinfo)
										  {
											  backgroundColor = "rgba(255,0,0, 0.7)",
										  };

										  new IHTMLSpan { " do we have a local copy?" }.AttachTo(xinfo);

										  // we should send udp to the archive server?
										  // if it has how can we load it up?

										  return;
									  }

									  new IStyle(xinfo)
									  {
										  backgroundColor = "rgba(255,255,0, 0.5)",
									  };



								  }
							  );

							  // https://www.youtube.com/embed/jQLNMljadyo?vers
							  // https://www.youtube.com/embed/M4RBW85J4Cg
							  // http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg



							  await sh.async.onmouseover;

							  // no reason to load it. its missing!
							  if (lookup_info_YTmissing[thumbnail404])
								  return;

							  xiframe.AttachTo(sh);
							  info.AttachTo(sh);

							  var copyToToolbar = new IHTMLButton { "+" }.AttachTo(info);


							  await copyToToolbar.async.onclick;
							  copyToToolbar.Orphanize();

							  //width = "128px",
							  //xiframe.style.transform = "scale(0.2)";

							  new IStyle(xiframe)
							  {
								  width = (128) + "px",
								  height = (96) + "px",
							  };

							  // This video contains content from WMG. It is restricted from playback on certain sites.
							  xiframe.AttachTo(
								//iframe.contentWindow.document.documentElement
								iframe.contentWindow.document.body
							  );



						  }
					 );




					Console.WriteLine("create iframe... done");


					//iframe.allowTransparency = true;
					// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150423
					// __8__1 is null. why? a struct?
					//     b.__this.__8__1.scope = new ctor$vQEABrCB_bTmuL0jGQp_bnVw(b.__this._iframe_5__2);

					// oh crap. the container is initialized before await (HopToChromeTab)tab; thus lost due to context switch.
					var scope = new { iframe };

					//Console.WriteLine("iframe visible? " + new { scope });

					new IStyle(iframe)
					{
						borderWidth = "0",

						// wont animate?

						transition = "left 300ms linear",

						// dont want the white box while it loads..
						backgroundColor = "rgba(0, 0, 255, 0)",

						position = IStyle.PositionEnum.@fixed,


						//left = "1px",
						top = "32px",
						width = "128px",

						// animateIFrame
						// pre hide it
						left = "-120px",

						//height = "100px",

						// wont work on slashdot?
						//bottom = "3em"

						// can we be topmost?
						//zIndex = 30000
						zIndex = 1999999999

					};

					fixHeight(iframe);
					animateIFrame(iframe);

					//var __iframe = iframe;
					await iframe.async.onload;




					//new IStyle(iframe)
					//{
					//	backgroundColor = "rgba(0, 0, 255, 0.7)",
					//};

					Console.WriteLine("lets hop from tab context to iframe context... ");
					await (HopToIFrame)iframe;

					Console.WriteLine("lets hop from tab context to iframe context... done!");


					new IStyle(Native.document.body)
					{
						margin = "0px",
						//marginRight = "1em",

						padding = "0px",
						paddingRight = "1em",

						transition = "background-color 300ms linear",
						backgroundColor = "rgba(0, 0, 255, 0.1)",

						//border = "1px solid red"
					};




					var button4 = new IHTMLButton { "hop to parent, extension, app" }.AttachToDocument();

					new IStyle(button4)
					{
						display = IStyle.DisplayEnum.block
					};

					// not yet. need a new example
					button4.disabled = true;



					//Native.body.backgroundColor = "rgba(0, 0, 255, 0.7)";

					//var text3 = new IHTMLTextArea { value = "hey" }.AttachToDocument();

					// need to use static, as scope variables are being encapsulated, and due to context jumps we dont support it yet
					text3 = new IHTMLTextArea { value = "hey" }.AttachToDocument();
					text3.style.width = "100%";

					var button3 = new IHTMLButton { "hop to parent, extension" }.AttachToDocument();

					new IStyle(button3)
					{
						display = IStyle.DisplayEnum.block
					};

					button3.onclick += async delegate
					{
						// can we hop back?

						var data3 = text3.value;
						Console.WriteLine("enter button3 " + new { data3 });
						// 2602ms enter button3 {{ data3 = hey }}

						// why do we need this fake await?
						// cannot resume state otherwise?
						await Task.Delay(1);

						await default(HopToParent);


						var tab_title = Native.document.title;

						// 3105ms are strings being synchronized to iframe? {{ tab_title = IANA — IANA-managed Reserved Domains, data3 = null }}
						Console.WriteLine("are strings being synchronized from iframe? " + new { tab_title, data3 });

						/// 2926ms will hop back to extension!? can we resume later?
						await default(HopToExtension);

						//Native.window.alert("hi! i am back home! do we even know which tab we were in? did i get some data yet? " + new { tab_title });
						Console.WriteLine("hi! i am back home! do we even know which tab we were in? did i get some data yet? " + new { tab_title, data3 });
						// 13844ms hi! i am back home! do we even know which tab we were in? did i get some data yet? {{ tab_title = IANA — IANA-managed Reserved Domains }}

						// lets guess which tab we clicked on?
						var tt = await chrome.tabs.getCurrent();

						// https://developer.chrome.com/extensions/tabs
						// https://developer.chrome.com/extensions/windows
						// https://developer.chrome.com/extensions/processes

						//chrome.runtime.
						new chrome.Notification(
							title: new { data3, tt }.ToString()

						);


						//chrome.tabs.rel

						// can we do appwindow here or we need to jump out of extension?
					};


					var button2 = new IHTMLButton { "hop to parent" }.AttachToDocument();

					new IStyle(button2)
					{
						display = IStyle.DisplayEnum.block
					};

					button2.onclick += async delegate
					{
						// can we hop back?

						Console.WriteLine("enter button2");

						// why do we need this fake await?
						// cannot resume state otherwise?
						await Task.Delay(1);

						await default(HopToParent);


						var tab_title = Native.document.title;

						Console.WriteLine("are strings being synchronized to iframe? " + new { tab_title });


						// we are jumping back, yet into a new state machine.
						//Native.window.alert("hi! in a tab, in an extension! " + new
						//{
						//	Native.document.title
						//	,
						//	iframe
						//});

						// can we jump back? is the iframe awaiting for multiple jumps?
						await (HopToIFrame)iframe;

						Native.window.alert("hi! iframe, in a tab, in an extension! " + new { Native.document.title, tab_title });

						// ok. we now know how to
						// jump from extension to tab to iframe to tab to iframe

						// what about workers, and jumping back to extension?


						// but likely we did not jump to the same data?


					};

					var button1 = new IHTMLButton { "click me" }.AttachToDocument();

					new IStyle(button1)
					{
						display = IStyle.DisplayEnum.block
					};

					//new { }.With(
					//	async delegate
					//	{
					//		// stack variables not visible, why?
					//		while (await button1.async.onmouseover)
					//		{
					//			new IStyle(Native.document.body)
					//			{
					//				backgroundColor = "rgba(0, 0, 255, 0.8)",
					//			};

					//			await button1.async.onmouseout;

					//			new IStyle(Native.document.body)
					//			{
					//				backgroundColor = "rgba(0, 0, 255, 0.2)",
					//			};
					//		}
					//	}
					//);

					//oldschool as a workaround


					button1.onclick += delegate
					{
						Native.window.alert("hi! iframe, in a tab, in an extension! " + new { Native.document.title });

					};


					button1.onmouseover +=
						e =>
						{
							new IStyle(Native.document.body)
							{
								backgroundColor = "rgba(255, 0, 0, 0.9)",
							};

							e.stopPropagation();
						};

					button1.onmouseout +=
						delegate
						{
							new IStyle(Native.document.body)
							{
								backgroundColor = "rgba(0, 0, 255, 0.1)",
							};
						};


					// we are in iframe!
					Native.document.onmouseover +=
						delegate
						{
							new IStyle(Native.document.body)
							{
								backgroundColor = "rgba(0, 0, 255, 0.3)",
							};
						};

					Native.document.onmouseout +=
						delegate
						{
							new IStyle(Native.document.body)
							{
								backgroundColor = "rgba(0, 0, 255, 0.1)",
							};
						};




					//var f = new IHTMLButton { "in the frame! click to notify parent" }.AttachToDocument();

					//await default(HopToParent);


					// why need this stackfix?
					//var stackfix_iframe = iframe;

					//               new { }.With(
					//	async delegate
					//	{
					//		while (await Native.window.async.onresize)
					//		{
					//			stackfix_iframe.style.height = (Native.window.Height - 64) + "px";
					//		}
					//	}
					//);


					// X:\jsc.svn\examples\javascript\Test\TestHopFromIFrame\TestHopFromIFrame\Application.cs
					// can we jump?

					// <div class="player-video-title">Ariana Grande - One Last Time (Official)</div>

					//Native.document.title = "(" + Native.document.title + ")";

					// X:\jsc.svn\examples\javascript\xml\FindByClassAndObserve\FindByClassAndObserve\Application.cs

					// luckyly its only hidden... no need to await the element and find it later

					// <span id="eow-title" class="watch-title " dir="ltr" title="THORnews Weird Weather Watch! Wind Dragon inbound to USA Pacific Coast!">


					//var yt0 = Native.document.querySelectorAll(" [class='player-video-title']");
					//var yt1 = Native.document.querySelectorAll(" [class='watch-title ']");

					//yt0.Concat(yt1).WithEach(
					//	 async e =>
					//	 {
					//		 do
					//		 {
					//			 Native.document.title = e.innerText;

					//			 // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs
					//			 // we would need to jump back here to do extension notification
					//			 // the jump back would be to another state machine tho
					//			 // we would need other ports opened?

					//			 Native.document.documentElement.style.borderLeft = "1em solid yellow";
					//			 for (int xi = 0; xi < 5; xi++)
					//			 {
					//				 Native.body.style.borderLeft = "1em solid yellow";
					//				 await Task.Delay(100);
					//				 Native.body.style.borderLeft = "1em solid black";
					//				 await Task.Delay(100);
					//			 }
					//			 Native.document.documentElement.style.borderLeft = "1em solid red";

					//			 // or actually instead of jumping back we need to send back progress?
					//		 }
					//		 while (await e.async.onmutation);
					//	 }
					// );

					// lets start monitoring
				};



				return;
			}
			#endregion

			// 420ms TypeError: Cannot read property 'url' of null

			Console.WriteLine("nop");

#if true


			#region inside iframe
			if (Native.window.parent != Native.window)
			{
				// X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs
				// inside iframe

				new { }.With(
					async delegate
					{
						// start the handshake
						// we gain intellisense, but the type is partal, likely not respawned, acivated, initialized 
						//var m = await Native.window.parent.postMessageAsync<TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine>();

						//	new IHTMLPre {
						//			"inside iframe awaiting onmessage"
						//}.AttachToDocument();

						// first null jump

						//Native.window.parent.postMessage(r.shadowstate);

						var m = await Native.window.parent.postMessageAsync(default(TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine));

						Console.WriteLine("iframe got the first state...");
						// we can now send one hop back?
						InternalInvoke(m.data);
					}
				);

				return;
			}
			#endregion

#endif

			Console.WriteLine("nop");

			// we made the jump?
			//Native.body.style.borderLeft = "0em solid red";

			// yes we did. can we talk to the chrome extension?

			// lets do some SETI

			// The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.

			// Severity	Code	Description	Project	File	Line
			//Error       'runtime.onMessage' is inaccessible due to its protection level ChromeExtensionHopToTabThenIFrame X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs 272

			// public static event System.Action<object, object, object> Message

			Action<object> PostToExtension = null;

			#region Connect
			chrome.runtime.Connect +=
				 port =>
				 {
					 Console.WriteLine("chrome.runtime.Connect " + new { port.name, port.sender });

					 // 8295ms will invoke sendResponse... done?? {{ message = jump! }}
					 //port.postMessage("jump! " + new { port.name, port.sender });

					 PostToExtension = xdata =>
					 {
						 // PostToExtension {{ xdata = [object Object] }}
						 Console.WriteLine("PostToExtension " + new { xdata });
						 //Console.WriteLine("PostToExtension " + new { xdata = JSON.stringify(xdata) });

						 port.postMessage(xdata);
					 };
				 };
			#endregion

			#region chrome.runtime.Message
			chrome.runtime.Message += (object message, chrome.MessageSender sender, IFunction sendResponse) =>
			{
				var s = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)message;

				if (url != null)
				{
					Console.WriteLine("jumping back to tab for more? done");

					InternalInvoke(s);

					return;
				}

				Console.WriteLine("chrome.runtime.Message " + new { s.state, sender.id, code = s.code.Length });
				// at this point we can initialize hop to iframe since we have the code we can actually use?

				// 276ms xonmessage {{ state = 1, id = fkgibadjpabiongmgoeomdbcefhabmah, code = 3296612 }}

				#region url
				var aFileParts = new[] { s.code };
				var oMyBlob = new Blob(aFileParts, new { type = "text/javascript" });
				//var url = oMyBlob.ToObjectURL();
				url = URL.createObjectURL(oMyBlob);
				#endregion



				Console.WriteLine("will we want to jump back to extension?");

				HopToExtension.VirtualOnCompleted +=
					(that, continuation) =>
					{
						Console.WriteLine("will hop back to extension!? can we resume later?");

						var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

						// can we only send once?
						//Console.WriteLine("will invoke sendResponse... " + new { sendResponse });
						Console.WriteLine("will invoke sendResponse... ");
						//sendResponse.apply(null, r);

						//will invoke sendResponse...
						//(program):51533 1664ms enter catch
						//{
						//	mname = < 0154 > ldarg.0.try } ClauseCatchLocal:
						//	(program):51533 1664ms TypeError: Converting circular structure to JSON

						// planB

						PostToExtension(r.shadowstate);
					};


				InternalInvoke(s);



				//Task.Delay(1000).ContinueWith(
				//	delegate
				//	{
				//		sendResponse.apply(null, "response");
				//	}
				//);

			};
			#endregion


			//         Native.window.onmessage += e =>
			//{

			//};
		}
コード例 #24
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //Native.body.Clear();


            Native.document.body.style.backgroundColor = "cyan";

            new { }.With(
                async delegate
                {
                    var isroot = Native.window.parent == Native.window.self;

                    new IHTMLPre { new { isroot } }.AttachToDocument();

                    if (!isroot)
                    {
                        // we have the id now.

                        Native.window.onmessage += e =>
                        {
                            // lets test messages to see if we could do a hop

                            new IHTMLPre { e.data }.AttachToDocument();

                        };

                        new IHTMLButton { "Identity" }.AttachToDocument().onclick += async e =>
                        {
                            var Identity = await base.Identity();

                            e.Element.innerText = new { Identity }.ToString();

                        };

                        return;
                    }

                    Native.document.body.style.backgroundColor = await base.Color();

                    var hostname = Native.document.location.host.TakeUntilIfAny(":");
                    var hostport = Native.document.location.host.SkipUntilOrEmpty(":");

                    await new IHTMLButton { "login " + new{
                        Native.document.location.protocol,
                        Native.document.location.host,

                        Native.document.baseURI
                    } }.AttachToDocument().async.onclick;

                    // port + 1 iframe?
                    Native.document.body.style.backgroundColor = "cyan";

                    var hostport1 = Convert.ToInt32(hostport) + 1;
                    var host1 = hostname + ":" + hostport1;

                    new IHTMLPre { new { host1 } }.AttachToDocument();

                    var baseURI1 = "https://" + host1;

                    var iframe = new IHTMLIFrame { src = baseURI1 }.AttachToDocument();
                    var iframeloaded = await iframe.async.onload;

                    new IHTMLPre { "ready! " + new { Native.document.baseURI } }.AttachToDocument();

                    // http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage
                    var iframeContentWindowIsNull = iframe.contentWindow == null;

                    new IHTMLButton { "send " + new { iframeContentWindowIsNull } }.AttachToDocument().onclick += delegate
                    {
                        //((IHTMLIFrame)iframeloaded.Element).contentWindow.postMessage("hello from above");
                        iframe.contentWindow.postMessage("hello from above");

                        // this now works.
                        // in chrome
                        // in IE
                        // firefox complains null cert chain.
                    };

                    // change base?
                    // would be cool if we were to be able to do that huh.
                    // isntead lets hop into the iframe?

                    //await new IHTMLButton { "upgrade" }.AttachToDocument().async.onclick;


                    //new IHTMLBase { href = baseURI1 }.AttachToHead();

                    ////Native.document.baseURI = baseURI1;

                    //new IHTMLPre { "ready! " + new { Native.document.baseURI } }.AttachToDocument();


                    //new IHTMLButton { "Identity" }.AttachToDocument().onclick += async e =>
                    //{
                    //    var Identity = await base.Identity();

                    //    e.Element.innerText = new { Identity }.ToString();

                    //};
                }
            );
        }
コード例 #25
0
        public Application(IApp page)
        {
            // per iframe there is one only.
            // we should be respawning async state this pointer while jmping into iframe.
            __base = this;

            #region  magic
            var isroot = Native.window.parent == Native.window.self;

            //new IHTMLPre { new { isroot } }.AttachToDocument();

            if (!isroot)
            {
                #region HopToParent
                HopToParent.VirtualOnCompleted = async (that, continuation) =>
                {
                    // the state is in a member variable?

                    var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                    // should not be a zero state
                    // or do we have statemachine name clash?

                    //new IHTMLPre {
                    //    "iframe about to jump to parent " + new { r.shadowstate.state }
                    //}.AttachToDocument();

                    Native.window.parent.postMessage(r.shadowstate);

                    // we actually wont use the response yet..
                };
                #endregion


                // start the handshake
                // we gain intellisense, but the type is partal, likely not respawned, acivated, initialized 

                //  new IHTMLPre {
                //  "inside iframe awaiting state"
                //}.AttachToDocument();




                var c = new MessageChannel();

                c.port1.onmessage +=
                    m =>
                    {
                        var that = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)m.data;

                        //new IHTMLPre {
                        //            "inside iframe got state " +
                        //            new { that.state }
                        //      }.AttachToDocument();

                        // about to invoke

                        #region xAsyncStateMachineType
                        var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                              item =>
                              {
                                  // safety check 1

                                  //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                                  var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                                  if (xisIAsyncStateMachine)
                                  {
                                      //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                      return item.FullName == that.TypeName;
                                  }

                                  return false;
                              }
                          );
                        #endregion


                        var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                        var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                        var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                        #region 1__state
                        xAsyncStateMachineType.GetFields(
                                    System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                                ).WithEach(
                                 AsyncStateMachineSourceField =>
                                 {

                                     Console.WriteLine(new { AsyncStateMachineSourceField });

                                     if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                                     {
                                         AsyncStateMachineSourceField.SetValue(
                                             NewStateMachineI,
                                             that.state
                                          );
                                     }

                                     var xStringField = that.StringFields.AsEnumerable().FirstOrDefault(
                                         f => DecoratedString(f.FieldName) == DecoratedString(AsyncStateMachineSourceField.Name)
                                     );

                                     if (xStringField != null)
                                     {
                                         // once we are to go back to client. we need to reverse it?

                                         AsyncStateMachineSourceField.SetValue(
                                             NewStateMachineI,
                                             xStringField.value
                                          );
                                         // next xml?
                                         // before lets send our strings back with the new state!
                                         // what about exceptions?
                                     }
                                 }
                            );
                        #endregion

                        //new IHTMLPre {
                        //        "inside iframe invoke state"
                        //    }.AttachToDocument();

                        NewStateMachineI.MoveNext();

                        // we can now send one hop back?
                    };

                c.port1.start();
                c.port2.start();

                Native.window.parent.postMessage(null,
                    "*",
                    c.port2
                );





                return;
            }

            var lookup = new Dictionary<IHTMLIFrame, MessageEvent> { };

            #region HopToIFrame
            HopToIFrame.VirtualOnCompleted = async (that, continuation) =>
            {
                var m = default(MessageEvent);
                var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                if (lookup.ContainsKey(that.frame))
                {
                    //    new IHTMLPre {
                    //    "parent already nows the iframe..."
                    //}.AttachToDocument();

                    m = lookup[that.frame];

                }
                else
                {
                    //    new IHTMLPre {
                    //    "parent is awaiting handshake of the newly loaded iframe..."
                    //}.AttachToDocument();


                    // X:\jsc.svn\examples\javascript\Test\TestSwitchToIFrame\TestSwitchToIFrame\Application.cs
                    //var m = await that.frame.contentWindow.async.onmessage;
                    m = await that.frame.async.onmessage;

                    lookup[that.frame] = m;



                    #region onmessage
                    that.frame.ownerDocument.defaultView.onmessage +=
                        e =>
                        {
                            if (e.source != that.frame.contentWindow)
                                return;

                            var shadowstate = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)e.data;

                            // are we jumping into a new statemachine?

                            //      new IHTMLPre {
                            //      "parent saw iframe instructions to jump back " + new { shadowstate.state }
                            //}.AttachToDocument();

                            // about to invoke

                            #region xAsyncStateMachineType
                            var xAsyncStateMachineType = typeof(Application).Assembly.GetTypes().FirstOrDefault(
                                  item =>
                                  {
                                      // safety check 1

                                      //Console.WriteLine(new { sw.ElapsedMilliseconds, item.FullName });

                                      var xisIAsyncStateMachine = typeof(IAsyncStateMachine).IsAssignableFrom(item);
                                      if (xisIAsyncStateMachine)
                                      {
                                          //Console.WriteLine(new { item.FullName, isIAsyncStateMachine });

                                          return item.FullName == shadowstate.TypeName;
                                      }

                                      return false;
                                  }
                              );
                            #endregion


                            var NewStateMachine = FormatterServices.GetUninitializedObject(xAsyncStateMachineType);
                            var isIAsyncStateMachine = NewStateMachine is IAsyncStateMachine;

                            var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

                            #region 1__state
                            xAsyncStateMachineType.GetFields(
                                        System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
                                    ).WithEach(
                                     AsyncStateMachineSourceField =>
                                     {

                                         Console.WriteLine(new { AsyncStateMachineSourceField });

                                         if (AsyncStateMachineSourceField.Name.EndsWith("1__state"))
                                         {
                                             AsyncStateMachineSourceField.SetValue(
                                                 NewStateMachineI,
                                                 shadowstate.state
                                              );
                                         }

                                         var xStringField = shadowstate.StringFields.AsEnumerable().FirstOrDefault(
                                               f => DecoratedString(f.FieldName) == DecoratedString(AsyncStateMachineSourceField.Name)
                                           );

                                         if (xStringField != null)
                                         {
                                             // once we are to go back to client. we need to reverse it?

                                             AsyncStateMachineSourceField.SetValue(
                                                 NewStateMachineI,
                                                 xStringField.value
                                              );
                                             // next xml?
                                             // before lets send our strings back with the new state!
                                             // what about exceptions?
                                         }
                                     }
                                );
                            #endregion

                            //      new IHTMLPre {
                            //      "parent saw iframe instructions to jump back. invoking... "
                            //}.AttachToDocument();

                            NewStateMachineI.MoveNext();

                        };
                    #endregion

                }




                //new IHTMLPre {
                //    "parent is sending state after handshake..."
                //}.AttachToDocument();


                m.postMessage(r.shadowstate);
            };
            #endregion


            #endregion



            // can we log in via MID?
            // where is the last test?
            // Z:\jsc.svn\examples\javascript\crypto\VerifyIdentityAffinity\VerifyIdentityAffinity\Application.cs

            // can we modify roslyn to compile comments into IL?
            new IHTMLPre { "guest, EID, MID. which are we?" }.AttachToDocument();
            new IHTMLPre { new { Native.document.location.protocol, Native.document.location.host } }.AttachToDocument();
            // NFC ?
            new IHTMLPre { new { Native.window.navigator.userAgent } }.AttachToDocument();

            var hostname = Native.document.location.host.TakeUntilIfAny(":");
            var hostport = Native.document.location.host.SkipUntilOrEmpty(":");

            if (string.IsNullOrEmpty(hostport))
                hostport = "443";


            new IHTMLPre { new { base.identity, hostname, hostport } }.AttachToDocument();

            // { identity = { value = guest, signature = 70d1638ccb1627209f7d5751b989dd5cc399ff17c72aff075f2e05ff1b3c9a1f474cf5813c6470b8e9ee77b5911316acee62c6bf3534b2bc4942bc9de4344fc9 } }

            // doesnt jsc assetslibary do public key?
            // should we want to validate the identity on client?
            // can we? if we run on http we cant.


            #region EID
            new IHTMLButton { "EID" }.AttachToDocument().With(
                async e =>
                {
                    #region statemachine fixup?
                    await Task.CompletedTask;
                    #endregion

                    // are we running nfc web browser?
                    if (Native.window.navigator.userAgent.Contains("NFCDID"))
                        e.innerText = "NFC DID";


                    // NFC ?
                    await e.async.onclick;

                    Native.document.body.Clear();

                    // https://technet.microsoft.com/en-us/library/dd979547(v=ws.10).aspx
                    new IHTMLPre { e.innerText + " - Please insert smart card..." }.AttachToDocument();

                    // need hopping support.

                    var hostport1 = Convert.ToInt32(hostport) + 1;
                    var host1 = hostname + ":" + hostport1;
                    var baseURI1 = "https://" + host1;

                    iframe = new IHTMLIFrame { src = baseURI1, frameBorder = "0" }.AttachToDocument();

                    // if the iframe is on another port, ssl client certificate may be prompted
                    //await (HopTo)iframe;
                    await (HopToIFrame)iframe;

                    // ding ding ding.

                    //new IHTMLPre { "hello __base?" }.AttachToDocument();



                    //var xidenity_value = base.identity.value;
                    //var xidenity_signature = base.identity.signature;

                    var xidenity_value = __base.identity.value;
                    //var xidenity_signature = __base.identity.signature;

                    // jsc wont do byte array jumps yet?
                    var xidenity_signature = Convert.ToBase64String(__base.identity.signature);


                    await default(HopToParent);

                    //new IHTMLPre { new { xidenity_value, xidenity_signature, base.identity } }.AttachToDocument();
                    //new IHTMLPre { new { xidenity_value, xidenity_signature, __base.identity } }.AttachToDocument();


                    __base.identity = new VerifiableString
                    {
                        value = xidenity_value,
                        signature = Convert.FromBase64String(xidenity_signature)
                    };

                    __base.foo = "bar";

                    Native.document.body.Clear();
                    new IHTMLPre { new { __base.identity, __base.foo } }.AttachToDocument();

                    // IE cant verify?

                    // verify our new identity.

                    await new IHTMLButton { "Verify" }.AttachToDocument().async.onclick;
                    Native.document.body.style.backgroundColor = "yellow";
                    if (await __base.Verify())
                        Native.document.body.style.backgroundColor = "cyan";
                    else
                        Native.document.body.style.backgroundColor = "red";


                    //await new IHTMLButton { "close" }.AttachToDocument().async.onclick;

                    //// cant close?
                    //Native.window.close();
                }
            );
#endregion

            new IHTMLButton { "MID" }.AttachToDocument().With(
              async e =>
              {
                  await e.async.onclick;

                  Native.document.body.Clear();

                  new IHTMLPre { "MID login..." }.AttachToDocument();

                  var state = await base.MobileAuthenticateAsync15();

                  if (state == null)
                  {
                      new IHTMLPre { "fault" }.AttachToDocument();
                      return;
                  }

                  new IHTMLPre { new { state.MobileAuthenticateAsync15_UserIDCode } }.AttachToDocument();
                  new IHTMLPre { new { state.MobileAuthenticateAsync15_Sesscode } }.AttachToDocument();
                  new IHTMLPre { new { state.MobileAuthenticateAsync15_ChallengeID } }.AttachToDocument();

                  new IHTMLCenter { state.MobileAuthenticateAsync15_ChallengeID.value }.AttachToDocument();

                  var sw = Stopwatch.StartNew();

                  //new IHTMLPre { base.MobileAuthenticateAsync15_ChallengeID, () => new { sw.ElapsedMilliseconds } }.AttachToDocument();
                  //using (new IHTMLPre { () => new { sw.ElapsedMilliseconds } }.AttachToDocument())
                  var u = (new IHTMLPre { () => new { sw.ElapsedMilliseconds } }.AttachToDocument());
                  {
                      await Task.Delay(15000);
                      sw.Stop();
                  }
                  u.Dispose();

                  Native.document.documentElement.style.borderLeft = "2px solid yellow";

                  await base.MobileAuthenticateAsync15Continue(state);

                  // { identity = { value = 14212128025, signature = 818a158d2497c54e9bde7cc7ee498b264282b709a87394be7037c09a7e38d57d515d34fa3cd7a93e8487bd477e4bd20d3f6bfbdce3c07926a1ede5935b6e5d3e } }

                  Native.document.body.Clear();
                  new IHTMLPre { new { base.identity } }.AttachToDocument();

                  await new IHTMLButton { "Verify" }.AttachToDocument().async.onclick;
                  Native.document.body.style.backgroundColor = "yellow";
                  if (await __base.Verify())
                      Native.document.body.style.backgroundColor = "cyan";
                  else
                      Native.document.body.style.backgroundColor = "red";
              }
          );
        }
コード例 #26
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page = null)
        {
            // ! start big, then resize to small





            var ScreenWidth = Native.Screen.width;
            var ScreenHeight = Native.Screen.height;

            Console.WriteLine(
                new { ScreenWidth, ScreenHeight, Native.window.Width, Native.window.Height }
            );


            #region workaround for ThreeJS/chrome webgl upscale bug
            // workaround for not knowing how to tell three js to upscale correctly..
            // X:\jsc.svn\examples\javascript\Test\TestNestedIFrameForMoreWidth\TestNestedIFrameForMoreWidth\Application.cs
            // instead of reloading full app
            // could we run part of it instead?
            // like let jsc know that this sub application should be reloadable?
            // this will be like threading
            // the outer code wil just stop doing anything
            // and the inner app will take over.

            var ApplyWorkaround = false;
            var location = "";

            try
            {
                location = Native.Document.location.href;
                //var pl = Native.Window.parent.document.location;

                if (Native.window.Width < Native.screen.width)
                    ApplyWorkaround = true;
            }
            catch
            {

            }

            if (ApplyWorkaround)
            {
                #region make sure the url looks different to make iframe actually load
                Native.window.parent.With(
                    parent =>
                    {
                        // http://stackoverflow.com/questions/5934538/is-there-a-limitation-on-an-iframe-containing-another-iframe-with-the-same-url

                        var parentlocation = "";

                        try
                        {
                            parentlocation = parent.document.location.href;
                        }
                        catch
                        {
                            // parent from another origin
                        }

                        Console.WriteLine(new { parentlocation });

                        if (parentlocation.TakeUntilIfAny("#") == location.TakeUntilIfAny("#"))
                        {
                            var withouthash = location.TakeUntilIfAny("#");
                            var onlyhash = location.SkipUntilOrEmpty("#");

                            withouthash += "?";

                            if (onlyhash != "")
                            {
                                withouthash += "#" + onlyhash;
                            }

                            location = withouthash;
                        }
                    }
                );
                #endregion

                #region ApplyWorkaround

                // this check only looks for default screen width
                // what about height and secondary screens?
                Console.WriteLine("will prepare... " + location);

                var iframe = new IHTMLIFrame
                {
                    frameBorder = "0",
                    allowFullScreen = true
                };

                iframe.style.minWidth = Native.Screen.width + "px";
                iframe.style.minHeight = Native.Screen.height + "px";

                iframe.style.position = IStyle.PositionEnum.absolute;
                iframe.style.left = "0px";
                iframe.style.top = "0px";
                iframe.style.width = "100%";
                iframe.style.height = "100%";

                Native.Document.body.Clear();
                Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;

                Native.window.onmessage +=
                   e =>
                   {
                       Console.WriteLine("Native.Window.onmessage " + new { e.data });

                       // pure trickery :P
                       if ((string)e.data == "WoodsXmasByRobert.loaded")
                       {
                           iframe.style.minWidth = "";
                           iframe.style.minHeight = "";
                       }
                   };

                iframe.onload +=
                    delegate
                    {
                        if (iframe.src != location)
                            return;

                        Native.window.requestAnimationFrame +=
                          delegate
                          {
                              Console.WriteLine("reload done! " + new { location, iframe.src });
                              iframe.contentWindow.postMessage("ready yet?");
                          };
                    };

                Native.window.requestAnimationFrame +=
                    delegate
                    {
                        Console.WriteLine("will reload... " + location);
                        iframe.AttachToDocument();
                        iframe.src = location;
                    };
                #endregion


                return;
            }




            #endregion


            new AppReferences().With(
                References =>
                {

                    var source = new[]
                    {
                        References.Three,
                        //incompatible
                        // new THREELibrary.opensource.gihtub.three.js.build.three().Content,

                        References.Tween,
                        References.CopyShader,
                        References.FilmShader,
                        References.VignetteShader,
                        References.EffectComposer,
                        References.MaskPass,
                        References.RenderPass,
                        References.ShaderPass,
                        References.FilmPass,
                    };

                    var yield = source.ForEach(
                         (SourceScriptElement, i, MoveNext) =>
                         {
                             //Console.WriteLine("will load: " + SourceScriptElement.src);
                             SourceScriptElement.AttachToDocument().onload +=
                                 delegate
                                 {
                                     //Console.WriteLine("loaded: " + SourceScriptElement.src);
                                     MoveNext();
                                 };
                         }
                     );

                    yield(
                         delegate
                         {
                             //Console.WriteLine("will load WoodsXmasByRobert");

                             InitializeContent();
                         }
                     );

                }
            );

        }
コード例 #27
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            #region con
            //var con = new Abstractatech.ConsoleFormPackage.Library.ConsoleForm();
            var con = new ConsoleForm();

            con.InitializeConsoleFormWriter();

            con.Show();

            con.Left = Native.Window.Width - con.Width;
            con.Top = 0;

            Native.Window.onresize +=
                  delegate
                  {
                      con.Left = Native.Window.Width - con.Width;
                      con.Top = 0;
                  };


            con.Opacity = 0.6;



            con.HandleFormClosing = false;
            con.PopupInsteadOfClosing();
            #endregion

            Console.WriteLine("click on InitializeOurFacebookLoginService!");

            Native.Window.onmessage +=
                 e =>
                 {
                     // http://developer.klout.com/blog/read/fb_identity_lookup

                     Console.WriteLine("onmessage: " + e.data);
                 };

            // wont work as chrome app!
            page.InitializeOurFacebookLoginService.WhenClicked(
                delegate
                {
                    Console.WriteLine("loading... ");

                    // http://caniuse.com/iframe-sandbox
                    // http://security.stackexchange.com/questions/15146/using-iframes-to-sandbox-untrusted-code
                    var i = new IHTMLIFrame { };

                    // http://www.w3schools.com/tags/att_iframe_sandbox.asp
                    // The value of the sandbox attribute can either be an empty string (all the restrictions is applied), or a space-separated list of pre-defined values that will REMOVE particular restrictions.

                    // http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

                    // this will break our popups and cookies for facebook!
                    //i.setAttribute("sandbox", "allow-scripts allow-forms allow-popups");
                    i.src = "http://young-beach-4377.herokuapp.com/";
                    i.AttachToDocument();

                    i.onload +=
                        delegate
                        {
                            Console.WriteLine("loading... done " + new { i.src });

                            // can we now talk to it?
                            // 
                        };
                }
            );

            page.InitializeOurFacebookLoginServiceViaWindow.WhenClicked(
               delegate
               {
                   Console.WriteLine("loading... ");
                   //var i = new IWindow { };
                   //i.document.location.href = "http://young-beach-4377.herokuapp.com/";

                   var i = Native.Window.open("http://young-beach-4377.herokuapp.com/", "_blank", 400, 225);


                   // doesnt tell us when loaded?
                   i.onload +=
                       delegate
                       {
                           Console.WriteLine("loading... done...");
                           //Console.WriteLine("loading... done " + new { i.document.title });
                           //Console.WriteLine("loading... done " + new { i.document.location.href });

                           // can we now talk to it?
                           // 
                       };

                   // popup will be blocked
                   //new IHTMLButton { innerText = "send DoLogin" }.AttachToDocument().WhenClicked(
                   //     delegate
                   //     {
                   //         Console.WriteLine("send DoLogin");

                   //         i.postMessage(
                   //             new XElement("DoLogin", new XAttribute("tag", "foo")).ToString()
                   //         );


                   //     }
                   //);
               }
           );


            page.InitializeOurFacebookLoginServiceViaWindowAndClose.WhenClicked(
              delegate
              {
                  Console.WriteLine("loading... ");
                  //var i = new IWindow { };
                  //i.document.location.href = "http://young-beach-4377.herokuapp.com/";

                  var i = Native.Window.open("http://young-beach-4377.herokuapp.com/#c", "_blank", 400, 225);


                  // doesnt tell us when loaded?
                  i.onload +=
                      delegate
                      {
                          Console.WriteLine("InitializeOurFacebookLoginServiceViaWindowAndClose loading... done...");
                          //Console.WriteLine("loading... done " + new { i.document.title });
                          //Console.WriteLine("loading... done " + new { i.document.location.href });

                          // can we now talk to it?
                          // 
                      };

                  i.onbeforeunload +=
                      delegate
                      {
                          Console.WriteLine("InitializeOurFacebookLoginServiceViaWindowAndClose onbeforeunload");

                      };

                  // popup will be blocked
                  //new IHTMLButton { innerText = "send DoLogin" }.AttachToDocument().WhenClicked(
                  //     delegate
                  //     {
                  //         Console.WriteLine("send DoLogin");

                  //         i.postMessage(
                  //             new XElement("DoLogin", new XAttribute("tag", "foo")).ToString()
                  //         );


                  //     }
                  //);
              }
          );


            page.HerokuFacebookLoginAppLoginExperience.WhenClicked(
                delegate
                {
                    HerokuFacebookLoginAppLoginExperience.Login(
                            (string id, string name, string third_party_id) =>
                            {
                                Console.WriteLine(new { id, name, third_party_id });

                            }
                );
                }
            );

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            //service.WebMethod2(
            //    @"A string from JavaScript.",
            //    value => value.ToDocumentTitle()
            //);
        }
コード例 #28
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            Native.Document.body.onmousemove +=
                e =>
                {
                    var horizontal = e.CursorX / (double)Native.window.Width;
                    var vertical = e.CursorY / (double)Native.window.Height;


                    //$('.ipad').css({
                    //    '-webkit-transform': 'rotateX(' + (7 - (vertical * 14)) + 'deg) rotateY(' + (-10 + (horizontal * 20)) + 'deg)'
                    //});


                    page.ipad.style.transform = "rotateX(" + (7 - (vertical * 14)) + "deg) rotateY(" + (-10 + (horizontal * 20)) + "deg)";


                    //$('.specular').css({
                    //    'background-position': (-200 + (horizontal * -500)) + 'px ' + (-vertical * 600) + 'px',
                    //    'opacity': 1 - (horizontal * .45) - (vertical * .45)
                    //});

                    page.specular.style.backgroundPosition = (-200 + (horizontal * -500)) + "px " + (-vertical * 600) + "px";
                    page.specular.style.Opacity = 1 - (horizontal * .45) - (vertical * .45);

                    //$('.home-btn').css({
                    //    'background': '-webkit-linear-gradient(-' + (80 - horizontal * 20) + 'deg, transparent 50%, rgba(255, 255, 255, .05) 50.1%, rgba(255, 255, 255, ' + (.4 - (horizontal * .1) - (vertical * .1)) + '))'
                    //});

                    //page.home.style.background = "-webkit-linear-gradient(-" + (80 - horizontal * 20) + "deg, transparent 50%, rgba(255, 255, 255, .05) 50.1%, rgba(255, 255, 255, " + (.4 - (horizontal * .1) - (vertical * .1)) + "))";



                    //$('.ipad.white .home-btn').css({
                    //    'background': '-webkit-linear-gradient(-' + (80 - horizontal * 20) + 'deg, rgba(0, 0, 0, ' + (.05 + (horizontal * .05) + (vertical * .05)) + '), rgba(0, 0, 0, 0) 50%, transparent 50.1%)',
                    //    '-webkit-box-shadow': '0 0 1px rgba(0, 0, 0, .1)'
                    //});

                    //$('.shadow').css({
                    //    '-webkit-transform': 'rotateX(' + (65 + (vertical * 20)) + 'deg) rotateY(' + (10 - (horizontal * 20)) + 'deg) skewX(-15deg)'
                    //});

                    page.shadow.style.transform = "rotateX(" + (65 + (vertical * 20)) + "deg) rotateY(" + (10 - (horizontal * 20)) + "deg) skewX(-15deg)";

                };

            Action onclick = delegate
            {
                if (page.home.disabled)
                    return;

                var discover = new IHTMLIFrame { src = "http://discover.xavalon.net", frameBorder = "0" }.AttachTo(page.ipad);

                var scale = 2;
                var zoom = 1;

                discover.style.transform = "scale(" + (1 / scale) + ")";
                discover.style.transformOrigin = "0% 0%";

                discover.style.SetSize(
                    (int)(page.ipad.clientWidth * zoom * scale),
                     (int)(page.ipad.clientHeight * zoom * scale)
                );

                //dynamic ds = discover.style;

                //ds.zoom = (1.0 / zoom) + "";

                page.specular.Hide();
                page.homescreen.Hide();
                page.home.disabled = true;
            };

            page.home.onclick +=
             delegate
             {

                 onclick();
             };

            new ScriptCoreLib.JavaScript.Runtime.Timer(
                delegate
                {
                    onclick();
                }
            ).StartTimeout(5000);

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }
コード例 #29
0
		private static void AddSection11(Action<string, IHTMLDiv> AddSection)
		{
			var ToolbarHeight = "24px";

			var Content = new IHTMLDiv().With(
				k =>
				{
					k.style.border = "1px solid gray";
					k.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.relative;
					k.style.width = "100%";
					k.style.height = "20em";
				}
			);

            //global::ScriptCoreLib.Ultra.Components.HTML
            // reload the project to make visual studio happy!
			new TwentyTenWorkspace().ToBackground(Content.style, true);

			var ToolbarContainerBackground = new IHTMLDiv().With(
				k =>
				{
					k.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
					k.style.left = "0px";
					k.style.right = "0px";
					k.style.top = "0px";
					k.style.height = ToolbarHeight;

					k.style.backgroundColor = Color.White;
					k.style.Opacity = 0.5;
				}
			).AttachTo(Content);

			var ToolbarContainer = new IHTMLDiv().With(
				k =>
				{
					k.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
					k.style.left = "0px";
					k.style.right = "0px";
					k.style.top = "0px";
					k.style.height = ToolbarHeight;


				}
			).AttachTo(Content);

			var PreviewContainer = new IHTMLDiv().With(
				k =>
				{
					k.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
					k.style.left = "0px";
					k.style.right = "0px";
					k.style.top = ToolbarHeight;
					k.style.bottom = "0px";
				}
			).AttachTo(Content);


			var PreviewFrame = new IHTMLIFrame { src = "about:blank" };

			PreviewFrame.style.width = "100%";
			PreviewFrame.style.height = "100%";
			PreviewFrame.style.border = "0";
			PreviewFrame.style.margin = "0";
			PreviewFrame.style.padding = "0";
			PreviewFrame.frameBorder = "0";
			PreviewFrame.border = "0";

			PreviewFrame.AttachTo(PreviewContainer);

			PreviewContainer.Hide();

			var EditorContainer = new IHTMLDiv().With(
				k =>
				{
					k.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
					k.style.left = "0px";
					k.style.right = "0px";
					k.style.top = ToolbarHeight;
					k.style.bottom = "0px";
				}
			).AttachTo(Content);

			var EditorFrame = VisualStudioView.CreateEditor().AttachTo(EditorContainer);

			PreviewFrame.allowTransparency = true;
			EditorFrame.allowTransparency = true;

			EditorFrame.WhenContentReady(
				body =>
				{
					body.style.backgroundColor = Color.Transparent;

					new IHTMLDiv
					{
						"Hello world :)"
					}.With(
						div =>
						{
							div.style.backgroundColor = Color.White;
							div.style.borderColor = Color.Gray;
							div.style.borderStyle = "solid";
							div.style.borderWidth = "1px";

							div.style.margin = "2em";
							div.style.padding = "2em";
						}
					).AttachTo(body);

				}
			);

			var ToolbarContent = new IHTMLDiv().AttachTo(ToolbarContainer);

			ToolbarContent.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.relative;

			Action<IHTMLElement> ApplyToolbarButtonStyle =
				k =>
				{
					k.style.verticalAlign = "top";

					k.style.padding = "0";
					k.style.margin = "0";
					k.style.overflow = ScriptCoreLib.JavaScript.DOM.IStyle.OverflowEnum.hidden;
					k.style.SetSize(24, 24);

					VisualStudioView.ApplyMouseHoverStyle(k, Color.Transparent);
				};

			Func<IHTMLImage, IHTMLButton> AddButtonDummy =
				(img) =>
				{
					return new IHTMLButton { img.WithinContainer() }.With(k => ApplyToolbarButtonStyle(k)).AttachTo(ToolbarContent);
				};

			Func<IHTMLImage, Action, IHTMLButton> AddButtonAction =
				(img, command) =>
				{
					return AddButtonDummy(img).With(
						k =>
						{
							k.onclick +=
								delegate
								{
									command();
								};

						}
					);
				};

			Func<IHTMLImage, string, IHTMLButton> AddButton =
				(img, command) =>
				{
					return AddButtonAction(img, () =>
						EditorFrame.contentWindow.document.execCommand(
							command, false, null
						)
					);
				};


			//AddButtonDummy(new RTA_save());

			var SaveContainer = new IHTMLDiv().With(k => ApplyToolbarButtonStyle(k)).AttachTo(ToolbarContent);


			SaveContainer.style.display = ScriptCoreLib.JavaScript.DOM.IStyle.DisplayEnum.inline_block;

			//var Save = new InternalSaveActionSprite();

			//Save.ToTransparentSprite();
			//Save.AttachSpriteTo(SaveContainer);


			var s = new { VisualStudioTemplates.VisualCSharpProject };

			EditorFrame.WhenContentReady(
				body =>
				{
					var t = (IHTMLTextArea)EditorFrame.contentWindow.document.createElement("textarea");

					t.AttachTo(body);

					t.value = s.ToString();

				}
			);

			//Save.WhenReady(
			//    i =>
			//    {
			//        i.FileName = "Project1.zip";


			//        i.Add("Project1.txt", "x");
			//        i.Add("Project1.csproj", s.VisualCSharpProject);
			//    }
			//);

			ToolbarContent.Add(new RTA_separator_horizontal());

			var RTAButtons = new Dictionary<string, IHTMLImage>
			{
				// http://trac.symfony-project.org/browser/plugins/dmCkEditorPlugin/web/js/ckeditor/_source/plugins?rev=27455

				{"Bold", new RTA_bold()},
				{"Underline", new RTA_underline()},
				{"Strikethrough", new RTA_strikethrough()},
				{"Italic", new RTA_italic()},
				{"JustifyLeft", new RTA_justifyleft()},
				{"JustifyCenter", new RTA_justifycenter()},
				{"JustifyRight", new RTA_justifyright()},
				{"JustifyFull", new RTA_justifyfull()},
				{"Indent", new RTA_indent()},
				{"Outdent", new RTA_outdent()},
				{"Superscript", new RTA_superscript()},
				{"Subscript", new RTA_sub()},
				{"Removeformat", new RTA_removeformat()},
				{"InsertOrderedList", new RTA_numberedlist()},
				{"InsertUnorderedList", new RTA_numberedlist()},
				{"undo", new RTA_undo()},
				{"redo", new RTA_redo()},
			}.ToDictionary(
				k => k.Key,
				k => AddButton(k.Value, k.Key)
			);




			var ButtonDesign = default(IHTMLButton);
			var ButtonHTML = default(IHTMLButton);

			ButtonDesign = AddButtonAction(new RTA_mode_design(),
				delegate
				{
					ButtonDesign.Hide();
					ButtonHTML.Show();

					EditorContainer.Show();
					PreviewContainer.Hide();
				}
			);

			ButtonHTML = AddButtonAction(new RTA_mode_html(),
				delegate
				{
					ButtonHTML.Hide();


					PreviewFrame.WithContent(
						body =>
						{
							body.style.backgroundColor = Color.Transparent;
							body.innerHTML = EditorFrame.contentWindow.document.body.innerHTML;

							EditorContainer.Hide();
							PreviewContainer.Show();
							ButtonDesign.Show();
						}
					);
				}
			);

			ButtonDesign.Hide();

			AddSection(
				"Editor with toolbar with background and preview",
				Content
			);
		}