/// <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 controls = new[] { 
                content.vjLogoComponent4,
                content.vjLogoComponent5
            };
            foreach (Component item in controls)
            {
                (item as ImageLinkComponent).With(
                    c =>
                    {
                        var a = new IHTMLAnchor { href = c.href }.AttachToDocument();

                        c.img.AttachTo(a);

                        //a.style.SetLocation(c.Left, c.Top);
                    }
                );
            }

            //content.AttachControlTo(page.Content);
            //content.AutoSizeControlTo(page.ContentSize);
            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }
Beispiel #2
0
        private static IHTMLAnchor InternalConstructor()
        {
            IHTMLAnchor a = (IHTMLAnchor) new IHTMLElement(HTMLElementEnum.a);


            return(a);
        }
Beispiel #3
0
        private static IHTMLAnchor InternalConstructor(string text)
        {
            IHTMLAnchor a = InternalConstructor("about:blank", text);


            return(a);
        }
Beispiel #4
0
        private static IHTMLAnchor InternalConstructor(string href, params INode[] children)
        {
            IHTMLAnchor a = (IHTMLAnchor) new IHTMLElement(HTMLElementEnum.a);

            a.href   = href;
            a.target = "_blank";
            a.appendChild(children);

            return(a);
        }
Beispiel #5
0
        private static IHTMLAnchor InternalConstructor(string href, string text)
        {
            IHTMLAnchor a = (IHTMLAnchor) new IHTMLElement(HTMLElementEnum.a);

            a.href   = href;
            a.target = "_blank";

            if (text != null)
            {
                a.appendChild(text);
            }

            return(a);
        }
        // shadow with by http://www.cycloloco.com/shadowmaker/shadowmaker.htm

        public ExampleGalleryPlain()
        {

            var Menu = new IHTMLDiv().AttachToDocument();
            var Title = typeof(ExampleGalleryPlain).Name;

            new IHTMLElement(IHTMLElement.HTMLElementEnum.h1,
                Title).AttachTo(Menu);

            new IHTMLDiv("This is a collection of projects developed with jsc. They were coded in c# and translated to javascript with jsc. Click on the pictures to load the applications or on the names to open them in a new window. You might need to press refresh to come back to this index. Enoy! :)").AttachTo(Menu);

            base.Initialize(Menu,
                (image, href, type, TypeClicked) =>
                {
                    var div = new IHTMLDiv();

                    var a = new IHTMLAnchor(href, "");

                    a.target = "_blank";
                    a.style.textDecoration = "none";
                    a.style.whiteSpace = IStyle.WhiteSpaceEnum.nowrap;

                    image.style.border = "0px solid black";
                    image.style.SetSize(120, 90);
                    image.AttachTo(a);
                    image.style.margin = "0.2em";
                    image.style.marginRight = "1em";
                    image.style.verticalAlign = "middle";

                    a.appendChild(type.Name);

                    a.onclick +=
                        ev =>
                        {
                            ev.PreventDefault();

                            TypeClicked(type);
                        };

                    a.AttachTo(div);

                    return div;
                }
           );
        }
        public __LinkLabel()
        {
            // X:\jsc.svn\examples\javascript\forms\Test\TestHyperlink\TestHyperlink\ApplicationControl.cs

            this.InternalAnchor = new IHTMLAnchor { }.AttachTo(this.HTMLTargetContainer);

            this.InternalLabel.Orphanize().AttachTo(this.InternalAnchor);

            this.HTMLTarget = this.InternalAnchor;

            // should the rules be static?
            this.InternalAnchor.css.hover.style.textDecoration = "underline";

            this.css_active = this.InternalAnchor.css.active;
            this.css_active.style.color = "red";

            // script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.LinkLabel.set_LinkColor(System.Drawing.Color)]

            this.css = this.InternalAnchor.css;

            this.css.style.color = "blue";
            this.css.style.cursor = DOM.IStyle.CursorEnum.pointer;

            // script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.LinkLabel.set_ActiveLinkColor(System.Drawing.Color)]


            // we might use a real A element instead
            //this.HTMLTargetRef.style.color = ScriptCoreLib.JavaScript.Runtime.JSColor.Blue;

            // http://www.w3schools.com/Css/pr_text_text-decoration.asp
            //this.HTMLTargetRef.style.textDecoration = "underline";
            //this.HTMLTargetRef.style.cursor = ScriptCoreLib.JavaScript.DOM.IStyle.CursorEnum.pointer;

            this.InternalAnchor.onclick +=
                delegate
                {
                    // we could do a lazy bind here instead
                    // but we assume a link will have a handler anyway

                    if (this.LinkClicked != null)
                        this.LinkClicked(this, new LinkLabelLinkClickedEventArgs(null));
                };
        }
        /// <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)
        {
            IHTMLDiv Control = new IHTMLDiv();


            Control.AttachToDocument();

            Control.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, "This page will ask you to confirm in order to unload the page"));

            var check = new IHTMLInput(HTMLInputTypeEnum.checkbox).AttachToDocument();
            var label = new IHTMLLabel("Bypass check", check).AttachToDocument();



            Native.window.onbeforeunload +=
                delegate (IWindow.Confirmation ev)
                {

                    Timer.DoAsync(
                        delegate
                        {
                            Native.document.body.style.backgroundColor = JSColor.Red;


                            new Timer((t) => Native.document.body.style.backgroundColor = JSColor.White, 500, 0);
                        }
                    );

                    if (check.@checked)
                        return;

                    ev.Text = "This is a secure website, do you want to leave?";
                };

            var anchor = new IHTMLAnchor("http://example.com", "example.com");

            anchor.target = "_self";

            Control.appendChild(anchor);


        }
        //public readonly ApplicationWebService service = new ApplicationWebService();

        /// <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)
        {
            var service = this;

            #region pre
            Func<string, IHTMLDiv, IHTMLElement> pre =
                (value, output) =>
                {
                    return new IHTMLPre { innerText = value }.AttachTo(output);
                };
            #endregion

            #region pre
            Func<string, IHTMLDiv, IHTMLElement> browse = null;

            browse =
                (path, output) =>
                {

                    var list = new IHTMLButton { innerText = path }.AttachTo(output);


                    var group = new IHTMLDiv().AttachTo(output);




                    list.onclick +=
                        delegate
                        {
                            group.style.margin = "1em";
                            group.style.paddingLeft = "1em";
                            group.style.border = "1px solid gray";

                            list.disabled = true;

                            service.File_list(path,
                                ydirectory: value =>
                                {
                                    browse(path + "/" + value, group);
                                },

                                yfile: value =>
                                {
                                    var link = new IHTMLAnchor { href = "/io" + path + "/" + value, innerText = value };

                                    link.style.display = IStyle.DisplayEnum.block;
                                    link.AttachTo(group);
                                }
                            );
                        };

                    return group;
                };
            #endregion



            #region f
            Action<string, string, Action<string, Action<string>>, Func<string, IHTMLDiv, IHTMLElement>> f =
                (text, arg1, c, y) =>
                {
                    var btn = new IHTMLButton(text).AttachToDocument();
                    var output = new IHTMLDiv().AttachToDocument();

                    btn.onclick +=
                        e =>
                        {
                            btn.style.color = JSColor.Red;

                            output.Clear();

                            c(arg1,
                                value =>
                                {
                                    btn.style.color = JSColor.Blue;


                                    y(value, output);
                                }
                            );
                        }
                    ;
                };
            #endregion

            #region ff
            Action<string, Func<Task<string>>, Func<string, IHTMLDiv, IHTMLElement>> ff =
                (text, c, y) =>
                {
                    var btn = new IHTMLButton(text).AttachToDocument();
                    var output = new IHTMLDiv().AttachToDocument();

                    btn.WhenClicked(
                        async e =>
                        {
                            btn.style.color = JSColor.Red;

                            output.Clear();

                            var value = await c();

                            btn.style.color = JSColor.Blue;


                            y(value, output);
                        }
                     );
                };
            #endregion


#if CORE_PARTIAL
            ff("Environment_getDataDirectory", () => service.Environment_getDataDirectory(), browse);
            ff("Environment_getDownloadCacheDirectory", () => service.Environment_getDownloadCacheDirectory(), browse);
            ff("Environment_getExternalStorageDirectory", () => service.Environment_getExternalStorageDirectory(), browse);
            ff("Environment_getExternalStorageState", () => service.Environment_getExternalStorageState(), pre);
            ff("Environment_getRootDirectory", () => service.Environment_getRootDirectory(), browse);

            //service.Environment_DIRECTORY("",
            //    (
            //        string DIRECTORY_MUSIC,
            //        string DIRECTORY_PODCASTS,
            //        string DIRECTORY_RINGTONES,
            //        string DIRECTORY_ALARMS,
            //        string DIRECTORY_NOTIFICATIONS,
            //        string DIRECTORY_PICTURES,
            //        string DIRECTORY_MOVIES,
            //        string DIRECTORY_DOWNLOADS,
            //        string DIRECTORY_DCIM
            //    ) =>

            f("Environment_getExternalStoragePublicDirectory DIRECTORY_MUSIC", DIRECTORY_MUSIC, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_PODCASTS", DIRECTORY_PODCASTS, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_RINGTONES", DIRECTORY_RINGTONES, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_ALARMS", DIRECTORY_ALARMS, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_NOTIFICATIONS", DIRECTORY_NOTIFICATIONS, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_PICTURES", DIRECTORY_PICTURES, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_MOVIES", DIRECTORY_MOVIES, service.Environment_getExternalStoragePublicDirectory, browse);
            f("Environment_getExternalStoragePublicDirectory DIRECTORY_DOWNLOADS", DIRECTORY_DOWNLOADS, service.Environment_getExternalStoragePublicDirectory, browse);

#endif

            f("Environment_getExternalStoragePublicDirectory DIRECTORY_DCIM", DIRECTORY_DCIM, service.Environment_getExternalStoragePublicDirectory, browse);



            new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();



            // new IHTMLButton("Environment_getDownloadCacheDirectory").AttachToDocument().onclick +=
            //    e => service.Environment_getDownloadCacheDirectory("",
            //            value => new IHTMLPre { innerText = value }.AttachToDocument()
            //);
        }
        public ConvertASToCS()
        {
            Native.Document.title = "ConvertASToCS";

            Native.Document.body.style.padding = "0";
            Native.Document.body.style.margin = "0";


            var cookie = new Cookie("DeclaringType").BindTo(DeclaringType);

            #region Title
            var MyTitleText = new IHTMLDiv("This tool allows you to copy various parts of flash doc html file in and generate C# headers.");
            MyTitleText.style.paddingTop = "12px";
            MyTitleText.style.paddingLeft = "15px";
            MyTitleText.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;
            MyTitleText.style.fontSize = "13px";


            var MyTitle = new IHTMLDiv(MyTitleText);
            MyTitle.style.background = "url(" + Assets.Path + "titleTableTop.jpg) repeat-x";
            MyTitle.style.height = "44px";
            MyTitle.AttachToDocument();

            var MyTitleMiddleTextFloat = new IHTMLDiv();

            MyTitleMiddleTextFloat.style.paddingTop = "3px";
            MyTitleMiddleTextFloat.style.Float = IStyle.FloatEnum.right;

            var MyTitleMiddleText = new IHTMLDiv(new IHTMLLabel("DeclaringType: ", DeclaringType), DeclaringType);
            MyTitleMiddleText.style.paddingTop = "3px";
            MyTitleMiddleText.style.paddingLeft = "15px";
            MyTitleMiddleText.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;
            MyTitleMiddleText.style.fontSize = "20px";



            var MyTitleMiddle = new IHTMLDiv(MyTitleMiddleTextFloat, MyTitleMiddleText);
            MyTitleMiddle.style.background = "url(" + Assets.Path + "titleTableMiddle.jpg) repeat-x";
            MyTitleMiddle.style.height = "31px";
            MyTitleMiddle.AttachToDocument();

            var MyTitleShadow = new IHTMLDiv("");
            MyTitleShadow.style.background = "url(" + Assets.Path + "titleTableBottom.jpg) repeat-x";
            MyTitleShadow.style.height = "5px";
            MyTitleShadow.AttachToDocument();
            #endregion



            DocumentBody = new IHTMLDiv().AttachToDocument();
            DocumentBody.style.padding = "1em";
            DocumentBody.style.backgroundImage = "url(assets/ConvertASToCS/flash_logo.png)";
            DocumentBody.style.backgroundPosition = "right top";
            DocumentBody.style.backgroundRepeat = "no-repeat";


            a = new IHTMLTextArea().AttachTo(DocumentBody);
            a.style.backgroundColor = Color.Transparent;
            a.style.border = "1px solid gray";


            Func<IHTMLImage, string, IHTMLAnchor> CreateButton =
                (img, text) =>
                {
                    img.style.border = "0px";

                    var htext = new IHTMLAnchor("#", img, new IHTMLSpan(text)).AttachTo(MyTitleMiddleTextFloat);

                    htext.onclick += e => e.PreventDefault();
                    htext.style.margin = "1em";

                    return htext;
                };


            AddEvents(CreateButton((Assets.Path + "ak590dyt.pubevent(en-US,VS.80).gif"), "Events"));
            AddConstants(CreateButton((Assets.Path + "ak590dyt.pubproperty(en-US,VS.80).gif"), "Constants"));
            AddProperties(CreateButton((Assets.Path + "ak590dyt.pubproperty(en-US,VS.80).gif"), "Properties"));
            AddMethods(CreateButton((Assets.Path + "deshae98.pubmethod(en-us,VS.90).gif"), "Methods"));
            AddAny(CreateButton((Assets.Path + "deshae98.pubmethod(en-us,VS.90).gif"), "Any"));
            AddProxy(CreateButton((Assets.Path + "deshae98.pubmethod(en-us,VS.90).gif"), "Proxy"));
        }
        private void AddProxy(IHTMLAnchor htext)
        {
            var content = new IHTMLDiv().AttachTo(DocumentBody);

            // content.Hide();

            htext.onclick +=
              delegate
              {
                  content.ToggleVisible();
              };

            var LastUpdate = new IHTMLDiv("Not updated yet").AttachTo(content);

            var pre = new IHTMLElement(IHTMLElement.HTMLElementEnum.pre).AttachTo(content);

            Action update =
                delegate
                {
                    LastUpdate.innerText = "Last update: " + DateTime.Now;

                    pre.removeChildren();

                    System.Console.WriteLine("Any.ProxyProvider");

                    RenderProxyTo(new Any.ProxyProvider(a.value), pre);


                };


            a.onchange += delegate { update(); };
        }
        public void __Application(IApplicationLoader app)
        {
            //app.LoadingAnimation.FadeOut();

            var DefaultTitle = "jsc solutions";


            Native.Document.title = DefaultTitle;

            StringActionAction GetTitleFromServer = new UltraWebService().GetTitleFromServer;



            GetTitleFromServer(
                n => Native.Document.title = n
            );

            var MyPagesBackground = new IHTMLDiv
            {

            };

            MyPagesBackground.style.overflow = IStyle.OverflowEnum.hidden;
            MyPagesBackground.style.position = IStyle.PositionEnum.absolute;
            MyPagesBackground.style.width = "100%";
            MyPagesBackground.style.height = "100%";
            MyPagesBackground.AttachToDocument();

            var MyPages = new IHTMLDiv
            {

            };

            MyPages.style.overflow = IStyle.OverflowEnum.auto;
            MyPages.style.position = IStyle.PositionEnum.absolute;
            MyPages.style.width = "100%";
            MyPages.style.height = "100%";
            MyPages.AttachToDocument();

            var MyPagesInternal = new IHTMLDiv();

            MyPagesInternal.style.margin = "4em";
            MyPagesInternal.AttachTo(MyPages);

            // http://www.google.com/support/forum/p/Google+Analytics/thread?tid=486a963e463df665&hl=en
            var gapathname = Native.Document.location.pathname;
            var gasearch = Native.Document.location.search;
            var gahash = Native.Window.escape(Native.Document.location.hash);
            var gapageview = gapathname + gasearch + gahash;

            var hash = Native.Document.location.hash;

            Action<string> Analytics = delegate { };

        #region logo
            {
                var IsStudio = Native.Document.location.hash.StartsWith("#/studio");

                if (Native.Document.location.host.StartsWith("studio."))
                {
                    IsStudio = true;
                }

                if (IsStudio)
                {
                    new StudioView(AddSaveButton).Content.AttachToDocument();
                }
                else if (Native.Document.location.hash.StartsWith("#/docs"))
                {
                    var view = new DocumentationCompilationViewer();

                    view.TouchTypeSelected +=
                        type =>
                        {
                            Native.Document.location.hash = "#/docs/" + type.FullName;

                            Analytics("#/docs/" + type.FullName);
                        };

                }
                else if (Native.Document.location.hash.StartsWith("#/warehouse"))
                {
                    new UltraWebService().ThreeDWarehouse(
                        y =>
                        {
                            Func<string, IHTMLAnchor> Build =
                                mid =>
                                {
                                    var a = new IHTMLAnchor { href = "http://sketchup.google.com/3dwarehouse/details?ct=hppm&mid=" + mid }.AttachTo(MyPagesInternal);
                                    var img = new IHTMLImage { src = "http://sketchup.google.com/3dwarehouse/download?rtyp=st&ctyp=other&mid=" + mid }.AttachTo(a);

                                    return a;
                                };

                            var imgs = Enumerable.ToArray(
                                from k in y.Elements()
                                select Build(k.Value)

                            );
                        }
                    );

                }

                else if (Native.Document.location.hash == "#/source")
                {

                    var sln = new TreeNode(() => new VistaTreeNodePage());

                    sln.Text = "Solution";
                    sln.IsExpanded = true;

                    Action<TreeNode> AddReferences =
                        p =>
                        {
                            var r = p.Add("References", new References());

                            r.Add("System", new Assembly());
                            r.Add("System.Core", new Assembly());
                            r.Add("ScriptCoreLib", new Assembly());
                            r.Add("ScriptCoreLib.Ultra", new Assembly());
                            r.Add("ScriptCoreLib.Ultra.Library", new Assembly());
                            r.Add("ScriptCoreLib.Ultra.Controls", new Assembly());
                            r.Add("ScriptCoreLibJava", new Assembly());
                            r.Add("jsc.meta", new Assembly());
                        };

                    Action<TreeNode> AddUltraSource =
                        p =>
                        {
                            var my = p.Add("My.UltraSource");
                            my.Add("Default.htm", new HTMLDocument());
                            my.Add("jsc.png", new ImageFile());

                        };

                    {
                        var p = sln.Add("Visual C# Project", new VisualCSharpProject());


                        AddReferences(p);
                        AddUltraSource(p);



                        p.Add("Application.cs", new VisualCSharpCode());
                        p.Add("WebService.cs", new VisualCSharpCode());
                        p.Add("Program.cs", new VisualCSharpCode());
                    }

                    {
                        var p = sln.Add("Visual Basic Project", new VisualBasicProject());

                        AddReferences(p);
                        AddUltraSource(p);

                        p.Add("Application.vb", new VisualBasicCode());
                        p.Add("WebService.vb", new VisualBasicCode());
                        p.Add("Program.vb", new VisualBasicCode());
                    }


                    {
                        var p = sln.Add("Visual F# Project", new VisualFSharpProject());

                        AddReferences(p);
                        AddUltraSource(p);


                        p.Add("Application.fs", new VisualFSharpCode());
                        p.Add("WebService.fs", new VisualFSharpCode());
                        p.Add("Program.fs", new VisualFSharpCode());
                    }

                    sln.Container.style.Float = IStyle.FloatEnum.right;
                    sln.Container.AttachTo(MyPagesInternal);

                    new SourceEditorHeader().Container.AttachTo(MyPagesInternal);

                    //new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, "Create your own Ultra Application project template").AttachTo(MyPagesInternal);

                    var n = new TextEditor(MyPagesInternal);

                    n.Width = 600;
                    n.Height = 400;

                    //n.InnerHTML = "<p>Create your own <b>Ultra Application</b> Project Template</p>";


                    new DefaultPage1().Container.AttachTo(n.Document.body);

                    var m1 = new SimpleCodeView();

                    m1.Container.AttachTo(MyPagesInternal);
                    //m1.SelectType.onchange +=
                    //    delegate
                    //    {
                    //        m1.TypeName.innerText = m1.SelectType.value;
                    //    };

                    //m1.RunJavaScript.onclick +=
                    //    delegate
                    //    {
                    //        m1.RunJavaScript.style.color = JSColor.Blue;

                    //        try
                    //        {
                    //            Native.Window.eval(m1.Code1.value);

                    //            1000.AtDelay(
                    //                delegate
                    //                {
                    //                    m1.RunJavaScript.style.color = JSColor.None;
                    //                }
                    //            );
                    //        }
                    //        catch
                    //        {
                    //            m1.RunJavaScript.style.color = JSColor.Red;

                    //            1000.AtDelay(
                    //                delegate
                    //                {
                    //                    m1.RunJavaScript.style.color = JSColor.None;
                    //                }
                    //            );
                    //        }
                    //    };
                    new Compilation().GetArchives().SelectMany(k => k.GetAssemblies()).First(k => k.Name == "ScriptCoreLib").WhenReady(
                        ScriptCoreLib =>
                        {
                            // we do not have reflection in place for native wrappers :/

                            m1.SelectEvent.Clear();

                            var Element = ScriptCoreLib.GetTypes().Single(k => k.FullName == "ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement");
                            //var Element = ScriptCoreLib.GetTypes().Single(k => k.HTMLElement == "ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement");

                            Action<CompilationEvent> Add =
                                SourceEvent =>
                                {
                                    m1.SelectEvent.Add(
                                        new IHTMLOption { innerText = SourceEvent.Name }
                                    );
                                };

                            Element.GetEvents().ForEach(Add);

                        }
                    );


                    m1.SelectEvent.onchange +=
                        delegate
                        {
                            m1.EventName.innerText = m1.SelectEvent.value;
                        };




                }
                else if (Native.Document.location.hash == "#/UltraApplicationWithAssets")
                {
                    new UltraApplicationWithAssets().Container.AttachToDocument();
                }
                else
                    if (Native.Document.location.hash == "#/audio")
                    {
                        Action AtTimer = delegate { };

                        (1000 / 15).AtInterval(
                            tt =>
                            {
                                AtTimer();
                            }
                        );

                        new SoundCloudBackground().Container.AttachTo(MyPagesBackground);
                        new SoundCloudHeader().Container.AttachTo(MyPagesInternal);

                        var page = 1;

                        var Tracks = new IHTMLDiv().AttachTo(MyPagesInternal);
                        Tracks.style.margin = "1em";

                        var More = new SoundCloudMore();

                        var AudioLinks = default(AudioLink);

                        var LoadCurrentPage = default(Action);

                        LoadCurrentPage = delegate
                        {
                            var loading = new SoundCloudLoading();

                            loading.Container.AttachTo(Tracks);


                            new UltraWebService().SoundCloudTracksDownload(
                                System.Convert.ToString(page),
                                ee =>
                                {
                                    if (loading != null)
                                    {
                                        loading.Container.Orphanize();
                                        loading = null;
                                    }

                                    var t = new SoundCloudTrack();

                                    t.Content.ApplyToggleConcept(t.HideContent, t.ShowContent).Hide();

                                    t.Title.innerHTML = ee.trackName;
                                    t.Waveform.src = ee.waveformUrl;

                                    t.Audio.src = ee.streamUrl;
                                    t.Audio.autobuffer = true;


                                    AudioLinks = new AudioLink
                                    {
                                        Audio = t.Audio,
                                        Prev = AudioLinks
                                    };

                                    var _AudioLinks = AudioLinks;

                                    if (AudioLinks.Prev != null)
                                        AudioLinks.Prev.Next = AudioLinks;
                                    else
                                        // we are the first  :)
                                        t.Audio.play();

                                    t.MoreButton.onclick +=
                                        delegate
                                        {
                                            t.Audio.pause();

                                            if (_AudioLinks.Next != null)
                                            {
                                                _AudioLinks.Next.Audio.currentTime = 0;
                                                _AudioLinks.Next.Audio.play();

                                                if (_AudioLinks.Next.Next == null)
                                                {
                                                    page++;
                                                    LoadCurrentPage();
                                                }
                                            }
                                        };

                                    t.Audio.onended +=
                                        delegate
                                        {
                                            if (_AudioLinks.Next != null)
                                            {
                                                _AudioLinks.Next.Audio.currentTime = 0;
                                                _AudioLinks.Next.Audio.play();

                                                if (_AudioLinks.Next.Next == null)
                                                {
                                                    page++;
                                                    LoadCurrentPage();
                                                }
                                            }
                                        };

                                    t.Identity.innerText = ee.uid;

                                    t.Play.onclick += eee => { eee.PreventDefault(); t.Audio.play(); };
                                    t.Pause.onclick += eee => { eee.PreventDefault(); t.Audio.pause(); };

                                    t.Title.style.cursor = IStyle.CursorEnum.pointer;
                                    t.Title.onclick += eee =>
                                        {
                                            eee.PreventDefault();

                                            var playing = true;

                                            if (t.Audio.paused)
                                                playing = false;

                                            if (t.Audio.ended)
                                                playing = false;

                                            if (!playing)
                                                t.Audio.play();
                                            else
                                                t.Audio.pause();
                                        };

                                    DoubleAction SetProgress1 = p =>
                                    {

                                        t.Gradient3.style.width = System.Convert.ToInt32(800 * p) + "px";
                                        t.Gradient4.style.width = System.Convert.ToInt32(800 * p) + "px";
                                    };

                                    t.Gradient5.style.Opacity = 0.4;
                                    t.Gradient6.style.Opacity = 0.4;

                                    DoubleAction SetProgress2 = p =>
                                    {

                                        t.Gradient5.style.width = System.Convert.ToInt32(800 * p) + "px";
                                        t.Gradient6.style.width = System.Convert.ToInt32(800 * p) + "px";
                                    };

                                    AtTimer +=
                                        delegate
                                        {
                                            if (t.Audio.duration == 0)
                                            {
                                                t.Play.Hide();
                                                t.Pause.Hide();
                                                return;
                                            }
                                            else
                                            {

                                                var playing = true;

                                                if (t.Audio.paused)
                                                    playing = false;

                                                if (t.Audio.ended)
                                                    playing = false;

                                                if (!playing)
                                                    t.Title.style.color = Color.None;
                                                else
                                                    t.Title.style.color = Color.Blue;

                                                t.Play.Show(!playing);
                                                t.Pause.Show(playing);
                                            }

                                            var p = t.Audio.currentTime / t.Audio.duration;
                                            SetProgress1(p);
                                        };

                                    t.Waveform.onmouseout +=
                                        delegate
                                        {
                                            SetProgress2(0);
                                        };

                                    t.Waveform.onmousemove +=
                                        eee =>
                                        {
                                            SetProgress2(eee.OffsetX / 800.0);
                                        };

                                    t.Waveform.onclick +=
                                        eee =>
                                        {
                                            t.Audio.currentTime = t.Audio.duration * (eee.OffsetX / 800.0);
                                            t.Audio.play();
                                        };

                                    t.Waveform.style.cursor = IStyle.CursorEnum.pointer;

                                    SetProgress1(0);
                                    SetProgress2(0);

                                    t.Container.AttachTo(Tracks);
                                }
                            );


                            10000.AtDelay(
                                delegate
                                {
                                    More.MoreButton.FadeIn(0, 1000, null);
                                }
                            );
                        };


                        More.MoreButton.Hide();
                        More.Container.AttachTo(MyPagesInternal);

                        More.MoreButton.onclick += eee =>
                            {
                                eee.PreventDefault();
                                More.MoreButton.FadeOut(1, 300,
                                    delegate
                                    {
                                        page++;
                                        LoadCurrentPage();
                                    }
                                );
                            };

                        LoadCurrentPage();

                    }
                    else
                    {
                        //new PromotionWebApplication1.HTML.Audio.FromAssets.Track1 { controls = true }.AttachToDocument();
                        //new PromotionWebApplication1.HTML.Audio.FromWeb.Track1 { controls = true, autobuffer = true }.AttachToDocument();

                        var IsAvalonJavaScript = hash == "#/avalon.js";
                        var IsAvalonActionScript = hash == "#/avalon.as";
                        var IsAvalon = IsAvalonActionScript || IsAvalonJavaScript;

                        //if (IsAvalon)
                        //{

                        //{
                        //    var ccc = new IHTMLDiv();

                        //    ccc.style.position = IStyle.PositionEnum.absolute;
                        //    ccc.style.left = "15%";
                        //    ccc.style.right = "15%";
                        //    ccc.style.top = "15%";


                        //    var Now = DateTime.Now;

                        //    var CountDown = new CountDownGadgetConcept(CountDownGadget.Create)
                        //    {
                        //        ShowOnlyDays = true,
                        //        Event = new DateTime(2010, 5, 24, 23, 59, 50),

                        //    };

                        //    CountDown.Element.GadgetContainer.style.color = "#808080";
                        //    CountDown.Element.GadgetContainer.style.textShadow = "#E0E0E0 1px 1px 1px";


                        //    CountDown.Element.GadgetContainer.AttachTo(ccc);
                        //    CountDown.Element.GadgetContainer.FadeIn(3000, 2000, null);

                        //    ccc.AttachToDocument();
                        //}

                        {
                            var ccc = new IHTMLDiv();

                            ccc.style.position = IStyle.PositionEnum.absolute;
                            ccc.style.left = "50%";
                            ccc.style.top = "50%";
                            ccc.style.marginLeft = (-JSCSolutionsNETCarouselCanvas.DefaultWidth / 2) + "px";
                            ccc.style.marginTop = (-JSCSolutionsNETCarouselCanvas.DefaultHeight / 2) + "px";

                            ccc.style.SetSize(JSCSolutionsNETCarouselCanvas.DefaultWidth, JSCSolutionsNETCarouselCanvas.DefaultHeight);

                            ccc.AttachToDocument();

                            if (IsAvalonActionScript)
                            {
                                var alof = new UltraSprite();
                                alof.ToTransparentSprite();
                                alof.AttachSpriteTo(ccc);
                            }
                            else
                            {
                                var alo = new JSCSolutionsNETCarouselCanvas();
                                alo.Container.AttachToContainer(ccc);

                                alo.AtLogoClick +=
                                    delegate
                                    {
                                        //Native.Window.open("http://sourceforge.net/projects/jsc/", "_blank");
                                        Native.Window.open("/download", "_blank");
                                    };

                            }
                        }
                        //}
                        //else
                        //{
                        //    var cc = new HTML.Pages.FromAssets.Controls.Named.CenteredLogo_Kamma();

                        //    cc.Container.AttachToDocument();

                        //    // see: http://en.wikipedia.org/wiki/Perl_control_structures
                        //    // "Unless" == "if not"  ;)

                        //    IsMicrosoftInternetExplorer.YetIfNotThen(cc.TheLogoImage.BeginPulseAnimation).ButIfSoThen(cc.TheLogoImage.HideNowButShowAtDelay);
                        //}

                        var aa = new About();
                        aa.Service.innerText = gapageview;
                        aa.Container.AttachToDocument();

                    }
            }
        #endregion


            Analytics =
                __hash =>
                {
                    var __gahash = Native.Window.escape(__hash);
                    var __gapageview = gapathname + gasearch + __gahash;


                    "UA-13087448-1".ToGoogleAnalyticsTracker(
                        pageTracker =>
                        {
                            pageTracker._setDomainName(".jsc-solutions.net");
                            pageTracker._trackPageview(__gapageview);


                        }
                    );
                };

            Analytics(Native.Document.location.hash);


        }
        // shadow with by http://www.cycloloco.com/shadowmaker/shadowmaker.htm

        public ExampleGalleryWithShadowsPlain()
        {

            var Menu = new IHTMLDiv().AttachToDocument();
            var Title = typeof(ExampleGalleryWithShadows).Name;

            new IHTMLElement(IHTMLElement.HTMLElementEnum.h1,
                Title).AttachTo(Menu);

            new IHTMLDiv("This is a collection of projects developed with jsc. They were coded in c# and translated to javascript with jsc. Click on the pictures to load the applications or on the names to open them in a new window. You might need to press refresh to come back to this index. Enoy! :)").AttachTo(Menu);


            new IHTMLImage("assets/ExampleGallery/PreviewShadow.png").InvokeOnComplete(
                img =>
                {
                    base.Initialize(Menu,
                        (image, href, type, TypeClicked) =>
                        {
                            var div = new IHTMLDiv();

                            div.style.SetSize(120, 90);
                            

                            var shadow = (IHTMLImage)img.cloneNode(false);

                            shadow.AttachTo(div);
                            shadow.style.SetLocation(0, 0);
                            shadow.style.zIndex = 0;


                            image.AttachTo(div);
                            image.style.SetSize(120, 90);




                            div.style.position = IStyle.PositionEnum.relative;
                            div.style.marginTop = "1em";
                            div.style.marginLeft = "1em";
                            div.style.marginRight = "12em";
                            div.style.marginBottom = "1em";
                            div.style.Float = IStyle.FloatEnum.left;
                            //div.style.clear =  "both";


                            #region name
                            var name = new IHTMLAnchor(href, type.Name);

                            name.style.position = IStyle.PositionEnum.absolute;
                            name.className = "PreviewName";
                            name.style.color = Color.Black;
                            name.style.textDecoration = "none";

                            name.target = "_blank";
                            name.style.left = "130px";
                            name.AttachTo(div);
                            #endregion

                            var a = new IHTMLAnchor(href, "");

                            a.target = "_blank";
                            a.style.display = IStyle.DisplayEnum.block;

               
                            image.style.border = "0px solid black";
                            image.style.zIndex = 2;
                            image.AttachTo(a);

                            a.className = "Preview";
                            a.AttachTo(div);
                            a.style.zIndex = 2;
                            a.style.SetLocation(0, 0, 120, 90);


                            a.onclick +=
                                ev =>
                                {
                                    ev.PreventDefault();

                                    Native.Document.body.style.backgroundImage = "";

                                    TypeClicked(type);
                                };

                            return div;
                        }
                   );
                });
        }
        /// <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 fName = new IHTMLInput().AttachToDocument();
            var lName = new IHTMLInput().AttachToDocument();
            var submit = new IHTMLButton { innerHTML = "Submit"}.AttachToDocument();
            var a = new IHTMLAnchor().AttachToDocument();
            a.style.visibility = IStyle.VisibilityEnum.visible;


            Action<string> startSession = async user => 
            {
                while (true)
                {
                    var res = await IsNfcApproved(user);
                    if (res != null)
                    {
                        if (!res.IsCard)
                        {
                            lName.style.visibility = IStyle.VisibilityEnum.visible;
                            fName.style.visibility = IStyle.VisibilityEnum.visible;
                            submit.style.visibility = IStyle.VisibilityEnum.visible;
                            a.style.visibility = IStyle.VisibilityEnum.hidden;
                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Result is NULL");
                    }
                    //Thread.Sleep(1000);
                    await 1000;
                }
            };

            submit.onclick += async delegate
            {

                var user = fName.value + lName.value;
                Console.WriteLine(user);

                //await InsertUserAuth(user,false);

                var counter = 0;

                while (true)
                {
                    if (counter <= 10)
                    {
                        lName.style.visibility = IStyle.VisibilityEnum.hidden;
                        fName.style.visibility = IStyle.VisibilityEnum.hidden;
                        submit.style.visibility = IStyle.VisibilityEnum.hidden;
                        a.style.visibility = IStyle.VisibilityEnum.visible;
                        a.innerHTML = "Waiting for NFC " + counter;

                        var res = await IsNfcApproved(user);
                        if (res != null)
                        {
                            if (res.IsCard)
                            {
                                a.innerHTML = "Welcome! " + fName + " " + lName;
                                startSession(user);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Result is NULL");
                        }
                        counter++;
                    }
                    else
                    {
                        lName.style.visibility = IStyle.VisibilityEnum.visible;
                        fName.style.visibility = IStyle.VisibilityEnum.visible;
                        submit.style.visibility = IStyle.VisibilityEnum.visible;
                        a.style.visibility = IStyle.VisibilityEnum.hidden;
                        break;
                    }
                    //Thread.Sleep(1000);
                    await 1000;
                }
            };


        }
        private static IHTMLDiv AddNamespace(IHTMLDiv parent, IHTMLDiv NextNamespaceOrDefault, string Namespace, Action<string> UpdateLocation)
        {
            var div = new IHTMLDiv();

            if (NextNamespaceOrDefault == null)
                div.AttachTo(parent);
            else
                NextNamespaceOrDefault.insertPreviousSibling(div);

            div.style.marginTop = "0.1em";
            div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
            div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


            var i = new Namespace().AttachTo(div);

            i.style.verticalAlign = "middle";
            i.style.marginRight = "0.5em";

            if (Namespace == "")
                Namespace = "<Module>";

            var s = new IHTMLAnchor { innerText = Namespace }.AttachTo(div);


            s.href = "#";
            s.style.textDecoration = "none";
            s.style.color = JSColor.System.WindowText;

            Action onclick = delegate
            {

            };

            s.onclick +=
                e =>
                {
                    e.PreventDefault();

                    s.focus();

                    UpdateLocation(Namespace);

                    onclick();
                };

            s.onfocus +=
                delegate
                {

                    s.style.backgroundColor = JSColor.System.Highlight;
                    s.style.color = JSColor.System.HighlightText;
                };

            s.onblur +=
                delegate
                {

                    s.style.backgroundColor = JSColor.None;
                    s.style.color = JSColor.System.WindowText;
                };

            var children = new IHTMLDiv().AttachTo(div);

            children.style.paddingLeft = "1em";
            children.Hide();


            var NextClickHide = default(Action);
            var NextClickShow = default(Action);

            NextClickHide =
                delegate
                {
                    children.Hide();

                    onclick = NextClickShow;
                };

            NextClickShow =
                delegate
                {
                    children.Show();

                    onclick = NextClickHide;
                };


            onclick = NextClickShow;

            return children;
        }
        public ScheduleController(Action<td, DateTime> ApplyStyle, DateTime date)
        {
            this.date = date;
            this.ApplyStyle = ApplyStyle;

            TotalPersentageStates = new[]
                {
                    new ToggleButtonState {  Percentage = 2 },
                    new ToggleButtonState {  Percentage = 2.5 },
                    new ToggleButtonState {  Percentage = 3 },
                    new ToggleButtonState {  Percentage = 3.5 },
                    new ToggleButtonState {  Percentage = 4 },
                    new ToggleButtonState {  Percentage = 0 },
                    new ToggleButtonState {  Percentage = 1 },
                    new ToggleButtonState {  Percentage = 1.5 },
                };

            WorkerStates = new[]
                {
                    new ToggleButtonState { Text = "·", Hours = 11.5, Percentage = 1 },
                    new ToggleButtonState { Text = "P", Hours = 0, Percentage = 0 },
                    new ToggleButtonState { Text = "17", Hours = 17 - 9.5, Percentage = 0.5 },
                    new ToggleButtonState { Text = "13", Hours = 21 - 13, Percentage = 0.5 },
                };

            days = date.DaysInMonth();

            this.ScheduleTable.style.border = "1px solid gray";
            this.ScheduleTable.border = 0;
            this.ScheduleTable.cellSpacing = 0;
            this.ScheduleTable.cellPadding = 0;

            this.Body = this.ScheduleTable.AddBody();







            this.RowOfDateNumbers = this.Body.AddRow();
            this.RowOfDayNames = this.Body.AddRow();

            //Console.WriteLine(DateTime.Now + " step 2");

            BuildTop();

            //Console.WriteLine(DateTime.Now + " step 3");

            BuildBottom();

            //Console.WriteLine(DateTime.Now + " step 4");


            Control.style.padding = "2em";

            Header = new IHTMLElement(IHTMLElement.HTMLElementEnum.h2);
            Header.innerText = "work schedule".Localize();

            var h4 = new IHTMLElement(IHTMLElement.HTMLElementEnum.h4);
            h4.style.Float = IStyle.FloatEnum.right;
            h4.innerText = date.Year + " / " + date.Month;

            var br = new IHTMLBreak();
            br.style.clear = "both";

            var close = new IHTMLAnchor("close!".Localize());
            close.className = "noprint";

            close.onclick +=
                ev =>
                {
                    ev.PreventDefault();

                    this.Control.Dispose();
                };

            close.style.Float = IStyle.FloatEnum.right;

            var c = new IHTMLElement(IHTMLElement.HTMLElementEnum.center, close, Header, h4, br, this.ScheduleTable);

            c.AttachTo(this.Control);


        }
        private static void AddTypeProperty(
    IHTMLDiv parent,
    CompilationProperty type,
    Action<string> UpdateLocation
    )
        {
            var div = new IHTMLDiv().AttachTo(parent);

            div.style.marginTop = "0.1em";
            div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
            div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


            var i = new PublicProperty().AttachTo(div);

            i.style.verticalAlign = "middle";
            i.style.marginRight = "0.5em";

            var s = new IHTMLAnchor { innerText = type.Name }.AttachTo(div);


            s.href = "#";
            s.style.textDecoration = "none";
            s.style.color = JSColor.System.WindowText;

            Action onclick = delegate
            {

            };

            s.onclick +=
                e =>
                {
                    e.PreventDefault();

                    s.focus();

                    UpdateLocation(type.Name);

                    onclick();
                };

            s.onfocus +=
                delegate
                {

                    s.style.backgroundColor = JSColor.System.Highlight;
                    s.style.color = JSColor.System.HighlightText;
                };

            s.onblur +=
                delegate
                {

                    s.style.backgroundColor = JSColor.None;
                    s.style.color = JSColor.System.WindowText;
                };


            onclick =
                delegate
                {
                    var children = new IHTMLDiv().AttachTo(div);

                    children.style.paddingLeft = "2em";

                    AddTypeMethod(children, type.GetGetMethod(), UpdateLocation);
                    AddTypeMethod(children, type.GetSetMethod(), UpdateLocation);


                    //a.GetTypes().ForEach(
                    //    (Current, Next) =>
                    //    {
                    //        AddType(GetNamespaceContainer(children, Current), Current, UpdateLocation);

                    //        ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                    //            50,
                    //            Next
                    //        );
                    //    }
                    //);


                    var NextClickHide = default(Action);
                    var NextClickShow = default(Action);

                    NextClickHide =
                        delegate
                        {
                            children.Hide();

                            onclick = NextClickShow;
                        };

                    NextClickShow =
                        delegate
                        {
                            children.Show();

                            onclick = NextClickHide;
                        };


                    onclick = NextClickHide;
                };
        }
        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public MonthSchedule()
        {
            //Native.Window.alert( "cookie:" + Native.Document.cookie);

            //var c = new Cookie("xx");

            //c.Value = "hello world";

            //Native.Document.cookie = "bandwidth=4;path=/;expires=Tue, 2 Jun 2015 00:00:00 UTC;";


            //Native.Window.alert( "cookie:" + Native.Document.cookie);


            IStyleSheet.Default.AddRule(".hover", "background-color: blue !important", 0);
            IStyleSheet.Default.AddRule(".hover", "color: white !important", 0);
            IStyleSheet.Default.AddRule("a", "text-decoration: none;", 0);
            IStyleSheet.Default.AddRule(".language_link", "margin: 1em;", 0);
            IStyleSheet.Default.AddRule(".about",
                r =>
                {
                    r.style.padding = "1em";
                    r.style.margin = "1em";
                    r.style.border = "1px dashed gray";

                }
            );

            var langbar = "div".AsElement().AttachTo(Native.Document.body);
            langbar.style.Float = IStyle.FloatEnum.right;



            #region SpawnLanguageLink
            Action<string> SpawnLanguageLink =
                   lang_value =>
                       new IHTMLAnchor(lang_value)
                       {
                           className = "language_link"
                       }.AttachTo(langbar).onclick +=
                       ev =>
                       {
                           ev.PreventDefault();

                           var dict = Native.Document.location.ArgumentsToDictonary();

                           dict["lang"] = lang_value;

                           Native.Document.location.DictonaryToArguments(dict);

                       };
            #endregion


            SpawnLanguageLink("eng");
            SpawnLanguageLink("est");
            SpawnLanguageLink("de");


            var loading = "div".AsElement().WithText("Loading...").AttachTo(Native.Document.body);

            Locals.Default.WhenDownloadComplete(
                delegate
                {

                    int stage = 0;

                    try
                    {
                        stage = 100;

                        var about_text = "about".Localize();

                        stage = 200;

                        var about = new IHTMLAnchor(about_text)
                            {
                                className = "language_link"
                            }.AttachTo(langbar);


                        stage = 3;
                        var about_div = "div".AsElement().AttachTo(Native.Document.body);
                        stage = 4;
                        about_div.className = "about";
                        stage = 5;

                        about_div.Show(!Storage.About);
                        stage = 6;
                        about_div.innerText = "This Application lets you manage the workschedule of your workers. You can add or remove workers on the left, specify how many workers must be present at any given day at the bottom, which days are free days, when to come later and when to go earlier. It also calculates total workhours on the right. You can use your mousewheel or just click on the buttons.".Localize();
                        stage = 7;
                        about.onclick +=
                            ev =>
                            {
                                ev.PreventDefault();

                                Storage.About = !about_div.ToggleVisible();
                            };
                        stage = 7;
                        SpawnDefaultView();
                        stage = 8;
                        loading.FadeOut();
                        stage = 9;
                    }
                    catch (Exception exc)
                    {
                        loading.innerText = "WhenDownloadComplete failed: {" + exc.Message + "}; stage: " + stage;
                        loading.style.color = Color.Red;
                    }
                }
            );

            /*
            var print = new IStyleSheet();

            print.Owner.media = "print";
            print.AddRule(".noprint", "display: none;", 0);
            */





        }
        private static void SpawnDefaultView()
        {
            // http://simiandesign.com/2006/04/18/superscripts-subscripts-css-and-the-line-height/

            #region ApplyStyle
            Action<td, DateTime> ApplyStyle = (col, x) =>
            {

                // users will want to notice weekends

                if (x.IsFirstDayOfMonth())
                    col.style.borderLeft = "1px solid gray";

                if (x.DayOfWeek == DayOfWeek.Saturday)
                {
                    col.style.borderLeft = "1px solid gray";
                    col.style.backgroundColor = "#efefef";
                }

                if (x.DayOfWeek == DayOfWeek.Sunday)
                {
                    col.style.borderRight = "1px solid gray";
                    col.style.backgroundColor = "#efefef";
                }

                if (x.IsLastDayOfMonth())
                    col.style.borderRight = "1px solid gray";

                col.style.width = "2em";
                col.style.height = "2em";
                col.style.textAlign = IStyle.TextAlignEnum.center;
            };
            #endregion

            //var sch = new ScheduleController(ApplyStyle);


            var DateSelectionChanged = default(Action);

            var date = DateTime.Now;

            #region spinners

            var YearSpinner = new SpinnerSpan<int>.SpinnerSpanSettings
            {
                Value = date.Year,
                GetText = i => "year".Localize() + ": " + i,
                GetNext = date.Year.MakeNextFunc(3),
                GetPrevious = date.Year.MakePreviousFunc(3),
                Changed =
                                    delegate
                                    {
                                        if (DateSelectionChanged != null) DateSelectionChanged();
                                    }

            }.Create();

            var MonthSpinner = new SpinnerSpan<int>.SpinnerSpanSettings
            {
                Value = date.Month,
                GetText = i => "month".Localize() + ": " + i,
                GetNext = i =>
                {
                    if (i == 12)
                    {
                        YearSpinner.Silent = true;
                        YearSpinner.GoNext();
                        YearSpinner.Silent = false;

                        return 1;
                    }

                    return i++;
                },
                GetPrevious = i =>
                {
                    if (i == 1)
                    {
                        YearSpinner.Silent = true;
                        YearSpinner.GoPrevious();
                        YearSpinner.Silent = false;
                        return 12;
                    }

                    return i--;
                },
                Changed =
                    delegate
                    {
                        if (DateSelectionChanged != null) DateSelectionChanged();
                    }
            }.Create();

            YearSpinner.Control.AttachTo(Native.Document.body);
            MonthSpinner.Control.AttachTo(Native.Document.body);

            var _DefaultWorkers = new[] { "Worker1", "Worker2" };

            if (Storage.Workers == null)
            {
                // safari wont save cookies when document isnt from a webserver
                Storage.Workers = _DefaultWorkers;


                //if (Storage.Workers == null)
                //    throw new Exception( "Cookies are not working!!");
                //if (Storage.Workers.Length != _new.Length)
                //    throw new Exception( "Cookies are not working!");
            }


            var Make = new IHTMLAnchor("make new work schedule".Localize());



            Action MakeNewSchedule =
                delegate
                {
                    int stage = 1;

                    try
                    {
                        stage = 2;
                        var schnew = new ScheduleController(ApplyStyle, new DateTime(YearSpinner.Value, MonthSpinner.Value, 1));

                        stage = 3;
                        schnew.Control.AttachTo(Native.Document.body);
                        stage = 4;
                        schnew.WorkersChanged +=
                            delegate
                            {
                                Storage.Workers = schnew.Workers.Where(w => !w.Name.IsNullOrEmpty()).Select(w => w.Name).ToArray();
                            };
                        stage = 5;

                        // compiler bug: passing params attribute when they are not first should use local variable!

                        var _Workers = Storage.Workers;

                        if (_Workers == null)
                            _Workers = _DefaultWorkers;

                        _Workers = _Workers.Concat(new[] { "" }).ToArray();

                        stage = 6;

                        schnew.LazyLoad(
                            () => { }, _Workers
                        );
                        stage = 7;
                    }
                    catch (Exception exc)
                    {
                        throw new Exception("MakeNewSchedule failed: {" + exc.Message + "}; stage: " + stage);
                    }
                };

            Make.AttachTo(Native.Document.body).onclick +=
                ev =>
                {
                    ev.PreventDefault();

                    MakeNewSchedule();
                };

            #endregion

            DateSelectionChanged =
                delegate
                {
                    // compiler bug: opcode strobj not supported - cannot store struct to field directly.

                    //var newdate = new DateTime(YearSpinner.Value, MonthSpinner.Value, 1);

                    //date = newdate;
                    //days = newdays;

                };

            //sch.Control.AttachTo(Native.Document.body);



            MakeNewSchedule();
        }
        // X:\jsc.svn\examples\javascript\Test\TestPackageAsApplication\TestPackageAsApplication\Application.cs

        /// <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)
        {
            Console.WriteLine("before");
            {
                var c = new CanvasRenderingContext2D(256, 256);


                var bytes = new byte[256 * 256 * 4];

                for (int x = 0; x < 256; x++)
                {
                    for (int y = 0; y < 256; y++)
                    {
                        bytes[x * 4 + 0 + 256 * 4 * y] = (byte)x;
                        bytes[x * 4 + 1 + 256 * 4 * y] = (byte)y;
                        bytes[x * 4 + 2 + 256 * 4 * y] = 0xff;
                        bytes[x * 4 + 3 + 256 * 4 * y] = 0xcf;
                    }


                }

                var i = c.getImageData();

                i.data.set(bytes, 0);

                c.putImageData(i, 0, 0, 0, 0, 256, 256);

                c.canvas.AttachToDocument();

            }


            {
                var bytes = new byte[256 * 256 * 4];

                for (int x = 0; x < 256; x++)
                {
                    for (int y = 0; y < 256; y++)
                    {
                        bytes[x * 4 + 0 + 256 * 4 * y] = 0;
                        bytes[x * 4 + 1 + 256 * 4 * y] = 0;
                        bytes[x * 4 + 2 + 256 * 4 * y] = 0;

                        // alpha?
                        bytes[x * 4 + 3 + 256 * 4 * y] = (byte)x;
                    }


                }

                // 1824 of 65536
                // 0.02783203125
                // 262144

                var slider = new IHTMLInput
                {

                    type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range,
                    max = 256 * 256
                }.AttachToDocument();


                new IHTMLPre { 
                    () =>
                    new { 
                        bytes.Length,
                        md5 = bytes.ToMD5Bytes().ToHexString(), 
                        slider.valueAsNumber,
                        u4 = new [] { 
                            bytes[slider.valueAsNumber * 4 + 0],
                            bytes[slider.valueAsNumber * 4 +1],
                            bytes[slider.valueAsNumber * 4 +2],
                            bytes[slider.valueAsNumber * 4 +3]
                        }.ToHexString() }
                }.AttachToDocument();

                var c = new CanvasRenderingContext2D(256, 256) { bytes = bytes };

                c.canvas.AttachToDocument();

                // https://code.google.com/p/chromium/issues/detail?id=312187
                // save for disk saving
                // https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement
                var csrc = c.canvas.toDataURL("image/png");
                var csrci = new IHTMLImage { src = csrc }.AttachToDocument();

                // do the reverse
                var z = new CanvasRenderingContext2D(256, 256);
                z.drawImage(csrci, 0, 0, 256, 256);
                z.canvas.AttachToDocument();

                // whats the bytes?

                var zbytes = z.bytes;

                new IHTMLPre { 
                    () =>
                    new {
                        zbytes.Length,
                        
                        md5 = zbytes.ToMD5Bytes().ToHexString() ,
                        slider.valueAsNumber,
                        u4 = new [] { 
                            zbytes[slider.valueAsNumber * 4 + 0],
                            zbytes[slider.valueAsNumber * 4 +1],
                            zbytes[slider.valueAsNumber * 4 +2],
                            zbytes[slider.valueAsNumber * 4 +3]
                        }.ToHexString() 
                    }
                }.AttachToDocument();


                // 00ff80cf vs 00ff7fcf
            }
            Console.WriteLine("after");


            new IHTMLButton { "make me the link " + new { Native.document.location.protocol } }.AttachToDocument().WhenClicked(
               makelink =>
               {
                   makelink.disabled = true;



                   #region PackageAsApplication
                   Action<IHTMLScript, XElement, Action<string>> PackageAsApplication =
                       (source0, xml, yield) =>
                       {
                           new IXMLHttpRequest(
                               ScriptCoreLib.Shared.HTTPMethodEnum.GET,
                               source0.src,
                               handler: (IXMLHttpRequest r) =>
                               {
                                   // store hash
                                   xml.Add(new XElement("link", new XAttribute("rel", "location"), new XAttribute("href", Native.Document.location.hash)));


                                   xml.Add(
                                       new XElement("script",
                                           "/* source */"
                                       )
                                   );

                                   var data = "";


                                   Action later = delegate
                                   {

                                       data = data.Replace("/* source */", r.responseText);

                                   };


                                   //Native.Document.getElementsByTagName("link").AsEnumerable().ToList().ForEach(

                                   xml.Elements("link").ToList().ForEach(
                                       (XElement link, Action next) =>
                                       {
                                           #region style
                                           var rel = link.Attribute("rel");
                                           if (rel.Value != "stylesheet")
                                           {
                                               next();
                                               return;
                                           }

                                           var href = link.Attribute("href");

                                           var placeholder = "/* " + href.Value + " */";

                                           //page.DragHTM.innerText += " " + placeholder;


                                           xml.Add(new XElement("style", placeholder));

                                           new IXMLHttpRequest(ScriptCoreLib.Shared.HTTPMethodEnum.GET, href.Value,
                                               rr =>
                                               {

                                                   later += delegate
                                                   {


                                                       data = data.Replace(placeholder, rr.responseText);

                                                   };

                                                   Console.WriteLine("link Remove");
                                                   link.Remove();

                                                   next();
                                               }
                                           );

                                           #endregion
                                       }
                                   )(
                                       delegate
                                       {


                                           data = xml.ToString();
                                           Console.WriteLine("data: " + data);
                                           later();

                                           yield(data);
                                       }
                                   );
                               }
                           );

                       };
                   #endregion

                   // XMLHttpRequest cannot load file:///D:/view-source. Cross origin requests are only supported for HTTP. 



                   Console.WriteLine("before PackageAsApplication");
                   PackageAsApplication(

                       // how would we know our current source location?
                       new IHTMLScript { src = "view-source" },
                       XElement.Parse(AppSource.Text),
                       async data =>
                       {
                           Console.WriteLine("enter PackageAsApplication");
                           var bytes0 = Encoding.UTF8.GetBytes(data);
                           var w0 = (int)Math.Ceiling(Math.Sqrt(bytes0.Length));

                           var padding0 = (w0 * w0) - bytes0.Length;

                           // { Length = 2072331, padding0 = 1269 }
                           new IHTMLPre {
                               new { 
                                   bytes0.Length, 
                                   padding0
                               }
                           }.AttachToDocument();


                           var bytes = Encoding.UTF8.GetBytes(
                               data

                               +
                               Encoding.UTF8.GetString(new byte[padding0])

                               // too slow?
                               //+ new string(' ', padding0)
                               );

                           //var bytes = Encoding.ASCII.GetBytes(data);

                           // { Length = 2019412 }


                           // why wont intellisense work like excel, debugger
                           // and tell me the anwser without running
                           // the other option is to step in via F11

                           //  Math.Sqrt(2019412) 1421.0601676213432

                           var w = (int)Math.Ceiling(Math.Sqrt(bytes.Length));

                           //{ Length = 2049266, w = 1432 }
                           //{ Length = 8202496 }

                           new IHTMLPre {
                               new { 
                                   bytes.Length, 
                                   w, 
                                   
                                 u8 = new [] { 
                                        bytes[0 * 4 + 0],
                                        bytes[0 * 4 +1],
                                        bytes[0 * 4 +2],
                                        bytes[0 * 4 +3],

                                        bytes[1 * 4 + 0],
                                        bytes[1 * 4 +1],
                                        bytes[1 * 4 +2],
                                        bytes[1 * 4 +3]
                                    }.ToHexString() ,

                                   md5 = bytes.ToMD5Bytes().ToHexString() }
                           }.AttachToDocument();

                           // 77,828 bytes)
                           var wbyteswatch = Stopwatch.StartNew();

                           // { Length = 2069090, w = 1439, u8 = 3c68746d6c3e0a20, md5 = 4fa4af629b63b267da4d4a142c9cb171 }
                           // { Length = 2070721, md5 = 0186a2c2d01257cf4ba6a5524ec4743d, u8 = 3c68746d6c3e0a20 }


                           #region encode
                           var wbytes = await Task.Factory.StartNew(
                               new { bytes, w },
                               scope =>
                               {
                                   // Native.Console.WriteLine += ?

                                   // { Length = 2053956, u4 = 3c68746d } 

                                   Console.WriteLine(
                                    new
                                    {
                                        scope.bytes.Length,

                                        u4 = new[] { 
                                            scope.bytes[0 * 4 + 0],
                                            scope.bytes[0 * 4 +1],
                                            scope.bytes[0 * 4 +2],
                                            scope.bytes[0 * 4 +3]
                                        }.ToHexString()
                                    }
                                   );


                                   // Uncaught Error: InvalidOperationException: { MethodToken = dAAABv_a4OTKgLfLC20SaJA } function is not available at { href =
                                   var ww = scope.w;

                                   var wwbytes = new byte[ww * ww * 4];
                                   var wi = 0;

                                   for (int i = 0; i < wwbytes.Length; i += 4)
                                   {
                                       //bytes[x * 4 + 0 + 256 * 4 * y] = 0;
                                       //bytes[x * 4 + 1 + 256 * 4 * y] = 0;
                                       //bytes[x * 4 + 2 + 256 * 4 * y] = 0;

                                       // can we get a red picture?
                                       // unless we alpha everything out!
                                       // 692 KB!
                                       //wwbytes[i + 0] = (byte)(0xff);
                                       wwbytes[i + 0] = 0;
                                       wwbytes[i + 1] = 0;
                                       wwbytes[i + 2] = 0;
                                       // alpha
                                       wwbytes[i + 3] =

                                           // the bytes histogram seems
                                           // to be in the middle?
                                           scope.bytes[wi];

                                       // reverse alpha?
                                       //(byte)(255 - scope.bytes[wi]);
                                       //(byte)~scope.bytes[wi];

                                       wi++;
                                   }



                                   return wwbytes;
                               }
                           );
                           #endregion


                           //{ Length = 2071072, w = 1440, u4 = 3c68746d, md5 = 5c45e67b07d9045882dfe305e9bf23fd }
                           //{ Length = 8294400, ElapsedMilliseconds = 9971, u8 = ff00003cff00003c }

                           new IHTMLPre {
                               new { 
                                   wbytes.Length, wbyteswatch.ElapsedMilliseconds,
                                    u8 = new [] { 
                                        wbytes[0 * 4 + 0],
                                        wbytes[0 * 4 +1],
                                        wbytes[0 * 4 +2],
                                        wbytes[0 * 4 +3],

                                        wbytes[1 * 4 + 0],
                                        wbytes[1 * 4 +1],
                                        wbytes[1 * 4 +2],
                                        wbytes[1 * 4 +3]
                                    }.ToHexString() 
                               }
                           }.AttachToDocument();


                           new IHTMLPre {
                               new { wbytes.Length, wbyteswatch.ElapsedMilliseconds, md5 = wbytes.ToMD5Bytes().ToHexString() }
                           }.AttachToDocument();

                           // { Length = 8236900, ElapsedMilliseconds = 2476, md5 = 166c1b692fad548789a12a3ae5f0a7ae }

                           var c = new CanvasRenderingContext2D(w, w) { bytes = wbytes };

                           // this would touch our precious alpha channel!

                           //c.fillText(
                           //    "rgb channel for preview, while alpha channel has the data of "
                           //    + new { bytes.Length },
                           //    64, 64, c.canvas.width
                           //    );


                           c.canvas.style.backgroundColor = "yellow";
                           c.canvas.style.border = "1px solid red";
                           c.canvas.AttachToDocument();

                           // https://code.google.com/p/chromium/issues/detail?id=312187
                           // save for disk saving
                           // https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement
                           var csrc = c.canvas.toDataURL("image/png");


                           // this wont help at all
                           // https://bugzilla.mozilla.org/show_bug.cgi?id=676619

                           var csrca = new IHTMLAnchor { download = "view-source.png", href = csrc, title = "view-source", innerText = "do not drag, click to download view-source.png" }.AttachToDocument();
                           // http://caniuse.com/download


                           var csrci = new IHTMLImage { src = csrc }.AttachToDocument();
                           csrci.style.backgroundColor = "yellow";
                           csrci.style.border = "1px solid red";

                           // um. time to reverse?


                           // do the reverse
                           var z = new CanvasRenderingContext2D(w, w);
                           z.drawImage(csrci, 0, 0, w, w);
                           z.canvas.AttachToDocument();

                           // whats the bytes?

                           var zbytes = z.bytes;

                           new IHTMLPre { 
                                new {
                                    zbytes.Length,
                        
                                    md5 = zbytes.ToMD5Bytes().ToHexString() ,
                                    u8 = new [] { 
                                        zbytes[0 * 4 + 0],
                                        zbytes[0 * 4 +1],
                                        zbytes[0 * 4 +2],
                                        zbytes[0 * 4 +3],

                                        zbytes[1 * 4 + 0],
                                        zbytes[1 * 4 +1],
                                        zbytes[1 * 4 +2],
                                        zbytes[1 * 4 +3]
                                    }.ToHexString() 
                                }
                            }.AttachToDocument();

                           // { Length = 8236900, md5 = 166c1b692fad548789a12a3ae5f0a7ae, u4 = 0000003c }

                           #region decode
                           var decodebytes = await Task.Factory.StartNew(
                               new { zbytes },
                               scope =>
                               {
                                   // Native.Console.WriteLine += ?

                                   // { Length = 2053956, u4 = 3c68746d } 

                                   Console.WriteLine(
                                    new
                                    {
                                        scope.zbytes.Length,

                                        u4 = new[] { 
                                            scope.zbytes[0 * 4 + 0],
                                            scope.zbytes[0 * 4 +1],
                                            scope.zbytes[0 * 4 +2],
                                            scope.zbytes[0 * 4 +3]
                                        }.ToHexString()
                                    }
                                   );


                                   // Uncaught Error: InvalidOperationException: { MethodToken = dAAABv_a4OTKgLfLC20SaJA } function is not available at { href =

                                   var wwbytes = new byte[scope.zbytes.Length / 4];
                                   var wi = 0;

                                   for (int i = 0; i < scope.zbytes.Length; i += 4)
                                   {
                                       // that be the red
                                       //wwbytes[wi] = scope.zbytes[i];

                                       // bet we need alpha
                                       wwbytes[wi] = scope.zbytes[i + 3];
                                       wi++;
                                   }



                                   return wwbytes;
                               }
                           );
                           #endregion

                           //{ Length = 8282884, md5 = ece6f7e935f0b424082445b273b8ed65, u4 = ff00003c }
                           //{ Length = 2070721, md5 = 47f7ec04a0b7cfc27e706583cc1a9bf7, u4 = 3c3c3c3c }

                           new IHTMLPre { 
                                new {
                                    decodebytes.Length,
                        
                                    md5 = decodebytes.ToMD5Bytes().ToHexString() ,
                                    u8 = new [] { 
                                        decodebytes[0 * 4 + 0],
                                        decodebytes[0 * 4 +1],
                                        decodebytes[0 * 4 +2],
                                        decodebytes[0 * 4 +3],

                                        decodebytes[1 * 4 + 0],
                                        decodebytes[1 * 4 +1],
                                        decodebytes[1 * 4 +2],
                                        decodebytes[1 * 4 +3]
                                    }.ToHexString() 
                                }
                            }.AttachToDocument();
                       }
                  );


               }
            );

        }
Beispiel #21
0
        //[Obsolete("experimental, what about reentry? signal the previous via scope?")]
        public static IHTMLAnchor Historic(
            this IHTMLAnchor e,
            Action <HistoryScope <object> > yield,
            bool replace = false
            )
        {
            // X:\jsc.svn\examples\javascript\async\AsyncHistoricActivities\AsyncHistoricActivities\Application.cs
            //X:\jsc.svn\examples\javascript\Test\TestHistoricWithBaseElement\TestHistoricWithBaseElement\Application.cs
            // X:\jsc.svn\examples\javascript\test\TestHistoryForwardEvent\TestHistoryForwardEvent\Application.cs

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201312/20131222-form
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517

            //var url = "/#/" + e.innerText.Replace(" ", "+").ToLower();


            // Historic: { domain = 192.168.1.75, baseURI = http://otherhost/, href = http://192.168.1.75:10007/ }


            // http://otherhost/http://192.168.1.75:24121/#/click+to+enter+a+new+historic+state
            var url = "";

            var xlocation = Native.document.location.href.TakeUntilIfAny("#");
            var xbaseURI  = Native.document.baseURI.TakeUntilIfAny("#");

            Console.WriteLine(
                "enter Historic: " + new
            {
                Native.document.domain,
                Native.document.baseURI,

                location = Native.document.location.href,
                xlocation,
                href = e.href
            }
                );


            // http://otherhost/#/click+to+enter+a+new+historic+state

            if (string.IsNullOrEmpty(e.href))
            {
                //0:9ms HistoryExtensions enter view-source:35994
                //0:15ms Foo.Historic view-source:35994
                //0:16ms enter Historic: { domain = 192.168.1.91,
                // baseURI = http://192.168.1.91:20443/#/bar,
                //location = http://192.168.1.91:20443/#/bar, href = http://192.168.1.91:20443/#/foo } view-source:35994

                //0:17ms update { href = http://192.168.1.91:20443/#/foo, url = http://192.168.1.91:20443/#/bar }

                var z = e.innerText;

                // http://192.168.1.75:22130/#/click+to+enter+a+new+historic+state

                url = xlocation + "#/" + z.Replace(" ", "+").ToLower().Trim();

                // enable new tab click
                // start from root

                //Console.WriteLine("update " + new { e.href, url, e.innerText });
                e.href = url;
            }

            // X:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Ultra\WebService\InternalGlobalExtensions.cs
            else
            {
                // reusing jsc server redirector
                // Historic enter. activate? { url = #/http://192.168.43.252:19360, length = 1, hash = #/fake-right }
                //Console.WriteLine(
                //    new { e.href, location = Native.document.location.href }
                //);

                // will this support offline reload?
                // { href = http://192.168.43.252:22188/#/zTop, location = http://192.168.43.252:22188/ }



                //:20ms enter Historic: { domain = 192.168.1.91, baseURI = http://192.168.1.91:6393/#/bar, location = http://192.168.1.91:6393/#/bar, xlocation = http://192.168.1.91:6393/, href = http://192.168.1.91:6393/#/bar } view-source:35994
                //0:20ms update { href = http://192.168.1.91:6393/#/bar, url = http://192.168.1.91:6393/ }

                // http://otherhost/#/pre
                url = xlocation
                      + e.href.SkipUntilLastOrEmpty(xbaseURI);

                //Console.WriteLine("update " + new { e.href, url });
                e.href = url;
            }

            url = url.SkipUntilBeforeOrEmpty("#");

            e.title = url;

            //Console.WriteLine("Historic enter. activate? " + new { url, Native.window.history.length, Native.document.location.hash });


            #region onclick
            e.onclick +=
                ev =>
            {
                //Console.WriteLine("onclick: " + new { e.href, ev.MouseButton, IEvent.MouseButtonEnum.Left });

                if (ev.MouseButton == IEvent.MouseButtonEnum.Left)
                {
                    // tested by
                    // X:\jsc.svn\examples\javascript\Test\TestImplicitTimelineRecordingEvents\TestImplicitTimelineRecordingEvents\Application.cs

                    Console.WriteLine("event: onclick " + new { e.href, ev.MouseButton });

                    ev.preventDefault();
                    ev.stopPropagation();


                    var xreplace = replace;

                    // reentry shall reload?
                    if (Native.document.location.hash == url)
                    {
                        xreplace = true;
                    }


                    //Console.WriteLine("Historic onclick " + new { url, Native.window.history.length, Native.document.location.hash });

                    if (xreplace)
                    {
                        Native.window.history.replaceState(
                            state: new object(),
                            url: e.href,
                            // exlusive replace means current state will be forgotten
                            exclusive: true,
                            yield: yield
                            );
                    }
                    else
                    {
                        Native.window.history.pushState(
                            state: new object(),
                            url: e.href,
                            exclusive: true,
                            yield: yield
                            );
                    }
                }
            };
            #endregion

            if (Native.document.location.hash == url)
            {
                //Console.WriteLine("activate after onpopstate!");

                //HistoryExtensions.yield(
                //    delegate
                //    {
                Console.WriteLine("event: activate! " + new { Native.document.location.hash, url });

                // safari?
                e.click();
                //    }
                //);
            }



            return(e);
        }
        private static void AddTypeEvent(
        IHTMLDiv parent,
        CompilationEvent type,
        Action<string> UpdateLocation
        )
        {
            var div = new IHTMLDiv().AttachTo(parent);

            div.style.marginTop = "0.1em";
            div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
            div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


            var i = new PublicEvent().AttachTo(div);

            i.style.verticalAlign = "middle";
            i.style.marginRight = "0.5em";

            var s = new IHTMLAnchor { innerText = type.Name }.AttachTo(div);


            s.href = "#";
            s.style.textDecoration = "none";
            s.style.color = JSColor.System.WindowText;

            Action onclick = delegate
            {

            };

            s.onclick +=
                e =>
                {
                    e.PreventDefault();

                    s.focus();

                    UpdateLocation(type.Name);

                    onclick();
                };

            s.onfocus +=
                delegate
                {

                    s.style.backgroundColor = JSColor.System.Highlight;
                    s.style.color = JSColor.System.HighlightText;
                };

            s.onblur +=
                delegate
                {

                    s.style.backgroundColor = JSColor.None;
                    s.style.color = JSColor.System.WindowText;
                };


            onclick =
                delegate
                {
                    var children = new IHTMLDiv().AttachTo(div);

                    children.style.paddingLeft = "2em";

                    AddTypeMethod(children, type.GetAddMethod(), UpdateLocation);
                    AddTypeMethod(children, type.GetRemoveMethod(), UpdateLocation);



                    var NextClickHide = default(Action);
                    var NextClickShow = default(Action);

                    NextClickHide =
                        delegate
                        {
                            children.Hide();

                            onclick = NextClickShow;
                        };

                    NextClickShow =
                        delegate
                        {
                            children.Show();

                            onclick = NextClickHide;
                        };


                    onclick = NextClickHide;
                };
        }
        private void AddType(IHTMLDiv parent, CompilationType type, Action<string> UpdateLocation)
        {
            var div = new IHTMLDiv().AttachTo(parent);

            div.style.marginTop = "0.1em";
            div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
            div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


            var i = default(IHTMLImage);

            if (type.IsInterface)
            {
                i = new PublicInterface();
            }
            else
            {
                i = new PublicClass();
            }

            i.AttachTo(div);

            i.style.verticalAlign = "middle";
            i.style.marginRight = "0.5em";

            var s = new IHTMLAnchor { innerText = type.Name, title = "" + type.MetadataToken }.AttachTo(div);

            if (!string.IsNullOrEmpty(type.HTMLElement))
            {
                var c = new IHTMLCode();

                Action<string, JSColor> Write =
                    (Text, Color) =>
                    {
                        var cs = new IHTMLSpan { innerText = Text };

                        cs.style.color = Color;

                        cs.AttachTo(c);
                    };

                Write("<", JSColor.Blue);
                Write(type.HTMLElement, JSColor.FromRGB(0xa0, 0, 0));
                Write("/>", JSColor.Blue);

                //c.style.marginLeft = "1em";
                c.style.Float = ScriptCoreLib.JavaScript.DOM.IStyle.FloatEnum.right;

                c.AttachTo(s);
            }

            s.href = "#";
            s.style.textDecoration = "none";
            s.style.color = JSColor.System.WindowText;

            Action onclick = delegate
            {

            };

            s.onclick +=
                e =>
                {
                    e.PreventDefault();

                    s.focus();

                    if (TouchTypeSelected != null)
                        TouchTypeSelected(type);

                    UpdateLocation(type.FullName + " - " + type.Summary + " - HTML:" + type.HTMLElement);

                    onclick();
                };

            s.onfocus +=
                delegate
                {

                    s.style.backgroundColor = JSColor.System.Highlight;
                    s.style.color = JSColor.System.HighlightText;
                };

            s.onblur +=
                delegate
                {

                    s.style.backgroundColor = JSColor.None;
                    s.style.color = JSColor.System.WindowText;
                };



            onclick =
                delegate
                {

                    var children = new IHTMLDiv().AttachTo(div);

                    children.style.paddingLeft = "1em";

                    Func<IHTMLDiv> Group = () => new IHTMLDiv().AttachTo(children);

                    var Groups = new
                    {
                        Nested = Group(),
                        Constructors = Group(),
                        Methods = Group(),
                        Events = Group(),
                        Fields = Group(),
                        Properties = Group(),
                    };


                    type.GetNestedTypes().ForEach(
                        (Current, Next) =>
                        {
                            AddType(Groups.Nested, Current, UpdateLocation);

                            ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                50,
                                Next
                            );
                        }
                    );

                    type.GetConstructors().ForEach(
                        (Current, Next) =>
                        {
                            AddTypeConstructor(Groups.Constructors, Current, UpdateLocation);

                            ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                50,
                                Next
                            );
                        }
                    );

                    var HiddenMethods = new List<int>();

                    Action<CompilationMethod> AddIfAny =
                        SourceMethod =>
                        {
                            if (SourceMethod == null)
                                return;

                            HiddenMethods.Add(SourceMethod.MetadataToken);
                        };

                    Action AfterEvents = delegate
                    {

                        type.GetMethods().ForEach(
                            (Current, Next) =>
                            {
                                if (!HiddenMethods.Contains(Current.MetadataToken))
                                {
                                    AddTypeMethod(Groups.Methods, Current, UpdateLocation);
                                }

                                ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                    50,
                                    Next
                                );
                            }
                        );

                    };

                    Action AfterProperties = delegate
                    {
                        type.GetEvents().ForEach(
                            (Current, Next) =>
                            {
                                AddIfAny(Current.GetAddMethod());
                                AddIfAny(Current.GetRemoveMethod());

                                AddTypeEvent(Groups.Events, Current, UpdateLocation);

                                ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                    50,
                                    Next
                                );
                            }
                        )(AfterEvents);
                    };

                    type.GetProperties().ForEach(
                        (Current, Next) =>
                        {
                            AddIfAny(Current.GetSetMethod());
                            AddIfAny(Current.GetGetMethod());

                            AddTypeProperty(Groups.Properties, Current, UpdateLocation);

                            ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                50,
                                Next
                            );
                        }
                    )(AfterProperties);






                    type.GetFields().ForEach(
                        (Current, Next) =>
                        {
                            AddTypeField(Groups.Fields, Current, UpdateLocation);

                            ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                50,
                                Next
                            );
                        }
                    );




                    var NextClickHide = default(Action);
                    var NextClickShow = default(Action);

                    NextClickHide =
                        delegate
                        {
                            children.Hide();

                            onclick = NextClickShow;
                        };

                    NextClickShow =
                        delegate
                        {
                            children.Show();

                            onclick = NextClickHide;
                        };


                    onclick = NextClickHide;
                };
        }
        private void RenderAssemblies(
            CompilationArchiveBase archive,
            IHTMLElement parent,
            Func<string, IHTMLDiv> AllTypes,
            Action<string> UpdateLocation,
            Action<Action<Action>> YieldLoadAction)
        {
            var Assemblies = archive.GetAssemblies();

            foreach (var Assembly in Assemblies)
            {
                Console.WriteLine(new { Assembly.Name });

            }

            var q = from a in Assemblies
                    where a.Name.StartsWith("ScriptCoreLib")
                    orderby a.Name
                    select a;

            // limit to only first one for speedup

            foreach (var item2 in q.Take(1))
            {
                var item = item2;

                var div = new IHTMLDiv().AttachTo(parent);

                div.style.marginTop = "0.1em";
                div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
                div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


                var i = new Assembly().AttachTo(div);

                i.style.verticalAlign = "middle";
                i.style.marginRight = "0.5em";

                var s = new IHTMLAnchor { innerText = item2.Name }.AttachTo(div);

                //s.style.color = JSColor.Gray;

                s.href = "#";
                s.style.textDecoration = "none";
                s.style.color = JSColor.System.GrayText;

                Action onclick = delegate
                {

                };

                s.onclick +=
                    e =>
                    {
                        e.PreventDefault();

                        s.focus();

                        UpdateLocation(item.Name);

                        onclick();
                    };

                s.onfocus +=
                    delegate
                    {

                        s.style.backgroundColor = JSColor.System.Highlight;
                        s.style.color = JSColor.System.HighlightText;
                    };

                s.onblur +=
                    delegate
                    {

                        s.style.backgroundColor = JSColor.None;
                        s.style.color = JSColor.System.WindowText;
                    };

                var NamespaceLookup = new Dictionary<string, IHTMLDiv>();

                Func<IHTMLDiv, CompilationType, IHTMLDiv> GetNamespaceContainer =
                    (Container, SourceType) =>
                    {
                        if (!NamespaceLookup.ContainsKey(SourceType.Namespace))
                        {
                            NamespaceLookup[SourceType.Namespace] = null;

                            var NextNamespaceOrDefault = default(IHTMLDiv);

                            //var NextNamespaceOrDefault = NamespaceLookup.Keys.OrderBy(k => k).SkipWhile(k => k == SourceType.Namespace).Select(k => NamespaceLookup[k]).FirstOrDefault();

                            NamespaceLookup[SourceType.Namespace] = AddNamespace(Container, NextNamespaceOrDefault, SourceType.Namespace, UpdateLocation);
                        }

                        return NamespaceLookup[SourceType.Namespace];
                    };


                var children = new IHTMLDiv().AttachTo(div);

                children.style.paddingLeft = "1em";
                Action<Action> LoadAction =
                    done =>
                    {
                        Console.WriteLine("enter LoadAction");

                        s.style.color = JSColor.System.Highlight;

                        Action done_ = delegate
                        {
                            done();
                        };



                        item.WhenReady(
                            a =>
                            {
                                Console.WriteLine("enter WhenReady");

                                s.style.color = JSColor.System.WindowText;

                                Console.WriteLine("before GetTypes ToArray");
                                var TypesArray = a.GetTypes().ToArray();


                                //Console.WriteLine("before TypesByName");

                                //var TypesByName = TypesArray.OrderBy(k => k.Name);

                                //Console.WriteLine("before TypesByName ToArray");
                                //// chokes on android?
                                //var TypesByNameArray = TypesByName.ToArray();

                                //Console.WriteLine("before ForEach");

                                TypesArray.ForEach(
                                    (Current, Index, Next) =>
                                    {
                                        Console.WriteLine("AddType");

                                        if (!Current.IsNested)
                                        {
                                            AddType(
                                                GetNamespaceContainer(children, Current),
                                                Current,
                                                UpdateLocation
                                            );

                                            AddType(
                                                AllTypes(Current.Namespace),
                                                Current,
                                                UpdateLocation
                                            );
                                        }


                                        if (Index % 8 == 0)
                                        {
                                            ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                                                7,
                                                Next
                                            );
                                        }
                                        else
                                        {
                                            Next();
                                        }
                                    }
                                )(done_);

                                Console.WriteLine("exit WhenReady");

                            }
                        );
                    };

                Console.WriteLine("before YieldLoadAction");
                YieldLoadAction(LoadAction);
                Console.WriteLine("after YieldLoadAction");


                var NextClickHide = default(Action);
                var NextClickShow = default(Action);

                NextClickHide =
                    delegate
                    {
                        children.Hide();

                        onclick = NextClickShow;
                    };

                NextClickShow =
                    delegate
                    {
                        children.Show();

                        onclick = NextClickHide;
                    };


                NextClickHide();
            }
        }
		private void RenderWriteHistory(Dictionary<SolutionFileTextFragment, Color> Lookup, SolutionFile f, IHTMLElement Container)
		{
			Func<SolutionFileTextFragment, Color> LookupOrDefault =
				ff =>
				{
					if (this.Colors.ContainsKey(ff))
						return this.Colors[ff];

					return this.Colors[SolutionFileTextFragment.None];
				};

			var Content = new IHTMLDiv().AttachTo(Container);


			Content.style.position = IStyle.PositionEnum.relative;

			var ViewBackground = new IHTMLDiv().AttachTo(Content);

			ViewBackground.style.position = IStyle.PositionEnum.absolute;
			ViewBackground.style.left = "0px";
			ViewBackground.style.top = "0px";
			ViewBackground.style.width = "4em";
			ViewBackground.style.borderRight = "1px dotted gray";
			ViewBackground.style.paddingRight = "0.5em";

			var ViewTrap = new IHTMLDiv().AttachTo(Content);

			ViewTrap.style.position = IStyle.PositionEnum.absolute;
			ViewTrap.style.left = "0px";
			ViewTrap.style.top = "0px";
			ViewTrap.style.right = "0px";
			ViewTrap.style.bottom = "0px";
			//ViewTrap.style.backgroundColor = Color.White;

			var ViewTrapContainer = new IHTMLDiv().AttachTo(ViewTrap);

			ViewTrapContainer.style.cursor = IStyle.CursorEnum.text;
			ViewTrapContainer.style.position = IStyle.PositionEnum.relative;
			ViewTrapContainer.style.paddingLeft = "5em";

			var View = new IHTMLDiv().AttachTo(ViewTrapContainer);



			var ContentHeightDummy = new IHTMLDiv().AttachTo(Content);

			var RegionStack = new Stack<List<Action<bool>>>();
			var RegionGlobal = new List<Action<bool>>();
			RegionStack.Push(RegionGlobal);

			var Lines = new List<IHTMLDiv>();

			var CurrentLineDirty = false;
			var CurrentLine = default(IHTMLDiv);
			var CurrentLineContent = default(IHTMLDiv);

			Action NextLine = delegate
			{
				CurrentLineDirty = false;

				var c = new IHTMLDiv();
				var cc = new IHTMLDiv();
				var cb = new IHTMLDiv();

				CurrentLine = c.AttachTo(View);
				CurrentLineContent = cc.AttachTo(c);

				var CurrentRegion = RegionStack.Peek();

				RegionStack.WithEach(
					k =>
					{
						k.Add(
							IsActive =>
							{
								// should we react when in a global region
								if (k == RegionGlobal)
									return;

								if (IsActive)
								{
									cc.style.backgroundColor = Color.FromGray(0xf9);
									cb.style.backgroundColor = Color.FromGray(0xf9);
								}
								else
								{
									cc.style.backgroundColor = Color.None;
									cb.style.backgroundColor = Color.None;
								}
							}
						);
					}
				);

				CurrentLine.onmouseover +=
					delegate
					{
						CurrentRegion.Invoke(true);
						cc.style.backgroundColor = Color.FromGray(0xf0);
						cb.style.backgroundColor = Color.FromGray(0xf0);
					};

				CurrentLine.onmouseout +=
					delegate
					{
						CurrentRegion.Invoke(false);
						cc.style.backgroundColor = Color.None;
						cb.style.backgroundColor = Color.None;
					};


				Lines.Add(CurrentLine);
				//CurrentLineContent.style.marginLeft = "5em";

				var BCurrentLine = cb.AttachTo(ViewBackground);

				BCurrentLine.style.textAlign = IStyle.TextAlignEnum.right;

				var span = new IHTMLCode { innerText = "" + Lines.Count };
				span.style.color = Lookup[SolutionFileTextFragment.Type];
				span.AttachTo(BCurrentLine);

				//Content.style.height = Lines.Count + "em";

				new IHTMLDiv { new IHTMLCode { innerText = Environment.NewLine } }.AttachTo(ContentHeightDummy);
			};



			foreach (var item in f.WriteHistory.ToArray())
			{
				if (item is SolutionFileWriteArguments.BeginRegion)
				{
					RegionStack.Push(new List<Action<bool>>());
				}

				if (item is SolutionFileWriteArguments.EndRegion)
				{
					RegionStack.Pop();
				}

				if (CurrentLine == null)
					NextLine();



				var innerText = item.Text;
				innerText = innerText.TakeUntilLastIfAny(Environment.NewLine);

				if (!string.IsNullOrEmpty(innerText))
				{
					var span = new IHTMLCode { innerText = innerText };

					if (item.Fragment == SolutionFileTextFragment.Indent)
					{
						span.style.width = "2em";
						span.style.display = IStyle.DisplayEnum.inline_block;

						if (CurrentLineDirty)
							span.style.borderLeft = "1px dotted #afafaf";
					}


					span.style.color = LookupOrDefault(item.Fragment);

					CurrentLineDirty = true;
					span.AttachTo(CurrentLineContent);

					if (item.Tag != null)
					{
						span.style.cursor = ScriptCoreLib.JavaScript.DOM.IStyle.CursorEnum.pointer;
						span.onmouseover +=
							delegate
							{
								span.style.textDecoration = "underline";
							};

						span.onmouseout +=
							delegate
							{
								span.style.textDecoration = "";
							};



						var Type = item.Tag as SolutionProjectLanguageType;
						if (Type != null)
						{
							span.title = Type.FullName;
						}

						var Method = item.Tag as SolutionProjectLanguageMethod;
						if (Method != null)
						{
							span.title = Method.Name;
						}


						var Uri = item.Tag as Uri;
						if (Uri != null)
						{
							var a = new IHTMLAnchor();
							a.style.color = LookupOrDefault(item.Fragment);

							a.href = Uri.ToString();
							a.target = "_blank";
							a.Add(span);
							a.AttachTo(CurrentLineContent);

							a.onclick +=
								e =>
								{
                                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151103
									e.preventDefault();

									if (LinkCommentClick != null)
										LinkCommentClick(Uri);
								};
						}
					}
				}

				if (item.Text.EndsWith(Environment.NewLine))
				{
					if (!CurrentLineDirty)
					{
						var span = new IHTMLCode { innerText = " " };
						span.AttachTo(CurrentLineContent);
					}

					CurrentLine = null;
				}
			}
		}
        public ApplicationLoader()
        {
            // remember current base
            //page.a.href = page.audio.src;

            //   <link rel="alternate" type="application/rss+xml" href="http://idea-remixer.tumblr.com/rss">


            Action<string, Action<string, FeedContainer>> gfeeds =
                (rss, yield) =>
                {

                    IFunction.OfDelegate(yield).Export("gfeeds_yield");

                    var src = "http://www.google.com/uds/Gfeeds?callback=gfeeds_yield&scoring=h&context=0&num=250&hl=en&output=json&v=1.0&nocache=0&q=" + rss;

                    new IHTMLScript { src = src }.AttachToHead();
                };

            Action<FeedContainer> ondata =
                data =>
                {

                    //var entries =
                    //    from e in data.feed.entries
                    //    from g in e.mediaGroups
                    //    from c in g.contents
                    //    select new { c.url, e.title };



                    data.feed.entries.WithEach(
                        e =>
                        {
                            //{"responseData": {"feed":
                            // {"feedUrl":"http://idea-remixer.tumblr.com/rss","title":"idea-remixer","link":"http://idea-remixer.tumblr.com/","author":"","description":"","type":"rss20",
                            // "entries":[
                            // {"mediaGroups":[{"contents":[{"url":"http://a.tumblr.com/tumblr_mgrts0AGjU1rs64dko1.mp3","fileSize":"2628334","type":"audio/mpeg"}]}],

                            e.mediaGroups.WithEach(
                                g =>
                                {
                                    g.contents.WithEach(
                                        c =>
                                        {
                                            var a = new IHTMLAnchor { href = c.url, innerText = e.title }.AttachToHead();

                                            a.style.display = IStyle.DisplayEnum.block;

                                            Console.WriteLine(new { e.title, c.url });
                                        }
                                    );
                                }
                            );
                        }
                    );

                    // switch base

                    Console.WriteLine("data ready. will load code.");



                    x.AttachToHead();
                    s.AttachToHead();

                };

            gfeeds("http://idea-remixer.tumblr.com/rss",
                (tag, data) =>
                {
                    Console.WriteLine("got data!");
                    Console.WriteLine(new { data });

                    ondata(data);
                }
            );



        }
