public IHTMLTableRow AddRow(params object[] e)
        {
            IHTMLTableRow r = AddRow();

            foreach (object x in e)
            {
                IHTMLTableColumn c = new IHTMLTableColumn();

                Expando q = Expando.Of(x);

                if (x == null)
                {
                    // do nothing
                }
                else if (q.IsString)
                {
                    c.innerHTML = q.GetValue();
                }
                else
                {
                    c.appendChild(q.To <INode>());
                }

                r.appendChild(c);
            }

            return(r);
        }
Esempio n. 2
0
        public IXMLDocument Serialize(TRoot e)
        {
            IXMLDocument doc = new IXMLDocument(Expando.Of(e).TypeMetaName);

            SerializeTo(doc, doc.documentElement, Expando.Of(e));

            return(doc);
        }
Esempio n. 3
0
        private static IHTMLElement Dump(object xs, IHTMLElement to, object diff)
        {
            var c = new IHTMLDiv();

            c.style.backgroundColor = Color.White;
            c.style.border          = "1px solid gray";
            c.style.padding         = "1em";
            c.style.fontFamily      = IStyle.FontFamilyEnum.Consolas;

            var ttx = new IHTMLDiv(xs.ToString());

            c.appendChild(ttx);

            var dx = Expando.Of(diff);

            foreach (var v in Expando.Of(xs).GetMembers())
            {
                var tt = default(IHTMLDiv);
                var ok = true;

                if (dx != null)
                {
                    if (dx.Contains(v.Name))
                    {
                        if (dx[v.Name] == v.Self)
                        {
                            ok = false;
                        }
                    }
                }

                if (ok)
                {
                    if (v.Self.IsFunction)
                    {
                        tt             = new IHTMLDiv(v.Self.TypeString + " " + v.Name);
                        tt.style.color = Color.Red;
                    }
                    else if (v.Self.IsObject)
                    {
                        tt             = new IHTMLDiv(v.Self.TypeString + " " + v.Name + " = " + v.Self.ToString());
                        tt.style.color = Color.Blue;
                    }
                    else
                    {
                        tt = new IHTMLDiv(v.Self.TypeString + " " + v.Name + " = " + v.Self.ToString());
                    }

                    c.appendChild(tt);
                }
            }

            to.appendChild(c);

            return(to);
        }
        static Expando DeserializeAsValue(INode e)
        {
            if (e.childNodes.Length == 1)
            {
                if (e.childNodes[0].nodeType == INode.NodeTypeEnum.TextNode)
                {
                    return(Expando.Of(e.childNodes[0].nodeValue));
                }
            }

            return(DeserializeAsExpando(e));
        }
Esempio n. 5
0
        public IXMLSerializer(params object[] k)
        {
            if (k == null)
            {
                throw new Exception("IXMLSerializer: k is null");
            }

            foreach (object x in k)
            {
                Expando o = Expando.Of(x);

                KnownTypes.SetMember(o.TypeMetaName, o);
            }
        }
Esempio n. 6
0
        public int Compare(object ka, object kb)
        {
            if (ka == kb)
            {
                return(0);
            }
            if (ka == null)
            {
                return(-1);
            }
            if (kb == null)
            {
                return(1);
            }

            var r = -2;

            if (Expando.Of(ka).IsString)
            {
                r = Expando.Compare(ka, kb);
            }

            if (Expando.Of(ka).IsNumber)
            {
                r = Expando.Compare(ka, kb);
            }

            if (Expando.Of(ka).IsBoolean)
            {
                r = Expando.Compare(ka, kb);
            }


            if (r == -2)
            {
                if (ka == kb)
                {
                    return(0);
                }

                // how do we compare two objects?
                // X:\jsc.svn\core\ScriptCoreLib\ActionScript\BCLImplementation\System\Collections\Comparer.cs
                return(1);
            }

            return(r);
        }
Esempio n. 7
0
        public static string GetScriptApplicationSourceForInlineWorker()
        {
            // ncaught TypeError: Cannot use 'in' operator to search for 'InternalScriptApplicationSource' in null

            var value = ScriptApplicationSourceForInlineWorker;

            //if (ScriptApplicationSourceForInlineWorker == null)
            {
                var x = Expando.Of(Native.self);

                // by default we should be running as view-source
                // what if we are being loaded from a blob?

                //value = Worker.ScriptApplicationSource;


                if (x.Contains("InternalScriptApplicationSource"))
                {
                    value = (string)Expando.InternalGetMember(Native.self, "InternalScriptApplicationSource");
                }

                // GetScriptApplicationSourceForInlineWorker { source = view-source }

                // { InternalScriptApplicationSource = blob:http%3A//192.168.43.252%3A21646/b74d8ef2-5b0a-4eee-8721-2f1ad91826ee }
                // GetScriptApplicationSourceForInlineWorker { source = blob:http%3A//192.168.43.252%3A21646/b74d8ef2-5b0a-4eee-8721-2f1ad91826ee }



                value += "#worker";
            }


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

            //Console.WriteLine("GetScriptApplicationSourceForInlineWorker "
            //    + new { value });

            return(value);
        }
Esempio n. 8
0
        // used by X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Threading\Tasks\Task\Task.ctor.cs
        public static object GetTypeIndex(string Name, Type TargetType)
        {
            // X:\jsc.svn\examples\javascript\async\test\TestSwitchToServiceContextAsync\TestSwitchToServiceContextAsync\ApplicationWebService.cs

            var AllMemberNames = Expando.Of(Native.self).GetMemberNames();

            var TargetTypeHandle = TargetType.TypeHandle;
            var prototype        = (object)TargetTypeHandle.Value;


            //function IzkeSBiD_aTGMsWPjgYVYEg() {}
            //IzkeSBiD_aTGMsWPjgYVYEg.TypeName = "IDataParameter";
            //IzkeSBiD_aTGMsWPjgYVYEg.Assembly = _7ryscGGN80KExNOXH5xlgw;
            //IzkeSBiD_aTGMsWPjgYVYEg.Interfaces =
            //{
            //  f7G82WqfyzOLoZ_b8v0KVxw: 1
            //};

            //var type$IzkeSBiD_aTGMsWPjgYVYEg = IzkeSBiD_aTGMsWPjgYVYEg.prototype;
            //type$IzkeSBiD_aTGMsWPjgYVYEg.constructor = IzkeSBiD_aTGMsWPjgYVYEg;


            var prototype_constructor = Expando.InternalGetMember(prototype, "constructor");

            if (prototype_constructor == null)
            {
                return(null);
            }


            //0:4257ms { Name = foo, prototype_constructor_TypeName =  }

            var prototype_constructor_TypeName = Expando.InternalGetMember(prototype_constructor, "TypeName");

            if (prototype_constructor_TypeName == null)
            {
                return(null);
            }

            //Console.WriteLine(new { Name, prototype_constructor_TypeName });

            var TargetTypeIndex = AllMemberNames.FirstOrDefault(
                item =>
            {
                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                dynamic self = Native.self;
                object value = self[item];

                if (value == prototype)
                {
                    //Console.WriteLine(new { item, f });
                    return(true);
                }

                return(false);
            }
                );


            // what are we to return?
            return(TargetTypeIndex);
        }
Esempio n. 9
0
        public static IFunction Of(string name)
        {
            // tested by x:\jsc.svn\examples\javascript\Test\TestThreadStart\TestThreadStart\Application.cs

            return(Expando.Of(Native.self).GetMember <IFunction>(name));
        }
Esempio n. 10
0
        public static IFunction Of(object target, string name)
        {
            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Runtime\CompilerServices\CallSite.cs

            return(Expando.Of(target).GetMember <IFunction>(name));
        }
