Пример #1
0
        void t_Tick(Timer e)
        {
            if (_async)
                return;

            _async = true;


            try
            {
                r = new IXMLHttpRequest();
                r.open(HTTPMethodEnum.HEAD, Url);
                r.send();
            }
            catch
            {
                Native.window.alert(" send error ");
            }

            r.InvokeOnComplete(
                delegate(IXMLHttpRequest rr)
                {
                    

                    if (RequestComplete != null)
                        RequestComplete(this);

                    if (rr.status == IXMLHttpRequest.HTTPStatusCodes.OK)
                    {
                        string z = rr.ETag;

                        bool b = (z != ETag) && (ETag != null) && (z != null);

                        ETag = z;

                        if (b)
                        {
                            if (ETagChanged != null)
                                ETagChanged(this);

                            this.Enabled = false;
                            return;
                        }


                    }
                    else
                    {
                        this.Enabled = false;
                        return;
                    }


                    _async = false;
                

            }
            );
        }
Пример #2
0
        private static IXMLHttpRequest InternalConstructor(HTTPMethodEnum method, string url, bool @async)
        {
            IXMLHttpRequest n = InternalConstructor();

            n.open(method, url, @async);

            return(n);
        }
        public static TaskAwaiter <IXMLHttpRequest> GetAwaiter(this IXMLHttpRequest r)
        {
            var s = new TaskCompletionSource <IXMLHttpRequest>();

            r.InvokeOnComplete(s.SetResult);

            return(s.Task.GetAwaiter());
        }
Пример #4
0
        /// <summary>
        /// sends http request, with no data
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        private static IXMLHttpRequest InternalConstructor(HTTPMethodEnum method, string url, Action <IXMLHttpRequest> handler)
        {
            IXMLHttpRequest req = new IXMLHttpRequest(method, url, true);

            req.send();

            req.InvokeOnComplete(handler);

            return(req);
        }
Пример #5
0
        /// <summary>
        /// sends data with POST method
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="handler"></param>
        /// <param name="async"></param>
        /// <returns></returns>
        private static IXMLHttpRequest InternalConstructor(string url, IXMLDocument data, Action <IXMLHttpRequest> handler, bool @async)
        {
            IXMLHttpRequest req = new IXMLHttpRequest(HTTPMethodEnum.POST, url, @async);

            req.send(data);

            req.InvokeOnComplete(handler, @async);

            return(req);
        }
Пример #6
0
        /// <summary>
        /// sends no data, with head method
        /// </summary>
        /// <param name="url"></param>
        /// <param name="handler"></param>
        /// <param name="async"></param>
        /// <returns></returns>
        private static IXMLHttpRequest InternalConstructor(string url, Action <IXMLHttpRequest> handler, bool @async)
        {
            IXMLHttpRequest req = InternalConstructor(HTTPMethodEnum.HEAD, url, @async);

            req.send();

            req.InvokeOnComplete(handler, @async);

            return(req);
        }
Пример #7
0
        public Locals(string source)
        {
            this.Source = source;

            this.Request = new IXMLHttpRequest(ScriptCoreLib.Shared.HTTPMethodEnum.GET, this.Source,
                delegate
                {
                    // xml document is not set at this moment? why is that

                    
                }
            );

        }
Пример #8
0
        private static IXMLHttpRequest InternalConstructor()
        {
            IXMLHttpRequest n = null;

            try
            {
                n = (IXMLHttpRequest)((object)new InternalXMLHttpRequest());
            }
            catch
            {
                // do we need this?
                n = (IXMLHttpRequest)((object)new IActiveX("Msxml2.XMLHTTP.3.0", "Microsoft.XMLHTTP"));
            }


            return(n);
        }
Пример #9
0
        private static IXMLHttpRequest InternalConstructor()
        {
            IXMLHttpRequest n = null;

            try
            {
                n = (IXMLHttpRequest)((object)new InternalXMLHttpRequest());
            }
            catch
            {
                // https://social.msdn.microsoft.com/Forums/ie/en-US/677af000-d029-496b-b907-79e652858780/post-data-not-sent-in-ie-11-using-the-webbrowser-control?forum=iewebdevelopment

                // do we need this?
                n = (IXMLHttpRequest)((object)new IActiveX("Msxml2.XMLHTTP.3.0", "Microsoft.XMLHTTP"));
            }


            return(n);
        }
Пример #10
0
        public string DownloadString(string address)
        {

            // X:\jsc.svn\examples\javascript\Test\TestDownloadStringAsync\TestDownloadStringAsync\Application.cs

            var x = new IXMLHttpRequest();

            x.open(Shared.HTTPMethodEnum.GET, address.ToString(), async: false);

            //Console.WriteLine("DownloadStringAsync");
            x.send();

            return x.responseText;
        }
