// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/20151102/csv
        // Z:\jsc.svn\examples\javascript\chrome\hybrid\ChromeHybridCaptureAE\Application.cs




        static Application()
        {
            #region document
            if (Native.document != null)
            {
                // patch the awaiter..
                Console.SetOut(new xConsole());


                // also. all workers we will be creating will need to start to expect switch commands...
                // how can we tap in them?

                //__worker_onfirstmessage: {{ 
                // ManagedThreadId = 10, href = https://192.168.1.196:13946/view-source#worker, 
                // MethodTargetTypeIndex = type$PgZysaxv_bTu4GEkwmJdJrQ, 
                // MethodTargetType = ___ctor_b__1_5_d, 
                // MethodToken = jwsABpdwBjGQu09dvBXjxw, 
                // MethodType = FuncOfObjectToObject, 
                // stateTypeHandleIndex = null, 
                // stateType = null, 
                // state = [object Object], 
                // IsIProgress = false }}
                // 

                // can we start a task, yet also have special access for the posted messages?

                // what about threads that did not hop to background?
                // dont they want to hop to background?
                HopToThreadPoolAwaitable.VirtualOnCompleted = continuation =>
                {
                    Action<ShadowIAsyncStateMachine> MoveNext0 = null;

                    // async dont like ref?
                    var shadowstate = ShadowIAsyncStateMachine.FromContinuation(continuation, ref MoveNext0);
                    var MoveNext = MoveNext0;

                    Console.WriteLine("enter HopToThreadPoolAwaitable.VirtualOnCompleted " + new { shadowstate.state });

                    // post a message to the document 
                    var xx = new __Task.InternalTaskExtensionsScope { InternalTaskExtensionsScope_function = continuation };


                    var x = new __Task<object>();

                    // reusing thread init for generic task start, although, resuming needs special implementation..
                    x.InternalInitializeInlineWorker(
                        new Action(xx.f),
                        //action,
                        default(object),
                        default(CancellationToken),
                        default(TaskCreationOptions),
                        TaskScheduler.Default,

                        yield: (worker, e) =>
                        {
                            // like operator for JSON?

                            //Console.WriteLine("enter HopToThreadPoolAwaitable InternalInitializeInlineWorker yield");

                            var data = new
                            {
                                HopToUIAwaitable = new
                                {
                                    // state to hop back

                                    shadowstate = default(ShadowIAsyncStateMachine)
                                }
                            };

                            data = (dynamic)e.data;

                            //if (data.HopToUIAwaitable )

                            if (data.HopToUIAwaitable == null)
                                return;


                            // time to hop back on continuation?

                            Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine("enter HopToThreadPoolAwaitable yield HopToUIAwaitable, resume state? " + new { data.HopToUIAwaitable.shadowstate.state });
                            Console.ForegroundColor = ConsoleColor.Black;


                            //enter HopToThreadPoolAwaitable yield HopToUIAwaitable
                            //worker Task Run function has returned {{ value_Task = null, value_TaskOfT = null }}
                            //__Task.InternalStart inner complete {{ yield = {{ value = null }} }}

                            // the worker should be in a suspended state, as we may want to jump back?

                            // 
                            MoveNext(data.HopToUIAwaitable.shadowstate);

                        }
                    );


                    x.Start();


                };

                return;
            }
            #endregion


            #region worker
            if (Native.worker != null)
            {
                Console.WriteLine("about to enable HopToUIAwaitable...");

                Native.worker.onfirstmessage += e =>
                {
                    Console.WriteLine("enter onfirstmessage");

                    HopToUIAwaitable.VirtualOnCompleted = continuation =>
                    {

                        // first jump out?
                        InternalInlineWorker.InternalOverrideTaskOfT = new TaskCompletionSource<object>().Task;

                        // post a message to the document 

                        // um. how can we signal that we are not done?


                        Action<ShadowIAsyncStateMachine> MoveNext = null;

                        // async dont like ref?
                        var shadowstate = ShadowIAsyncStateMachine.FromContinuation(continuation, ref MoveNext);

                        Console.WriteLine("enter HopToUIAwaitable.VirtualOnCompleted, postMessage " + new { shadowstate.state });


                        // postMessageAsync ? if ui wants to return, instead of restaring this thread?
                        e.postMessage(
                            new
                            {
                                HopToUIAwaitable = new
                                {
                                    // state to hop back

                                    shadowstate
                                }
                            }
                        );

                    };
                };


                return;
            }
            #endregion

        }
        static Application()
        {
            #region document
            if (Native.document != null)
            {
                // patch the awaiter..
                //Console.SetOut(new xConsole());


                // also. all workers we will be creating will need to start to expect switch commands...
                // how can we tap in them?

                //__worker_onfirstmessage: {{ 
                // ManagedThreadId = 10, href = https://192.168.1.196:13946/view-source#worker, 
                // MethodTargetTypeIndex = type$PgZysaxv_bTu4GEkwmJdJrQ, 
                // MethodTargetType = ___ctor_b__1_5_d, 
                // MethodToken = jwsABpdwBjGQu09dvBXjxw, 
                // MethodType = FuncOfObjectToObject, 
                // stateTypeHandleIndex = null, 
                // stateType = null, 
                // state = [object Object], 
                // IsIProgress = false }}
                // 

                // can we start a task, yet also have special access for the posted messages?

                // what about threads that did not hop to background?
                // dont they want to hop to background?
                HopToWorker.VirtualOnCompleted = continuation =>
                {
                    Action<ShadowIAsyncStateMachine> MoveNext0 = null;

                    // async dont like ref?
                    var shadowstate = ShadowIAsyncStateMachine.FromContinuation(continuation, ref MoveNext0);
                    var MoveNext = MoveNext0;

                    Console.WriteLine("enter HopToWorker " + new { shadowstate.state });

                    // post a message to the document 
                    var xx = new __Task.InternalTaskExtensionsScope { InternalTaskExtensionsScope_function = continuation };


                    var x = new __Task<object>();

                    // reusing thread init for generic task start, although, resuming needs special implementation..
                    x.InternalInitializeInlineWorker(
                        new Action(xx.f),
                        //action,
                        default(object),
                        default(CancellationToken),
                        default(TaskCreationOptions),
                        TaskScheduler.Default,

                        yield: (worker, e) =>
                        {
                            // like operator for JSON?

                            //Console.WriteLine("enter HopToThreadPoolAwaitable InternalInitializeInlineWorker yield");

                            var data = new
                            {
                                vSetTitle = default(string),

                                HopToUIAwaitable = new
                                {
                                    // state to hop back

                                    shadowstate = default(ShadowIAsyncStateMachine)
                                }
                            };

                            data = (dynamic)e.data;

                            //if (data.HopToUIAwaitable )

                            if (data.vSetTitle != null)
                            {
                                Console.Title = data.vSetTitle;
                            }

                            if (data.HopToUIAwaitable == null)
                                return;


                            // time to hop back on continuation?

                            var that = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)data.HopToUIAwaitable.shadowstate;


                            //Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine("work about to hop into ui " + new { that.state });
                            //Console.ForegroundColor = ConsoleColor.Black;


                            //enter HopToThreadPoolAwaitable yield HopToUIAwaitable
                            //worker Task Run function has returned {{ value_Task = null, value_TaskOfT = null }}
                            //__Task.InternalStart inner complete {{ yield = {{ value = null }} }}

                            // the worker should be in a suspended state, as we may want to jump back?

                            // 
                            //MoveNext(data.HopToUIAwaitable.shadowstate);



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

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

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

                                          return item.FullName == that.TypeName;
                                      }

                                      return false;
                                  }
                              );
                            #endregion


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

                            var NewStateMachineI = (IAsyncStateMachine)NewStateMachine;

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

                                         Console.WriteLine(new { AsyncStateMachineSourceField });

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

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

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

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

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

                            NewStateMachineI.MoveNext();

                        }
                    );


                    x.Start();


                };

                return;
            }
            #endregion


            #region worker
            if (Native.worker != null)
            {
                Console.WriteLine("about to enable HopToUI...");


                Native.worker.onfirstmessage += e =>
                {
                    Console.WriteLine("enter onfirstmessage");

                    ScriptCoreLib.JavaScript.BCLImplementation.System.__Console.vSetTitle = value =>
                    {
                        e.postMessage(
                          new
                          {
                              vSetTitle = value
                          }
                        );
                    };


                    HopToUI.VirtualOnCompleted = continuation =>
                    {
                        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151102/hoptoui

                        // first jump out?
                        InternalInlineWorker.InternalOverrideTaskOfT = new TaskCompletionSource<object>().Task;

                        // post a message to the document 

                        // um. how can we signal that we are not done?


                        //Action<ShadowIAsyncStateMachine> MoveNext = null;

                        // async dont like ref?
                        //var shadowstate = ShadowIAsyncStateMachine.FromContinuation(continuation, ref MoveNext);
                        var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation);

                        Console.WriteLine("enter HopToUI, postMessage " + new { r.shadowstate.state });


                        // postMessageAsync ? if ui wants to return, instead of restaring this thread?
                        e.postMessage(
                            new
                            {
                                HopToUIAwaitable = new
                                {
                                    // state to hop back

                                    r.shadowstate
                                }
                            }
                        );

                    };
                };


                return;
            }
            #endregion

        }