Esempio n. 11
0
        // who is calling?
        // triggered by InternalInvoke
        static void __worker_onfirstmessage(
            MessageEvent e,

            int InternalThreadCounter,
            object data___string,

            bool[] MethodTargetObjectDataIsProgress,
            object[] MethodTargetObjectData,

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201411/20141112
            object[] MethodTargetObjectDataTypes,

            object MethodTargetTypeIndex,


            // set by ?
            string MethodToken,
            string MethodType,


            object state_ObjectData,
            object stateTypeHandleIndex,
            object state,

            bool IsIProgress,
            //bool IsTuple2_Item1_IsIProgress,

            __Task <object>[] TaskArray
            )
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201501/20150111

            #region ConsoleFormWriter
            var w = new InternalInlineWorkerTextWriter();

            var o = Console.Out;

            Console.SetOut(w);

            w.AtWrite =
                AtWrite =>
            {
                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                //dynamic zdata = new object();
                //zdata.AtWrite = x;

                // working with multiple threads, keep the id in the log!
                // () means we are setting the thread up... [] is the thread
                AtWrite = "[" + Thread.CurrentThread.ManagedThreadId + "] " + AtWrite;

                var zdata = new { AtWrite };



                foreach (MessagePort port in e.ports)
                {
                    port.postMessage((object)zdata, new MessagePort[0]);
                }
            };

            #endregion

            __Thread.InternalCurrentThread.ManagedThreadId = InternalThreadCounter;
            __Thread.InternalCurrentThread.IsBackground    = true;

            // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
            dynamic self = Native.self;

            var stateType = default(Type);

            if (stateTypeHandleIndex != null)
            {
                stateType = Type.GetTypeFromHandle(new __RuntimeTypeHandle((IntPtr)self[stateTypeHandleIndex]));
            }

            // X:\jsc.svn\examples\javascript\async\AsyncNonStaticHandler\AsyncNonStaticHandler\Application.cs
            var MethodTargetType = default(Type);

            if (MethodTargetTypeIndex != null)
            {
                MethodTargetType = Type.GetTypeFromHandle(new __RuntimeTypeHandle((IntPtr)self[MethodTargetTypeIndex]));
            }
            // stateType = <Namespace>.xFoo,



            // MethodTargetTypeIndex = type$GV0nCx_bM8z6My5NDh7GXlQ,

            Console.WriteLine(
                "__worker_onfirstmessage: " +
                new
            {
                Thread.CurrentThread.ManagedThreadId,
                Native.worker.location.href,

                MethodTargetTypeIndex,
                MethodTargetType,

                MethodToken,
                MethodType,


                //IsTuple2_Item1_IsIProgress,


                // X:\jsc.svn\examples\javascript\test\TestTypeHandle\TestTypeHandle\Application.cs
                stateTypeHandleIndex,
                stateType,
                state,
                IsIProgress,

                //MethodTokenReference
            }
                );

            #region MethodTokenReference
            var MethodTokenReference = default(IFunction);
            var MethodTarget         = default(object);

            if (MethodTargetType == null)
            {
                MethodTokenReference = IFunction.Of(MethodToken);
            }
            else
            {
                MethodTarget = FormatterServices.GetUninitializedObject(MethodTargetType);

                var MethodTargetTypeSerializableMembers = FormatterServices.GetSerializableMembers(MethodTargetType);

                // X:\jsc.svn\examples\javascript\async\test\TestWorkerScopeProgress\TestWorkerScopeProgress\Application.cs

                for (int i = 0; i < MethodTargetTypeSerializableMembers.Length; i++)
                {
                    var xMember     = MethodTargetTypeSerializableMembers[i] as FieldInfo;
                    var xObjectData = MethodTargetObjectData[i];

                    var xMethodTargetObjectDataTypeIndex = MethodTargetObjectDataTypes[i];


                    var xIsProgress = MethodTargetObjectDataIsProgress[i];

                    // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServer\ChromeTCPServer\Application.cs
                    // does our chrome tcp server get the damn path?
                    Console.WriteLine(new { xMember, xMethodTargetObjectDataTypeIndex, xObjectData, xIsProgress });

                    // need to resurrect the semaphores!
                    // X:\jsc.svn\examples\javascript\async\Test\TestSemaphoreSlim\TestSemaphoreSlim\ApplicationControl.cs


                    #region MethodTargetObjectDataIsProgress
                    // cant we use xMethodTargetObjectDataType instead?
                    if (xIsProgress)
                    {
                        var ii = i;
                        MethodTargetObjectData[ii] = new __Progress <object>(
                            ProgressEvent =>
                        {
                            // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                            dynamic zdata = new object();

                            zdata.MethodTargetObjectDataProgressReport = new { ProgressEvent, ii };

                            foreach (MessagePort port in e.ports)
                            {
                                port.postMessage((object)zdata, new MessagePort[0]);
                            }

                            //Console.WriteLine(new { MethodTargetTypeSerializableMember, MethodTargetTypeSerializableMemberIsProgress, ProgressEvent });
                        }
                            );
                    }
                    #endregion

                    else
                    {
                        var xMethodTargetObjectDataType = default(Type);
                        if (xMethodTargetObjectDataTypeIndex != null)
                        {
                            xMethodTargetObjectDataType = Type.GetTypeFromHandle(new __RuntimeTypeHandle((IntPtr)self[xMethodTargetObjectDataTypeIndex]));
                        }

                        // now we know the type. should we review it?

                        if (xMethodTargetObjectDataType != null)
                        {
                            var scope2copy = FormatterServices.GetUninitializedObject(xMethodTargetObjectDataType);

                            //shall we copy the members too?
                            //FormatterServices.PopulateObjectMembers(scope2copy, scope2TypeSerializableMembers, scope2ObjectData);

                            MethodTargetObjectData[i] = scope2copy;

                            #region __SemaphoreSlim
                            // X:\jsc.svn\examples\javascript\async\Test\TestSemaphoreSlim\TestSemaphoreSlim\ApplicationControl.cs
                            var xSemaphoreSlim = scope2copy as __SemaphoreSlim;
                            if (xSemaphoreSlim != null)
                            {
                                // we now have to complete the entanglement. we have the caller on the UI.

                                Action <string> WriteLine0 = text =>
                                {
                                    Console.WriteLine("(" + xMember.Name + ") " + text);
                                };


                                //xSemaphoreSlim.InternalIsEntangled = true;



                                #region InternalVirtualWaitAsync
                                var xInternalVirtualWaitAsync = default(TaskCompletionSource <object>);

                                xSemaphoreSlim.InternalVirtualWaitAsync += continuation =>
                                {
                                    WriteLine0("enter xSemaphoreSlim.InternalVirtualWaitAsync, worker is now awaiting for signal");

                                    xInternalVirtualWaitAsync = continuation;
                                };

                                // at this point lets call the UI to set up a new signal channel..

                                //new MessageChannel();

                                var c = new MessageChannel();

                                c.port1.onmessage +=
                                    ce =>
                                {
                                    // ui has released?

                                    if (xInternalVirtualWaitAsync == null)
                                    {
                                        // what if the thread is not yet awaiting?
                                        WriteLine0("ui has sent a release signal, yet nobody awaiting");
                                        return;
                                    }

                                    WriteLine0("ui has sent a release signal, resync");

                                    // we should have byte fields now.
                                    // next strings as in thread hopping...

                                    dynamic data = ce.data;

                                    #region read xSemaphoreSlim_ByteArrayFields
                                    {
                                        __Task.xByteArrayField[] xSemaphoreSlim_ByteArrayFields = data.xSemaphoreSlim_ByteArrayFields;

                                        // X:\jsc.svn\examples\javascript\async\test\TestBytesToSemaphore\TestBytesToSemaphore\Application.cs
                                        if (xSemaphoreSlim_ByteArrayFields != null)
                                        {
                                            foreach (var item in xSemaphoreSlim_ByteArrayFields)
                                            {
                                                var xFieldInfo = (FieldInfo)MethodTargetTypeSerializableMembers[item.index];

                                                // can we set the value?
                                                WriteLine0("worker resync " + new
                                                {
                                                    item.index,
                                                    //item.Name,
                                                    xFieldInfo = xFieldInfo.Name,
                                                    item.value
                                                });

                                                xFieldInfo.SetValue(
                                                    MethodTarget,

                                                    // null?
                                                    item.value
                                                    );
                                            }
                                        }
                                    }
                                    #endregion

                                    xInternalVirtualWaitAsync.SetResult(null);
                                };

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

                                WriteLine0("will set up the signal channel");

                                foreach (var p in e.ports)
                                {
                                    p.postMessage(
                                        new { xSemaphoreSlim = xMember.Name },
                                        transfer: new[] { c.port2 }
                                        );
                                }
                                #endregion


                                #region InternalVirtualRelease
                                xSemaphoreSlim.InternalVirtualRelease += delegate
                                {
                                    WriteLine0("enter xSemaphoreSlim.InternalVirtualRelease, will send a signal to ui...");

                                    // worker needs sync data about now.
                                    // the ui would be happy to have the latest version of the data.
                                    // this is tricky. we would really need to know which data fields have changed by now
                                    // and what will happen if the data was also changed on the ui.
                                    // technically we are doing a merge conflict resolver...

                                    // this is somewhat the same situation, we alrady have
                                    // when entering a worker
                                    // when exiting a worker
                                    // when hoping to or from a worker.

                                    // what data fields do we have to upload yo ui?
                                    // how much IL analysis is available for us to know what to sync
                                    // we should not sync fields that wont be used on the ui

                                    // the thread hop looks at strings only right now, as they are immputable yet primitive
                                    // what about bytewarrays?
                                    // X:\jsc.svn\examples\javascript\async\test\TestBytesFromSemaphore\TestBytesFromSemaphore\Application.cs

                                    #region xSemaphoreSlim_ByteArrayFields
                                    var xSemaphoreSlim_ByteArrayFields = new List <__Task.xByteArrayField>();


                                    var MethodTargetTypeSerializableMembers_index = 0;
                                    foreach (FieldInfo item in MethodTargetTypeSerializableMembers)
                                    {
                                        // how would we know if the array is a byte array?

                                        // FieldType is not exactly available yet
                                        //Console.WriteLine("worker resync candidate " + new { item.Name, item.FieldType, item.FieldType.IsArray });

                                        var item_value = item.GetValue(MethodTarget);
                                        if (item_value != null)
                                        {
                                            var item_value_constructor = Expando.Of(item_value).constructor;
                                            var item_value_IsByteArray = Native.self_Uint8ClampedArray == item_value_constructor;

                                            if (item_value_IsByteArray)
                                            {
                                                var value = (byte[])item_value;

                                                xSemaphoreSlim_ByteArrayFields.Add(
                                                    new __Task.xByteArrayField
                                                {
                                                    index = MethodTargetTypeSerializableMembers_index,

                                                    // keep name for diagnostics
                                                    Name = item.Name,

                                                    value = value
                                                }
                                                    );

                                                WriteLine0("worker resync xByteArrayField candidate " + new { item.Name, value.Length });
                                            }
                                        }


                                        MethodTargetTypeSerializableMembers_index++;
                                    }
                                    #endregion


                                    foreach (var p in e.ports)
                                    {
                                        p.postMessage(
                                            new
                                        {
                                            xSemaphoreSlim = xMember.Name,
                                            xSemaphoreSlim_ByteArrayFields = xSemaphoreSlim_ByteArrayFields.ToArray()
                                        }
                                            );
                                    }
                                };
                                #endregion
                            }
                            #endregion
                        }
                    }
                }

                FormatterServices.PopulateObjectMembers(
                    MethodTarget,
                    MethodTargetTypeSerializableMembers,
                    MethodTargetObjectData
                    );



                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                MethodTokenReference = (MethodTarget as dynamic)[MethodToken];
            }

            // what if we are being called from within a secondary app?

            //  stateTypeHandleIndex = type$XjKww8iSKT_aFTpY_bSs5vBQ,
            if (MethodTokenReference == null)
            {
                // tested at
                // X:\jsc.svn\examples\javascript\WorkerInsideSecondaryApplication\WorkerInsideSecondaryApplication\Application.cs


                // X:\jsc.svn\examples\javascript\Test\TestHopToThreadPoolAwaitable\TestHopToThreadPoolAwaitable\Application.cs
                // why?
                throw new InvalidOperationException(
                          new { MethodToken } +" function is not available at " + new { Native.worker.location.href }
                          );
            }
            #endregion

            //Console.WriteLine(
            //     new
            //     {
            //         MethodTokenReference,
            //         Thread.CurrentThread.ManagedThreadId
            //     }
            // );

            // whats the type?



            #region xstate
            var xstate = default(object);

            if (stateType != null)
            {
                xstate = FormatterServices.GetUninitializedObject(stateType);
                var xstate_SerializableMembers = FormatterServices.GetSerializableMembers(stateType);

                FormatterServices.PopulateObjectMembers(
                    xstate,
                    xstate_SerializableMembers,
                    (object[])state_ObjectData
                    );

                // MethodType = FuncOfObjectToObject
                //Console.WriteLine("as FuncOfObjectToObject");
            }
            #endregion

            #region CreateProgress
            Func <__Progress <object> > CreateProgress =
                () => new __Progress <object>(
                    value =>
            {
                //Console.WriteLine("__IProgress_Report " + new { value });

                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                dynamic zdata = new object();

                zdata.__IProgress_Report = new { value };

                foreach (MessagePort port in e.ports)
                {
                    port.postMessage((object)zdata, new MessagePort[0]);
                }
            }
                    );

            // X:\jsc.svn\examples\javascript\async\Test\TestWorkerProgress\TestWorkerProgress\Application.cs
            if (IsIProgress)
            {
                xstate = CreateProgress();
            }


            #endregion



            #region __string
            // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
            dynamic target = __string;
            var     m      = Expando.Of(data___string).GetMembers();
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201308/20130826-domainmemory
            foreach (ExpandoMember nn in m)
            {
                target[nn.Name] = nn.Value;

                var trigger         = "set_" + nn.Name;
                var trigger_default = IFunction.Of(trigger);

                (Native.self as dynamic)[trigger] = IFunction.OfDelegate(
                    new Action <string>(
                        Value =>
                {
                    if (nn.Value == Value)
                    {
                        return;
                    }

                    trigger_default.apply(null, Value);

                    #region sync one field only

                    {
                        dynamic zdata          = new object();
                        dynamic zdata___string = new object();

                        zdata.__string = zdata___string;


                        zdata___string[nn.Name] = Value;

                        // prevent sync via diff
                        nn.Value = Value;

                        foreach (MessagePort port in e.ports)
                        {
                            port.postMessage((object)zdata, new MessagePort[0]);
                        }
                    }


                    #endregion
                }
                        )
                    );
            }
            #endregion


            {
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201308/20130828-thread-run
                // for now we only support static calls


                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                dynamic zdata = new object();


                if (MethodType == typeof(ActionOfDedicatedWorkerGlobalScope).Name)
                {
                    MethodTokenReference.apply(null, Native.worker);
                }
                else if (MethodType == typeof(FuncOfObjectToObject).Name)
                {
                    //Console.WriteLine("worker Task Run function call");


                    #region FuncOfObjectToObject
                    // X:\jsc.svn\examples\javascript\test\TestTaskStartToString\TestTaskStartToString\Application.cs
                    // X:\jsc.svn\examples\javascript\async\test\TestTaskRun\TestTaskRun\Application.cs
                    // X:\jsc.svn\examples\javascript\Test\TestGetUninitializedObject\TestGetUninitializedObject\Application.cs


                    var value = MethodTokenReference.apply(MethodTarget, xstate);

                    // X:\jsc.svn\examples\javascript\async\test\TaskAsyncTaskRun\TaskAsyncTaskRun\Application.cs

                    // whatif its an Action not a Func?
                    //enter HopToThreadPoolAwaitable yield HopToUIAwaitable
                    //worker Task Run function has returned {{ value_Task = null, value_TaskOfT = null }}
                    //__Task.InternalStart inner complete {{ yield = {{ value = null }} }}

                    var value_Task    = value as __Task;
                    var value_TaskOfT = value as __Task <object>;

                    // if we are in a hop. allow the return task to be overriden.
                    if (InternalOverrideTaskOfT != null)
                    {
                        value_TaskOfT = InternalOverrideTaskOfT;
                    }


                    // 0:25611ms Task Run function has returned { value_Task = [object Object], value_TaskOfT = [object Object] }
                    //Console.WriteLine("worker Task Run function has returned " + new { value_Task, value_TaskOfT, InternalOverrideTaskOfT });
                    // 0:4284ms Task Run function has returned { value_Task = { IsCompleted = 1, Result =  }, value_TaskOfT = { IsCompleted = 1, Result =  } }
                    // 0:5523ms Task Run function has returned { value_Task = { IsCompleted = false, Result =  }, value_TaskOfT = { IsCompleted = false, Result =  } }

                    if (value_TaskOfT != null)
                    {
                        // special situation

                        // if IsCompleted, called twice? or heard twice?
                        value_TaskOfT.ContinueWith(
                            t =>
                        {
                            //Console.WriteLine("worker Task Run ContinueWith " + new { t });


                            // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                            dynamic zzdata = new object();

                            // null?
                            if (t.Result == null)
                            {
                                zzdata.ContinueWithResult = new { t.Result };
                                foreach (MessagePort port in e.ports)
                                {
                                    port.postMessage((object)zzdata, new MessagePort[0]);
                                }
                                return;
                            }

                            var ResultType      = t.Result.GetType();
                            var ResultTypeIndex = __Type.GetTypeIndex("workerResult", ResultType);

                            var ResultTypeSerializableMembers = FormatterServices.GetSerializableMembers(ResultType);
                            var ResultObjectData = FormatterServices.GetObjectData(t.Result, ResultTypeSerializableMembers);

                            var ContinueWithResult = new
                            {
                                ResultTypeIndex,
                                ResultObjectData,

                                t.Result
                            };

                            zzdata.ContinueWithResult = ContinueWithResult;

                            foreach (MessagePort port in e.ports)
                            {
                                port.postMessage((object)zzdata, new MessagePort[0]);
                            }
                        }
                            );
                    }
                    else
                    {
                        if (value_Task != null)
                        {
                            // X:\jsc.svn\examples\javascript\async\test\TestWorkerScopeProgress\TestWorkerScopeProgress\Application.cs

                            throw new NotImplementedException();
                        }
                        else
                        {
                            var yield = new { value };

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

                            zdata.yield = yield;
                        }
                    }
                    #endregion
                    // now what?
                }
                else if (MethodType == typeof(FuncOfTaskToObject).Name)
                {
                    // tested by?
                    #region FuncOfTaskToObject
                    // need to reconstruct the caller task?


                    var value = MethodTokenReference.apply(null, TaskArray.Single());
                    var yield = new { value };

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

                    zdata.yield = yield;
                    #endregion
                    // now what?
                }
                else if (MethodType == typeof(FuncOfTaskOfObjectArrayToObject).Name)
                {
                    // tested by?

                    #region FuncOfTaskOfObjectArrayToObject
                    // need to reconstruct the caller task?

                    Console.WriteLine("__worker_onfirstmessage: " + new { TaskArray = TaskArray.Length });

                    //Debugger.Break();

                    var args = new object[] { TaskArray };

                    var value = MethodTokenReference.apply(
                        o: null,

                        // watch out
                        args: args
                        );

                    var yield = new { value };

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

                    zdata.yield = yield;
                    #endregion
                    // now what?
                }

                #region [sync] diff and upload changes to DOM context, the latest now
                {
                    dynamic zdata___string = new object();

                    zdata.__string = zdata___string;

                    foreach (ExpandoMember nn in m)
                    {
                        string Value = (string)Expando.InternalGetMember((object)target, nn.Name);
                        // this is preferred:
                        //string Value = target[nn.Name];

                        if (Value != nn.Value)
                        {
                            zdata___string[nn.Name] = Value;
                        }
                    }
                }
                #endregion

                //e.post
                foreach (MessagePort port in e.ports)
                {
                    port.postMessage((object)zdata, new MessagePort[0]);
                }
            }
        }