Пример #11
0
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160108

        // X:\jsc.svn\examples\javascript\android\com.abstractatech.appmanager\com.abstractatech.appmanager\Application.cs

        // tested by
        // X:\jsc.svn\examples\javascript\android\com.abstractatech.adminshell\com.abstractatech.adminshell\Application.cs

        //02000066 ScriptCoreLib.JavaScript.Experimental.X+<>c__DisplayClassc+<<GetAwaiter>b__7>d__11
        //script: error JSC1000: if block not detected correctly, opcode was { Branch = [0x0020] beq        +0 -2{[0x0019] ldfld      +1 -1{[0x0018] ldarg.0    +1 -0} } {[0x001e] ldc.i4.s   +1 -0} , Location =
        // assembly: T:\com.abstractatech.adminshell.Application.exe
        // type: ScriptCoreLib.JavaScript.Experimental.X+<>c__DisplayClassc+<<GetAwaiter>b__7>d__11, com.abstractatech.adminshell.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
        // offset: 0x0020
        //  method:Int32 <>02000019<>06000044<>MoveNext<0000>.try(<>02000019<>06000044<>MoveNext, <<GetAwaiter>b__7>d__11 ByRef, System.Runtime.CompilerServices.TaskAwaiter`1[System.Byte[]] ByRef, System.Runtime.CompilerServices.TaskAwaiter`1[System.Byte[]] ByRef) }

        //public static object 


        // .NET 4.5!!!
        public static TaskAwaiter<InternalScriptApplicationSource> GetAwaiter(this Type __e)
        {
            Console.WriteLine("enter ScriptCoreLib.JavaScript.Experimental " + new { __e.Name });

            // http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest

            var y = new TaskCompletionSource<InternalScriptApplicationSource>();

            //var ysource = Native.window.sessionStorage[__e.Name];
            //if (ysource != null)
            //{
            //    y.SetResult(ysource);

            //    return y.Task.GetAwaiter();
            //}

            //return 

            //InternalInitializeInlineWorker Report: { __IProgress_Report = { value = [object Object] } }
            // view-source:27346
            //{ Name = a, loaded = 4538818, total = 4538818 } view-source:27346

            // view-source:27346
            //loading secondary app in a moment... { responseType = arraybuffer, ManagedThreadId = 10 }
            // view-source:27346
            //loading secondary app in a moment... { Length = 4538818 } decrypting...
            // view-source:27346
            //loading secondary app in a moment... { Length = 2269409 } done!

            var bar = new IHTMLDiv { }.AttachToDocument();

            bar.style.SetLocation(0, -2);
            bar.style.position = IStyle.PositionEnum.@fixed;
            bar.style.height = "3px";
            bar.style.backgroundColor = "red";
            //bar.style.borderBottom = "1px solid darkred";

            // http://stackoverflow.com/questions/9670075/css-transition-shorthand-with-multiple-properties

            (bar.style as dynamic).webkitTransition = "top 0.5s linear";
            //(bar.style as dynamic).webkitTransitionProperty = "top, width, background-color";
            (bar.style as dynamic).webkitTransitionProperty = "top, width";




            var state = new
                {
                    __e.Name,

                    backgroundColor = "red",

                    loaded = default(long),
                    total = default(long),
                    source = default(string),

                    Native.document.location.href,


                    references = new InternalScriptApplicationReference[0]
                };

            Console.WriteLine("call Task.Factory.StartNewWithProgress");

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160108

            Task.Factory.StartNewWithProgress(
                state,

                progress: x =>
                {
                    bar.style.top = "0px";


                    #region bar
                    if (x.loaded > 0)
                        if (x.total > 0)
                        {
                            //if (x.loaded == x.total)
                            //{
                            //}
                            //else
                            //{
                            //    bar.style.SetLocation(0, 0);
                            //}

                            var xx = (int)(100 * x.loaded / x.total);

                            ;
                            // 
                            // 3% is the minimum we want to show
                            var per = Math.Max(3, xx) + "%";

                            //Console.WriteLine(new { per, x.loaded, x.total, x.backgroundColor });

                            bar.style.backgroundColor = x.backgroundColor;
                            bar.style.width = per;

                        }
                    #endregion



                    //Console.WriteLine(
                    //    new { x.Name, x.loaded, x.total }
                    //);

                    #region SetResult
                    x.source.With(
                        async source =>
                        {
                            //        // should we analyze? IFunction

                            //Console.WriteLine("wall save source to localStorage " + new { __e.Name, source.Length });

                            // sessionStorage out of memory?
                            //Native.window.sessionStorage[__e.Name] = source;

                            //Native.window.eval(
                            //    //x.responseText
                            //    source
                            //);


                            bar.style.backgroundColor = "yellow";
                            await Task.Delay(300);
                            bar.style.backgroundColor = "red";
                            await Task.Delay(300);
                            bar.style.backgroundColor = "yellow";
                            await Task.Delay(300);
                            bar.style.backgroundColor = "red";
                            await Task.Delay(300);
                            bar.Orphanize();

                            //                            { index = 0, name =  ScriptCoreLib.dll.js, size = 1330538 } view-source:27530

                            // view-source:27530
                            //{ index = 1, name =  WorkerInsideSecondaryApplicationWithBackButton.Application+x.exe.js, size = 507500 } view-source:2753


                            y.SetResult(
                                new InternalScriptApplicationSource
                                {
                                    source = source,
                                    references = x.references
                                }

                            );
                        }
                    );
                    #endregion


                },


                function:
                    tuple =>
                    {
                        var progress = tuple.Item1;
                        var scope = tuple.Item2;

                        // http://stackoverflow.com/questions/13870853/how-to-upload-files-in-web-workers-when-formdata-is-not-defined
                        // FormData is not defined
                        //var f = new FormData();

                        //f.append("Application", scope.Name);


                        // can we use WebClient instead now?
                        var x = new IXMLHttpRequest();

                        // { src = /more-source } 

                        // { src = blob:http%3A//192.168.43.252%3A5485/fdec11d3-735f-4165-937a-43f25ef8d8d3#worker/more-source } 
                        // worker location might not help us talk to our server!

                        //var src = Native.worker.location.href + "/more-source";
                        //POST http://public:[email protected]:14356//more-source 400 (Bad Request) 
                        var src = scope.href;

                        Console.WriteLine(new { src });

                        x.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, src,
                            async: true,
                            user: "******",
                            password: "******"
                        );

                        // Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
                        x.setRequestHeader(
                            "X-Application", scope.Name
                        );

                        // what about progress?


                        // http://stackoverflow.com/questions/10956574/why-might-xmlhttprequest-progressevent-lengthcomputable-be-false

                        var xprogress = new { scope.loaded, scope.total };

                        // AppEngine will not report progress

                        #region onprogress
                        x.onprogress +=
                            e =>
                            {
                                // make room for decrypt progress
                                var loaded = e.loaded / 2;

                                xprogress = new { loaded, e.total };

                                //Console.WriteLine();

                                progress.Report(
                                    new
                                    {
                                        scope.Name,
                                        scope.backgroundColor,
                                        xprogress.loaded,
                                        xprogress.total,
                                        scope.source,
                                        scope.href,
                                        scope.references
                                    }
                                );

                            };
                        #endregion


                        #region decrypt
                        Action<byte[]> decrypt = response =>
                        {
                            var AllResponseHeaders = x.getAllResponseHeaders();

                            //AllResponseHeaders = Date: Wed, 11 Sep 2013 14:31:43 GMT
                            //X-Reference-0: ScriptCoreLib.dll.js 1330538
                            //Server: ASP.NET Development Server/11.0.0.0
                            //X-AspNet-Version: 4.0.30319
                            //X-Reference-1: WorkerInsideSecondaryApplicationWithBackButton.Application+x.exe.js 487668
                            //X-DiagnosticsMakeItSlowAndAddSalt: ok
                            //Content-Type: application/octet-stream
                            //Cache-Control: public
                            //Connection: Close
                            //Content-Length: 3636412
                            //Expires: Wed, 11 Sep 2013 14:46:43 GMT

                            var prefix = "X-Reference-";

                            var references = AllResponseHeaders.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Where(k => k.StartsWith(prefix)).Select(
                                k =>
                                {
                                    var text = k.Substring(prefix.Length);

                                    var index = int.Parse(text.TakeUntilIfAny(":"));
                                    var name = text.SkipUntilIfAny(":").TakeUntilLastIfAny(" ");
                                    var size = int.Parse(text.SkipUntilIfAny(":").SkipUntilLastIfAny(" "));

                                    return new InternalScriptApplicationReference
                                    {
                                        index = index,
                                        name = name,
                                        size = size
                                    };
                                }
                            ).ToArray();


                            Console.WriteLine(
                                "loading secondary app in a moment... "
                                + new
                                {
                                    response.Length,
                                    Thread.CurrentThread.ManagedThreadId
                                } + " decrypting...");

                            // loading secondary app in a moment... { Length = 6265416, ManagedThreadId = 10 } decrypting...


                            //                            X-Reference-0:ScriptCoreLib.dll.js 1330538
                            //X-Reference-1:WorkerInsideSecondaryApplicationWithBackButton.Application+x.exe.js 485234
                            // "X:\jsc.svn\examples\javascript\WorkerInsideSecondaryApplication\WorkerInsideSecondaryApplication.sln"

                            //y.SetResult(new { x.responseText.Length }.ToString());
                            // X:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Ultra\WebService\InternalGlobalExtensions.cs

                            var mstopwatch = Stopwatch.StartNew();
                            var m = new MemoryStream();

                            var lo = default(byte);
                            var lo_set = false;

                            foreach (var item in response)
                            {
                                if (lo_set)
                                {
                                    lo_set = false;

                                    var hi = (byte)(item << 4);

                                    m.WriteByte(
                                        (byte)(lo | hi)
                                    );

                                    if ((m.Length % 1024 * 8) == 0)
                                    {
                                        var loaded = xprogress.total / 2 + m.Length;

                                        xprogress = new { loaded, xprogress.total };

                                        //Console.WriteLine(new
                                        //{
                                        //    Thread.CurrentThread.ManagedThreadId,

                                        //    mstopwatch.ElapsedMilliseconds,
                                        //    xprogress
                                        //});

                                        progress.Report(
                                            new
                                            {
                                                scope.Name,
                                                backgroundColor = "cyan",
                                                xprogress.loaded,
                                                xprogress.total,
                                                scope.source,
                                                scope.href,
                                                scope.references
                                            }
                                        );
                                    }
                                }
                                else
                                {
                                    lo = item;
                                    lo_set = true;
                                }
                            }

                            // decrypted
                            Console.WriteLine("UTF8.GetString " + new { m.Length });

                            var source = Encoding.UTF8.GetString(m.ToArray());


                            Console.WriteLine("loading secondary app in a moment... " + new { source.Length } + " done!");

                            //return new { response.Length, responseText = source };

                            progress.Report(
                                new
                                {
                                    scope.Name,
                                    backgroundColor = "green",
                                    xprogress.loaded,
                                    xprogress.total,
                                    source,
                                    scope.href,
                                    references
                                }
                            );

                        };
                        #endregion


                        Action send = async delegate
                        {


                            var response = await x.bytes;


                            decrypt(response);

                        };


                        send();

                        // no changes yet
                        return scope;
                    }


            );


            return y.Task.GetAwaiter();


        }