Beispiel #27
0
        // X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\CanvasFromBytes\Application.cs

        public static void AllowToDragAsApplicationPackage(this IHTMLAnchor dragme)
        {
            //img.width = Native.Window.Width / 2;
            //img.height = Native.Window.Height / 2;


            #region PackageAsApplication
            Action <IHTMLScript, XElement, Action <string> > PackageAsApplication =
                (source0, xml, yield) =>
            {
                new IXMLHttpRequest(
                    ScriptCoreLib.Shared.HTTPMethodEnum.GET,
                    source0.src,
                    handler: (IXMLHttpRequest r) =>
                {
                    // store hash
                    xml.Add(new XElement("link", new XAttribute("rel", "location"), new XAttribute("href", Native.Document.location.hash)));


                    xml.Add(
                        new XElement("script",
                                     "/* source */"
                                     )
                        );

                    var data = "";


                    Action later = delegate
                    {
                        data = data.Replace("/* source */", r.responseText);
                    };


                    //Native.Document.getElementsByTagName("link").AsEnumerable().ToList().ForEach(

                    xml.Elements("link").ToList().ForEach(
                        (XElement link, Action next) =>
                    {
                        #region style
                        var rel = link.Attribute("rel");
                        if (rel.Value != "stylesheet")
                        {
                            next();
                            return;
                        }

                        var href = link.Attribute("href");

                        var placeholder = "/* " + href.Value + " */";

                        //page.DragHTM.innerText += " " + placeholder;


                        xml.Add(new XElement("style", placeholder));

                        new IXMLHttpRequest(ScriptCoreLib.Shared.HTTPMethodEnum.GET, href.Value,
                                            rr =>
                        {
                            later += delegate
                            {
                                data = data.Replace(placeholder, rr.responseText);
                            };

                            Console.WriteLine("link Remove");
                            link.Remove();

                            next();
                        }
                                            );

                        #endregion
                    }
                        )(
                        delegate
                    {
                        data = xml.ToString();
                        Console.WriteLine("data: " + data);
                        later();

                        yield(data);
                    }
                        );
                }
                    );
            };
            #endregion

            // XMLHttpRequest cannot load file:///D:/view-source. Cross origin requests are only supported for HTTP.



            Console.WriteLine("before PackageAsApplication");
            PackageAsApplication(

                // how would we know our current source location?
                new IHTMLScript {
                src = "view-source"
            },
                XElement.Parse(AppSource.Text),
                data =>
            {
                Console.WriteLine("enter PackageAsApplication");
                var bytes = Encoding.UTF8.GetBytes(data);
                //var bytes_string =
                // https://developer.mozilla.org/en-US/docs/Web/API/WorkerLocation
                // https://developer.mozilla.org/en-US/docs/Web/Reference/Functions_and_classes_available_to_workers
                // https://bugs.webkit.org/show_bug.cgi?id=55663
                // http://www.w3schools.com/jsref/met_win_btoa.asp
                // https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
                // http://stackoverflow.com/questions/15386585/standard-functions-not-working-in-web-worker

                // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#atob
                // [object Uint8ClampedArray]

                //  both the input and output of these functions are Unicode strings.
                //Func<byte[], string> ToBase64String =

                // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\IO\BinaryReader.cs
                // Uncaught RangeError: Maximum call stack size exceeded
                //Func<byte[], string> ToBase64String =
                //    x => (string)
                //        new IFunction("return window.btoa(this);").apply(__fromCharCode(x));

                //  String.fromCharCode.apply(null, new Uint8ClampedArray([40, 41]))


                //var data64 = System.Convert.ToBase64String(bytes);
                //var data64 = ToBase64String(bytes);
                var s = Stopwatch.StartNew();
                Console.WriteLine("before ToBase64String");
                //var data64 = ToBase64String(bytes);
                // 0:4173ms after ToBase64String { ElapsedMilliseconds = 181 }
                //__Convert.InternalToBase64String = ToBase64String;
                var data64 = System.Convert.ToBase64String(bytes);
                Console.WriteLine("after ToBase64String " + new { s.ElapsedMilliseconds });


                var datastream =
                    "application/octet-stream:App.htm:data:application/octet-stream;base64," + data64;

                //Console.WriteLine(new { data64 });


                // X:\jsc.svn\examples\javascript\DragDataTableIntoCSVFile\DragDataTableIntoCSVFile\Application.cs
                // X:\jsc.svn\examples\javascript\DragIntoCRX\DragIntoCRX\Application.cs
                //new IHTMLButton

                dragme.css.style.textDecoration = "underline";
                dragme.css.style.cursor         = IStyle.CursorEnum.pointer;

                dragme.css.hover.style.color  = "blue";
                dragme.css.active.style.color = "red";

                Console.WriteLine("before ondragstart");

                //dragme.draggable = true;

                dragme.ondragstart +=
                    e =>
                {
                    Console.WriteLine("enter ondragstart");

                    e.dataTransfer.effectAllowed = "copy";

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

                    //e.dataTransfer.setData("text/plain", "Sphere");

                    // http://codebits.glennjones.net/downloadurl/virtualdownloadurl.htm
                    //e.dataTransfer.setData("DownloadURL", "image/png:Sphere.png:" + icon);


                    // X:\jsc.svn\market\synergy\javascript\chrome\chrome\DOM\DataTransferExtensions.cs


                    e.dataTransfer.setData(
                        "DownloadURL", datastream
                        );

                    ////e.dataTransfer.setDownloadURL(

                    e.dataTransfer.setData("text/html", data);
                    //e.dataTransfer.setData("text/uri-list", Native.document.location.href);

                    //e.dataTransfer.setDragImage(img, img.width / 2, img.height / 2);
                };
            }
                );
        }
		/// <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)
		{
			new JSCSolutionsNETImage().ToBackground(page.Item1.style, false);
			new JSCSolutionsNETImage().ToBackground(page.Item2.style, false);


			// Update document title
			// http://do.jsc-solutions.net/Update-document-title

			@"Hello world".ToDocumentTitle();
			// Send xml to server
			// http://do.jsc-solutions.net/Send-xml-to-server

			var v = new SolutionFileView();

			var f = new SolutionFile();

			f.WriteHTMLElement(StockPageDefault.Element);

			v.File = f;

			var Container = new IHTMLDiv();

			Container.style.position = IStyle.PositionEnum.relative;
			Container.style.display = IStyle.DisplayEnum.inline_block;
			Container.style.width = "600px";
			Container.style.height = "400px";
			Container.style.border = "1px solid gray";

			var ToolbarHeight = "1.3em";
			var Content = new IHTMLDiv().AttachTo(Container);

			Content.style.position = IStyle.PositionEnum.absolute;
			Content.style.left = "0px";
			Content.style.top = "0px";
			Content.style.right = "0px";
			Content.style.bottom = ToolbarHeight;


			var Toolbar = new IHTMLDiv().AttachTo(Container);

			Toolbar.style.backgroundColor = Color.FromGray(0xef);
			Toolbar.style.position = IStyle.PositionEnum.absolute;
			Toolbar.style.left = "0px";
			Toolbar.style.height = ToolbarHeight;
			Toolbar.style.right = "0px";
			Toolbar.style.bottom = "0px";

			Action<IHTMLImage, string, Action> AddToolbarButton =
				(img, text, handler) =>
				{
					var span = new IHTMLSpan { innerText = text };

					span.style.paddingLeft = "1.5em";
					span.style.paddingRight = "0.3em";

					var a = new IHTMLAnchor
					{
						img, span
					};

					img.style.verticalAlign = "middle";
					img.border = 0;
					img.style.position = IStyle.PositionEnum.absolute;

					a.style.backgroundColor = Color.FromGray(0xef);
					a.style.color = Color.Black;
					a.style.textDecoration = "none";
					a.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;

					a.href = "javascript: void(0);";
					a.onclick +=
						delegate
						{
							handler();
						};
					a.style.display = IStyle.DisplayEnum.inline_block;
					a.style.height = "100%";


					a.onmousemove +=
						delegate
						{
							a.style.backgroundColor = Color.FromGray(0xff);
						};

					a.onmouseout +=
						delegate
						{
							a.style.backgroundColor = Color.FromGray(0xef);
						};

					Toolbar.Add(a);
				};


			v.Container.style.height = "100%";
			v.Container.AttachTo(Content);


			Content.Add(v.Container);

			var i = CreateEditor();

			i.AttachTo(Content);



			var ii = new IHTMLPre().AttachTo(Content);

			ii.style.position = IStyle.PositionEnum.absolute;
			ii.style.left = "0px";
			ii.style.top = "0px";
			ii.style.right = "0px";
			ii.style.bottom = "0px";
			ii.style.overflow = IStyle.OverflowEnum.auto;
			ii.style.padding = "0px";
			ii.style.margin = "0px";
			ii.style.whiteSpace = IStyle.WhiteSpaceEnum.normal;

			v.Container.style.display = IStyle.DisplayEnum.none;
			i.style.display = IStyle.DisplayEnum.empty;
			ii.style.display = IStyle.DisplayEnum.none;

			AddToolbarButton(new RTA_mode_design(), "Design",
				delegate
				{
					v.Container.style.display = IStyle.DisplayEnum.none;
					ii.style.display = IStyle.DisplayEnum.none;
					i.style.display = IStyle.DisplayEnum.empty;
				}
			);

			AddToolbarButton(new RTA_mode_html(), "Source",
				delegate
				{
					v.Container.style.display = IStyle.DisplayEnum.empty;
					ii.style.display = IStyle.DisplayEnum.none;
					i.style.display = IStyle.DisplayEnum.none;

					f.Clear();

					i.WhenContentReady(
						body =>
						{
							f.WriteHTMLElement(body.AsXElement());

							// update
							v.File = f;
						}
					);


				}
			);

			AddToolbarButton(new RTA_mode_html(), "Source raw",
				delegate
				{
					v.Container.style.display = IStyle.DisplayEnum.none;
					ii.style.display = IStyle.DisplayEnum.empty;
					i.style.display = IStyle.DisplayEnum.none;



					i.WhenContentReady(
						body =>
						{
							ii.innerText = body.AsXElement().ToString();
						}
					);


				}
			);

			page.PageContainer.Add(Container);

			new ApplicationWebService().WebMethod2(
				new XElement(@"Document",
					new object[] {
						new XElement(@"Data", 
							new object[] {
								@"Hello world"
							}
						),
						new XElement(@"Client", 
							new object[] {
								@"Unchanged text"
							}
						)
					}
				),
				delegate(XElement doc)
				{
					// Show server message as document title
					// http://do.jsc-solutions.net/Show-server-message-as-document-title

					doc.Element(@"Data").Value.ToDocumentTitle();
				}
			);
		}
        /// <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 IHTMLPre { () => "loaded at " + new { DateTime.Now } }.AttachToDocument();
            new IHTMLPre { "loaded at " + new { DateTime.Now } }.AttachToDocument();

            Native.css[IHTMLElement.HTMLElementEnum.a].style.display = IStyle.DisplayEnum.block;




            new { }.With(
                async delegate
                {
                    var foo = new IHTMLAnchor { href = "#foo", innerText = "#foo" }.AttachToDocument();

                    var a = new AsyncHash { hash = "#foo" };

                    new IHTMLButton { "go foo" }.AttachToDocument().onclick += delegate
                    {
                        Native.document.location.hash = a.hash;
                    };



                    while (await a.onenter)
                    {
                        new IHTMLPre { "onenter" }.AttachToDocument();
                        foo.style.backgroundColor = "yellow";


                        await a.onexit;

                        new IHTMLPre { "onexit" }.AttachToDocument();
                        foo.style.backgroundColor = "";
                    }

                }
            );


            new { }.With(
              async delegate
              {
                  var bar = new IHTMLAnchor { href = "#bar", innerText = "#bar" }.AttachToDocument();

                  var a = new AsyncHash { hash = "#bar" };

                  new IHTMLButton { "go bar" }.AttachToDocument().onclick += delegate
                  {
                      //Native.document.location.hash = a.hash;

                      a.Go();
                  };




                  while (await a.onenter)
                  {
                      //new IHTMLPre { "onenter" }.AttachToDocument();
                      bar.style.backgroundColor = "cyan";


                      // using
                      var goback = new IHTMLButton { "go back" }.AttachToDocument();

                      goback.onclick += delegate
                      {
                          //Native.document.location.hash = a.hash;

                          //a.Go();

                          Native.window.history.back();
                      };

                      await a.onexit;

                      goback.Dispose();

                      //new IHTMLPre { "onexit" }.AttachToDocument();
                      bar.style.backgroundColor = "";
                  }

              }
          );


            new IHTMLAnchor { href = "", innerText = "go home with reload" }.AttachToDocument();
            //new IHTMLAnchor { href = "/", innerText = "go home" }.AttachToDocument();
            new IHTMLAnchor { href = "#", innerText = "go home" }.AttachToDocument();

            Native.window.onhashchange += delegate
            {
                new IHTMLPre { new { Native.document.location.hash } }.AttachToDocument();
            };


            // await hash of


            // await cancel
        }
        public ExampleGalleryWithReflections()
        {

            Native.Document.body.style.Aggregate(
               style =>
               {
                   style.backgroundColor = Color.Gray;
                   style.backgroundImage = "url(assets/ExampleGallery/bg.png)";

                   style.color = Color.White;
               }
           );

            try
            {
                IStyleSheet.Default.AddRule("a.Preview img.PreviewShadow").style.display = IStyle.DisplayEnum.none;
                IStyleSheet.Default.AddRule("a.Preview:hover img.PreviewShadow").style.display = IStyle.DisplayEnum.block;
            }
            catch
            {
                // no css support
            }

            var Menu = new IHTMLDiv().AttachToDocument();
            var Title = typeof(ExampleGalleryWithReflections).Name;

            new IHTMLElement(IHTMLElement.HTMLElementEnum.h1,
                Title).AttachTo(Menu);

            Native.Document.title = Title;

            new IHTMLImage("assets/ExampleGallery/PreviewSelection.png").InvokeOnComplete(
            selection =>
                {
                    base.Initialize(Menu,
                        (image, href, type, TypeClicked) =>
                        {
                            var div =
                                new ReflectionSetup
                                {
                                    Image = image,
                                    Position = new Point(0, 0),
                                    Size = new Point(120, 90),
                                    ReflectionZoom = 0.5,
                                    Drag = false,
                                    Bottom = 2
                                }.ConvertToImageReflection();

                            div.style.position = IStyle.PositionEnum.relative;
                            div.style.marginTop = "3em";
                            div.style.marginLeft = "1em";
                            div.style.marginRight = "1em";
                            div.style.marginBottom = "3em";
                            div.style.Float = IStyle.FloatEnum.left;

                            #region name
                            var name = new IHTMLAnchor(href, type.Name);

                            name.style.position = IStyle.PositionEnum.absolute;
                            name.style.textDecoration = "none";
                            name.style.color = Color.White;
                            name.className = "PreviewName";

                            name.target = "_blank";
                            name.style.top = "-1.5em";
                            name.AttachTo(div);
                            #endregion

                            var a = new IHTMLAnchor(href, "");

                            var cselection = (IHTMLImage)selection.cloneNode(false);
                            cselection.style.borderWidth = "0px";
                            cselection.style.SetLocation(-9, -9);
                            cselection.style.zIndex = 1;
                            cselection.className = "PreviewShadow";
                            cselection.AttachTo(a);

                            a.className = "Preview";
                            a.target = "_blank";
                            image.style.border = "0px solid black";
                            image.AttachTo(a);
                            image.style.zIndex = 2;
                            a.AttachTo(div);
                            a.style.zIndex = 2;
                            a.style.SetLocation(0, 0);

                            a.onclick +=
                                ev =>
                                {
                                    ev.PreventDefault();

                                    TypeClicked(type);
                                };

                            return div;
                        });
                    }
             );
        }
        // shadow with by http://www.cycloloco.com/shadowmaker/shadowmaker.htm

        public ExampleGalleryWithShadows()
        {

            var style = "assets/ExampleGallery/ExampleGallery.css".ImportStyleSheet();

            Native.Document.body.style.backgroundImage = "url(assets/ExampleGallery/bg.png)";
	
            var Menu = new IHTMLDiv().AttachToDocument();
            var Title = typeof(ExampleGalleryWithShadows).Name;

            new IHTMLElement(IHTMLElement.HTMLElementEnum.h1,
                Title).AttachTo(Menu);

            Native.Document.title = Title;


            new IHTMLImage("assets/ExampleGallery/PreviewSelection.png").InvokeOnComplete(
                selection =>
            new IHTMLImage("assets/ExampleGallery/PreviewShadow.png").InvokeOnComplete(
                img =>
                {
                    base.Initialize(Menu,
                        (image, href, type, TypeClicked) =>
                        {
                            var div = new IHTMLDiv();

                            div.style.SetSize(120, 90);

                            var shadow = (IHTMLImage)img.cloneNode(false);

                            shadow.AttachTo(div);
                            shadow.style.SetLocation(0, 0);
                            shadow.style.zIndex = 0;


                            image.AttachTo(div);
                            image.style.SetSize(120, 90);




                            div.style.position = IStyle.PositionEnum.relative;
                            div.style.marginTop = "3em";
                            div.style.marginLeft = "1em";
                            div.style.marginRight = "1em";
                            div.style.marginBottom = "1em";
                            div.style.Float = IStyle.FloatEnum.left;

                            #region name
                            var name = new IHTMLAnchor(href, type.Name);

                            name.style.position = IStyle.PositionEnum.absolute;
                            name.className = "PreviewName";
                            name.style.color = Color.White;
                            name.style.textDecoration = "none";

                            name.target = "_blank";
                            name.style.top = "-1.5em";
                            name.AttachTo(div);
                            #endregion

                            var a = new IHTMLAnchor(href, "");

                            a.target = "_blank";
                            a.style.display = IStyle.DisplayEnum.block;

                            var cselection = (IHTMLImage)selection.cloneNode(false);
                            cselection.style.borderWidth = "0px";
                            cselection.style.SetLocation(-9, -9);
                            cselection.style.zIndex = 1;
                            cselection.className = "PreviewShadow";
                            cselection.AttachTo(a);


                            image.style.border = "0px solid black";
                            image.style.zIndex = 2;
                            image.AttachTo(a);

                            a.className = "Preview";
                            a.AttachTo(div);
                            a.style.zIndex = 2;
                            a.style.SetLocation(0, 0, 120, 90);


                            a.onclick +=
                                ev =>
                                {
                                    ev.PreventDefault();

                                    Native.Document.body.style.backgroundImage = "";

                                    TypeClicked(type);
                                };

                            return div;
                        }
                   );
                }
            )
            );
        }
        private static void AddTypeConstructor(IHTMLDiv parent, CompilationConstructor type, Action<string> UpdateLocation)
        {
            var div = new IHTMLDiv().AttachTo(parent);

            div.style.marginTop = "0.1em";
            div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
            div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


            var i = new PublicConstructor().AttachTo(div);

            i.style.verticalAlign = "middle";
            i.style.marginRight = "0.5em";

            var w = new StringBuilder();

            w.Append(type.DeclaringType.Name);

            w.Append("(");

            type.GetParameters().ForEach(
                (p, pi) =>
                {
                    if (pi > 0)
                        w.Append(", ");

                    w.Append(p.Name);
                }
            );

            w.Append(")");


            var s = new IHTMLAnchor { innerText = w.ToString() }.AttachTo(div);


            s.href = "#";
            s.style.textDecoration = "none";
            s.style.color = JSColor.System.WindowText;

            Action onclick = delegate
            {

            };

            s.onclick +=
                e =>
                {
                    e.PreventDefault();

                    s.focus();

                    UpdateLocation(type.DeclaringType.Name + ".ctor");

                    onclick();
                };

            s.onfocus +=
                delegate
                {

                    s.style.backgroundColor = JSColor.System.Highlight;
                    s.style.color = JSColor.System.HighlightText;
                };

            s.onblur +=
                delegate
                {

                    s.style.backgroundColor = JSColor.None;
                    s.style.color = JSColor.System.WindowText;
                };


            onclick =
                delegate
                {
                    //var children = new IHTMLDiv().AttachTo(div);

                    //children.style.paddingLeft = "2em";

                    //a.GetTypes().ForEach(
                    //    (Current, Next) =>
                    //    {
                    //        AddType(GetNamespaceContainer(children, Current), Current, UpdateLocation);

                    //        ScriptCoreLib.Shared.Avalon.Extensions.AvalonSharedExtensions.AtDelay(
                    //            50,
                    //            Next
                    //        );
                    //    }
                    //);


                    var NextClickHide = default(Action);
                    var NextClickShow = default(Action);

                    NextClickHide =
                        delegate
                        {
                            //children.Hide();

                            onclick = NextClickShow;
                        };

                    NextClickShow =
                        delegate
                        {
                            //children.Show();

                            onclick = NextClickHide;
                        };


                    onclick = NextClickHide;
                };
        }