Esempio n. 12
0
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201308/20130816-web-worker
        // called by?
        public static global::ScriptCoreLib.JavaScript.DOM.Worker InternalConstructor(
            Action <DedicatedWorkerGlobalScope> yield
            )
        {
            var MethodToken = ((__MethodInfo)yield.Method).InternalMethodToken;

            Console.WriteLine("InternalInlineWorker InternalConstructor " + new
            {
                MethodToken,
                InternalThreadCounter
            });

            // discard params



            // we need some kind of per Application activation index
            // so multiple inline workers could know which they are.

            // x:\jsc.svn\examples\javascript\Test\TestThreadStart\TestThreadStart\Application.cs
            // share scope

            // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
            dynamic xdata = new object();

            xdata.InternalThreadCounter = InternalInlineWorker.InternalThreadCounter;
            xdata.MethodToken           = MethodToken;
            xdata.MethodType            = typeof(ActionOfDedicatedWorkerGlobalScope).Name;

            #region xdata___string
            dynamic xdata___string = new object();

            // how much does this slow us down?
            // connecting to a new scope, we need a fresh copy of everything
            // we can start with strings
            foreach (ExpandoMember nn in Expando.Of(__string).GetMembers())
            {
                if (nn.Value != null)
                {
                    xdata___string[nn.Name] = nn.Value;
                }
            }
            #endregion

            xdata.__string = xdata___string;

            // ?
            InternalInlineWorker.InternalThreadCounter++;

            var w = new global::ScriptCoreLib.JavaScript.DOM.Worker(
                GetScriptApplicationSourceForInlineWorker()
                );

            w.postMessage((object)xdata,
                          e =>
            {
                // what kind of write backs do we expect?
                // for now it should be console only

                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                dynamic zdata = e.data;

                #region AtWrite
                string AtWrite = zdata.AtWrite;

                if (!string.IsNullOrEmpty(AtWrite))
                {
                    Console.Write(AtWrite);
                }
                #endregion

                #region __string
                var zdata___string = (object)zdata.__string;
                if (zdata___string != null)
                {
                    #region __string
                    dynamic target = __string;
                    var m          = Expando.Of(zdata___string).GetMembers();

                    foreach (ExpandoMember nn in m)
                    {
                        Console.WriteLine("Worker has sent changes " + new { nn.Name });

                        target[nn.Name] = nn.Value;
                    }
                    #endregion
                }
                #endregion
            }
                          );

            return(w);
        }
Esempio n. 13
0
 public static string SerializeToJSON <T>(this T e)
     where T : class, new()
 {
     return(Expando.Of(e).ToJSON());
 }