Пример #12
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            // http://html5doctor.com/drag-and-drop-to-server/

            #region ondrop
            Native.document.body.ondragover +=
                evt =>
                {
                    evt.stopPropagation();
                    evt.preventDefault();

                    evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.


                    page.Header.style.color = JSColor.Green;


                    var types = evt.dataTransfer.types == null ? 0 : evt.dataTransfer.types.Length;

                    if (evt.dataTransfer.types != null)
                        foreach (var type in evt.dataTransfer.types.AsEnumerable())
                        {
                            Console.WriteLine(
                                new { type }
                                );
                        }

                    var items = evt.dataTransfer.items == null ? 0u : evt.dataTransfer.items.length;
                    var files = evt.dataTransfer.files == null ? 0u : evt.dataTransfer.files.length;



                    Console.WriteLine("ondragover: " +
                        new
                        {

                            types,
                            items,
                            files
                        }
                    );
                };


            Native.document.body.ondragleave +=
                delegate
                {
                    page.Header.style.color = JSColor.None;
                };

            #region DetectCanvasFromBytesExperiment
            Action<Form, WebBrowser, string, string, long> DetectCanvasFromBytesExperiment =
                (ff, web, ContentValue, src, ContentBytesLength) =>
                {
                    web.Navigated +=
                           async delegate
                           {
                               if (ContentValue != "png.png")
                                   return;

                               // X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\CanvasFromBytes\Application.cs
                               //Console.WriteLine("interesting, is it one of ours? " + new { ContentValue });
                               ff.Text = "interesting, is it one of ours? " + new { ContentValue };

                               var csrci = new IHTMLImage { src = src };

                               //await csrci.async.onlo
                               await csrci;

                               if (csrci.width != csrci.height)
                                   return;


                               var w = csrci.width;


                               // 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;

                               ff.Text = "will decode " + new { zbytes.Length, ContentBytesLength }.ToString();

                               #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


                               var html = Encoding.UTF8.GetString(decodebytes);

                               ff.Text = "decoded " + new { html.Length, ContentBytesLength }.ToString();

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


                               // um hide old data.
                               web.Hide();

                               var xweb = new WebBrowser { Dock = DockStyle.Fill };
                               xweb.AttachTo(ff);
                               xweb.DocumentText = html;
                               ff.Text = "!decoded " + new { html.Length, ContentBytesLength }.ToString();
                           };

                };
            #endregion


            Native.document.body.ondrop +=
                evt =>
                {
                    //if (evt.dataTransfer == null)
                    //    return;

                    var types = evt.dataTransfer.types == null ? 0 : evt.dataTransfer.types.Length;

                    var items = evt.dataTransfer.items == null ? 0u : evt.dataTransfer.items.length;
                    var files = evt.dataTransfer.files == null ? 0u : evt.dataTransfer.files.length;


                    Console.WriteLine("ondrop: " +
                        new
                        {

                            types,
                            items,
                            files
                        }
                    );


                    page.Header.style.color = JSColor.None;


                    //var xfiles = evt.dataTransfer.files.AsEnumerable().Concat(
                    //    from x in evt.dataTransfer.items.AsEnumerable()
                    //    let f = x.getAsFile()
                    //    where f != null
                    //    select f
                    //);

                    #region DataTable
                    if (evt.dataTransfer.items != null)
                    {
                        // X:\jsc.svn\examples\javascript\DragDataTableIntoCSVFile\DragDataTableIntoCSVFile\Application.cs

                        evt.dataTransfer.items.AsEnumerable().Where(
                            x =>

                                x.type.ToLower() ==

                                // let jsc type system sort it out?
                                // how much reflection does jsc give us nowadays?
                                typeof(DataTable).Name.ToLower()

                        ).WithEach(
                            async x =>
                            {
                                // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dfnReturnLink-0
                                var DataTable_xml = await x.getAsString();

                                var DataTable = StringConversionsForDataTable.ConvertFromString(DataTable_xml);

                                var ff = new Form { Text = new { typeof(DataTable).Name }.ToString() };

                                var g = new DataGridView { DataSource = DataTable, Dock = DockStyle.Fill };

                                ff.Controls.Add(g);


                                ff.Show();

                            }
                        );
                    }
                    #endregion

                    #region files
                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            Console.WriteLine(
                                new
                                {

                                    f.name,
                                    f.size,
                                    f.lastModifiedDate
                                }
                            );

                            var ff = new Form();
                            ff.PopupInsteadOfClosing(HandleFormClosing: false);



                            ff.Text = new { f.type, f.name, f.size }.ToString();


                            ff.Show();

                            ff.MoveTo(
                                evt.CursorX + 32 * index,
                                evt.CursorY + 24 * index
                            );

                            var fc = ff.GetHTMLTargetContainer();

                            fc.title = ff.Text;

                            #region image
                            var i = default(IHTMLImage);

                            if (f.type.StartsWith("image/"))
                            {
                                // um would we have a timing issue here?
                                f.ToDataURLAsync(
                                    src =>
                                    {
                                        i = new IHTMLImage { src = src }.AttachTo(fc);
                                        i.style.width = "100%";

                                        i.InvokeOnComplete(
                                            delegate
                                            {

                                                ff.ClientSize = new System.Drawing.Size(
                                                    // keep it reasonable!
                                                    i.width.Min(600),
                                                    i.height.Min(400)
                                                );

                                            }
                                        );
                                    }
                                );
                            }
                            #endregion

                            // http://html5doctor.com/drag-and-drop-to-server/

#if FUTURE
                            service.XUpload(f, delegate { });
#endif


                            var d = new FormData();

                            d.append("foo", f, f.name);

                            var xhr = new IXMLHttpRequest();

                            xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/upload");

                            #region InvokeOnComplete
                            xhr.InvokeOnComplete(
                                delegate
                                {
                                    Console.WriteLine("upload complete!");

                                    SystemSounds.Beep.Play();

                                    //Console.Beep();
                                    XElement.Parse(xhr.responseText).Elements("ContentKey").WithEach(
                                        ContentKey =>
                                        {
                                            var __ContentKey = (Table1_ContentKey)int.Parse(ContentKey.Value);

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

                                            web.Hide();
                                            web.AttachTo(ff);


                                            var src = "/io/" + ContentKey.Value;

                                            if (i == null)
                                            {
                                                web.Show();
                                            }
                                            else
                                            {
                                                web.Navigated +=
                                                    delegate
                                                    {
                                                        i.Orphanize();
                                                        web.Show();
                                                    };
                                            }


                                            // "X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\png.png"
                                            DetectCanvasFromBytesExperiment(
                                                ff,
                                                web,
                                                 f.name,
                                                src,
                                               (long)f.size
                                            );

                                            web.Navigate(src);


                                            //if (i != null)
                                            //{
                                            //    i.src = src;
                                            //}

                                            __ContentKey.SetLeft(ff.Left);
                                            __ContentKey.SetTop(ff.Top);

                                            ff.LocationChanged +=
                                                delegate
                                                {
                                                    __ContentKey.SetLeft(ff.Left);
                                                    __ContentKey.SetTop(ff.Top);
                                                };

                                            ff.SizeChanged +=
                                                delegate
                                                {
                                                    __ContentKey.SetWidth(ff.Width);
                                                    __ContentKey.SetHeight(ff.Height);
                                                };

                                            ff.FormClosing +=
                                                delegate
                                                {
                                                    __ContentKey
                                                        .Delete();
                                                };


                                            #region onmousewheel
                                            ff.GetHTMLTarget().With(
                                                ffh =>
                                                {
                                                    dynamic ffhs = ffh.style;
                                                    // http://css-infos.net/property/-webkit-transition
                                                    //ffhs.webkitTransition = "webkitTransform 0.3s linear";

                                                    ffh.onmousewheel +=
                                                        e =>
                                                        {
                                                            e.preventDefault();
                                                            e.stopPropagation();


                                                            if (e.WheelDirection > 0)
                                                            {
                                                                ff.Width = (int)(ff.Width * 1.1);
                                                                ff.Height = (int)(ff.Height * 1.1);
                                                            }
                                                            else
                                                            {
                                                                ff.Width = (int)(ff.Width * 0.9);
                                                                ff.Height = (int)(ff.Height * 0.9);
                                                            }

                                                        };

                                                }
                                            );
                                            #endregion

                                        }
                                    );
                                }
                            );
                            #endregion


                            //------WebKitFormBoundaryDmGHAZzeMBbcD5mu
                            //Content-Disposition: form-data; name="foo"; filename="FlashHeatZeeker.UnitPedControl.ApplicationSprite.swf"
                            //Content-Type: application/x-shockwave-flash


                            //------WebKitFormBoundaryDmGHAZzeMBbcD5mu--

                            Console.WriteLine("before upload...");
                            xhr.send(d);
                        }
                    );
                    #endregion


                    // let's disable other handlers
                    //evt.dataTransfer = null;

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();
                };
            #endregion

            #region restore
            {
                var index = 0;

                default(Table1_ContentKey).WithEach(
                    (__ContentKey, ContentBytesLength, ContentValue, Left, Top, Width, Height) =>
                    {

                        var ff = new Form();
                        ff.PopupInsteadOfClosing(HandleFormClosing: false);


                        ff.Text = new { __ContentKey, ContentValue, ContentBytesLength }.ToString();


                        ff.Show();

                        if (Left > 0)
                            ff.MoveTo(
                                Left,
                                Top
                            );
                        else

                            ff.MoveBy(
                                32 * index,
                                24 * index
                            );

                        index++;

                        #region onmousewheel
                        ff.GetHTMLTarget().With(
                            ffh =>
                            {
                                dynamic ffhs = ffh.style;
                                // http://css-infos.net/property/-webkit-transition
                                //ffhs.webkitTransition = "webkitTransform 0.3s linear";

                                ffh.onmousewheel +=
                                    e =>
                                    {
                                        e.preventDefault();
                                        e.stopPropagation();

                                        if (e.WheelDirection > 0)
                                        {
                                            ff.Width = (int)(ff.Width * 1.1);
                                            ff.Height = (int)(ff.Height * 1.1);
                                        }
                                        else
                                        {
                                            ff.Width = (int)(ff.Width * 0.9);
                                            ff.Height = (int)(ff.Height * 0.9);
                                        }

                                    };

                            }
                        );
                        #endregion



                        //var fc = ff.GetHTMLTargetContainer();
                        var src = "/io/" + __ContentKey;

                        //var i = new IHTMLImage { src = src }.AttachTo(fc);
                        //i.style.width = "100%";

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

                        web.AttachTo(ff);

                        //script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.WebBrowser.add_DocumentCompleted(System.Windows.Forms.WebBrowserDocumentCompletedEventHandler)]
                        //script: warning JSC1000: Did you reference ScriptCoreLib via IAssemblyReferenceToken?
                        //script: error JSC1000: error at DropFileIntoSQLite.Application+<>c__DisplayClass2e.<.ctor>b__15,
                        // assembly: V:\DropFileIntoSQLite.Application.exe
                        // type: DropFileIntoSQLite.Application+<>c__DisplayClass2e, DropFileIntoSQLite.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

                        //web.DocumentCompleted +=
                        //    delegate
                        //    {



                        //};

                        DetectCanvasFromBytesExperiment(
                            ff,
                            web,
                            ContentValue,
                            src,
                            ContentBytesLength
                        );


                        web.Navigate(src);

                        if (Width > 0)
                            ff.SizeTo(
                               Width,
                               Height
                           );
                        //else
                        //    i.InvokeOnComplete(
                        //        delegate
                        //        {


                        //            ff.ClientSize = new System.Drawing.Size(i.width, i.height);

                        //        }
                        //    );

                        ff.LocationChanged +=
                            delegate
                            {
                                __ContentKey.SetLeft(ff.Left);
                                __ContentKey.SetTop(ff.Top);
                            };

                        ff.SizeChanged +=
                            delegate
                            {
                                __ContentKey.SetWidth(ff.Width);
                                __ContentKey.SetHeight(ff.Height);
                            };

                        ff.FormClosing +=
                            delegate
                            {
                                __ContentKey.Delete();
                            };
                    }
                );
            }
            #endregion



            // can we write about this?
            #region bookmark launcher
            var href = @"javascript:
