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

            var s = new StringBuilder();

            s.AppendLine("alert('hi');");


            //script: error JSC1000: You tried to instance a class which seems to be marked as native.
            //script: error JSC1000: type has no callable constructor: [ScriptCoreLib.JavaScript.DOM.Blob] Void .ctor(System.String[])

            var blob = new Blob(new[] { s.ToString() });
            //var url = URL.createObjectURL(blob);

            //<script src="blob:http%3A//192.168.43.252%3A28384/6a37d088-4403-4eb2-b45e-1d19083b304e"></script>

            new IHTMLScript { src = blob.ToObjectURL() }.AttachToDocument();

        }
 public void readAsBinaryString(Blob blob)
 { }
 public void readAsText(Blob blob, string encoding)
 { }
Example #4
0
 public Blob(Blob[] blobParts, object options) { }
 public void write(Blob data)
 { }
Example #6
0
 public static string createObjectURL(Blob blob)
 {
     return default(string);
 }
		public Application(IApp page)
		{
			// GetScriptApplicationSourceForInlineWorker { value = view-source#worker }

			//Native.document.curr
			new IHTMLPre { new { Native.document.currentScript } }.AttachToDocument();
			//{ { currentScript = null } }

			// we could jump to encrypted secondary app here...
			new IHTMLButton { "prefetch source (edit and continue can update code?)" }.AttachToDocument().WhenClicked(
					//async 
					button =>
					{
						//Request URL:http://192.168.43.252:17858/view-source
						//Request Method:0

						new IXMLHttpRequest(
							ScriptCoreLib.Shared.HTTPMethodEnum.GET,
							"view-source",
							r =>
							{
								//new IHTMLPre { new { r.responseType } }.AttachToDocument();
								new IHTMLPre { new { r.responseText.Length } }.AttachToDocument();

								var aFileParts = new[] { r.responseText };
								var oMyBlob = new Blob(aFileParts, new { type = "text/html" });	// the blob


								var url = oMyBlob.ToObjectURL();

								InternalInlineWorker.ScriptApplicationSourceForInlineWorker = url;

								new IHTMLPre { new { InternalInlineWorker.ScriptApplicationSourceForInlineWorker } }.AttachToDocument();
							}

						);



					}
			);

			new IHTMLButton { "work" }.AttachToDocument().WhenClicked(
				async button =>
				{
					var state = new
					{
						input_for_other_thread = new { Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsBackground }
					};

					// X:\jsc.svn\core\ScriptCoreLib.Extensions\ScriptCoreLib.Extensions\Extensions\TaskExtensions.cs

					//var x = await Task<string>.Factory.StartNew(
					var x = await Task.Factory.StartNew(
						state,
						scope =>
						{
							// Console is special. { scope = [object Object] }

							Console.WriteLine(
								//"Console is special. " + new { scope }
								"Console is special. " + new { scope.input_for_other_thread.ManagedThreadId }
							);



							return new
							{
								output = "who is serializing this? only the browser API? jsc not helping here yet?",

								scope,

								inside = new
								{
									Thread.CurrentThread.ManagedThreadId,
									Thread.CurrentThread.IsBackground
								}
							};
							//return "who is serializing this? only the browser API? jsc not helping here yet?";
						}
					//, state
					);


					new IHTMLPre { new { x.output, x.scope, x.inside } }.AttachToDocument();

				}
			);

		}
 public string readAsDataURL(Blob blob) { throw null; }
        //public static Task WriteAllBytes(this DirectoryEntry that, string filename, WebGL.WebGLRenderingContext gl)
        //{
        //}

        public static Task WriteAllBytes(this DirectoryEntry that, string filename, IHTMLCanvas canvas)
        {
            //            754986ms WriteAllBytes { filename = 00272.png, position = 3101246, size = 3101246 }
            //view-source:63706 FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'.
            //view-source:54105 757622ms WriteAllBytes onerror { code = 7, message = An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk., error = [object FileError] }
            //view-source:54105 757623ms out of files?
            //view-source:54105 757624ms WriteAllBytes { filename = 00273.png, position = 0, size = 3143207 }
            //view-source:54105 757624ms what happened? retry?
            //view-source:54105 760625ms what happened? retry!
            //view-source:54105 760626ms what happened? retry! retry7?
            //view-source:38832 Uncaught TypeError: Cannot read property 'toDataURL' of null

            //var data = canvas.toDataURL();

            // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360\x360eiffieballs\Application.cs
            //Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360\x360x83\Application.cs
            // 8K img png will be 50mb
            //var data = canvas.toDataURL(quality: 0.9);
            var data = canvas.toDataURL(quality: 1.0);
            //var data = canvas.toDataURL(quality: 0.1);

            // Z:\jsc.svn\examples\javascript\chrome\apps\WebGL\360stereo\x360stereotransition\Application.cs

            var prefix = "base64,";



            var fileBytes = System.Convert.FromBase64String(
                data.Substring(data.IndexOf(prefix) + prefix.Length));

            // https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/jcrEI_jfYFs
            // this blob wont delete?
            bytes = new Blob(
                blobParts: new ArrayBufferView[] { fileBytes },
                options: new { type = "application/octet-stream;" + filename }
            );

            fileBytes = null;
            data = null;
            //canvas = null;

            var c = new TaskCompletionSource<DirectoryEntry>();


            // can do up to 120 files?
            // not disposing blob?


            //Blob blob = bytes;

            that.getFile(
                //"0000.jpg",
                filename,
                new
                {
                    create = true,
                    exclusive = false
                },
                fentry =>
                {
                    // {{ fentry = [object FileEntry] }}
                    //new IHTMLPre { new { fentry } }.AttachToDocument();


                    fentry.createWriter(
                        w =>
                        {

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

                            // new Blob([document.getElementById("HTMLFile").value],
                            //{ type: 'text/plain'}

                            //var blob = new Blob(
                            //    blobParts: new ArrayBufferView[] { fileBytes },
                            //    options: new { type = "application/octet-stream" }
                            //);

                            // http://stackoverflow.com/questions/12168909/blob-from-dataurl
                            //w.write(fileBytes);
                            //w.write(bytes);


                            ////w.write()


                            //// ready?


                            var retry7 = false;

                            //c.SetResult(that);
                            //WriteAllBytes onerror { error = [object FileError], code = 7 }
                            w.onerror = new Action(
                                delegate
                                {
                                    // https://developer.mozilla.org/en-US/docs/Web/API/FileError

                                    Console.WriteLine("WriteAllBytes onerror " + new { w.error.code, w.error.message, w.error });

                                    if (w.error.code == 7)
                                    {
                                        Console.WriteLine("out of files? " + new { filename });
                                        //https://code.google.com/p/chromium/issues/detail?id=83736
                                        retry7 = true;
                                    }
                                }
                            );



                            //1063359ms WriteAllBytes onerror { code = 7, message = An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk., error = [object FileError] }
                            //view-source:54104 1063360ms out of files?
                            //view-source:54104 1063361ms WriteAllBytes { filename = 00265.png, position = 0, size = 3058562 }
                            //view-source:54104 1063361ms what happened? retry?
                            //view-source:54104 1066363ms what happened? retry!


                            w.onwriteend = new Action(
                              delegate
                              {
                                  var position = w.position;

                                  Console.WriteLine("onwriteend WriteAllBytes " + new { filename, position, bytes.size });

                                  if (position < (long)bytes.size)
                                  {


                                      Console.WriteLine("what happened? retry? " + new { filename });

                                      if (position == 0)
                                      {



                                          Native.setTimeout(
                                              delegate
                                              {

                                                  if (retry7)
                                                  {
                                                      Console.WriteLine("what happened? retry7? " + new { filename });


                                                      WriteAllBytes(that, filename, canvas).ContinueWith(
                                                          delegate
                                                          {
                                                              Console.WriteLine("what happened? retry7! " + new { filename });
                                                              c.SetResult(that);
                                                              fentry = null;
                                                          }
                                                      );


                                                      return;
                                                  }
                                                  Console.WriteLine("what happened? retry! " + new { filename });

                                                  w.write(bytes);
                                              }, 5000
                                            );
                                      }

                                      return;
                                  }

                                  // https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/6Behx6zrbCI
                                  //Console.WriteLine("WriteAllBytes Blob close");

                                  // https://code.google.com/p/chromium/issues/detail?id=404301

                                  // chrome://blob-internals/

                                  //bytes.close();
                                  bytes = null;

                                  //w.truncate(w.position);
                                  w = null;


                                  // need it?
                                  //Native.window.requestAnimationFrame += delegate


                                  //Console.WriteLine("WriteAllBytes yield");
                                  c.SetResult(that);

                                  fentry = null;
                              }
                          );

                            w.write(bytes);
                        }
                    );

                }
            );


            return c.Task;

        }
        /// <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(IDisclaimer page)
        {

            #region go
            Action<string> go =
                //async 
                     source =>
                     {
                         // show login

                         #region layout
                         var layout = new Login();

                         // loaded app will expect id's, restore em
                         layout.Login.id = "Login";

                         var newbody = layout.body;
                         var oldbody = Native.document.body;

                         // switch layouts

                         Native.document.body.parentNode.replaceChild(
                             newbody,
                             oldbody
                         );
                         #endregion


                         // how did we get the source?
                         //var app = new x(layout);

                         //await 

                         //new IHTMLScript { src = new Blob(source).ToObjectURL().SetInternalScriptApplicationSource() }.AttachToHead();

                         var src = new Blob(source).ToObjectURL().SetInternalScriptApplicationSource();
                         //await new IHTMLScript { src = src };
                         Native.window.eval(source);

                         // now what?
                     };
            #endregion

            #region onclick
            page.Continue.onclick +=
                async delegate
                {
                    page.Continue.disabled = true;

                    if (go.Target != null)
                        if (go.Target != Native.self)
                            throw new InvalidOperationException("we can only continue with global methods for now... " + new { go.Target });

                    var MethodToken = ((__MethodInfo)go.Method).MethodToken;


                    var source = await typeof(x);

                    // we can now Activate it?
                    //Activator.CreateInstance(typeof(x));


                    Native.window.history.replaceState(
                        new
                        {
                            Native.window.history.state,

                            hint = "typeof(x)",

                            // arguments:

                            invoke = new { function = MethodToken, arguments = new[] { source } }
                        }
                    );

                    // invoke as state?
                    //go(source);

                    // or reload?
                    Native.document.location.reload();
                };
            #endregion


            // first time:
            // Application onpopstate { e = { state =  }, history = { state =  } }


            // after replaceState and reload
            // Application onpopstate { e = { state =  }, history = { state = [object Object] } }

            #region onpopstate
            Native.window.onpopstate +=
                 e =>
                 {

                     #region x
                     var x = new Stack<Func<Task<object>>>();

                     Action<object> y = null;

                     y = xstate =>
                     {
                         if (xstate == null)
                             return;

                         dynamic state = xstate;

                         // if there is parent, we have to restore that first?

                         string hint = state.hint;

                         dynamic invoke = state.invoke;

                         string MethodToken = invoke.function;
                         object arguments = invoke.arguments;

                         x.Push(
                             delegate
                             {
                                 var z = new TaskCompletionSource<object>();
                                 var sw = new Stopwatch();
                                 sw.Start();

                                 if (!Expando.Of(Native.self).Contains(MethodToken))
                                 {
                                     //{ hint = typeof(y) } missing { MethodToken = CAAABoz2jD6nJMVTcci_a_bQ }


                                     Console.WriteLine(new { hint } + " missing " + new { MethodToken });

                                     //Could not load type 'ctor>b__6>d__17' from assembly 'WorkerInsideSecondaryApplicationWithStateReplace.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
                                     // script: error JSC1000: No implementation found for this native method, please implement [System.Threading.Tasks.Task.ContinueWith(System.Action`1[[System.Threading.Tasks.Task, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]])]
                                 }


                                 IFunction.ByName(MethodToken).ContinueWithResult(
                                     f =>
                                     {
                                         // { hint = typeof(y) } ok { MethodToken = CQAABoz2jD6nJMVTcci_a_bQ, ElapsedMilliseconds = 171 }
                                         Console.WriteLine(new { hint } + " ok " + new { MethodToken, sw.ElapsedMilliseconds });

                                         f.apply(null, args: (object[])arguments);
                                         //go(source);

                                         z.SetResult(null);
                                     }
                                 );

                                 return z.Task;
                             }
                         );

                         object parent = state.state;
                         y(parent);
                     };


                     y(Native.window.history.state);
                     #endregion


                     Console.WriteLine(
                         "Application onpopstate " + new
                         {
                             e = new { e.state },
                             history = new { Native.window.history.state }
                         }
                        + "\n steps to resume this state: " + new { x.Count }
                     );

                     //steps to resume this state: { Count = 1 }


                     Action all = async delegate
                     {
                         while (x.Count > 0)
                         {
                             await x.Pop()();
                         }

                     };

                     all();
                 };
            #endregion

        }
            public x(ILogin page)
            {

                // Uncaught Error: InvalidOperationException: { MethodToken = BgAABqe4Nzm_bBv4spuPWGg } function is not available at { href = http://192.168.43.252:24113/view-source#worker } 


                #region go 2
                new IHTMLButton { innerText = "go 2" }.AttachToDocument().WhenClicked(
                    //async
                 delegate
                 {
                     // hsc, why wont lambda declaration work within async scope?

                     // http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx

                     Console.WriteLine("before");

                     // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201309-1/20130904-iprogress
                     //var x =
                     //await 
                     Task.Factory.StartNewWithProgress(

                     new { value = "world!" },

                     progress:
                        xx =>
                        {
                            Console.WriteLine("DOM Progress: " + new { xx.value, Thread.CurrentThread.ManagedThreadId });

                            Native.document.title = new { xx.value, Thread.CurrentThread.ManagedThreadId }.ToString();
                        },

                     function:
                         scope =>
                         {
                             #region scope is null
                             if (scope == null)
                             {
                                 // { x = scope_progress is null { state = [object Object], BackgroundThread = 10 }, ManagedThreadId = 1 }
                                 return new { value = "scope is null " + new { BackgroundThread = Thread.CurrentThread.ManagedThreadId } };
                             }
                             #endregion



                             var state = scope.Item2;

                             #region scope_progress
                             var scope_progress = scope.Item1;
                             if (scope_progress == null)
                             {
                                 // { x = null { BackgroundThread = 10 }, ManagedThreadId = 1 }
                                 return new { value = "scope_progress is null " + new { state, BackgroundThread = Thread.CurrentThread.ManagedThreadId } };
                             }
                             #endregion

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

                             scope_progress.Report(
                                  new
                                  {
                                      value = "hi " + new { e.ElapsedMilliseconds, BackgroundThread = Thread.CurrentThread.ManagedThreadId }
                                  }
                             );


                             for (int i = 0; i < 20; i++)
                             {
                                 scope_progress.Report(
                                    new
                                    {
                                        value = ". " + new { i, state.value, e.ElapsedMilliseconds, BackgroundThread = Thread.CurrentThread.ManagedThreadId }
                                    }
                                 );

                                 Thread.Sleep(100);
                             }


                             return new { value = "done " + new { e.ElapsedMilliseconds, BackgroundThread = Thread.CurrentThread.ManagedThreadId } };
                         }
                 ).ContinueWithResult(
                     x =>
                     {
                         Console.WriteLine("after");
                         Native.document.title = new { x.value, Thread.CurrentThread.ManagedThreadId }.ToString();
                     }
                 );

                 }
             );
                #endregion

                //Uncaught Error: InvalidOperationException: { MethodToken = BgAABqe4Nzm_bBv4spuPWGg } function is not available at { href = http://192.168.43.252:18192/view-source#worker } 

                #region go
                Action<string> go =
                    //async 
                      source =>
                      {
                          // show login

                          var layout = new App();

                          var newbody = layout.body;
                          var oldbody = Native.document.body;

                          // switch layouts

                          Native.document.body.parentNode.replaceChild(
                              newbody,
                              oldbody
                          );

                          // how did we get the source?
                          //var app = new y(layout);

                          var src = new Blob(source).ToObjectURL().SetInternalScriptApplicationSource();
                          //await new IHTMLScript { src = src };
                          Native.window.eval(source);


#if FUTURE
                      var yy = await new y(default(IProgress<string>), data: default(string));
#endif


                      };
                #endregion


                #region onclick
                page.Login.onclick +=
                    async delegate
                    {
                        page.Login.disabled = true;

                        var source = await typeof(y);

                        // we can now Activate it?
                        //Activator.CreateInstance(typeof(x));

                        Native.window.history.replaceState(
                             new
                             {
                                 Native.window.history.state,

                                 hint = "typeof(y)",

                                 invoke = new { function = ((__MethodInfo)go.Method).MethodToken, arguments = new[] { source } }
                             }
                        );

                        // invoke as state?
                        //go(source);

                        Native.document.location.reload();
                    };
                #endregion

            }
        /// <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)
        {
            // see also
            // X:\jsc.svn\examples\javascript\DragIntoCRX\DragIntoCRX\Application.cs

            page.Data.WhenClicked(
                async button =>
                {
                    var DataTable = await this.DoEnterData();
                    var DataTable_xml = StringConversionsForDataTable.ConvertToString(
                                        DataTable
                                    );


                    var grid = new DataGridView { DataSource = DataTable };


                    grid.AttachControlTo(page.output);

                    var csv = WriteCSV(DataTable);


                    // http://www.w3.org/TR/file-writer-api/

                    page.x.title = "special.csv";
                    page.x.style.textDecoration = "underline";

                    page.x.css.hover.style.color = "red";


                    // http://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link
                    var blob = new Blob(new[] { csv.ToString() }, new { type = "octet/stream" });

                    var href = blob.ToObjectURL();



                    page.x.href = href;

                    // we can now click on the link
                    page.x.download = page.x.title;

                    // hide the fact, we are actually using <a>
                    //page.x.Hide();

                    //var iframe = new IHTMLIFrame { name = "y" }.AttachToDocument();
                    //page.x.target = iframe.name;

                    // http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
                    // http://msdn.microsoft.com/en-us/library/ie/hh779016(v=vs.85).aspx
                    // http://stackoverflow.com/questions/4309958/can-i-write-files-with-html5-js




                    page.Csv.disabled = false;
                    page.Csv.onclick +=
                        delegate
                        {
                            page.x.click();

                        };

                    page.Csv.ondragstart +=
                          e =>
                          {
                              Console.WriteLine("ondragstart");

                              // public void addElement(IHTMLElement element);
                              //e.dataTransfer.addElement(
                              // http://help.dottoro.com/ljxfefku.php

                              // X:\jsc.svn\examples\javascript\DropFileIntoSQLite\DropFileIntoSQLite\Application.cs
                              e.dataTransfer.effectAllowed = "copy";

                              e.dataTransfer.setData(

                                   typeof(DataTable).Name
                                    //"jsc/datatable"
                                    ,
                                    DataTable_xml

                              );

                              //                              ondragover: { types = 1, items = 1, files = 0 }
                              // view-source:29615
                              //{ type = jsc/datatable } 

                              Console.WriteLine("setDownloadURL");
                              // http://www.thecssninja.com/html5/gmail-dragout
                              // Unfortunately it doesn’t work anymore in any browser, not also in chrome

                              // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer#setData.28.29
                              e.dataTransfer.setDownloadURL(
                                 page.x.title,
                                  Encoding.UTF8.GetBytes(csv.ToString())
                              );
                          };


                }
            );

        }
 public string readAsText(Blob blob, string encoding) { throw null; }
 public void readAsArrayBuffer(Blob blob)
 {
 }
        public static Task WriteAllBytes(this DirectoryEntry that, string filename, Blob bytes)
        {
            // can do up to 120 files?
            // not disposing blob?

            var c = new TaskCompletionSource<DirectoryEntry>();

            //Blob blob = bytes;

            that.getFile(
                //"0000.jpg",
                filename,
                new
                {
                    create = true,
                    exclusive = false
                },
                fentry =>
                {
                    // {{ fentry = [object FileEntry] }}
                    //new IHTMLPre { new { fentry } }.AttachToDocument();


                    fentry.createWriter(
                        w =>
                        {

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

                            // new Blob([document.getElementById("HTMLFile").value],
                            //{ type: 'text/plain'}

                            //var blob = new Blob(
                            //    blobParts: new ArrayBufferView[] { fileBytes },
                            //    options: new { type = "application/octet-stream" }
                            //);

                            // http://stackoverflow.com/questions/12168909/blob-from-dataurl
                            //w.write(fileBytes);
                            //w.write(bytes);


                            ////w.write()


                            //// ready?

                            //c.SetResult(that);

                            w.onerror = new Action(
                                delegate
                                {
                                    // https://developer.mozilla.org/en-US/docs/Web/API/FileError

                                    Console.WriteLine("WriteAllBytes onerror " + new { w.error, w.error.code });

                                }
                            );

                            w.onwriteend = new Action(
                              delegate
                              {
                                  var position = w.position;

                                  Console.WriteLine("WriteAllBytes " + new { filename, position, bytes.size });

                                  if (position < (long)bytes.size)
                                  {
                                      Console.WriteLine("what happened? retry?");

                                      if (position == 0)
                                      {
                                          Native.setTimeout(
                                              delegate
                                              {
                                                  Console.WriteLine("what happened? retry!");

                                                  w.write(bytes);
                                              }, 3000
                                            );
                                      }

                                      return;
                                  }

                                  // https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/6Behx6zrbCI
                                  Console.WriteLine("WriteAllBytes Blob close");

                                  // https://code.google.com/p/chromium/issues/detail?id=404301

                                  // chrome://blob-internals/

                                  //bytes.close();
                                  bytes = null;

                                  //w.truncate(w.position);
                                  w = null;


                                  // need it?
                                  //Native.window.requestAnimationFrame += delegate


                                  Console.WriteLine("WriteAllBytes yield");
                                  c.SetResult(that);


                              }
                          );

                            w.write(bytes);
                        }
                    );

                }
            );


            return c.Task;

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

        // Z:\jsc.svn\examples\javascript\chrome\apps\ChromeWriteFiles\ChromeWriteFiles\bin\Debug\staging\ChromeWriteFiles.Application\web

        //        subst /D b:
        //subst b: s:\jsc.svn\examples\javascript\chrome\apps\ChromeWriteFiles\ChromeWriteFiles\bin\Debug\staging\ChromeWriteFiles.Application\web

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

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            #region += Launched chrome.app.window
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_socket = self_chrome.socket;

            if (self_chrome_socket != null)
            {
                if (!(Native.window.opener == null && Native.window.parent == Native.window.self))
                {
                    Console.WriteLine("chrome.app.window.create, is that you?");

                    // pass thru
                }
                else
                {
                    // should jsc send a copresence udp message?
                    chrome.runtime.UpdateAvailable += delegate
                    {
                        new chrome.Notification(title: "UpdateAvailable");

                    };

                    chrome.app.runtime.Launched += async delegate
                    {
                        // 0:12094ms chrome.app.window.create {{ href = chrome-extension://aemlnmcokphbneegoefdckonejmknohh/_generated_background_page.html }}
                        Console.WriteLine("chrome.app.window.create " + new { Native.document.location.href });

                        new chrome.Notification(title: "ChromeWriteFiles");

                        var xappwindow = await chrome.app.window.create(
                               Native.document.location.pathname, options: null
                        );

                        //xappwindow.setAlwaysOnTop

                        xappwindow.show();

                        await xappwindow.contentWindow.async.onload;

                        Console.WriteLine("chrome.app.window loaded!");
                    };


                    return;
                }
            }
            #endregion

            // X:\jsc.svn\examples\javascript\chrome\apps\ChromeWriteFiles\ChromeWriteFiles\Application.cs

            //{{ Length = 4 }}
            //{{ prefixLength = 64, name = {D7020941-742E-4570-93B2-C0372D3D870F}, address = fe80::88c0:f0a:9ccf:cba0 }}
            //{{ prefixLength = 24, name = {D7020941-742E-4570-93B2-C0372D3D870F}, address = 192.168.43.28 }}
            //{{ prefixLength = 64, name = {A8657A4E-8BFA-41CC-87BE-6847E33E1A81}, address = 2001:0:9d38:6abd:20a6:2815:3f57:d4e3 }}
            //{{ prefixLength = 64, name = {A8657A4E-8BFA-41CC-87BE-6847E33E1A81}, address = fe80::20a6:2815:3f57:d4e3 }}

            new { }.With(
                async delegate
                {
                    // http://css-infos.net/property/-webkit-user-select
                    // http://caniuse.com/#feat=user-select-none
                    //(Native.body.style as dynamic).userSelect = "auto";
                    (Native.body.style as dynamic).webkitUserSelect = "text";

                    // https://css-tricks.com/almanac/properties/u/user-select/
                    //Native.body.style.setProperty(
                    // X:\jsc.svn\examples\java\hybrid\JVMCLRNIC\JVMCLRNIC\Program.cs
                    // clr does not have it async. 

                    //var refresh = 
                    new IHTMLButton { "0000.txt" }.AttachToDocument().onclick += async delegate
                    //while (await refresh.async.onclick)
                    {
                        new IHTMLHorizontalRule { }.AttachToDocument();

                        // TypeError: Cannot read property 'getVolumeList' of undefined
                        //var n = await chrome.fileSystem.getVolumeList();


                        //{
                        //    "fileSystem" : ["write", "directory"]
                        //    }
                        // TypeError: Cannot read property 'chooseEntry' of undefined
                        var entry = await chrome.fileSystem.chooseEntry(
                                            new { type = "openDirectory" }
                                        );

                        // {{ entry = [object DirectoryEntry] }}
                        new IHTMLPre { new { entry } }.AttachToDocument();

                        // http://sharpkit.net/help/SharpKit.PhoneGap/SharpKit.PhoneGap/DirectoryEntry/getFile(JsString,Flags,FileEntry%5D%5D,JsAction).htm
                        // https://developer.mozilla.org/en-US/docs/Web/API/DirectoryEntry#getFile
                        var dir = (DirectoryEntry)entry;

                        dir.getFile(
                            "0000.txt",
                            new
                            {
                                create = true,
                                exclusive = false
                            },
                            fentry =>
                            {
                                // {{ fentry = [object FileEntry] }}
                                new IHTMLPre { new { fentry } }.AttachToDocument();


                                fentry.createWriter(
                                    w =>
                                    {
                                        new IHTMLPre { new { w } }.AttachToDocument();

                                        // new Blob([document.getElementById("HTMLFile").value],
                                        //{ type: 'text/plain'}

                                        var blob = new Blob(
                                            blobParts: new[] { "hello\nworld" },
                                            options: new { type = "text/plain" }
                                        );

                                        // http://stackoverflow.com/questions/12168909/blob-from-dataurl
                                        w.write(blob);


                                        //w.write()
                                    }
                                );

                            }
                        );
                        //foreach (var item in n)
                        //{
                        //    new IHTMLPre { new { item, item.volumeId, item.writable } }.AttachToDocument();
                        //}
                    };



                    IHTMLImage c0002 = new IHTMLDiv { "frame2 " + new { DateTime.Now } };
                    IHTMLImage c0001 = new IHTMLDiv { "frame1 " + new { DateTime.Now } };
                    IHTMLImage c = new IHTMLDiv { "lets render this div into file " + new { DateTime.Now } };

                    c.AttachToDocument();

                    // "Z:\jsc.svn\examples\javascript\chrome\apps\ChromeWriteFiles\ChromeWriteFiles\bin\Debug\staging\ChromeWriteFiles.Application\web\manifest.json"

                    //var data = c.toDataURL();

                    //new IHTMLPre { new { data } }.AttachToDocument();
                    // { data = data:image/png;base64,iVBORw


                    //var fileBytes = Convert.FromBase64String(data.SkipUntilOrEmpty("base64,"));
                    // { Length = 1382 }

                    //new IHTMLPre { new { fileBytes.Length, fileBytes } }.AttachToDocument();


                    new IHTMLButton { "0000.jpg" }.AttachToDocument().onclick += async delegate
                    //while (await refresh.async.onclick)
                    {
                        new IHTMLHorizontalRule { }.AttachToDocument();

                        // TypeError: Cannot read property 'getVolumeList' of undefined
                        //var n = await chrome.fileSystem.getVolumeList();


                        //{
                        //    "fileSystem" : ["write", "directory"]
                        //    }
                        // TypeError: Cannot read property 'chooseEntry' of undefined
                        // 1757ms TypeError: Cannot read property 'chooseEntry' of undefined
                        var entry = await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });

                        // {{ entry = [object DirectoryEntry] }}
                        new IHTMLPre { new { entry } }.AttachToDocument();

                        // http://sharpkit.net/help/SharpKit.PhoneGap/SharpKit.PhoneGap/DirectoryEntry/getFile(JsString,Flags,FileEntry%5D%5D,JsAction).htm
                        // https://developer.mozilla.org/en-US/docs/Web/API/DirectoryEntry#getFile
                        var dir = (DirectoryEntry)entry;

                        dir.getFile(
                            "0000.jpg",
                            new
                            {
                                create = true,
                                exclusive = false
                            },
                            fentry =>
                            {
                                // {{ fentry = [object FileEntry] }}
                                new IHTMLPre { new { fentry } }.AttachToDocument();


                                fentry.createWriter(
                                    w =>
                                    {

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

                                        // new Blob([document.getElementById("HTMLFile").value],
                                        //{ type: 'text/plain'}

                                        //var blob = new Blob(
                                        //    blobParts: new ArrayBufferView[] { fileBytes },
                                        //    options: new { type = "application/octet-stream" }
                                        //);

                                        // http://stackoverflow.com/questions/12168909/blob-from-dataurl
                                        //w.write(fileBytes);
                                        w.write(c);


                                        //w.write()
                                    }
                                );

                            }
                        );
                        //foreach (var item in n)
                        //{
                        //    new IHTMLPre { new { item, item.volumeId, item.writable } }.AttachToDocument();
                        //}
                    };

                    new IHTMLButton { "0001.png" }.AttachToDocument().onclick += async delegate
                       {
                           new IHTMLHorizontalRule { }.AttachToDocument();

                           var dir = (DirectoryEntry)await chrome.fileSystem.chooseEntry(new { type = "openDirectory" });


                           await dir.WriteAllBytes("0001.png", c0001);
                           await dir.WriteAllBytes("0002.png", c0002);

                           new IHTMLPre { "done" }.ToString();
                       };

                }
            );
        }
 //public ArrayBuffer readAsArrayBuffer(Blob blob);
 public string readAsBinaryString(Blob blob) { throw null; }