Esempio n. 14
0
        // X:\jsc.svn\examples\javascript\async\test\TestSwitchToServiceContextAsync\TestSwitchToServiceContextAsync\Application.cs

        // called by
        // Task.Run,
        // Task.ctor
        // TaskFactory.StartNew

        public void InternalInitializeInlineWorker(
            //Func<object, TResult> function,
            Delegate function,

            object state,

            CancellationToken c,
            TaskCreationOptions o,
            TaskScheduler s,


            // X:\jsc.svn\examples\javascript\async\AsyncHopToUIFromWorker\AsyncHopToUIFromWorker\Application.cs
            // allow special callbacks
            Action <Worker, MessageEvent> yield = null
            )
        {
            var InternalThreadCounter = InternalInlineWorker.InternalThreadCounter;

            InternalInlineWorker.InternalThreadCounter++;



            Delegate xfunction = function;

            #region WriteLine
            Action <string> UIWriteLine =
                text =>
            {
                if (InternalInlineWorkerTextWriter.WorkerConsoleDisabled)
                {
                    return;
                }

                // () means we are setting the thread up... [] is the thread
                Console.WriteLine("UI(" + InternalThreadCounter + ") " + text);
            };
            #endregion

            //WriteLine("enter InternalInitializeInlineWorker");


            // whatif the delegate is Action?

            // X:\jsc.svn\examples\javascript\Test\TestRedirectWebWorker\TestRedirectWebWorker\Application.cs
            // what happened? also, as interface cannot handle ull yet


            var MethodType = typeof(FuncOfObjectToObject).Name;



            // what if this is a GUI task?

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201308/20130828-thread-run

            #region MethodToken


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


            if (xfunction.Target != null)
            {
                if (xfunction.Target != Native.self)
                {
                    // X:\jsc.svn\examples\javascript\Test\TestMemoryStreamPerformance\TestMemoryStreamPerformance\Application.cs
                    // X:\jsc.svn\examples\javascript\async\AsyncNonStaticHandler\AsyncNonStaticHandler\Application.cs

                    var TargetType = xfunction.Target.GetType();

                    //Console.WriteLine("InternalInitializeInlineWorker " + new { Target = function.Target.ToString(), TargetType });

                    // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                    Delegate InternalTaskExtensionsScope_function = (xfunction.Target as dynamic).InternalTaskExtensionsScope_function;
                    // X:\jsc.svn\core\ScriptCoreLib.Extensions\ScriptCoreLib.Extensions\Extensions\TaskExtensions.cs

                    if (InternalTaskExtensionsScope_function != null)
                    {
                        //MethodToken = ((__MethodInfo)InternalTaskExtensionsScope_function.Method).InternalMethodToken;

                        xfunction = InternalTaskExtensionsScope_function;
                    }
                }
            }
            #endregion

            var MethodToken = ((__MethodInfo)xfunction.Method).InternalMethodToken;



            #region MethodTargetTypeIndex
            var MethodTargetTypeIndex = default(object);



            // shall we get level2 types accross
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201411/20141112
            var MethodTargetObjectDataTypes = default(object[]);

            var MethodTargetObjectData           = default(object[]);
            var MethodTargetObjectDataProgress   = default(__IProgress <object>[]);
            var MethodTargetObjectDataIsProgress = default(bool[]);

            // we need to send in also the this argument of the function, lets find whats the token of the type
            if (xfunction.Target != null)
            {
                // functions bound to self/window are considered to be static
                if (xfunction.Target != Native.self)
                {
                    // X:\jsc.svn\examples\javascript\async\AsyncNonStaticHandler\AsyncNonStaticHandler\Application.cs

                    var TargetType = xfunction.Target.GetType();

                    MethodTargetTypeIndex = __Type.GetTypeIndex("TargetType", TargetType);


                    // lets hope all the fields are transferable!

                    var MethodTargetSerializableMembers = FormatterServices.GetSerializableMembers(TargetType);

                    //foreach (var item in MethodTargetSerializableMembers)
                    //{
                    //    // do we have usage/security information available from the analyzer?
                    //    Console.WriteLine("__Task will share scope, field " + item.Name);
                    //    // for scope sharing first we may see IEvent. that cannot be sent over
                    //    // as it is not a primitive and not under our control either
                    //    // how can we exclude it?
                    //    // we should also know who exactyl can use it in the inner scope
                    //}

                    MethodTargetObjectData = FormatterServices.GetObjectData(xfunction.Target, MethodTargetSerializableMembers);

                    // X:\jsc.svn\examples\javascript\async\test\TestWorkerScopeProgress\TestWorkerScopeProgress\Application.cs
                    MethodTargetObjectDataTypes      = new object[MethodTargetObjectData.Length];
                    MethodTargetObjectDataProgress   = new __IProgress <object> [MethodTargetObjectData.Length];
                    MethodTargetObjectDataIsProgress = new bool[MethodTargetObjectData.Length];

                    for (int i = 0; i < MethodTargetObjectData.Length; i++)
                    {
                        var MemberName  = MethodTargetSerializableMembers[i].Name;
                        var MemberValue = MethodTargetObjectData[i];

                        if (MemberValue != null)
                        {
                            //0:6967ms __Task scope { MemberName = foo, isString = false, isInt32 = false, idx = vgAABBwAgD2RX0Pk4wU2RQ }
                            // 0:5749ms __Task scope { MemberName = foo, isString = false, isInt32 = false, idx = vgAABBwAgD2RX0Pk4wU2RQ, MemberType = <Namespace>. }
                            // 0:3093ms __Task scope { MemberName = row, isString = false, isInt32 = false, idx = type$_2LWH6_a6FzTCDOJSbur6JKQ, MemberType = <Namespace>.xRow }

                            // is it our type/secure or not? or is it primitive?
                            var MemberType = MemberValue.GetType();

                            var IsString = Expando.Of(MemberValue).IsString;
                            //var isString = MemberType == typeof(string);
                            //var isInt32 = MemberType == typeof(int);
                            var IsNumber    = Expando.Of(MemberValue).IsNumber;
                            var IsByteArray = Expando.Of(MemberValue).IsByteArray;

                            // are we to send typeIndex to the other side for member reconstruction?
                            var TypeIndex = __Type.GetTypeIndex(MemberName, MemberType);

                            MethodTargetObjectDataTypes[i] = TypeIndex;

                            //0:4812ms __Task scope { MemberName = scope1, isString = false, isInt32 = false } view-source:40687
                            //0:4814ms __Task scope { MemberName = e, isString = false, isInt32 = false }



                            // null it out as we are not able to clone that object for the other thread
                            if (TypeIndex == null)
                            {
                                if (!IsString)
                                {
                                    if (!IsNumber)
                                    {
                                        if (!IsByteArray)
                                        {
                                            MethodTargetObjectData[i] = null;
                                        }
                                    }
                                }
                            }

                            // we do not know yet how to handle cloning events on level2
                            var IsDelegate = MemberValue is Delegate;
                            if (IsDelegate)
                            {
                                MethodTargetObjectData[i] = null;
                            }



                            #region xSemaphoreSlim
                            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\DOM\Worker.cs

                            // X:\jsc.svn\examples\javascript\async\Test\TestSemaphoreSlim\TestSemaphoreSlim\ApplicationControl.cs
                            var xSemaphoreSlim = MemberValue as __SemaphoreSlim;
                            if (xSemaphoreSlim != null)
                            {
                                // will sending a null over create the object on the other side?
                                MethodTargetObjectData[i] = null;


                                var             MemberName0  = MemberName;
                                Action <string> UIWriteLine0 = text =>
                                {
                                    UIWriteLine("$" + MemberName0 + " " + text);
                                };


                                // we need to entangle the fields in current and the new thread..
                                // if we were to get the signal, how?

                                // 1 or more

                                //var xInternalVirtualWaitAsync = default(TaskCompletionSource<object>);

                                // X:\jsc.svn\examples\javascript\async\test\TestSemaphoreSlimAwaitThenReleaseInWorker\TestSemaphoreSlimAwaitThenReleaseInWorker\Application.cs
                                // is somebody already awaiting?
                                var xInternalVirtualWaitAsyncTask = new TaskCompletionSource <TaskCompletionSource <object> >();
                                var xInternalVirtualWaitAsync     = xSemaphoreSlim.InternalVirtualWaitAsync0;
                                if (xInternalVirtualWaitAsync != null)
                                {
                                    xInternalVirtualWaitAsyncTask.SetResult(xInternalVirtualWaitAsync);
                                }

                                xSemaphoreSlim.InternalVirtualWaitAsync += continuation =>
                                {
                                    UIWriteLine0("enter xSemaphoreSlim.InternalVirtualWaitAsync, ui is now awaiting for signal " + new { xSemaphoreSlim.Name });

                                    // we need a signal from the worker, or the ui
                                    xInternalVirtualWaitAsync = continuation;
                                    xInternalVirtualWaitAsyncTask.SetResult(xInternalVirtualWaitAsync);
                                };



                                var xSemaphoreSlim_InternalIsEntangled = false;

                                // called by?
                                #region yield_xSemaphoreSlim
                                Action <Worker, MessageEvent> yield_xSemaphoreSlim =


                                    // we want in. lets wait for messages from the thread..
                                    //yield += (Worker worker, MessageEvent e) =>
                                    (Worker worker, MessageEvent e) =>
                                {
                                    dynamic data             = e.data;
                                    string  __xSemaphoreSlim = data.xSemaphoreSlim;

                                    if (__xSemaphoreSlim == null)
                                    {
                                        return;
                                    }


                                    if (__xSemaphoreSlim != MemberName0)
                                    {
                                        return;
                                    }

                                    //

                                    // now we have a port to send the release signal?
                                    //WriteLine("xSemaphoreSlim MessageEvent " + new { MemberName0 });

                                    // next will be a release from the worker?

                                    // we made contact!
                                    #region InternalVirtualRelease
                                    if (!xSemaphoreSlim_InternalIsEntangled)
                                    {
                                        UIWriteLine0("yield_xSemaphoreSlim, worker is now listening for release signal");

                                        xSemaphoreSlim_InternalIsEntangled = true;

                                        xSemaphoreSlim.InternalVirtualRelease += delegate
                                        {
                                            // um. we need to post a message to the other side.
                                            // do we have a port channel for it?
                                            // does the other side expect signals?

                                            //WriteLine("xSemaphoreSlim.InternalVirtualRelease " + new { MemberName0 });
                                            UIWriteLine0("xSemaphoreSlim.InternalVirtualRelease, ui is sending signal to worker, resync");

                                            // xSemaphoreSlim_ByteArrayFields
                                            #region xSemaphoreSlim_ByteArrayFields
                                            var xSemaphoreSlim_ByteArrayFields = new List <__Task.xByteArrayField>();


                                            var MethodTargetTypeSerializableMembers_index = 0;

                                            // MethodTargetSerializableMembers
                                            // MethodTargetTypeSerializableMembers

                                            foreach (FieldInfo item in MethodTargetSerializableMembers)
                                            {
                                                // how would we know if the array is a byte array?

                                                // FieldType is not exactly available yet
                                                //Console.WriteLine("worker resync candidate " + new { item.Name, item.FieldType, item.FieldType.IsArray });

                                                var item_value = item.GetValue(xfunction.Target);
                                                if (item_value != null)
                                                {
                                                    var item_value_IsByteArray = Expando.Of(item_value).IsByteArray;

                                                    if (item_value_IsByteArray)
                                                    {
                                                        var value = (byte[])item_value;

                                                        xSemaphoreSlim_ByteArrayFields.Add(
                                                            new __Task.xByteArrayField
                                                        {
                                                            index = MethodTargetTypeSerializableMembers_index,

                                                            // keep name for diagnostics
                                                            Name = item.Name,

                                                            value = value
                                                        }
                                                            );

                                                        UIWriteLine0("ui to worker resync xByteArrayField candidate " + new { item.Name, value.Length });
                                                    }
                                                }


                                                MethodTargetTypeSerializableMembers_index++;
                                            }
                                            #endregion

                                            foreach (var p in e.ports)
                                            {
                                                // release 1
                                                p.postMessage(
                                                    new
                                                {
                                                    // X:\jsc.svn\examples\javascript\async\Test\TestBytesToSemaphore\TestBytesToSemaphore\Application.cs
                                                    xSemaphoreSlim_ByteArrayFields = xSemaphoreSlim_ByteArrayFields.ToArray()
                                                }
                                                    );
                                            }
                                        };

                                        return;
                                    }
                                    #endregion


                                    // now wait for release from worker?

                                    // we never get the message?
                                    //e.ports[0].onmessage += ee =>
                                    //{
                                    //	Console.WriteLine("xSemaphoreSlim port0 onmessage " + new { MemberName0 });
                                    //};



                                    //e.ports[1].onmessage += ee =>
                                    //{
                                    //	Console.WriteLine("xSemaphoreSlim port1 onmessage " + new { MemberName0 });
                                    //};

                                    // workaround?

                                    UIWriteLine0("yield_xSemaphoreSlim, worker sent a release signal to UI, resync " + new { xInternalVirtualWaitAsyncTask.Task.IsCompleted });


                                    #region read xSemaphoreSlim_ByteArrayFields
                                    {
                                        __Task.xByteArrayField[] xSemaphoreSlim_ByteArrayFields = data.xSemaphoreSlim_ByteArrayFields;
                                        // 55779ms ui xSemaphoreSlim MessageEvent, resync, trigger InternalVirtualWaitAsync? {{ MemberName0 = bytes1sema, xInternalVirtualWaitAsync = [object Object], Length = 1 }}

                                        //Console.WriteLine("ui xSemaphoreSlim MessageEvent, resync, trigger InternalVirtualWaitAsync? " + new { MemberName0, xInternalVirtualWaitAsync, xSemaphoreSlim_ByteArrayFields.Length });

                                        // X:\jsc.svn\examples\javascript\async\test\TestBytesToSemaphore\TestBytesToSemaphore\Application.cs
                                        if (xSemaphoreSlim_ByteArrayFields != null)
                                        {
                                            foreach (var item in xSemaphoreSlim_ByteArrayFields)
                                            {
                                                var xFieldInfo = (FieldInfo)MethodTargetSerializableMembers[item.index];

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

                                                // can we set the value?
                                                UIWriteLine("ui resync " + new
                                                {
                                                    item.index,
                                                    //item.Name,
                                                    xFieldInfo = xFieldInfo.Name,
                                                    //item.value
                                                });

                                                xFieldInfo.SetValue(
                                                    xfunction.Target,

                                                    // null?
                                                    item.value
                                                    );
                                            }
                                        }
                                    }
                                    #endregion


                                    // what happens if we wnt to signal but nobody is waiting?
                                    // X:\jsc.svn\examples\javascript\async\test\TestBytesToSemaphore\TestBytesToSemaphore\Application.cs
                                    // X:\jsc.svn\examples\javascript\async\test\TestBytesFromSemaphore\TestBytesFromSemaphore\Application.cs



                                    xInternalVirtualWaitAsyncTask.Task.ContinueWith(
                                        __xInternalVirtualWaitAsync =>
                                    {
                                        UIWriteLine0("yield_xSemaphoreSlim, expect a new awaiter now?");

                                        //if (xInternalVirtualWaitAsync == null)
                                        //{
                                        //    UIWriteLine0("cannot signal, xInternalVirtualWaitAsync is null, why? missed by 1?");
                                        //}
                                        //else
                                        //{
                                        //    UIWriteLine0("yield_xSemaphoreSlim, expect a new awaiter now?");
                                        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/20150706/20150712/rgba_bytes0out_set
                                        xInternalVirtualWaitAsync     = null;
                                        xInternalVirtualWaitAsyncTask = new TaskCompletionSource <TaskCompletionSource <object> >();

                                        __xInternalVirtualWaitAsync.Result.SetResult(null);
                                        //}
                                    }
                                        );
                                };
                                #endregion



                                yield += yield_xSemaphoreSlim;
                            }
                            #endregion


                            // X:\jsc.svn\examples\javascript\async\test\TestWorkerScopeProgress\TestWorkerScopeProgress\Application.cs
                            var IsProgress = MemberValue is __IProgress <object>;
                            if (IsProgress)
                            {
                                MethodTargetObjectDataProgress[i] = (__IProgress <object>)MemberValue;
                                MethodTargetObjectData[i]         = null;

                                // let worker know we want progress reports sent back to us
                                MethodTargetObjectDataIsProgress[i] = true;
                            }

                            // X:\jsc.svn\examples\javascript\async\test\TestScopeWithDelegate\TestScopeWithDelegate\Application.cs
                            // lets make sure no delegates are at level2 either


                            var scope2 = MethodTargetObjectData[i];

                            if (IsString)
                            {
                                // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150428

                                // see path yet?
                                //Console.WriteLine("string: " + new { MemberName, scope2 });
                            }
                            else if (xSemaphoreSlim != null)
                            {
                                // the first entangled method. should we look a the fields?
                                //Console.WriteLine("xSemaphoreSlim: " + new { MemberName });
                            }
                            else
                            {
                                if (scope2 != null)
                                {
                                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201411/20141112
                                    // x:\jsc.svn\examples\javascript\test\testhoptothreadpoolawaitable\testhoptothreadpoolawaitable\application.cs


                                    var scope2Type = scope2.GetType();
                                    var scope2TypeSerializableMembers = FormatterServices.GetSerializableMembers(scope2Type);

                                    if (scope2TypeSerializableMembers.Length > 0)
                                    {
                                        // are there any members?
                                        UIWriteLine("will inspect scope2 as " + new { MemberName, scope2TypeSerializableMembers.Length });
                                        var scope2ObjectData = FormatterServices.GetObjectData(scope2, scope2TypeSerializableMembers);

                                        // the hacky way. later we need to refactor this a lot.
                                        for (int ii = 0; ii < scope2ObjectData.Length; ii++)
                                        {
                                            var scope2FieldName = scope2TypeSerializableMembers[ii].Name;

                                            UIWriteLine("scope2: " + MemberName + "." + scope2FieldName);


                                            var scope2value = scope2ObjectData[ii];
                                            if (scope2value != null)
                                            {
                                                var scope2IsDelegate = scope2value is Delegate;
                                                if (scope2IsDelegate)
                                                {
                                                    scope2ObjectData[ii] = null;

                                                    UIWriteLine("scope2 delegate discarded " + new { MemberName, scope2FieldName });
                                                }
                                            }
                                        }

                                        // um. lets remove typeinfo?
                                        // why? to get defaults?
                                        var scope2copy = FormatterServices.GetUninitializedObject(scope2Type);
                                        FormatterServices.PopulateObjectMembers(scope2copy, scope2TypeSerializableMembers, scope2ObjectData);
                                        MethodTargetObjectData[i] = scope2copy;
                                    }
                                }
                            }



                            UIWriteLine(
                                "Task scope " +
                                new
                            {
                                MemberName,
                                IsString,
                                IsNumber,
                                IsDelegate,
                                IsProgress,

                                // will
                                TypeIndex
                            }
                                );
                        }
                    }
                }
            }
            #endregion



            // X:\jsc.svn\examples\javascript\test\TestTypeHandle\TestTypeHandle\Application.cs

            #region stateTypeHandleIndex
            var stateTypeHandleIndex = default(object);
            var stateType            = default(Type);
            var state_ObjectData     = default(object);

            if (state != null)
            {
                stateType            = state.GetType();
                stateTypeHandleIndex = __Type.GetTypeIndex("state", stateType);
                var state_SerializableMembers = FormatterServices.GetSerializableMembers(stateType);
                // Failed to execute 'postMessage' on 'Worker': An object could not be cloned.
                state_ObjectData = FormatterServices.GetObjectData(state, state_SerializableMembers);
            }
            #endregion



            #region CreateWorker
            Action <string> CreateWorker = uri =>
            {
                // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160108


                Console.WriteLine("enter CreateWorker");



                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150401
                // since we can start scope sharing, static sync may be turned off?

                #region xdata___string
                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                dynamic xdata___string = new object();

                // how much does this slow us down?
                // connecting to a new scope, we need a fresh copy of everything
                // we can start with strings
                foreach (ExpandoMember nn in Expando.Of(InternalInlineWorker.__string).GetMembers())
                {
                    if (nn.Value != null)
                    {
                        xdata___string[nn.Name] = nn.Value;
                    }
                }
                #endregion


                var worker = new global::ScriptCoreLib.JavaScript.DOM.Worker(
                    uri
                    //InternalInlineWorker.GetScriptApplicationSourceForInlineWorker()
                    //global::ScriptCoreLib.JavaScript.DOM.Worker.ScriptApplicationSourceForInlineWorker
                    );


                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201309-1/20130904-iprogress

                // InternalInitializeInlineWorker { IsIProgress = false, state = [object Object] }
                // e = (a.state instanceof PWjgSJKGsjiGudzxTfGfaA);

                // jsc does not yet support is interface
                // function PWjgSJKGsjiGudzxTfGfaA() {}  PWjgSJKGsjiGudzxTfGfaA.TypeName = "IProgress_1";
                // we should add .Interfaces = []

                //Action<object> OnReportAction = default(__IProgress<object>).Report;
                //var OnReportMethod = OnReportAction.Method;


                // workaround until null as interface works.

                if (state == null)
                {
                    state = new object();
                }


                // what about delegates to the interface?
                #region IsIProgress
                var IsIProgress = state is __IProgress <object>;

                // InternalInitializeInlineWorker: { IsIProgress = true, state = [object Object] }
                var xProgress = default(__IProgress <object>);

                if (IsIProgress)
                {
                    // X:\jsc.svn\examples\javascript\async\test\TestWorkerProgress\TestWorkerProgress\Application.cs
                    xProgress            = (__IProgress <object>)state;
                    state                = null;
                    state_ObjectData     = null;
                    stateTypeHandleIndex = null;
                }
                #endregion

                //Console.WriteLine("InternalInitializeInlineWorker: " + new { IsIProgress, IsTuple2_Item1_IsIProgress, state });



                int responseCounter = 0;

                #region postMessage

                Console.WriteLine("before CreateWorker postMessage");

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


                var message = new
                {
                    InternalThreadCounter,


                    MethodTargetObjectDataIsProgress,

                    MethodTargetObjectData,

                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201411/20141112
                    MethodTargetObjectDataTypes,

                    MethodTargetTypeIndex,

                    // set by ?
                    MethodToken,
                    MethodType,



                    // X:\jsc.svn\examples\javascript\test\TestTaskStartToString\TestTaskStartToString\Application.cs
                    // fields


                    // are we in state machine hop?
                    state_SerializableMembers = default(object),
                    state_ObjectData,

                    stateTypeHandleIndex,

                    state = state,


                    IsIProgress,
                    //IsTuple2_Item1_IsIProgress,

                    __string = (object)xdata___string
                };


                Console.WriteLine("before CreateWorker postMessage \n\n" + new { message });

                worker.postMessage(
                    message
                    ,
                    e =>
                {
                    responseCounter++;

                    // what kind of write backs do we expect?
                    // for now it should be console only


                    //Console.WriteLine(
                    //    "InternalInitializeInlineWorker: new message! "
                    //    + new
                    //    {
                    //        data = string.Join(
                    //           ", ",
                    //           Expando.Of(e.data).GetMemberNames().Select(k => (string)k).ToArray()
                    //        )
                    //    }
                    //);

                    // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                    dynamic zdata = e.data;


                    // is it the same for service worker?
                    #region AtWrite
                    string AtWrite = zdata.AtWrite;

                    if (!string.IsNullOrEmpty(AtWrite))
                    {
                        // thread is writing to console isnt it.
                        // we have requested to be notified of it on the main thread instead.

                        if (AtWrite.EndsWith("\r\n"))
                        {
                            Console.WriteLine(AtWrite.Substring(0, AtWrite.Length - 2));
                        }
                        else
                        {
                            Console.Write(AtWrite);
                        }
                    }
                    #endregion

                    #region __string
                    var zdata___string = (object)zdata.__string;
                    if (zdata___string != null)
                    {
                        #region __string
                        // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                        dynamic target = InternalInlineWorker.__string;
                        var m          = Expando.Of(zdata___string).GetMembers();

                        foreach (ExpandoMember nn in m)
                        {
                            Console.WriteLine("Worker has sent changes " + new { nn.Name });

                            target[nn.Name] = nn.Value;
                        }
                        #endregion
                    }
                    #endregion


                    //zdata.MethodTargetObjectDataProgressReport = new { ProgressEvent, i };

                    #region MethodTargetObjectDataProgressReport
                    {
                        // X:\jsc.svn\examples\javascript\async\test\TestWorkerScopeProgress\TestWorkerScopeProgress\Application.cs
                        // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                        dynamic MethodTargetObjectDataProgressReport = zdata.MethodTargetObjectDataProgressReport;
                        if ((object)MethodTargetObjectDataProgressReport != null)
                        {
                            object ProgressEvent = MethodTargetObjectDataProgressReport.ProgressEvent;
                            int ii = MethodTargetObjectDataProgressReport.ii;

                            MethodTargetObjectDataProgress[ii].Report(
                                ProgressEvent
                                );
                        }
                    }
                    #endregion


                    #region ContinueWithResult
                    {
                        // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                        dynamic ContinueWithResult = zdata.ContinueWithResult;
                        if ((object)ContinueWithResult != null)
                        {
                            responseCounter++;

                            // X:\jsc.svn\examples\javascript\async\test\TaskAsyncTaskRun\TaskAsyncTaskRun\Application.cs

                            var ResultTypeIndex  = default(object);
                            var ResultObjectData = default(object);

                            object Result = ContinueWithResult.Result;

                            // primitives wont have index
                            if (Result != null)
                            {
                                // X:\jsc.svn\examples\javascript\async\test\TestWorkerScopeProgress\TestWorkerScopeProgress\Application.cs

                                ResultTypeIndex  = ContinueWithResult.ResultTypeIndex;
                                ResultObjectData = ContinueWithResult.ResultObjectData;
                            }

                            // are we getting multiple responses?
                            Console.WriteLine("Task ContinueWithResult " + new { responseCounter, ResultTypeIndex, Result });

                            if (ResultTypeIndex != null)
                            {
                                // X:\jsc.svn\examples\javascript\async\test\TestTaskRunReturnToString\TestTaskRunReturnToString\Application.cs
                                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                                dynamic self = Native.self;

                                var ResultType = Type.GetTypeFromHandle(new __RuntimeTypeHandle((IntPtr)self[ResultTypeIndex]));
                                var zResult    = FormatterServices.GetUninitializedObject(ResultType);
                                var zResultTypeSerializableMembers = FormatterServices.GetSerializableMembers(ResultType);


                                // available for flash too yet?
                                FormatterServices.PopulateObjectMembers(
                                    zResult,
                                    zResultTypeSerializableMembers,
                                    (object[])ResultObjectData
                                    );

                                var xResult = new TaskCompletionSource <object>();
                                //xResult.SetResult(Result);
                                xResult.SetResult(zResult);
                                this.InternalSetCompleteAndYield((TResult)(object)xResult.Task);
                            }
                            else
                            {
                                // :7170ms Task ContinueWithResult { ResultTypeIndex = type$rfUTAxaiVTOCOkKbE6i0hg }

                                //0:7506ms Task ContinueWithResult view-source:40742
                                //0:7508ms { Result = [object Object] }

                                var xResult = new TaskCompletionSource <object>();
                                //xResult.SetResult(Result);
                                xResult.SetResult(Result);
                                this.InternalSetCompleteAndYield((TResult)(object)xResult.Task);
                            }
                        }
                    }
                    #endregion


                    #region yield
                    {
                        // X:\jsc.svn\examples\javascript\async\AsyncHopToUIFromWorker\AsyncHopToUIFromWorker\Application.cs
                        // this should be disabled if we hopped to ui? how?
                        // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                        dynamic xyield = zdata.yield;
                        if ((object)xyield != null)
                        {
                            Console.WriteLine("worker sent a yield signal?");

                            object value = xyield.value;

                            // X:\jsc.svn\examples\javascript\async\test\TestSemaphoreSlimAwaitThenReleaseInWorker\TestSemaphoreSlimAwaitThenReleaseInWorker\Application.cs

                            Console.WriteLine("__Task.InternalStart inner complete (pre bugcheck) " + new { yield = new { value } });

                            // needs more tests.
                            // is causing trouble for older tests?

                            this.InternalDispose = delegate
                            {
                                Console.WriteLine("at InternalDispose");
                                worker.terminate();
                            };

                            this.InternalSetCompleteAndYield((TResult)value);



                            // when to terminate???
                            //w.terminate();
                        }
                    }
                    #endregion


                    #region __IProgress_Report
                    if (xProgress != null)
                    {
                        // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                        dynamic __IProgress_Report = zdata.__IProgress_Report;

                        if ((object)__IProgress_Report != null)
                        {
                            object value = __IProgress_Report.value;



                            //Console.WriteLine("InternalInitializeInlineWorker Report: " + new { __IProgress_Report = new { value } });


                            xProgress.Report(value);
                        }
                    }
                    #endregion


                    // X:\jsc.svn\examples\javascript\async\AsyncHopToUIFromWorker\AsyncHopToUIFromWorker\Application.cs
                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150401
                    #region  HopToUIAwaitable
                    // where can we send the signal?

                    #endregion

                    if (yield != null)
                    {
                        yield(worker, e);
                    }
                }
                    );
                #endregion
            };
            #endregion



            #region InternalStart
            this.InternalStart = delegate
            {
                // X:\jsc.svn\examples\javascript\Test\TestRedirectWebWorker\TestRedirectWebWorker\Application.cs

                // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160108
                Console.WriteLine("enter InternalStart");



                #region GetScriptApplicationSourceForInlineWorker
                var u = InternalInlineWorker.GetScriptApplicationSourceForInlineWorker();

                //GetScriptApplicationSourceForInlineWorker { value = view-source#worker }

                if (u == Worker.ScriptApplicationSource + "#worker")
                {
                    #region base not redirected
                    if (Native.document.baseURI == Native.document.location.href)
                    {
                        // X:\jsc.svn\examples\javascript\async\Test\TestDownloadStringTaskAsync\TestDownloadStringTaskAsync\Application.cs

                        // X:\jsc.svn\examples\javascript\test\TestTaskStartToString\TestTaskStartToString\Application.cs
                        //Console.WriteLine("Document base not redirected...");

                        // its about time to cache the inline worker source. if we have not done it before that is..

                        var sw = Stopwatch.StartNew();

                        if (InternalWorkerSourceToBlobCache.ContainsKey(u))
                        {
                            // in this case, lets continue in the blob..

                            UIWriteLine("worker source is in cache... pending");

                            InternalWorkerSourceToBlobCache[u].ContinueWith(
                                task =>
                            {
                                UIWriteLine("worker source is in cache... " + new { sw.ElapsedMilliseconds });


                                CreateWorker(task.Result);
                            }
                                );


                            return;
                        }

                        // otherwise lets download, once...
                        // X:\jsc.svn\examples\javascript\async\Test\TestBytesToSemaphore\TestBytesToSemaphore\Application.cs


                        UIWriteLine("will download worker source into cache...");

                        var pending = new TaskCompletionSource <string>();

                        InternalWorkerSourceToBlobCache[u] = pending.Task;


                        // 4.0 compatible, using 4.5 feats
                        new __WebClient().DownloadStringTaskAsync(u).ContinueWith(
                            task =>
                        {
                            UIWriteLine("will download worker source into cache... done " + new { task.Result.Length, sw.ElapsedMilliseconds });

                            var aFileParts = new[] { task.Result };
                            var oMyBlob    = new Blob(aFileParts, new { type = "text/javascript" });  // the blob
                            var url        = URL.createObjectURL(oMyBlob);

                            pending.SetResult(url);

                            CreateWorker(url);
                        }
                            );

                        return;
                    }
                    #endregion

                    // see also
                    // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionWithWorker\ChromeExtensionWithWorker\Application.cs

                    {
                        // tested by?
                        Console.WriteLine("Document base redirected...");

                        var w = new WebClient();


                        // continue with?
                        w.DownloadStringCompleted +=
                            (sender, args) =>
                        {
                            var aFileParts = new[] { args.Result };
                            var oMyBlob    = new Blob(aFileParts, new { type = "text/javascript" });  // the blob
                            var url        = URL.createObjectURL(oMyBlob);

                            InternalInlineWorker.ScriptApplicationSourceForInlineWorker = url;

                            u = InternalInlineWorker.GetScriptApplicationSourceForInlineWorker();

                            CreateWorker(u);
                        };

                        // Failed to load resource: the server responded with a status of 400 (Bad Request) http://192.168.1.75:24275/:view-source
                        w.DownloadStringAsync(
                            new Uri(Worker.ScriptApplicationSource, UriKind.Relative)
                            );

                        return;
                    }
                }
                #endregion


                CreateWorker(u);
            };
            #endregion
        }