((function(h,i)
{ 
    

    var a=-1, 
    b='onreadystatechange', 
    c=document.getElementsByTagName('HEAD')[0], 
    d, 
    e, 
    f, 
    g=c.childNodes, 
    d; 

    e=document.createElement('base');   
    e.href='%%';
    c.appendChild(e);     

    d = function () 
    {  
        next: while (1)  
        {   
            a++;     
            if (a ==h.length)   
            {   
                i();    
                return;   
            }     

            /*
            for (f=0;f<g.length;f++)   
            {   
                var v =g[f];    
                var w =h[a];       

                if (v.nodeName =='SCRIPT')    
                    if (v.src ==w || v.src.substr(v.src.length - w.length - 1,w.length + 1) =='/' + w)    
                        continue next;   
            } */      
            e=document.createElement('SCRIPT');   
            e.src='%%' + h[a];     
            e[b in e?b:'onload']=  function()    
            {       
                var f=e.readyState;    
                if(f==null||f=='loaded'||f=='complete')     
                    d();    
            };  
 
        c.appendChild(e);     
        return;  
    } 
}; 
d();

}

)(['view-source'],function(){}))".Replace("%%", Native.Document.location + "");

            page.Header.draggable = true;
            page.Header.ondragstart +=
                e =>
                {
                    e.dataTransfer.setData("text/uri-list", href);
                };


            IStyleSheet.Default["#Header:hover"].style.color = "red";
            IStyleSheet.Default["#Header:hover"].style.cursor = IStyle.CursorEnum.pointer;

            #endregion


            new About().Show();
        }
Пример #13
0
        // DownloadDataTaskAsync
        // X:\jsc.svn\examples\javascript\Test\TestScriptApplicationIntegrity\TestScriptApplicationIntegrity\Application.cs
        // shall we test it on a gif?
        // X:\jsc.svn\examples\javascript\io\GIFDecoderExperiment\GIFDecoderExperiment\Application.cs

        // NET 4.5
        public Task<byte[]> DownloadDataTaskAsync(string address)
        {
            // Z:\jsc.svn\examples\javascript\audio\StereoChannelVisualization\Application.cs

            var x = new IXMLHttpRequest();
            x.open(Shared.HTTPMethodEnum.GET, address);
            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\DOM\IXMLHttpRequest.cs

            return x.bytes;
        }
Пример #14
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {


            // http://html5doctor.com/drag-and-drop-to-server/

            Native.Document.body.ondragover +=
                evt =>
                {
                    evt.stopPropagation();
                    evt.preventDefault();

                    evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.


                    page.Header.style.color = JSColor.Green;

                    Console.WriteLine("ondragover: " + new
                    {

                        types = evt.dataTransfer.types.Length,
                        files = evt.dataTransfer.files.length
                    }
                    );
                };


            Native.Document.body.ondragleave +=
                delegate
                {
                    page.Header.style.color = JSColor.None;
                };

            Native.Document.body.ondrop +=
                async evt =>
                {
                    //if (evt.dataTransfer == null)
                    //    return;


                    // let's disable other handlers
                    //evt.dataTransfer = null;

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();


                    page.Header.style.color = JSColor.None;



                    #region files



                    // http://html5doctor.com/drag-and-drop-to-server/

#if FUTURE
                            service.XUpload(f, delegate { });
#endif


                    var d = new FormData();


                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                          (f, index) =>
                          {
                              d.append(
                                  "foo" + index,
                                  f,
                                  f.name
                              );
                          }
                    );


                    var xhr = new IXMLHttpRequest();

                    xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/upload");

                    //xhr.InvokeOnComplete(
                    //    delegate
                    //    {
                    //        SystemSounds.Beep.Play();

                    //    }
                    //);

                    xhr.send(d);

                    await xhr;

                    SystemSounds.Beep.Play();

                    #endregion


                };
        }
Пример #15
0
        public ApplicationContent(
            IApp page = null,
            IApplicationWebServiceX service = null)
        {
            // need absolute path when docked..
            page.style1.href = page.style1.href;

            // first order of business.
            // enable drop zone.
            var dz = new DropZone();


            dz.Container.AttachToDocument();
            dz.Container.Hide();

            var StayAlertTimer = default(Timer);
            var DoRefresh = default(Action);

            #region StayAlert
            Action<string> StayAlert =
                transaction_id =>
                {
                    StayAlertTimer = new Timer(
                        delegate
                        {
                            service.GetTransactionKeyAsync(
                                id =>
                                {
                                    if (id == transaction_id)
                                        return;

                                    // shot down during flight?
                                    if (!StayAlertTimer.IsAlive)
                                        return;

                                    Console.WriteLine("StayAlert " + new { id, transaction_id });

                                    DoRefresh();
                                }
                            );
                        }
                    );

                    StayAlertTimer.StartInterval(5000);
                };
            #endregion


            DoRefresh =
                delegate
                {
                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();

                    page.output.Clear();

                    new FileLoading().Container.AttachTo(page.output);

                    service.EnumerateFilesAsync(
                        y:
                        (
                            long ContentKey,
                            string ContentValue,
                            string ContentType,
                            long ContentBytesLength
                        ) =>
                        {
                            var e = new FileEntry();

                            #region ContentValue
                            e.ContentValue.value = ContentValue.TakeUntilLastIfAny(".");
                            e.ContentValue.onchange +=
                                delegate
                                {
                                    var ext = ContentValue.SkipUntilLastOrEmpty(".");

                                    if (ext != "")
                                        ext = "." + ext;

                                    ContentValue = e.ContentValue.value + ext;


                                    Console.WriteLine("before update!");

                                    service.UpdateAsync(
                                        ContentKey,
                                        ContentValue,
                                        // null does not really work?
                                        delegate
                                        {
                                            Console.WriteLine("update done!");
                                        }
                                    );

                                    e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                                };
                            e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                            e.open.target = Target;

                            #endregion

                            e.ContentType.innerText = ContentBytesLength + " bytes " + ContentType;


                            #region Delete
                            e.Delete.WhenClicked(
                                delegate
                                {
                                    //e.ContentValue.style.textDecoration = ""

                                    if (StayAlertTimer != null)
                                        StayAlertTimer.Stop();

                                    e.Container.style.backgroundColor = "red";

                                    service.DeleteAsync(
                                        ContentKey,
                                        delegate
                                        {

                                            DoRefresh();
                                        }
                                    );
                                }
                            );
                            #endregion


                            e.Container.AttachTo(page.output);



                            Console.WriteLine(
                                new { ContentKey, ContentValue, ContentType, ContentBytesLength }
                            );

                        },

                        done: transaction_id =>
                        {
                            Console.WriteLine(new { transaction_id });
                            new FileLoadingDone().Container.AttachTo(page.output);

                            StayAlert(transaction_id);
                        }
                    );
                };

            #region ondrop

            var TimerHide = new Timer(
                delegate
                {
                    dz.Container.Hide();
                }
            );

            Action<DragEvent> ondragover =
                evt =>
                {
                    //Console.WriteLine("ondragover");


                    evt.stopPropagation();
                    evt.preventDefault();

                    // ondragover { type = Files }

                    //foreach (var type in evt.dataTransfer.types)
                    //{
                    //    Console.WriteLine("ondragover " + new { type });
                    //}


                    if (evt.dataTransfer.types.Contains("Files"))
                    {


                        evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.

                        dz.Container.Show();
                        TimerHide.Stop();
                    }

                    //}

                    //Console.WriteLine(" Native.Document.body.ondragover");
                };

            Native.Document.body.ondragover += ondragover;
            dz.Container.ondragover += ondragover;

            //dz.Container.ondragstart +=
            //    evt =>
            //    {
            //        Console.WriteLine("ondragstart");


            //        evt.stopPropagation();
            //        evt.preventDefault();
            //    };

            dz.Container.ondragleave +=
                 evt =>
                 {
                     //Console.WriteLine("ondragleave");

                     //Console.WriteLine(" dz.Container.ondragleave");

                     evt.stopPropagation();
                     evt.preventDefault();

                     TimerHide.StartTimeout(90);
                 };

            dz.Container.ondrop +=
                evt =>
                {
                    //Console.WriteLine("ondrop");

                    TimerHide.StartTimeout(90);

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();

                    // can we use a webClient yet?
                    var xhr = new IXMLHttpRequest();

                    // does not work for chrome?
                    //xhr.setRequestHeader("WebServiceMethod", "FileStorageUpload");

                    // which server?
                    xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/FileStorageUpload");

                    // http://stackoverflow.com/questions/13870853/how-to-upload-files-in-web-workers-when-formdata-is-not-defined

                    //var c = new WebClient();

                    ////c.UploadData(
                    //c.UploadProgressChanged +=
                    //    (sender, args) =>
                    //    {

                    //    };

                    //c.UploadFileAsync(



                    #region send
                    var d = new FormData();

                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            d.append("file" + index, f, f.name);
                        }
                    );

                    xhr.InvokeOnComplete(
                        delegate
                        {
                            Console.WriteLine("upload complete!");

                            DoRefresh();
                        }
                    );

                    var upload = new Uploading();

                    upload.Container.AttachTo(page.output);
                    // http://www.matlus.com/html5-file-upload-with-progress/
                    xhr.upload.onprogress +=
                        e =>
                        {
                            var p = (int)(e.loaded * 100 / e.total) + "%";

                            upload.status = p;

                            Console.WriteLine("upload.onprogress " + new { e.total, e.loaded });
                        };

                    xhr.send(d);
                    #endregion


                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();



                };
            #endregion




            DoRefresh();
        }