Esempio n. 15
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://qscribble.blogspot.com/2012/07/asyncawait-vs-stack-switching.html
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201308/20130825

            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Delegate.cs

            yield_locals.loc0 = "foo";

            Action yield = delegate
            {
                Console.WriteLine("more work " + new { yield_locals.loc0, Thread.CurrentThread.ManagedThreadId });


                // this function can run in both DOM and WebWorker.

                // if we were to talk to DOM, would we need to detect and autoswitch the context?
                //page.Content.innerText = "goo";
            };



            // { Target = [object Window], Method = { MethodToken = AQAABrpGJTe973zWF5WUSg } }
            Console.WriteLine(
                new { yield.Target, yield.Method }
                );

            //yield.Method.MetadataToken

            var Method      = yield.Method;
            var MethodToken = (string)(object)((__MethodInfo)(object)Method).MethodToken;

            Console.WriteLine(
                new { MethodToken }
                );
            // { MethodToken = AQAABrpGJTe973zWF5WUSg }

            // should be static and parameterless call
            // more work { loc0 = foo }
            Method.Invoke(null, new object[0]);



            var counter = 0;

            new IHTMLButton {
                innerText = "spawn new thread"
            }.AttachToDocument().WhenClicked(
                delegate
            {
                counter++;

                yield_locals.loc0 = "loc0 #" + new { counter };


                var w = new Worker(
                    worker =>
                {
                    Console.WriteLine("will wait for scope ...");

                    worker.onmessage +=
                        e =>
                    {
                        // { data = ldstr:AQAABrpGJTe973zWF5WUSg }

                        Console.WriteLine(new { e.data });

                        dynamic data = e.data;
                        //var data___string = (object)data.__string;

                        //var datax = Expando.Of(data___string);

                        //dynamic target = __string;

                        //datax.GetMembers().WithEach(
                        //    nn =>
                        //    {
                        //        Console.WriteLine("worker reads " + nn.Name);

                        //        target[nn.Name] = nn.Value;
                        //    }
                        //);

                        string message = data.message;


                        var scope_MethodToken = message.SkipUntilOrEmpty("ldstr:");

                        if (!string.IsNullOrEmpty(scope_MethodToken))
                        {
                            Console.WriteLine(new { scope_MethodToken });

                            //yield_locals.loc0 = "bar";

                            // more work { loc0 = bar }
                            var scope_yield_add = (MulticastDelegate)IFunction.Of(scope_MethodToken);

                            // Uncaught TypeError: Object #<lxyFdjnUJTaDStMnfRqY_aQ> has no method 'bBoABiRtYD2yr4CzwPIbLw'
                            // will this fail? jsc might need to do a reconstructive cast here
                            Action scope_yield = delegate { scope_yield_add.Method.Invoke(null, new object[0]); };

                            // Uncaught TypeError: Cannot read property 'undefined' of null
                            //scope_yield += (Action)scope_yield_add;


                            //scope_yield_add.Method.Invoke(null, new object[0]);
                            scope_yield();
                        }


                        //f.apply(null);



                        // running in worker context. cannot talk to outer scope yet.

                        // fist thing to support should be to allow incoming local strings

                        Console.WriteLine("working ...");
                        var s = new Stopwatch();
                        s.Start();

                        // spin the cpu
                        // how long do we have to, in order for task manager to notice?
                        // this should keep one cpu utilized atleast at 70%
                        for (int i = 0; i < 5; i++)
                        {
                            var xs = new Stopwatch();
                            xs.Start();
                            while (xs.ElapsedMilliseconds < 1000)
                            {
                                ;
                            }

                            Console.WriteLine(".");
                        }

                        Console.WriteLine("working ... done " + new { s.Elapsed });


                        // how can we yield back to DOM?



                        // SynchronizationContext.Current.


                        // special magic to break out of webworker context?

                        // awaitable?
                        worker.yield(
                            delegate
                        {
                            // which context are we now in?
                            // DOM? nested worker?
                        }
                            );
                    };
                }
                    );


                // staticfields.string.data1
                // can we send a copy of all static fields?
                // send scope/context data
                // we need domain memory kind of thing
                // memory that can be swapped

                dynamic xdata = new object();

                xdata.message = "ldstr:" + MethodToken;

                //dynamic xdata___string = new object();

                //Expando.Of(__string).GetMembers().With(
                //      xx =>
                //      {
                //          xx.WithEach(
                //              nn =>
                //              {
                //                  if (nn.Value != null)
                //                  {
                //                      Console.WriteLine("will copy " + nn.Name);

                //                      xdata___string[nn.Name] = nn.Value;
                //                  }
                //              }
                //          );
                //      }
                // );

                ////xdata___string.fake = "fake";

                //xdata.__string = xdata___string;

                w.postMessage((object)xdata);
            }
                );



            Expando.Of(__string).GetMembers().With(
                xx =>
            {
                Console.WriteLine(new { xx.Length });

                var bytes = 0;

                xx.WithEach(
                    nn =>
                {
                    if (nn.Value != null)
                    {
                        bytes += nn.Value.Length;
                        Console.WriteLine(nn.Name + " = " + nn.Value);
                    }
                    else
                    {
                        Console.WriteLine(nn.Name + " = null");
                    }
                }
                    );

                Console.WriteLine(new { bytes });
            }
                );
        }
        //02000038 ScriptCoreLib.JavaScript.DOM.HistoryExtensions+<>c__DisplayClass6
        //script: error JSC1000: unsupported flow detected, try to simplify.
        // Assembly V:\AsyncImageTask.Application.exe
        // DeclaringType ScriptCoreLib.JavaScript.DOM.HistoryExtensions+<>c__DisplayClass6, AsyncImageTask.Application, Version= 1.0.0.0, Culture= neutral, PublicKeyToken= null
        // OwnerMethod<onpopstate> b__8
        // Offset 00be
        // .Try ommiting the return, break or continue instruction.
        //script: error JSC1000: Method: <onpopstate>b__8, Type: ScriptCoreLib.JavaScript.DOM.HistoryExtensions+<>c__DisplayClass6; emmiting failed : System.InvalidOperationException: unsupported flow detected, try to simplify.

        static void onpopstate(PopStateEvent e)
        {
            // not roslyn friendly yet!

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


            // why 2 of them?
            var x_history_state = new Stack <Func <Task <__entry> > >();
            var x_e_state       = new Stack <Func <Task <__entry> > >();

            #region y
            Action <string, Stack <Func <Task <__entry> > >, HistoryDetails> y = null;

            y = (sourcehint, x, state) =>
            {
                if (state == null)
                {
                    return;
                }

                if (state.state == null)
                {
                    Console.WriteLine("(state.state == null)");
                }


                //dynamic state = xstate;

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

                string hint      = state.hint;
                string url       = state.url;
                bool   exclusive = state.exclusive;

                // 0:226852ms onpopstate { sourcehint = e.state , hint = ScriptCoreLib.JavaScript.DOM.HistoryExtensions.pushState, url = /, exclusive = 0,
                // state =  }
                Console.WriteLine("onpopstate.y " + new
                {
                    sourcehint,
                    hint,
                    url,
                    exclusive,

                    // 0:25692ms onpopstate { sourcehint = e.state , MethodToken = , invoke = [object Object] }
                    state.invoke,
                    state.state
                });


                //0:45199ms HistoryExtensions at onpopstate view-source:38792
                //0:45200ms onpopstate { sourcehint = e.state , hint = ScriptCoreLib.JavaScript.DOM.HistoryExtensions.pushState, url = /, exclusive = 0, state =  } view-source:38792
                //0:45202ms onpopstate { sourcehint = history.state , hint = ScriptCoreLib.JavaScript.DOM.HistoryExtensions.pushState, url = /, exclusive = 0, state =  } view-source:38792
                //0:45202ms onpopstate did we just move forward? { Count = 1 } view-source:38792
                //0:45203ms preparing the task for { MethodToken =  } view-source:38792
                //0:45204ms NextStyle added to InternalHistoryAwareSheets { Count = 2 } view-source:38792
                //0:45204ms enter IFunction.ByName { name =  } view-source:38792
                //0:45207ms returning the task view-source:38792

                // who is setting the invoke? how can it be empty?
                // see :687
                dynamic invoke = state.invoke;

                // what if our dynamic is broken ???
                // roslyn $function ?
                // script: error JSC1000: No implementation found for this native method, please implement [static Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable`1[[Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo, Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]])]
                //string MethodToken0 = Expando.Of(invoke)["function"];
                //string MethodToken0 = Expando.Of(state.invoke)["function"].GetValue();
                //Debugger.Break();

                // wtf??
                // 0:40145ms onpopstate.y { sourcehint = e.state , MethodToken = , MethodToken0 = undefined, invoke = [object Object] }

                //string MethodToken = invoke.function;
                string MethodToken = invoke.MethodToken;

                // :226853ms { MethodToken = , invoke = [object Object] }
                Console.WriteLine("onpopstate.y " + new { sourcehint, MethodToken, invoke });

                object arguments = invoke.arguments;
                object arg0      = ((object[])arguments)[0];


                #region __unwind
                TaskCompletionSource <HistoryScope <object> > __unwind = null;

                Func <TaskCompletionSource <HistoryScope <object> > > __get_unwind =
                    delegate
                {
                    // ok, something is listening to inline unwind.
                    // lets wait for the event then and not reload

                    Console.WriteLine("__get_unwind");

                    if (__unwind == null)
                    {
                        __unwind = new TaskCompletionSource <HistoryScope <object> >();
                    }

                    return(__unwind);
                };
                #endregion



                var scope = new HistoryScope <object>
                {
                    __state = arg0,
                    __TaskCompletionSource = __get_unwind
                };


                // whats the x?
                x.Push(
                    delegate
                {
                    Console.WriteLine("preparing the task for " + new { MethodToken });

                    var z = new TaskCompletionSource <__entry>();

                    #region missing ?
                    var sw = Stopwatch.StartNew();

                    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]])]
                    }
                    #endregion

                    // test the refresh!
                    var NextStyle = new IStyleSheet();
                    NextStyle.Owner.setAttribute("historic-url", IStyleSheet.all.Owner.getAttribute("historic-url") + " -> " + url);
                    IStyleSheet.InternalHistoryAwareSheets.Push(NextStyle);

                    Console.WriteLine("NextStyle added to InternalHistoryAwareSheets " + new { IStyleSheet.InternalHistoryAwareSheets.Count });

                    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, scope);
                        //go(source);

                        z.SetResult(
                            new __entry
                        {
                            unwind_data = state,
                            unwind      =
                                delegate
                            {
                                if (__unwind == null)
                                {
                                    return(true);
                                }

                                // time to do inline unwind.
                                __unwind.SetResult(scope);

                                return(false);
                            }
                        }
                            );
                    }
                        );

                    Console.WriteLine("returning the task");

                    return(z.Task);
                }
                    );

                var parent = (HistoryDetails)state.state;
                y(sourcehint + " parent", x, parent);
            };
            #endregion

            // crude cast.
            // why are we calling both?
            y("e.state ", x_e_state, (HistoryDetails)e.state);
            y("history.state ", x_history_state, (HistoryDetails)Native.window.history.state);

            //Application onpopstate { e = { state = [object Object] }, history = { state = [object Object] } }

            // Application onpopstate { e = { state = 2 }, history = { state = 2 } }

            //Console.WriteLine(
            //    "HistoryExtensions onpopstate " + new
            //    {
            //        e.state,

            //        e = new { state = x_e_state.Count },
            //        history = new { state = x_history_state.Count },

            //        //previous_Count,
            //        HistoryScope.inline_unwind.Count,

            //        // X:\jsc.svn\examples\javascript\Test\TestNavigationTiming\TestNavigationTiming\Application.cs
            //        // not available for safari!
            //        //Native.window.performance.navigation.redirectCount,
            //        //Native.window.performance.navigation.type
            //    }
            //);

            //HistoryExtensions onpopstate { state = , e = { state = 0 }, history = { state = 0 }, Count = 1 }

            #region restoreall
            Action restoreall = null;

            restoreall = delegate
            {
                Console.WriteLine("at restoreall " + new { x_history_state.Count });

                if (x_history_state.Count > 0)
                {
                    var yield = x_history_state.Pop();

                    yield().ContinueWithResult(
                        z =>
                    {
                        //Application onpopstate { e = { state = 2 }, history = { state = 2 }, Count = 1 }

                        #region exclusive
                        if (z.unwind_data.exclusive)
                        {
                            foreach (var unwind in HistoryScope.inline_unwind.AsEnumerable())
                            {
                                var reload = unwind();

                                if (reload)
                                {
                                    throw new NotImplementedException("exclusve scope needs to unwind prior states, yet one of them asks for full reload. what to do?");
                                }
                            }
                        }
                        #endregion

                        Console.WriteLine("restored: " + new { z.unwind_data });

                        HistoryScope.inline_unwind_data.Push(z.unwind_data);
                        HistoryScope.inline_unwind.Push(z.unwind);


                        restoreall();
                    }
                        );

                    return;
                }


                Console.WriteLine("at restoreall done! " + new { HistoryScope.inline_unwind.Count });
            };

            #endregion

            #region did we just move backward
            if ((HistoryScope.inline_unwind.Count - 1) == x_history_state.Count)
            {
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517

                // Application onpopstate { e = { state = 0 }, history = { state = 1 }, Count = 0 }

                //  Native.window.performance.navigation.type,
                Console.WriteLine(" did we just move backward? " + new
                {
                    unwind_data = HistoryScope.inline_unwind_data.Count,
                    unwind      = HistoryScope.inline_unwind.Count,
                });

                var unwind_data = (HistoryDetails)HistoryScope.inline_unwind_data.Pop();
                var unwind      = HistoryScope.inline_unwind.Pop();

                // if exclusive we have to reactivete the remaining as if full reload?
                Console.WriteLine(new
                {
                    unwind,
                    unwind_data.url,
                    unwind_data.exclusive,
                    HistoryScope.inline_unwind.Count
                });

                var reload = unwind();

                Console.WriteLine(new { reload, HistoryScope.inline_unwind.Count });

                if (reload)
                {
                    location_reload();
                    return;
                }

                //2:3ms  did we just move backward? view-source:35996
                //2:3ms { unwind = [object Object], url = http://192.168.1.91:14617/#/bar, exclusive = 1, Count = 0 } view-source:35955
                //2:5ms { reload = false, Count = 0 }

                // X:\jsc.svn\examples\javascript\CSS\Test\CSSHistoric\CSSHistoric\Application.cs
                var css = IStyleSheet.InternalHistoryAwareSheets.Pop();
                if (css != null)
                {
                    Console.WriteLine("remove css " + css.Owner.getAttribute("historic-url")
                                      );

                    css.disabled = true;
                    css.Owner.Orphanize();
                }

                //previous_Count--;

                if (unwind_data.exclusive)
                {
                    HistoryScope.inline_unwind_data.Clear();
                    HistoryScope.inline_unwind.Clear();

                    restoreall();
                }

                return;
            }
            #endregion

            // HistoryExtensions onpopstate { state = [object Object], e = { state = 1 }, history = { state = 1 }, Count = 0 }


            #region did we just move forward?
            if ((HistoryScope.inline_unwind.Count + 1) == x_history_state.Count)
            {
                // X:\jsc.svn\examples\javascript\test\TestHistoryForwardEvent\TestHistoryForwardEvent\Application.cs
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517

                Console.WriteLine("onpopstate did we just move forward? " + new { x_history_state.Count });

                // where is it added to that list so we can invoke it?
                x_history_state.First()().ContinueWithResult(
                    z =>
                {
                    Console.WriteLine("onpopstate go forward " + new { z.unwind_data.url, z.unwind_data.exclusive });

                    #region exclusive
                    if (z.unwind_data.exclusive)
                    {
                        foreach (var unwind in HistoryScope.inline_unwind.AsEnumerable())
                        {
                            var reload = unwind();

                            if (reload)
                            {
                                throw new NotImplementedException("exclusve scope needs to unwind prior states, yet one of them asks for full reload. what to do?");
                            }
                        }
                    }
                    #endregion

                    HistoryScope.inline_unwind_data.Push(z.unwind_data);
                    HistoryScope.inline_unwind.Push(z.unwind);

                    Console.WriteLine(new { HistoryScope.inline_unwind.Count });
                }
                    );


                return;
            }
            #endregion

            //HistoryExtensions onpopstate { state = [object Object], e = { state = 2 }, history = { state = 2 }, Count = 2 }

            #region ? reload
            if (e.state != null)
            {
                // back: { e = { state = 2 }, history = { state = 2 }, previous_Count = 3 }
                // forward: { e = { state = 3 }, history = { state = 3 }, previous_Count = 2 }



                location_reload();

                return;
            }
            #endregion


            //previous_Count = x_history_state.Count;



            restoreall();
        }
Esempio n. 17
0
 public Expando.FindArgs <TItem> FindMember(System.Action <Expando.FindArgs <TItem> > e)
 {
     return(Expando.Of(this).Find(e));
 }
Esempio n. 18
0
        public Task <TResult> ContinueWhenAll <TAntecedentResult, TResult>(
            Task <TAntecedentResult>[] tasks,
            Func <Task <TAntecedentResult>[], TResult> continuationFunction,
            CancellationToken cancellationToken,
            TaskContinuationOptions continuationOptions,
            TaskScheduler scheduler)
        {
            //Console.WriteLine("ContinueWhenAll " + new { tasks.Length, scheduler, Thread.CurrentThread.ManagedThreadId });


            var t = new __Task <TResult> {
                InternalStart = null
            };

            var cstart = 0;
            var cstop  = 0;

            #region ContinueWhenAll_yield
            Action ContinueWhenAll_yield = delegate
            {
                // how can we pass array of tasks to background?

                //Console.WriteLine("ContinueWhenAll_yield " + new { scheduler });

                #region GUI
                if (scheduler != null)
                {
                    var r = continuationFunction(tasks);

                    t.InternalSetCompleteAndYield(r);
                    return;
                }
                #endregion


                // X:\jsc.svn\examples\javascript\appengine\Test\AppEngineFirstEverWebServiceTask\AppEngineFirstEverWebServiceTask\ApplicationWebService.cs

                var xfunction  = continuationFunction;
                var MethodType = typeof(FuncOfTaskOfObjectArrayToObject).Name;

                #region MethodToken
                var MethodToken = ((__MethodInfo)xfunction.Method).InternalMethodToken;

                if (xfunction.Target != null)
                {
                    if (xfunction.Target != Native.self)
                    {
                        // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                        Delegate InternalTaskExtensionsScope_function = (xfunction.Target as dynamic).InternalTaskExtensionsScope_function;

                        if (InternalTaskExtensionsScope_function == null)
                        {
                            var message = "inline scope sharing not yet implemented";
                            Console.WriteLine(message);
                            throw new InvalidOperationException(message);
                        }

                        MethodToken = ((__MethodInfo)InternalTaskExtensionsScope_function.Method).InternalMethodToken;
                    }
                }
                #endregion



                #region xdata___string
                // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                dynamic xdata___string = new object();

                // how much does this slow us down?
                // connecting to a new scope, we need a fresh copy of everything
                // we can start with strings
                foreach (ExpandoMember nn in Expando.Of(InternalInlineWorker.__string).GetMembers())
                {
                    if (nn.Value != null)
                    {
                        xdata___string[nn.Name] = nn.Value;
                    }
                }
                #endregion

                // is this correct?
                // OBSOLETE ! needs more tests. what about scope sharing?
                var w = new global::ScriptCoreLib.JavaScript.DOM.Worker(
                    InternalInlineWorker.GetScriptApplicationSourceForInlineWorker()
                    //global::ScriptCoreLib.JavaScript.DOM.Worker.ScriptApplicationSourceForInlineWorker
                    );

                var TaskArray = tasks.Select(k => new { k.Result }).ToArray();

                Console.WriteLine(new { TaskArray = TaskArray.Length });
                //Debugger.Break();


                #region postMessage
                w.postMessage(
                    new
                {
                    InternalInlineWorker.InternalThreadCounter,
                    MethodToken,
                    MethodType,

                    //state = state,

                    // pass the result for reconstruction

                    // task[0].Result

                    TaskArray,

                    __string = (object)xdata___string
                }
                    ,
                    e =>
                {
                    // what kind of write backs do we expect?
                    // for now it should be console only

                    // X:\jsc.svn\examples\javascript\Test\Test435CoreDynamic\Test435CoreDynamic\Class1.cs
                    dynamic zdata = e.data;

                    #region AtWrite
                    string AtWrite = zdata.AtWrite;

                    if (!string.IsNullOrEmpty(AtWrite))
                    {
                        Console.Write(AtWrite);
                    }
                    #endregion

                    #region __string
                    var zdata___string = (object)zdata.__string;
                    if (zdata___string != null)
                    {
                        #region __string
                        dynamic target = InternalInlineWorker.__string;
                        var m          = Expando.Of(zdata___string).GetMembers();

                        foreach (ExpandoMember nn in m)
                        {
                            Console.WriteLine("Worker has sent changes " + new { nn.Name });

                            target[nn.Name] = nn.Value;
                        }
                        #endregion
                    }
                    #endregion

                    #region yield
                    dynamic yield = zdata.yield;
                    if ((object)yield != null)
                    {
                        object value = yield.value;

                        //Console.WriteLine("__Task.InternalStart inner complete " + new { yield = new { value } });


                        t.InternalSetCompleteAndYield((TResult)value);

                        //w.terminate();
                    }
                    #endregion
                }
                    );
                #endregion

                InternalInlineWorker.InternalThreadCounter++;
            };
            #endregion


            #region ContinueWhenAll_yield
            foreach (__Task <TAntecedentResult> item in tasks)
            {
                cstart++;
                //Console.WriteLine("ContinueWhenAll before ContinueWith " + new { cstart, tasks.Length, Thread.CurrentThread.ManagedThreadId });

                item.ContinueWith(
                    task =>
                {
                    cstop++;
                    //Console.WriteLine("ContinueWhenAll ContinueWith yield " + new { cstop, tasks.Length, Thread.CurrentThread.ManagedThreadId });


                    if (cstop == tasks.Length)
                    {
                        //Console.WriteLine("before ContinueWhenAll_yield");

                        ContinueWhenAll_yield();
                        //Console.WriteLine("after ContinueWhenAll_yield");
                    }
                },

                    // just for the watchdog
                    scheduler: TaskScheduler.FromCurrentSynchronizationContext()
                    );
            }
            #endregion

            return(t);
        }