Пример #16
0
		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IApp page)
		{
			// http://developer.chrome.com/extensions/override.html

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

			if (self_chrome_tabs != null)
			{
				//                ---------------------------
				//Extension error
				//---------------------------
				//Could not load extension from 'A:\'. Could not load options page '_generated_background_page.html'.
				//---------------------------
				//OK   
				//---------------------------


				Action<Tab> pageActionClick = delegate
				{
				};

				Console.WriteLine("loading ChromeTabsExperiment...");

				chrome.Notification.DefaultTitle = "ChromeTabsExperiment";

				#region chrome.runtime

				// unavailable for extension
				//  chrome.app.runtime.Restarted +=
				//delegate
				//{
				//    new Notification
				//    {
				//        Message = "Restarted!"
				//    };
				//};


				chrome.runtime.Installed += delegate
				{
					new chrome.Notification
					{
						Message = "Extension Installed"
					};
				};

				chrome.runtime.Startup +=
					delegate
					{
						new chrome.Notification
						{
							Message = "Startup!"
						};
					};


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

				chrome.runtime.Suspend +=
					delegate
					{
						var n = new chrome.Notification
						{
							Message = "Suspend! " + new { t.ElapsedMilliseconds }
						};

						n.Clicked += delegate
						{
							runtime.reload();
						};

					};
				#endregion


				//chrome.tabs.Created +=
				//    tab =>
				//    {
				//        if (tab.url.StartsWith("chrome-devtools://"))
				//            return;

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

				//        new chrome.Notification
				//        {
				//            Message = "chrome.tabs.Created " + new
				//            {
				//                tab.id,
				//                tab.url,
				//                tab.status,
				//                tab.title
				//            }
				//        };



				//    };


				chrome.tabs.Updated +=
					(i, x, tab) =>
					{
						// chrome://newtab/

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

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

						if (tab.status == "complete")
						{


							// lso keep in mind that content scripts are not injected into any chrome:// or extension gallery pages.
							//chrome.tabs.insertCSS(

							//tab.id.insertCSS(
							//    new
							//    {
							//        code = "body { background-color: cyan; }"
							//    },
							//    null
							//);


							// this does not work
							//tab.id.insertCSS(
							//    new
							//    {
							//        code = "body { background-color: yellow; }"
							//    },
							//    IFunction.OfDelegate(
							//        new Action(
							//            delegate
							//            {
							//            }
							//        )
							//    )
							//);

							// can we have a new Worker here?
							// upon click?


							var xhr = new IXMLHttpRequest();
							//Console.WriteLine(new { asset });

							xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.GET, "view-source");


							xhr.bytes.ContinueWith(
								task =>
								{
									var code = Encoding.UTF8.GetString(task.Result);

									//var n = new chrome.Notification
									//{
									//    Title = "click to inject... ",
									//    Message = tab.url,
									//};

									#region inject
									Action inject = async delegate
									{
										Console.WriteLine("executeScript");

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

										//var port = tab.id.connect();

										////port.
										//port.onMessage.addListener(
										//    new Action<object>(
										//        data =>
										//        {
										//            Console.WriteLine(
										//                "onMessage " + new { tab.id, data }
										//            );
										//        }
										//    )
										//);

										await tab.id.executeScript(
											new { code }
										);

										//await System.Threading.Tasks.Task.Delay(200);

										Console.WriteLine("sendMessage " + new { st.ElapsedMilliseconds });

										// http://stackoverflow.com/questions/14790389/return-value-from-chrome-tabs-executescript

										var forever = true;

										while (forever)
										{
											await System.Threading.Tasks.Task.Delay(333);


											var responses = (object[])await tab.id.executeScript(
											  new { code = "(onxmessage('hello!'));" }
										  );

											//// http://ferdinandfly.blogspot.com/2013/04/chrome-extension-error-attempting-to.html
											//// message: "Attempting to use a disconnected port object"
											//port.postMessage(
											//      new { hello = "world" }
											//    );

											//var response = await tab.id.sendMessage(
											//    new { hello = "world" }
											//);

											if (responses != null)
											{
												responses.WithEach(
													response =>
													{
														if (response == null)
															return;

														forever = false;

														var nn = new chrome.Notification
														{
															Title = "signal!",
															Message = (string)response,
														};


														// does this work?
														nn.Closed +=
															delegate
															{

															};
														tab.id.show();

													}
												);
											}
										}

									};
									#endregion


									// http://stackoverflow.com/questions/4022179/chrome-page-action-click-not-working
									// Uncaught TypeError: Cannot read property 'onClicked' of undefined 
									chrome.pageAction.Clicked +=
										xtab =>
										{
											if (xtab.id != tab.id)
												return;

											// let extension call app
											// which in turn can call
											// udp android
											pageActionClick(tab);

											if (inject != null)
											{
												tab.id.hide();

												inject();
												inject = null;
											}
										};

									//tab.id.setTitle(
									tab.id.show();

									//n.Clicked += async delegate
									//{

									//};


								}
							);

							return;
						}

						//new chrome.Notification
						//{
						//    Message = "chrome.tabs.Updated " + new
						//    {
						//        tab.id,
						//        tab.url,
						//        tab.status,
						//        tab.title
						//    }
						//};
					};


				chrome.tabs.Detached +=
				  (id, x) =>
				  {
					  new chrome.Notification
					  {
						  Message = "chrome.tabs.Detached " + new { id }
					  };
				  };


				//new Notification
				//{
				//    Message = "extension!"
				//};

				#region slave
				// Port: Could not establish connection. Receiving end does not exist. 
				var slave = "fkgibadjpabiongmgoeomdbcefhabmah";
				// http://stackoverflow.com/questions/13921970/google-chrome-socket-api-in-extensions
				// No, extensions do not have access to the socket API, and they aren't likely to ever get it.

				Console.WriteLine("connect " + new { slave });
				chrome.runtime.connect(slave).With(
					port =>
					{
						Console.WriteLine("connect done " + new { slave });

						port.onDisconnect.addListener(
							 new Action(
								  delegate
								  {
									  Console.WriteLine("connect onDisconnect");

								  }
							  )
						);

						port.onMessage.addListener(
							  new Action<object>(
								  message =>
								  {
									  Console.WriteLine("connect onMessage " + new { message });

									  var nn = new chrome.Notification
									  {
										  Title = "hybrid app signal!",
										  Message = new { message }.ToString(),
									  };
								  }
							  )
						  );

						port.postMessage(
										 new { hello = "slave" }
									 );


						pageActionClick +=
							tab =>
							{
								Console.WriteLine("pageActionClick " + new { tab.id });

								try
								{
									port.postMessage(
										new { tab.id }
									);
								}
								catch
								{
									Console.WriteLine("error pageActionClick " + new { tab.id });
								}

							};

						Console.WriteLine("connect posted " + new { slave });
					}
				);
				#endregion



				return;
			}



			Console.WriteLine("hello!");

			IStyleSheet.Default["h1"].style.color = "blue";
			IStyleSheet.Default["body"].style.backgroundColor = "yellow";


			//http://developer.chrome.com/extensions/messaging.html
			// This will expose the messaging API to any page which matches the URL patterns you specify. The URL pattern must contain at least a second-level domain - that is, hostname patterns like "*", "*.com", "*.co.uk", and "*.appspot.com" are prohibited. From the web page, use the runtime.sendMessage or runtime.connect APIs to send a message to a specific app or extension. For example:

			// this wont be called by the chrome overlord?
			Native.window.onmessage +=
				e =>
				{
					Console.WriteLine("onmessage " + new { e.data });

					e.ports.WithEach(
						port =>
						{
							port.postMessage(new { marko = new { e.data } });

						}
					);

				};

			#region onxmessage
			var xst = new Stopwatch();

			xst.Start();

			// this will work
			Func<string, object> onxmessage =
				data =>
				{
					Console.WriteLine("onxmessage " + new { data });

					if (xst.IsRunning)
						if (xst.ElapsedMilliseconds > 2000)
						{
							xst.Stop();

							return "special message from " + new { Native.document.location.href, data };

						}
					return null;
				};


			(Native.self as dynamic).onxmessage = onxmessage;
			#endregion

			// http://slashdot.org/
			//<iframe id="google_ads_iframe_243358" name="google_ads_iframe_243358"

			Native.document.getElementsByTagName("iframe").WithEach(
				iframe =>
				{
					if (iframe.name.StartsWith("google_ads"))
					{
						iframe.style.Opacity = 0.3;
						return;
					}

					// aswift
					if (iframe.name.StartsWith("aswift"))
					{
						iframe.style.Opacity = 0.3;
						return;
					}

					// "<iframe width="300" height="250" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&amp;&amp;s.handlers,h=H&amp;&amp;H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&amp;&amp;d&amp;&amp;(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){w.location.replace(h)}}" id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;"></iframe>"


					//<div id="rightCol" role="complementary" aria-label="Reminders, people you may know, and ads"><

				}
			);

			Native.document.getElementsByTagName("div").WithEach(
				 x =>
				 {

					 if (x.attributes.Any(a => a.value == "Reminders, people you may know, and ads"))
					 {
						 x.style.Opacity = 0.3;
						 return;
					 }

					 //<div id="rightCol" role="complementary" aria-label="Reminders, people you may know, and ads"><

				 }
			 );

			//chrome.runtime.Message +=
		}
Пример #17
0
        // used by?
        public void DownloadStringAsync(Uri address)
        {
            var x = new IXMLHttpRequest();

            x.open(Shared.HTTPMethodEnum.GET, address.ToString());

            x.InvokeOnComplete(
                r =>
                {
                    //var e = new __DownloadStringCompletedEventArgs { Error = new Exception("Not implemented. (__WebClient.DownloadStringAsync)") };
                    var e = new __DownloadStringCompletedEventArgs { Result = r.responseText };

                    if (DownloadStringCompleted != null)
                        DownloadStringCompleted(null, (DownloadStringCompletedEventArgs)(object)e);
                }
            );

            //Console.WriteLine("DownloadStringAsync");
            x.send();

        }
Пример #18
0
		//static Dictionary<string, byte[]> CachedFiles = new Dictionary<string, byte[]>();

		// why return anything?
		static void WorkerApplicationHandler(Tuple<IProgress<x>, x> scope)
		{
			var path = scope.Item2.path;





			// 9:31827ms at StartNewWithProgress: {{ path = , ManagedThreadId = 10 }} 
			Console.WriteLine("enter WorkerApplicationHandler: " + new { scope.Item2.path, Thread.CurrentThread.ManagedThreadId });


			#region WriteBytes
			Action<byte[]> WriteBytes =
				bytes =>
				{
					// worker is leting Main thread know to write bytes to socket?
					scope.Item1.Report(
						new x { path = scope.Item2.path, PageSource = default(string), write = bytes }
					);
				};
			#endregion




			#region WorkerApplicationHandlerDoResponse
			Func<Task> WorkerApplicationHandlerDoResponse = async delegate
			{
				//nn.Title = "before bytes";

				var xbytes = default(byte[]);
				var asset = scope.Item2.path.Substring(1);

				//if (CachedFiles.ContainsKey(asset))
				//{
				//    xbytes = CachedFiles[asset];
				//}
				//else
				//{

				//var xasset = chrome.runtime.getPackageDirectoryEntry

				// https://developer.chrome.com/extensions/runtime#method-getURL

				// ReferenceError: chrome is not defined at MwEABsZ41Dm4ljl54p7Rzg (blob:chrome-extension%3A//aemlnmcokphbneegoefdckonejmknohh/4a544517-ef14-420b-bfb0-58dc68aa4069:81197:30)
				// we have sandboxed ourselves out of chrome api?

				//var xasset = chrome.runtime.getURL(asset);

				// http://stackoverflow.com/questions/13832251/how-to-read-and-display-file-in-a-chrome-extension
				// 17989ms [11] WorkerApplicationHandlerDoResponse{{ asset = assets/TestTCPServer/App.css }} before bytes
				Console.WriteLine("WorkerApplicationHandlerDoResponse" + new { scope.Item2.chromePath } + " before bytes");

				var xhr = new IXMLHttpRequest();
				//Console.WriteLine(new { asset });

				// what if we are in a blob nowadays and this disconnects our ability to load?
				// can we stream our assets instead?
				xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.GET, scope.Item2.chromePath);

				xbytes = await xhr.bytes;

				//    CachedFiles[asset] = xbytes;
				//}


				if (xbytes == null)
				{
					Console.WriteLine("WorkerApplicationHandlerDoResponse worker did not find the asset? " + new { scope.Item2.chromePath });

					var outputString = "HTTP/1.0 404 go away\r\nConnection: close\r\n\r\n";

					var bytes = Encoding.UTF8.GetBytes(outputString);
					//var xx = new Uint8ClampedArray(bytes);
					WriteBytes(bytes);
					WriteBytes(null);
					return;
				}

				Console.WriteLine("WorkerApplicationHandlerDoResponse " + new { asset, xbytes.Length, Thread.CurrentThread.ManagedThreadId } + " after bytes");
				//nn.Title = "after bytes";

				{
					var o = new StringBuilder();

					o.AppendLine("HTTP/1.0 200 OK");
					o.AppendLine("Connection: close");
					o.AppendLine("Content-Length: " + xbytes.Length);
					o.AppendLine();


					var bytes = Encoding.UTF8.GetBytes(o.ToString());

					WriteBytes(bytes);
				}

				WriteBytes(xbytes);
				WriteBytes(null);

			};
			#endregion


			// 9:61606ms at StartNewWithProgress: {{ path = , ManagedThreadId = 10 }} 


			if (path == "")
			{
				var outputString = "HTTP/1.0 200 worker thread cant see the request path ? \r\nConnection: close\r\n\r\n";

				var bytes = Encoding.UTF8.GetBytes(outputString);
				//var xx = new Uint8ClampedArray(bytes);
				WriteBytes(bytes);
				WriteBytes(null);
			}
			else if (path == "/favicon.ico")
			{
				var outputString = "HTTP/1.0 404 go away\r\nConnection: close\r\n\r\n";

				var bytes = Encoding.UTF8.GetBytes(outputString);
				//var xx = new Uint8ClampedArray(bytes);
				WriteBytes(bytes);
				WriteBytes(null);
			}
			else if (path == "/")
			{
				// X:\jsc.svn\examples\java\hybrid\JVMCLRSSLTCPListener\JVMCLRSSLTCPListener\Program.cs

				#region /

				// wont work for web worker?
				//var xpage = XElement.Parse(PageSource);
				//xpage.Add(new XElement("script", new XAttribute("src", "view-source"), " "));

				//WriteString, 
				var outputString = "HTTP/1.0 200 OK\r\nConnection: close\r\n\r\n"
					+ scope.Item2.PageSource + "<script src='view-source'> </script>";

				//WriteString(output);


				var bytes = Encoding.UTF8.GetBytes(outputString);

				WriteBytes(bytes);
				WriteBytes(null);

				#endregion
			}
			else
			{
				// explicit;ly serve view-source instead?
				WorkerApplicationHandlerDoResponse();
			}

			// jsc cannot return task just yet, use progress instead
			// 20140607 now we can.
			//return scope.Item2;
		}
Пример #19
0
        // called by
        // X:\jsc.svn\core\ScriptCoreLib.Ultra\ScriptCoreLib.Ultra\JavaScript\Remoting\InternalWebMethodRequest.cs
        public Task<byte[]> UploadValuesTaskAsync(Uri address, NameValueCollection data)
        {
            //Console.WriteLine("enter WebClient.UploadValuesTaskAsync! " + new { address });
            // Z:\jsc.svn\examples\javascript\Test\TestAfterInvokeResponseHeaders\ApplicationWebService.cs


            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151123/uploadvaluestaskasync
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151123/ubuntumidexperiment

            var r = new TaskCompletionSource<byte[]> { };

            // Z:\jsc.svn\examples\javascript\ubuntu\Test\UbuntuTestUploadValues\Application.cs
            //  "Z:\jsc.svn\examples\javascript\ubuntu\Test\UbuntuTestUserHostAddress\UbuntuTestUserHostAddress.sln"



            // http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201401/20140119
            // http://stackoverflow.com/questions/8286934/post-formdata-via-xmlhttprequest-object-in-js-cross-browser
            // http://stackoverflow.com/questions/16917772/ie-lags-on-sending-post-data
            // http://robertnyman.com/2013/02/11/using-formdata-to-send-forms-with-xhr-as-keyvalue-pairs/
            // https://blog.yorkxin.org/posts/2014/02/06/ajax-with-formdata-is-broken-on-ie10-ie11/

            var x = new IXMLHttpRequest();

            // InvalidStateException
            //x.withCredentials = true;


            x.open(Shared.HTTPMethodEnum.POST, address.ToString(), async: true);
            x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");


            var xFormDataString = ToFormDataString(data);

            //Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': the object's state must be OPENED.
            // X:\jsc.svn\examples\javascript\Test\TestUploadValuesAsync\TestUploadValuesAsync\Application.cs

            // UploadValuesAsync { responseType = , response = <document><TaskComplete><TaskResult>13</TaskResult></TaskComplete></document> }

            x.InvokeOnComplete(
                delegate
                {
                    //Console.WriteLine("after WebClient.UploadValuesTaskAsync! " + new { address });

                    #region complete
                    var response = new byte[0];

                    // UploadValuesAsync { status = 204, responseType = arraybuffer, response = [object Uint8ClampedArray] }

                    //if (x.status == 204)
                    // 304?
                    //if (x.status == IXMLHttpRequest.HTTPStatusCodes.NoContent)
                    //{
                    //    // android webview  wants us to do this
                    //    response = new byte[0];
                    //}

                    //Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': 
                    // The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').

                    // X:\jsc.svn\examples\javascript\android\com.abstractatech.battery\com.abstractatech.battery\ApplicationWebService.cs
                    //Console.WriteLine("UploadValuesAsync " + new { x.status, x.responseType });

                    //I/chromium(10616): [INFO:CONSOLE(36216)] "%c0:576ms UploadValuesAsync { status = 204, responseType = arraybuffer }", source: http://192.168.1.103:10129/view-source (36216)
                    //I/chromium(10616): [INFO:CONSOLE(49940)] "Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.", source: http://192.168.1.103:10129/view-source (49940)

                    // what about android webview?
                    if (x.response == null)
                    {
                        //Console.WriteLine("UploadValuesAsync " + new { x.status, x.responseType, x.response, x.responseText });

                        //I/Web Console( 5012): %c0:198484ms UploadValuesAsync { status = 200, responseType = arraybuffer } at http://192.168.43.1:9417/view-source:37081
                        //I/Web Console( 5012): %c0:198500ms UploadValuesAsync { status = 200, responseType = arraybuffer, response = , responseText = <document><avatar><obj>aHR0cDovL3d3dy5ncmF2YXRhci5jb20vYXZhdGFyLzhlNmQzZGUw
                        //I/Web Console( 5012): %c0:198524ms InternalWebMethodRequest.Complete { Name = Gravatar, Length = 0 } at http://192.168.43.1:9417/view-source:37081

                        // did we not fix it already?
                        // android 2.3 only seems to have responseText

                        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201404/20140413

                        try
                        {
                            response = Encoding.UTF8.GetBytes(x.responseText);
                        }
                        catch
                        {
                            //I/chromium(30556): [INFO:CONSOLE(37861)] "%c92:28288ms UploadValuesAsync { status = 204, responseType = arraybuffer }", source: http://192.168.43.7:4394/view-source (37861)
                            //I/chromium(30556): [INFO:CONSOLE(37861)] "%c92:28290ms responseText failed. thanks webview devs. { status = 204 }", source: http://192.168.43.7:4394/view-source (37861)

                            // X:\jsc.svn\examples\javascript\p2p\SharedBrowserSessionExperiment\SharedBrowserSessionExperiment\ApplicationWebService.cs
                            Console.WriteLine("responseText failed? " + new { x.status });
                        }
                    }
                    else
                    {
                        // http://stackoverflow.com/questions/8022425/getting-blob-data-from-xhr-request

                        var a = (ArrayBuffer)x.response;

                        //Console.WriteLine("UploadValuesAsync " + new { x.status, x.responseType, a.byteLength });

                        // IE?
                        //var u8 = new Uint8Array(array: a);

                        // X:\jsc.svn\core\ScriptCoreLib.Async\ScriptCoreLib.Async\JavaScript\DOM\FileEntryAsyncExtensions.cs
                        var u8c = new Uint8ClampedArray(array: a);

                        response = u8c;
                    }

                    //Console.WriteLine("UploadValuesAsync " + new { x.status, x.responseType, response });


                    #region ResponseHeaders
                    this.ResponseHeaders = new WebHeaderCollection();
                    //this.ResponseHeaders.Clear();

                    var ResponseHeaders = x.getAllResponseHeaders();

                    // Z:\jsc.svn\examples\javascript\Test\TestAfterInvokeResponseHeaders\ApplicationWebService.cs
                    //Console.WriteLine("after WebClient.UploadValuesTaskAsync! " + new { ResponseHeaders });

                    //0:8209ms { ResponseHeaders = Date: Sat, 15 Mar 2014 12:25:45 GMT
                    //Server: ASP.NET Development Server/11.0.0.0
                    //X-AspNet-Version: 4.0.30319
                    //ETag: BqShORsRkdny750pWBdVyQ==
                    //X-ElapsedMilliseconds: 10
                    //Content-Type: text/xml; charset=utf-8
                    //Access-Control-Allow-Origin: *
                    //Cache-Control: private
                    //Connection: Close
                    //Content-Length: 239

                    foreach (var item in ResponseHeaders.Split('\n'))
                    {
                        var u = item.IndexOf(":");
                        if (u > 0)
                        {
                            var ukey = item.Substring(0, u);
                            var uvalue = item.Substring(u + 1).Trim();

                            //Console.WriteLine(new { ukey, uvalue });

                            this.ResponseHeaders[ukey] = uvalue;
                        }
                    }
                    #endregion

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


                    r.SetResult(response);

                    #endregion


                }
               );

            x.responseType = "arraybuffer";

            // Z:\jsc.svn\examples\javascript\ubuntu\UbuntuSSLWebApplication\UbuntuSSLWebApplication\Application.cs
            // allow basejump?
            // breaks Task<> call?
            //x.responseType = "text";


            // is IE actually sending it? or is our server decoding it wrong?
            //Console.WriteLine("WebClient.UploadValuesAsync IXMLHttpRequest " + new { xFormDataString });
            x.send(xFormDataString);


            return r.Task;
        }