Esempio n. 19
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            var t = typeof(Application);

            var h = t.TypeHandle;

            // i.constructor.prototype
            var i = h.Value;

            //          function LFTSZNW_bajmpg67CwzN3Xw() { }
            //          LFTSZNW_bajmpg67CwzN3Xw.TypeName = "IDbDataParameter";
            //          LFTSZNW_bajmpg67CwzN3Xw.Assembly = di7d9h5asU2PTUWT6s85lQ;
            //          LFTSZNW_bajmpg67CwzN3Xw.Interfaces =
            //{
            //          IzkeSBiD_aTGMsWPjgYVYEg:
            //              1
            //  , f7G82WqfyzOLoZ_b8v0KVxw:
            //              1
            //};

            //          var type$LFTSZNW_bajmpg67CwzN3Xw = LFTSZNW_bajmpg67CwzN3Xw.prototype;
            //          type$LFTSZNW_bajmpg67CwzN3Xw.constructor = LFTSZNW_bajmpg67CwzN3Xw;


            // 0:28ms {{ i = [object Object] }}
            Console.WriteLine(
                new { i }
                );

            // whats the name of the typeHandle?

            var scope = Expando.Of(Native.self).GetMemberNames();

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

            //0:53ms { { i = [object Object] } }
            //0:75ms { { Length = 4634 } }
            //0:104ms { { item = type$MHnq0rsJXjG69YnNoGDJfQ } }
            //0:105ms { { xt = < Namespace >.Application } }

            foreach (var item in scope)
            {
                dynamic s = Native.self;

                object value = s[item];

                if (value == (object)i)
                {
                    Console.WriteLine(new { item });

                    IntPtr            ii = s[item];
                    RuntimeTypeHandle xh = new __RuntimeTypeHandle(ii);
                    var xt = Type.GetTypeFromHandle(xh);

                    //stateTypeHandleIndex = type$XjKww8iSKT_aFTpY_bSs5vBQ, stateType = < Namespace >.,
                    Console.WriteLine(new { xt });

                    break;
                }
            }
        }