Пример #20
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            Native.document.body.ondragover +=
                evt =>
                {
                    evt.stopPropagation();
                    evt.preventDefault();

                    evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.

                    page.Header.innerText = new { files = evt.dataTransfer.items.length }.ToString();

                };

            Native.document.body.ondragleave +=
                delegate
                {
                    page.Header.innerText = "...";
                };

            Native.document.body.ondrop +=
                 evt =>
                 {
                     evt.stopPropagation();
                     evt.stopImmediatePropagation();

                     evt.preventDefault();


                     var s = Stopwatch.StartNew();
                     page.Header.innerText = "uploading...";

                     // defined at/
                     // X:\jsc.svn\core\ScriptCoreLib.Extensions\ScriptCoreLib.Extensions\JavaScript\DOM\FileExtensions.cs

                     evt.dataTransfer.files.AsEnumerable().WithEach(
                         async f =>
                         {
                             // { name = Chrome.Web.Server.1.0.0.0.nupkg, type = , size = 22940 }

                             page.Header.innerText += new { f.size, f.name, }.ToString();

                             // signature check
                             // like code contracts?
                             var bytes = await f.readAsBytes();

                             // { size = 47079, name = Abstractatech.JavaScript.ApplicationPerformance.1.0.0.0.nupkg }80

                             // { size = 31572, name = GIFEncoder.1.0.0.0.nupkg }0x504b

                             page.Header.innerText += "0x";
                             page.Header.innerText += bytes[0].ToString("x2");
                             page.Header.innerText += bytes[1].ToString("x2");

                             var d = new FormData();


                             d.append("foo", f, f.name);

                             var xhr = new IXMLHttpRequest();

                             xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/upload");

                             xhr.InvokeOnComplete(
                                 delegate
                                 {
                                     // upload complete... { ElapsedMilliseconds = 705 }
                                     page.Header.innerText = "upload complete... " + new { s.ElapsedMilliseconds };
                                 }
                              );

                             xhr.send(d);

                         }
                     );
                 };
        }
Пример #21
0
        public Task<string> DownloadStringTaskAsync(string address)
        {
            var z = new TaskCompletionSource<string>();

            var x = new IXMLHttpRequest();
            x.open(Shared.HTTPMethodEnum.GET, address);

            x.InvokeOnComplete(
                r =>
                {
                    z.SetResult(r.responseText);
                }
            );

            //Console.WriteLine("DownloadStringAsync");
            x.send();

            return z.Task;
        }
Пример #22
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            new IHTMLButton { "check" }.AttachToDocument().onclick += async delegate
            {
                var lastupload = await base.getlastupload();

                lastupload.WithEachIndex(
                     (x, index) =>
                     {
                         foreach (var header in x.Headers)
                         {
                             //Console.WriteLine(new { index, header });
                             new IHTMLPre { new { index, header } }.AttachToDocument();

                         }

                         //Console.WriteLine(new { index, x.Content });
                         new IHTMLPre { new { index, x.Content } }.AttachToDocument();

                     }
                 );
            };

            new { }.With(
                async delegate
                {
                    // http://footle.org/2007/07/31/binary-multipart-posts-in-javascript/

                    // https://msdn.microsoft.com/en-us/library/ms527355(v=exchg.10).aspx

                    var send = new IHTMLButton { "send" }.AttachToDocument();

                    while (await send.async.onclick)
                    {



                        // is it useful?

                        //var f = new FormData();

                        //f.append("hello", "world");
                        //f.append("foo", "bar");

                        // http://stackoverflow.com/questions/5165337/xmlhttprequest-overridemimetype-for-outgoing-data
                        var x = new IXMLHttpRequest(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/upload", true);

                        var doubleDash = "--";
                        var boundary = "12345678901234567890";


                        var wRequestPayload = new StringBuilder();

                        wRequestPayload.Append(@"--12345678901234567890
Content-Type: text/xml; charset=UTF-8


<xml1>hello</xml1>

--12345678901234567890
Content-type: text/xml
e-x: 34
e-y: pp

<xml1>world</xml1>
--12345678901234567890--"
                         );


                        var data = wRequestPayload.ToString();

                        x.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary);

                        // java stream hangs if we try to read past data?
                        //x.setRequestHeader("Content-Length", "" + data.Length);



                        x.send(data);

                    }

                    //x.overrideMimeType()

                }
            );

        }
        public static void ToMemoryStreamAsset(this string e, Action<MemoryStream> h)
        {
            // tested by?

            // X:\jsc.svn\core\ScriptCoreLib.Async\ScriptCoreLib.Async\JavaScript\Experimental\X.cs

            //var w = new WebClient();

            //w.DownloadDataCompleted
            var x = new IXMLHttpRequest();

            x.open(Shared.HTTPMethodEnum.GET, e);

            x.bytes.ContinueWith(
                task =>
                {
                    // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\IO\MemoryStream.cs
                    var m = new MemoryStream(task.Result);

                    h(m);
                }
            );

            //h(KnownEmbeddedResources.Default[e].ToByteArrayAsset().ToMemoryStream());
        }