Esempio n. 20
0
 public string ToJSON()
 {
     return(Expando.Of(Descriptor).ToJSON());
 }
        public ExposedFunctions()
        {
            // this variable is static
            // if this application would be initiated multiple times
            // the last initiation will simply overwrite that variable
            instructions = new IHTMLDiv(
                @"
<p>
	This C# to JavaScript project has exposed a method for scripting. 
	You can either click on the link or copy it's href to the adressbar.
</p>
<h3>Method exposed statically</h3>
<ul>
"

                // we will let the browser to parse this html snippet
                // as it contains a javascript href
                + "<li>" + ExposedFunctions_AddData1_Example1.ToLink() + "</li>"
                + "<li>" + ExposedFunctions_AddData1_Example2.ToLink() + "</li>"
                + "<li>" + ExposedFunctions_AddData1_Example3.ToLink() + "</li>"
                + @"
</ul>
			"
                );


            instructions.style.padding = "2em";



            // previously we defined a static method to be exposed
            // lets define one dynamically

            var MethodName = "ExposedFunctions_Dynamic1";

            var DynamicExample1 = "javascript:" + MethodName + "({text: 'hello', index: 1});";
            var DynamicExample2 = "javascript:" + MethodName + "({text: 'world', index: 2});";

            Action <Data1> DynamicEntry =
                data =>
            {
                // to prove the dynamic behaviour we shall modify the values
                // passed to us and we will in turn pass them to the static
                // entry method
                ExposedFunctions_AddData1(
                    new Data1
                {
                    index = data.index + 1,
                    text  = "dynamic: " + data.text
                }
                    );
            };


            // In c# there will be dynamic object support which could
            // help with more magic.
            // Future code would look like this:
            // Expando.window[MethodName] = DynamicEntry

            // until then we must use more verbose code...
            Expando.Of(Native.Window).SetMember(MethodName, IFunction.OfDelegate(DynamicEntry));

            // lets also advertise this dynamic method

            // modifing innerHTML directly will invalidate any references we
            // have to any of its childre, which we do not have at this time...
            instructions.innerHTML +=
                @"
<h3>Method exposed dynamically</h3>
<ul>
"

                // we will let the browser to parse this html snippet
                // as it contains a javascript href
                + "<li>" + DynamicExample1.ToLink() + "</li>"
                + "<li>" + DynamicExample2.ToLink() + "</li>"
                + @"
</ul>";

            new IHTMLImage(Assets.Path + "/Preview.png").AttachTo(instructions);
            instructions.AttachToDocument();
        }